1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// Copyright 2019 Baidu, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

//! `brpc-build` compiles `.proto` files for `brpc-rs`.
//!
//! `brpc-build` is designed to be used for build-time code generation as part of
//! a Cargo build-script.

use std::{env, io, path, process};

/// Compile .proto files into Rust files during a Cargo build.
///
/// The generated `.rs` files will be written to the Cargo `OUT_DIR` directory,
/// suitable for use with the `include!` macro.
///
/// This function should be called in a project's `build.rs`.
///
/// # Arguments
///
/// **`protos`** - Paths to `.proto` files to compile. Any transitively
/// [imported][3] `.proto` files will automatically be included.
///
/// **`includes`** - Paths to directories in which to search for imports.
/// Directories will be searched in order. The `.proto` files passed in
/// **`protos`** must be found in one of the provided include directories.
///
/// It's expected that this function call be `unwrap`ed in a `build.rs`; there
/// is typically no reason to gracefully recover from errors during a build.
///
/// # Example `build.rs`
///
/// ```norun
/// fn main() {
///     brpc_build::compile_protos(&["src/echo.proto",],
///                                 &["src"]).unwrap();
/// }
/// ```
pub fn compile_protos<P>(protos: &[P], includes: &[P]) -> io::Result<()>
where
    P: AsRef<path::Path>,
{
    let out_dir_path: path::PathBuf = env::var_os("OUT_DIR")
        .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "OUT_DIR env var is not set"))
        .map(Into::into)?;
    let out_dir = out_dir_path.as_os_str();

    // Step 0
    let _ = prost_build::compile_protos(protos, includes)?;

    // Step 1
    let mut cmd = process::Command::new("protoc");
    for include in includes {
        cmd.arg("-I").arg(include.as_ref());
    }
    for proto in protos {
        cmd.arg(proto.as_ref());
    }
    cmd.arg("--plugin=protoc-gen=brpc=`which protoc-gen-brpc`");
    cmd.arg("--brpc_out").arg(&out_dir);

    let output = cmd.output()?;
    if !output.status.success() {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            format!(
                "protoc failed in the first pass: {}",
                String::from_utf8_lossy(&output.stderr)
            ),
        ));
    }

    // Step 2
    let mut cmd = process::Command::new("protoc");
    let current_dir = out_dir_path.to_path_buf();
    cmd.arg("-I").arg(out_dir_path.to_path_buf());
    for proto in protos {
        let f = proto
            .as_ref()
            .file_name()
            .ok_or(io::Error::new(io::ErrorKind::Other, "Invalid file name"))?;
        cmd.arg(current_dir.join(f));
    }
    cmd.arg("--cpp_out").arg(out_dir_path.to_path_buf());
    let output = cmd.output()?;
    if !output.status.success() {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            format!(
                "protoc failed in the second pass: {}",
                String::from_utf8_lossy(&output.stderr)
            ),
        ));
    }

    // Step 3
    let mut builder = cc::Build::new();
    for proto in protos {
        let mut cc_to_build = out_dir_path.to_path_buf();
        let f = proto
            .as_ref()
            .file_name()
            .ok_or(io::Error::new(io::ErrorKind::Other, "Invalid file name"))?;
        cc_to_build.push(f);
        cc_to_build.set_extension("brpc.cc");
        builder.file(&cc_to_build);

        let mut cc_to_build = out_dir_path.to_path_buf();
        let f = proto
            .as_ref()
            .file_name()
            .ok_or(io::Error::new(io::ErrorKind::Other, "Invalid file name"))?;
        cc_to_build.push(f);
        cc_to_build.set_extension("pb.cc");
        builder.file(&cc_to_build);
    }

    builder.cpp(true).flag("-std=c++11").warnings(false);
    builder.compile("brpc_service");
    println!("cargo:rustc-link-lib=static=brpc_service");

    println!("cargo:rustc-link-lib=brpc");
    println!("cargo:rustc-link-lib=protobuf");
    println!("cargo:rustc-link-lib=gflags");
    println!("cargo:rustc-link-lib=leveldb");
    println!("cargo:rustc-link-lib=ssl");
    println!("cargo:rustc-link-lib=crypto");

    Ok(())
}