ProtocGenCs.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Google.ProtocolBuffers.Compiler.PluginProto;
  2. using Google.ProtocolBuffers.DescriptorProtos;
  3. using System;
  4. using System.Collections.Generic;
  5. // Usage example:
  6. // protoc.exe
  7. // --plugin=path\to\protoc-gen-cs.exe
  8. // --cs_out="-generated_code_attributes=true umbrella_namespace=TutorialProto :."
  9. // --proto_path=.\protos\
  10. // protos\tutorial\addressbook.proto
  11. namespace Google.ProtocolBuffers.ProtoGen
  12. {
  13. public static class ProtocGenCs
  14. {
  15. internal static void Run(CodeGeneratorRequest request, CodeGeneratorResponse.Builder response)
  16. {
  17. var arguments = new List<string>();
  18. foreach (var arg in request.Parameter.Split(' '))
  19. {
  20. var timmedArg = (arg ?? "").Trim();
  21. if (!string.IsNullOrEmpty(timmedArg))
  22. {
  23. arguments.Add(timmedArg);
  24. }
  25. }
  26. // Adding fake input file to make TryValidate happy.
  27. arguments.Add(System.Reflection.Assembly.GetExecutingAssembly().Location);
  28. GeneratorOptions options = new GeneratorOptions
  29. {
  30. Arguments = arguments
  31. };
  32. IList<string> validationFailures;
  33. if (!options.TryValidate(out validationFailures))
  34. {
  35. response.Error += new InvalidOptionsException(validationFailures).Message;
  36. return;
  37. }
  38. Generator generator = Generator.CreateGenerator(options);
  39. generator.Generate(request, response);
  40. }
  41. public static int Main(string[] args)
  42. {
  43. // Hack to make sure everything's initialized
  44. DescriptorProtoFile.Descriptor.ToString();
  45. ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance();
  46. CSharpOptions.RegisterAllExtensions(extensionRegistry);
  47. CodeGeneratorRequest request;
  48. var response = new CodeGeneratorResponse.Builder();
  49. try
  50. {
  51. using (var input = Console.OpenStandardInput())
  52. {
  53. request = CodeGeneratorRequest.ParseFrom(input, extensionRegistry);
  54. }
  55. Run(request, response);
  56. }
  57. catch (Exception e)
  58. {
  59. response.Error += e.ToString();
  60. }
  61. using (var output = Console.OpenStandardOutput())
  62. {
  63. response.Build().WriteTo(output);
  64. output.Flush();
  65. }
  66. return 0;
  67. }
  68. }
  69. }