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
// TODO: move into separate crate
#![doc(hidden)]

use plugin::*;
use protobuf::descriptor::FileDescriptorProto;
use protobuf::parse_from_reader;
use protobuf::Message;
use std::io::stdin;
use std::io::stdout;
use std::str;

pub struct GenRequest<'a> {
    pub file_descriptors: &'a [FileDescriptorProto],
    pub files_to_generate: &'a [String],
    pub parameter: &'a str,
}

pub struct GenResult {
    pub name: String,
    pub content: Vec<u8>,
}

pub fn plugin_main<F>(gen: F)
where
    F: Fn(&[FileDescriptorProto], &[String]) -> Vec<GenResult>,
{
    plugin_main_2(|r| gen(r.file_descriptors, r.files_to_generate))
}

pub fn plugin_main_2<F>(gen: F)
where
    F: Fn(&GenRequest) -> Vec<GenResult>,
{
    let req = parse_from_reader::<CodeGeneratorRequest>(&mut stdin()).unwrap();
    let result = gen(&GenRequest {
        file_descriptors: &req.get_proto_file(),
        files_to_generate: &req.get_file_to_generate(),
        parameter: req.get_parameter(),
    });
    let mut resp = CodeGeneratorResponse::new();
    resp.set_file(
        result
            .iter()
            .map(|file| {
                let mut r = CodeGeneratorResponse_File::new();
                r.set_name(file.name.to_string());
                r.set_content(str::from_utf8(file.content.as_ref()).unwrap().to_string());
                r
            })
            .collect(),
    );
    resp.write_to_writer(&mut stdout()).unwrap();
}