1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 // Generates Node gRPC service interface out of Protobuf IDL.
20
21 #include <memory>
22
23 #include "src/compiler/config.h"
24 #include "src/compiler/node_generator.h"
25 #include "src/compiler/node_generator_helpers.h"
26
27 using grpc_node_generator::GenerateFile;
28 using grpc_node_generator::GetJSServiceFilename;
29
30 class NodeGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
31 public:
NodeGrpcGenerator()32 NodeGrpcGenerator() {}
~NodeGrpcGenerator()33 ~NodeGrpcGenerator() {}
34
Generate(const grpc::protobuf::FileDescriptor * file,const grpc::string & parameter,grpc::protobuf::compiler::GeneratorContext * context,grpc::string * error) const35 bool Generate(const grpc::protobuf::FileDescriptor* file,
36 const grpc::string& parameter,
37 grpc::protobuf::compiler::GeneratorContext* context,
38 grpc::string* error) const {
39 grpc_node_generator::Parameters generator_parameters;
40 generator_parameters.minimum_node_version = 4;
41
42 if (!parameter.empty()) {
43 std::vector<grpc::string> parameters_list =
44 grpc_generator::tokenize(parameter, ",");
45 for (auto parameter_string = parameters_list.begin();
46 parameter_string != parameters_list.end(); parameter_string++) {
47 std::vector<grpc::string> param =
48 grpc_generator::tokenize(*parameter_string, "=");
49 if (param[0] == "minimum_node_version") {
50 sscanf(param[1].c_str(), "%d",
51 &generator_parameters.minimum_node_version);
52 } else {
53 *error = grpc::string("Unknown parameter: ") + *parameter_string;
54 return false;
55 }
56 }
57 }
58
59 grpc::string code = GenerateFile(file, generator_parameters);
60 if (code.size() == 0) {
61 return true;
62 }
63
64 // Get output file name
65 grpc::string file_name = GetJSServiceFilename(file->name());
66
67 std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output(
68 context->Open(file_name));
69 grpc::protobuf::io::CodedOutputStream coded_out(output.get());
70 coded_out.WriteRaw(code.data(), code.size());
71 return true;
72 }
73 };
74
main(int argc,char * argv[])75 int main(int argc, char* argv[]) {
76 NodeGrpcGenerator generator;
77 return grpc::protobuf::compiler::PluginMain(argc, argv, &generator);
78 }
79