-
Notifications
You must be signed in to change notification settings - Fork 13
/
GenerateCommand.cs
235 lines (197 loc) · 7.35 KB
/
GenerateCommand.cs
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
using CliFx;
using CliFx.Attributes;
using CliFx.Infrastructure;
using ZeroQL.Bootstrap;
using ZeroQL.CLI.Converters;
using ZeroQL.Config;
using ZeroQL.Core.Enums;
using ZeroQL.Extensions;
using ZeroQL.Internal;
namespace ZeroQL.CLI.Commands;
[Command("generate", Description = "Generates C# classes from graphql file.")]
public class GenerateCommand : ICommand
{
[CommandOption(
"config",
'c',
Description =
"The generation config file. For example, './zeroql.json'. Use `zeroql config init` to bootstrap.")]
public string? Config { get; set; }
[CommandOption(
"schema",
's',
Description = "The path to get the schema file. For example, './schema.graphql'")]
public string Schema { get; set; }
[CommandOption("namespace", 'n', Description = "The namespace for generated client")]
public string Namespace { get; set; }
[CommandOption(
"client-name",
'q',
Description = "The client name for the generated client")]
public string? ClientName { get; set; }
[CommandOption("output", 'o', Description = "The output file. For example, './Generated/GraphQL.g.cs'")]
public string Output { get; set; }
[CommandOption("visibility", 'v', Description = "The visibility within the assembly for the generated client")]
public ClientVisibility? Visibility { get; set; }
[CommandOption(
"warnings-to-ignore",
Description = "The warnings to ignore when generating the client. Example: --warnings-to-ignore=CS0168,CS0219")]
public string? WarningsToIgnore { get; set; }
[CommandOption(
"scalars",
Description =
"Custom scalars to use when generating the client. Example: --scalars Point=Geometry.Point --scalars Rect=Geometry.Rect",
Converter = typeof(HeaderConverter))]
public KeyValuePair<string, string>[]? Scalars { get; set; }
[CommandOption(
"netstandard-compatibility",
Description = "Enables netstandard compatibility during generation.")]
public bool? NetstandardCompatibility { get; set; } = null;
[CommandOption("force", 'f', Description = "Ignore checksum check and generate source code")]
public bool Force { get; set; }
public async ValueTask ExecuteAsync(IConsole console)
{
var canContinue = await ReadConfig(console);
if (!canContinue)
{
return;
}
var validationSuccessful = await Validate(console);
if (!validationSuccessful)
{
return;
}
if (!File.Exists(Schema))
{
await console.Error.WriteLineAsync("Schema file does not exist. Check that file exist.");
return;
}
var fileName = Path.GetFileName(Output);
if (string.IsNullOrEmpty(fileName))
{
await console.Error.WriteLineAsync(
"The output file name has wrong format. It should be path to file. For example, './Generated/GraphQL.g.cs'");
return;
}
var scalars = Scalars?
.ToDictionary(o => o.Key, o => o.Value);
var options = new GraphQlGeneratorOptions(Namespace, Visibility ?? ClientVisibility.Public)
{
ClientName = ClientName,
NetstandardCompatibility = NetstandardCompatibility,
Scalars = scalars,
WarningsToIgnore = WarningsToIgnore?.Split(","),
};
var outputPath = Path.IsPathRooted(Output) ? Output : Path.GetFullPath(Output);
await console.Output.WriteLineAsync($"Output path: {outputPath}");
if (!Force && File.Exists(outputPath))
{
var checksumFile = ChecksumHelper.GenerateChecksumFromSchemaFile(Schema, options);
var checksumSourceCode = ChecksumHelper.ExtractChecksumFromSourceCode(outputPath);
if (checksumFile == checksumSourceCode)
{
await console.Output.WriteLineAsync(
"The source code is up-to-date with graphql schema. Skipping code generation.");
return;
}
}
var graphql = await File.ReadAllTextAsync(Schema);
var csharpClient = GraphQLGenerator.ToCSharp(graphql, options);
var outputFolder = Path.GetDirectoryName(outputPath)!;
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
Exception? exception = null;
var count = 10;
for (int i = 0; i < count; i++)
{
try
{
using var file = File.Open(outputPath, FileMode.Create, FileAccess.Write, FileShare.None);
using var writer = new StreamWriter(file);
await writer.WriteAsync(csharpClient);
break;
}
catch (Exception e)
{
exception = e;
await console.Error.WriteLineAsync($"Failed write to '{outputPath}'");
await console.Error.WriteLineAsync($"Attempting in 1 second. {i + 1} / {count}");
await Task.Delay(1000);
}
}
if (exception is not null)
{
await console.Error.WriteLineAsync("Failed to write to file.");
await console.Error.WriteLineAsync(exception.Message);
}
}
private async Task<bool> Validate(IConsole console)
{
if (string.IsNullOrEmpty(Schema))
{
await console.Error.WriteLineAsync("Schema file is not specified. Use --schema option.");
return false;
}
if (string.IsNullOrEmpty(Namespace))
{
await console.Error.WriteLineAsync("Namespace is not specified. Use --namespace option.");
return false;
}
if (string.IsNullOrEmpty(Output))
{
await console.Error.WriteLineAsync("Output file is not specified. Use --output option.");
return false;
}
return true;
}
public async Task<bool> ReadConfig(IConsole console)
{
if (Config is null)
{
return true;
}
var (config, error) = ZeroQLConfigReader.ReadConfig(Config).Unwrap();
if (error)
{
using var redColor = console.WithForegroundColor(ConsoleColor.Red);
await console.Error.WriteLineAsync("Error reading config file.");
await console.Error.WriteLineAsync(error.Message);
return true;
}
if (string.IsNullOrEmpty(Schema))
{
Schema = config.GraphQL;
}
if (string.IsNullOrEmpty(Namespace))
{
Namespace = config.Namespace;
}
if (string.IsNullOrEmpty(ClientName))
{
ClientName = config.ClientName;
}
if (Scalars is null)
{
Scalars = config.Scalars?.ToArray();
}
if (!NetstandardCompatibility.HasValue)
{
NetstandardCompatibility = config.NetstandardCompatibility;
}
if (!Visibility.HasValue)
{
Visibility = config.Visibility;
}
if (WarningsToIgnore is null)
{
WarningsToIgnore = config.WarningsToIgnore?.Join(",");
}
if (string.IsNullOrEmpty(Output) && !string.IsNullOrEmpty(config.Output))
{
Output = config.Output;
}
return true;
}
}