-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
75 lines (67 loc) · 1.94 KB
/
Copy pathProgram.cs
File metadata and controls
75 lines (67 loc) · 1.94 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
using System.Text;
using DotPython.ParserGenerator.Generation;
return Run(args);
static int Run(string[] arguments)
{
if (arguments is not [var command, var grammarPath, var outputPath])
{
Console.Error.WriteLine(
"Usage: dotpython-parser-generator <generate|check> <grammar> <generated-output>"
);
return 2;
}
try
{
var grammar = File.ReadAllText(grammarPath);
var generated = PythonParserSourceGenerator.Generate(grammar);
return command switch
{
"generate" => WriteGeneratedOutput(outputPath, generated),
"check" => CheckGeneratedOutput(outputPath, generated),
_ => ReportUnknownCommand(command),
};
}
catch (Exception exception)
when (exception is IOException or UnauthorizedAccessException or InvalidDataException)
{
Console.Error.WriteLine(exception.Message);
return 1;
}
}
static int WriteGeneratedOutput(string outputPath, string generated)
{
if (
File.Exists(outputPath)
&& string.Equals(File.ReadAllText(outputPath), generated, StringComparison.Ordinal)
)
{
return 0;
}
var fullPath = Path.GetFullPath(outputPath);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);
File.WriteAllText(
fullPath,
generated,
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)
);
return 0;
}
static int CheckGeneratedOutput(string outputPath, string generated)
{
if (
File.Exists(outputPath)
&& string.Equals(File.ReadAllText(outputPath), generated, StringComparison.Ordinal)
)
{
return 0;
}
Console.Error.WriteLine(
$"Generated parser drift detected in '{outputPath}'. Run 'just parser-generate'."
);
return 1;
}
static int ReportUnknownCommand(string command)
{
Console.Error.WriteLine($"Unknown parser-generator command '{command}'.");
return 2;
}