aboutsummaryrefslogtreecommitdiff
path: root/csharp/src/ProtoGen/ProtocGenCs.cs
blob: 2926420005686d32df0a28124ddc708e3277eef1 (plain) (blame)
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
72
73
74
75
76
using Google.ProtocolBuffers.Compiler.PluginProto;
using Google.ProtocolBuffers.DescriptorProtos;
using System;
using System.Collections.Generic;

// Usage example:
//   protoc.exe
//     --plugin=path\to\protoc-gen-cs.exe
//     --cs_out="-generated_code_attributes=true umbrella_namespace=TutorialProto :."
//     --proto_path=.\protos\
//     protos\tutorial\addressbook.proto

namespace Google.ProtocolBuffers.ProtoGen
{
    public static class ProtocGenCs
    {
        internal static void Run(CodeGeneratorRequest request, CodeGeneratorResponse.Builder response)
        {
            var arguments = new List<string>();
            foreach (var arg in request.Parameter.Split(' '))
            {
                var timmedArg = (arg ?? "").Trim();
                if (!string.IsNullOrEmpty(timmedArg))
                {
                    arguments.Add(timmedArg);
                }
            }
            // Adding fake input file to make TryValidate happy.
            arguments.Add(System.Reflection.Assembly.GetExecutingAssembly().Location);

            GeneratorOptions options = new GeneratorOptions
            {
                Arguments = arguments
            };
            IList<string> validationFailures;
            if (!options.TryValidate(out validationFailures))
            {
                response.Error += new InvalidOptionsException(validationFailures).Message;
                return;
            }

            Generator generator = Generator.CreateGenerator(options);
            generator.Generate(request, response);
        }

        public static int Main(string[] args)
        {
            // Hack to make sure everything's initialized
            DescriptorProtoFile.Descriptor.ToString();
            ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance();
            CSharpOptions.RegisterAllExtensions(extensionRegistry);

            CodeGeneratorRequest request;
            var response = new CodeGeneratorResponse.Builder();
            try
            {
                using (var input = Console.OpenStandardInput())
                {
                    request = CodeGeneratorRequest.ParseFrom(input, extensionRegistry);
                }
                Run(request, response);
            }
            catch (Exception e)
            {
                response.Error += e.ToString();
            }

            using (var output = Console.OpenStandardOutput())
            {
                response.Build().WriteTo(output);
                output.Flush();
            }
            return 0;
        }
    }
}