node_plugin.cc 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. // Generates Node gRPC service interface out of Protobuf IDL.
  19. #include <memory>
  20. #include "src/compiler/config.h"
  21. #include "src/compiler/node_generator.h"
  22. #include "src/compiler/node_generator_helpers.h"
  23. using grpc_node_generator::GenerateFile;
  24. using grpc_node_generator::GetJSServiceFilename;
  25. class NodeGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
  26. public:
  27. NodeGrpcGenerator() {}
  28. ~NodeGrpcGenerator() {}
  29. bool Generate(const grpc::protobuf::FileDescriptor* file,
  30. const grpc::string& parameter,
  31. grpc::protobuf::compiler::GeneratorContext* context,
  32. grpc::string* error) const {
  33. grpc_node_generator::Parameters generator_parameters;
  34. generator_parameters.minimum_node_version = 4;
  35. if (!parameter.empty()) {
  36. std::vector<grpc::string> parameters_list =
  37. grpc_generator::tokenize(parameter, ",");
  38. for (auto parameter_string = parameters_list.begin();
  39. parameter_string != parameters_list.end(); parameter_string++) {
  40. std::vector<grpc::string> param =
  41. grpc_generator::tokenize(*parameter_string, "=");
  42. if (param[0] == "minimum_node_version") {
  43. sscanf(param[1].c_str(), "%d",
  44. &generator_parameters.minimum_node_version);
  45. } else {
  46. *error = grpc::string("Unknown parameter: ") + *parameter_string;
  47. return false;
  48. }
  49. }
  50. }
  51. grpc::string code = GenerateFile(file, generator_parameters);
  52. if (code.size() == 0) {
  53. return true;
  54. }
  55. // Get output file name
  56. grpc::string file_name = GetJSServiceFilename(file->name());
  57. std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output(
  58. context->Open(file_name));
  59. grpc::protobuf::io::CodedOutputStream coded_out(output.get());
  60. coded_out.WriteRaw(code.data(), code.size());
  61. return true;
  62. }
  63. };
  64. int main(int argc, char* argv[]) {
  65. NodeGrpcGenerator generator;
  66. return grpc::protobuf::compiler::PluginMain(argc, argv, &generator);
  67. }