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
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use protoc_grpcio::CompileResult;
use std::path::Path;

/// This crate provides a library for generating a Client trait for GRPC clients
/// generated by grpc-rs (protoc-grpcio)
///
/// This crate compliments the functionality provided by `protoc-grpcio` by defining a Trait for
/// the GRPC client service that can be used instead of the client directly for polymorphism and
/// testing.
///
///
/// ## Usage Example
///
/// To generate client trait as part of `build.rs` script, add:
///
/// ```ignore,no_run
/// grpcio_client::client_stub_gen(
///         &["calculator.proto"],               /* service files to generate traits for */
///         &["src/proto", "../deps/src/proto"], /* proto paths & includes */
///         "src/proto",                         /* target dir */
///     );
/// ```
///
/// This will create the file `calculator_client.rs` under `src/proto` folder.
///
/// The generated file will include 2 structures:
/// ```rust
/// // assuming the service name is `Calculator`
/// pub trait CalculatorClientTrait {
///     // methods
/// }
/// ```
/// and
///
/// ```rust
/// # struct CalculatorClient;
/// # pub trait CalculatorClientTrait {
/// #    // methods
/// # }
///
/// impl CalculatorClientTrait for CalculatorClient {
///     // method impl -- calling method from client
/// }
/// ```
mod codegen;
mod util;

/// Generate client trait for the GRPC Client
/// * `from` - the files with the services to generate client traits for
/// * `includes` - a vector of the parent folder of the files from `from` and all their includes.
/// * `to` - a path to a folder to store the generated files.
///
/// Generates client trait for the GRPC service defined in the first argument.
/// `from` argument includes
///
/// ## Example use:
///   client_stub_gen(&["src/proto/myservice.proto"], vec![], "src/proto");
pub fn client_stub_gen<P: AsRef<Path>>(
    from: &[&str],
    includes: &[&str],
    to: P,
) -> CompileResult<()> {
    let descriptor_set = util::protoc_descriptor_set(from, includes)?;
    util::write_out_generated_files(codegen::gen(descriptor_set.get_file(), from), &to)
        .expect("failed to write generated grpc definitions");

    Ok(())
}