This repository was archived by the owner on Jun 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathGenerateFromProto.cs
More file actions
239 lines (210 loc) · 8.62 KB
/
GenerateFromProto.cs
File metadata and controls
239 lines (210 loc) · 8.62 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Knacka.Se.ProtobufGenerator
{
public class GenerateFromProto : ICanGenerateFromProto
{
private readonly string _protocPath;
private readonly string _grpcPath;
public GenerateFromProto(string protocPath, string grpcPath)
{
_protocPath = protocPath;
_grpcPath = grpcPath;
}
public byte[] GenerateCsharpFromProto(string protoPath)
{
if (string.IsNullOrEmpty(_protocPath))
return null;
string indir = null;
var args = new Dictionary<string, List<string>>();
try
{
string infile = Path.GetFileName(protoPath);
indir = Path.GetDirectoryName(protoPath);
string outdir = GetTempDir();
args.Add("csharp_out", new List<string>(new string[] { outdir }));
args.Add("proto_path", new List<string>(new string[] { indir }));
if (!string.IsNullOrEmpty(_grpcPath))
{
args.Add("plugin", new List<string>(new string[] { "protoc-gen-grpc=" + _grpcPath }));
args.Add("grpc_out", new List<string>(new string[] { outdir }));
}
GetFileArguments(protoPath, ref args);
var argsValue = WriteArgs(infile, ref args);
Logger.Log("Running: " + _protocPath + " " + argsValue + " in working directory:" + indir);
string stderr = null;
string stdout = null;
var exitCode = RunProtoc(_protocPath, argsValue, indir, out stdout, out stderr);
Logger.LogIf(() => exitCode != 0,
() => "exitcode was " + exitCode +
". You might have a problem generating the code here. Command: " +
_protocPath + " " + argsValue + " in working directory: " + indir);
Logger.LogIf(() => stdout.Length > 0, () => "stdout: " + stdout);
Logger.LogIf(() => stderr.Length > 0, () => "stderr: " + stderr);
if (!string.IsNullOrEmpty(stderr))
{
throw new InvalidOperationException(stderr);
}
var files = Directory.GetFiles(outdir);
if (files?.Any() == true)
{
using (var ms = new MemoryStream())
using (var sw = new StreamWriter(ms))
{
sw.WriteLine($"// Generated by ProtobufGenerator {DateTime.Now:yyy-MM-dd HH:mm:ss}");
sw.WriteLine("\r\n#region Using statments\r\n");
foreach (var pass in Enumerable.Range(0, 2))
{
foreach (var file in files)
{
using (var fs = File.OpenRead(Path.Combine(outdir, file)))
using (var sr = new StreamReader(fs))
{
if (pass == 1) sw.WriteLine($"\r\n#region File \"{Path.GetFileName(file)}\"\r\n");
string line;
var re = new Regex(@"^\s*using");
while ((line = sr.ReadLine()) != null)
{
if (re.IsMatch(line) ^ pass == 1)
{
sw.WriteLine(line);
}
}
if (pass == 1) sw.WriteLine("\r\n#endregion");
}
}
if (pass == 0) sw.WriteLine("\r\n#endregion");
sw.Flush();
}
CleanTempDir(outdir);
return ms.ToArray();
}
}
CleanTempDir(outdir);
}
catch (Exception e)
{
var msg = e.Message ?? e.ToString();
Logger.Log("unhandled exception: " + msg);
}
finally
{
Logger.Log("Done with: " + _protocPath + " " + args + " in working directory:" + indir);
}
return null;
}
private static void CleanTempDir(string outdir)
{
try
{
Directory.Delete(outdir, true);
}
catch (Exception)
{
Logger.Log("warning: could not delete: " + outdir);
}
}
private static string GetTempDir()
{
var tmpPath = Path.GetTempPath();
var tries = 100;
var r = new Random();
while (tries-- > 0)
{
var path = Path.Combine(tmpPath, $"protoc-{r.Next():x}");
if (!Directory.Exists(path))
{
try
{
Directory.CreateDirectory(path);
return path;
}
catch (Exception x)
{
Logger.Log($"{x.GetType().Name}: {x.Message}, could not: create path \"{path}\"");
break;
}
}
}
return null;
}
private static string CommentArgumentLineRegex = "^///? ?ProtobufGenerator-Arg:([^:]*)(:(.*))?";
private void GetFileArguments(string protoPath, ref Dictionary<string, List<string>> args)
{
if (!File.Exists(protoPath))
{
return;
}
using (var fileReader = File.OpenRead(protoPath))
using (var streamReader = new StreamReader(fileReader))
{
while(!streamReader.EndOfStream)
{
var line = streamReader.ReadLine();
var match = Regex.Match(line, CommentArgumentLineRegex);
if (!match.Success)
{
continue;
}
var argName = match.Groups[1].Value;
var argValue = match.Groups[match.Groups.Count - 1].Value;
if (args.ContainsKey(argName))
{
args[argName].Add(argValue);
}
else
{
args.Add(argName, new List<string>(new string[] { argValue }));
}
}
}
}
private string WriteArgs(string protoFile, ref Dictionary<string, List<string>> args)
{
var sb = new StringBuilder();
foreach (var kvp in args)
{
foreach (var argInstance in kvp.Value)
{
sb.AppendFormat("--{0}={1} ", kvp.Key, argInstance);
}
}
sb.AppendFormat(" {0}", protoFile);
return sb.ToString();
}
static int RunProtoc(string path, string arguments, string workingDir, out string stdout, out string stderr)
{
using (var proc = new Process())
{
var psi = proc.StartInfo;
psi.FileName = path;
psi.Arguments = arguments;
if (!string.IsNullOrEmpty(workingDir)) psi.WorkingDirectory = workingDir;
psi.RedirectStandardError = psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
proc.Start();
var stdoutTask = proc.StandardOutput.ReadToEndAsync();
var stderrTask = proc.StandardError.ReadToEndAsync();
if (!proc.WaitForExit(5000))
{
try { proc.Kill(); } catch { }
}
var exitCode = proc.ExitCode;
stderr = stdout = "";
if (stdoutTask.Wait(1000)) stdout = stdoutTask.Result;
if (stderrTask.Wait(1000)) stderr = stderrTask.Result;
return exitCode;
}
}
}
}