forked from paulirwin/JavaToCSharp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
259 lines (214 loc) · 9.49 KB
/
Program.cs
File metadata and controls
259 lines (214 loc) · 9.49 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
using System.CommandLine;
using System.CommandLine.Invocation;
using JavaToCSharp;
using Microsoft.Extensions.Logging;
namespace JavaToCSharpCli;
/// <summary>
/// The main JavaToCSharpCli program class.
/// </summary>
public class Program
{
private static readonly ILoggerFactory _loggerFactory;
private static readonly ILogger _logger;
private static readonly Option<bool> _includeUsingsOption = new(
name: "--include-usings",
description: "Include using directives in output",
getDefaultValue: () => true);
private static readonly Option<bool> _includeNamespaceOption = new(
name: "--include-namespace",
description: "Include namespace in output",
getDefaultValue: () => true);
private static readonly Option<bool> _includeCommentsOption = new(
name: "--include-comments",
description: "Include comments in output",
getDefaultValue: () => true);
private static readonly Option<bool> _useDebugAssertOption = new(
name: "--use-debug-assert",
description: "Use Debug.Assert for asserts",
getDefaultValue: () => false);
private static readonly Option<bool> _startInterfaceNamesWithIOption = new(
name: "--start-interface-names-with-i",
description: "Prefix interface names with the letter I",
getDefaultValue: () => true);
private static readonly Option<bool> _commentUnrecognizedCodeOption = new(
name: "--comment-unrecognized-code",
description: "Include unrecognized code in output as commented-out code",
getDefaultValue: () => true);
private static readonly Option<bool> _systemOutToConsoleOption = new(
name: "--system-out-to-console",
description: "Convert System.out calls to Console",
getDefaultValue: () => false);
private static readonly Option<bool> _clearDefaultUsingsOption = new(
name: "--clear-usings",
description: "Remove all default usings provided by this app",
getDefaultValue: () => false);
private static readonly Option<List<string>> _addUsingsOption = new(
name: "--add-using",
description: "Adds a using directive to the collection of usings")
{
ArgumentHelpName = "namespace"
};
static Program()
{
_loggerFactory = LoggerFactory.Create(builder =>
builder.AddSimpleConsole().SetMinimumLevel(LogLevel.Information));
_logger = _loggerFactory.CreateLogger<Program>();
}
public static async Task Main(string[] args)
{
var rootCommand = new RootCommand("Java to C# Converter")
{
Description = "A syntactic transformer of source code from Java to C#."
};
rootCommand.AddCommand(CreateFileCommand());
rootCommand.AddCommand(CreateDirectoryCommand());
rootCommand.AddGlobalOption(_includeUsingsOption);
rootCommand.AddGlobalOption(_includeNamespaceOption);
rootCommand.AddGlobalOption(_includeCommentsOption);
rootCommand.AddGlobalOption(_useDebugAssertOption);
rootCommand.AddGlobalOption(_startInterfaceNamesWithIOption);
rootCommand.AddGlobalOption(_commentUnrecognizedCodeOption);
rootCommand.AddGlobalOption(_systemOutToConsoleOption);
rootCommand.AddGlobalOption(_clearDefaultUsingsOption);
rootCommand.AddGlobalOption(_addUsingsOption);
await rootCommand.InvokeAsync(args);
// flush logs
_loggerFactory.Dispose();
}
private static Command CreateFileCommand()
{
var inputArgument = new Argument<FileInfo>(
name: "input",
description: "A Java source code file to convert");
var outputArgument = new Argument<FileInfo?>(
name: "output",
description: "Path to place the C# output file, or stdout if omitted",
getDefaultValue: () => null);
var fileCommand = new Command("file", "Convert a Java file to C#");
fileCommand.AddArgument(inputArgument);
fileCommand.AddArgument(outputArgument);
fileCommand.SetHandler(context =>
{
var input = context.ParseResult.GetValueForArgument(inputArgument);
var output = context.ParseResult.GetValueForArgument(outputArgument);
var options = GetJavaConversionOptions(context);
ConvertToCSharpFile(input, output, options);
});
return fileCommand;
}
private static JavaConversionOptions GetJavaConversionOptions(InvocationContext context)
{
var options = new JavaConversionOptions
{
IncludeUsings = context.ParseResult.GetValueForOption(_includeUsingsOption),
IncludeComments = context.ParseResult.GetValueForOption(_includeCommentsOption),
IncludeNamespace = context.ParseResult.GetValueForOption(_includeNamespaceOption),
ConvertSystemOutToConsole = context.ParseResult.GetValueForOption(_systemOutToConsoleOption),
StartInterfaceNamesWithI = context.ParseResult.GetValueForOption(_startInterfaceNamesWithIOption),
UseDebugAssertForAsserts = context.ParseResult.GetValueForOption(_useDebugAssertOption),
UseUnrecognizedCodeToComment = context.ParseResult.GetValueForOption(_commentUnrecognizedCodeOption)
};
if (context.ParseResult.GetValueForOption(_clearDefaultUsingsOption))
{
options.ClearUsings();
}
foreach (string ns in context.ParseResult.GetValueForOption(_addUsingsOption) ?? new List<string>())
{
options.AddUsing(ns);
}
return options;
}
private static Command CreateDirectoryCommand()
{
var inputArgument = new Argument<DirectoryInfo>(
name: "input",
description: "A directory containing Java source code files to convert");
var outputArgument = new Argument<DirectoryInfo>(
name: "output",
description: "Path to place the C# output files");
var dirCommand = new Command("dir", "Convert a directory containing Java files to C#");
dirCommand.AddArgument(inputArgument);
dirCommand.AddArgument(outputArgument);
dirCommand.SetHandler(context =>
{
var input = context.ParseResult.GetValueForArgument(inputArgument);
var output = context.ParseResult.GetValueForArgument(outputArgument);
var options = GetJavaConversionOptions(context);
ConvertToCSharpDir(input, output, options);
});
return dirCommand;
}
private static void ConvertToCSharpDir(DirectoryInfo inputDirectory, DirectoryInfo outputDirectory, JavaConversionOptions options)
{
if (inputDirectory.Exists)
{
foreach (var f in inputDirectory.GetFiles("*.java", SearchOption.AllDirectories))
{
string? directoryName = f.DirectoryName;
if (string.IsNullOrWhiteSpace(directoryName))
{
continue;
}
if (!outputDirectory.Exists)
{
outputDirectory.Create();
}
ConvertToCSharpFile(f,
new FileInfo(Path.Combine(outputDirectory.FullName, Path.ChangeExtension(f.Name, ".cs"))),
options,
false);
}
}
else
_logger.LogError("Java input folder {path} doesn't exist!", inputDirectory);
}
private static void ConvertToCSharpFile(FileSystemInfo inputFile, FileSystemInfo? outputFile, JavaConversionOptions options, bool overwrite = true)
{
if (!overwrite && outputFile is { Exists: true })
_logger.LogInformation("{outputFilePath} exists, skip to next.", outputFile);
else if (inputFile.Exists)
{
try
{
string javaText = File.ReadAllText(inputFile.FullName);
options.WarningEncountered += (_, eventArgs) =>
{
if (outputFile != null)
{
_logger.LogWarning("Line {JavaLineNumber}: {Message}", eventArgs.JavaLineNumber,
eventArgs.Message);
}
OutputFileOrPrint(outputFile != null ? Path.ChangeExtension(outputFile.FullName, ".warning") : null,
eventArgs.Message + Environment.NewLine);
};
string? parsed = JavaToCSharpConverter.ConvertText(javaText, options);
OutputFileOrPrint(outputFile?.FullName, parsed ?? string.Empty);
if (outputFile != null)
{
_logger.LogInformation("{filePath} converted!", inputFile.Name);
}
}
catch (Exception ex)
{
_logger.LogError("{filePath} failed! {type}: {message}", inputFile.Name, ex.GetType().Name, ex);
if (outputFile != null)
{
File.WriteAllText(Path.ChangeExtension(outputFile.FullName, ".error"), ex.ToString());
}
}
}
else
_logger.LogError("Java input file {filePath} doesn't exist!", inputFile.FullName);
}
private static void OutputFileOrPrint(string? fileName, string contents)
{
if (fileName == null)
{
Console.Out.WriteLine(contents);
}
else
{
File.WriteAllText(fileName, contents);
}
}
}