-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathProgram.cs
More file actions
294 lines (258 loc) · 10 KB
/
Copy pathProgram.cs
File metadata and controls
294 lines (258 loc) · 10 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
using System.CommandLine;
using Melanchall.DryWetMidi.Core;
using MoonscraperChartEditor.Song.IO;
using YARG.Core;
using YARG.Core.Chart.AutoGeneration;
namespace AutoDownchartCli;
internal static class Program
{
private static readonly Dictionary<string, Instrument> Instruments = new(StringComparer.OrdinalIgnoreCase)
{
{ "guitar", Instrument.FiveFretGuitar },
{ "coop", Instrument.FiveFretCoopGuitar },
{ "bass", Instrument.FiveFretBass },
{ "rhythm", Instrument.FiveFretRhythm },
{ "keys", Instrument.Keys },
};
public static int Main(string[] args)
{
var inputArgument = new Argument<string>("input")
{
Description = "Path to a .mid file or a directory containing notes.mid files",
};
var outputOption = new Option<string?>("--output", "-o")
{
Description = "Output file, or output root for directory mode",
};
var intensityOption = new Option<double>("--intensity")
{
Description = "Reduction intensity (0.0-1.0, default: 1.0)",
DefaultValueFactory = _ => 1.0,
};
var instrumentOption = new Option<string?>("--instrument", "-i")
{
Description = "Comma-separated: guitar,coop,bass,rhythm,keys",
};
var replaceOption = new Option<bool>("--replace-existing")
{
Description = "Replace authored Hard, Medium, and Easy charts",
};
var inPlaceOption = new Option<bool>("--in-place")
{
Description = "Atomically replace each source MIDI",
};
var overwriteOption = new Option<bool>("--overwrite")
{
Description = "Replace existing output files",
};
var root = new RootCommand("Generate reduced MIDI difficulties from Expert five-fret charts")
{
inputArgument,
outputOption,
intensityOption,
instrumentOption,
replaceOption,
inPlaceOption,
overwriteOption,
};
root.Validators.Add(result =>
{
double intensity = result.GetValue(intensityOption);
if (double.IsNaN(intensity) || double.IsInfinity(intensity) ||
intensity < 0 || intensity > 1)
{
result.AddError("Intensity must be a number between 0 and 1.");
}
if (result.GetValue(inPlaceOption) && result.GetValue(outputOption) is not null)
{
result.AddError("--in-place cannot be combined with --output.");
}
string inputPath = result.GetValue(inputArgument)!;
string? outputPath = result.GetValue(outputOption);
if (outputPath is not null && File.Exists(inputPath))
{
var pathComparison = OperatingSystem.IsWindows()
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
if (string.Equals(Path.GetFullPath(inputPath), Path.GetFullPath(outputPath), pathComparison))
{
result.AddError("--output cannot be the input file. Use --in-place instead.");
}
}
string? instrumentValue = result.GetValue(instrumentOption);
if (instrumentValue is not null)
{
string[] instrumentNames = instrumentValue.Split(',',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (instrumentNames.Length == 0)
{
result.AddError("--instrument must contain at least one instrument name.");
}
foreach (string name in instrumentNames)
{
if (!Instruments.TryGetValue(name, out _))
{
result.AddError(
$"Unknown instrument '{name}'. Must be guitar, coop, bass, rhythm, or keys.");
}
}
}
});
root.SetAction(parseResult =>
{
var options = new CliOptions
{
InputPath = parseResult.GetValue(inputArgument)!,
OutputPath = parseResult.GetValue(outputOption),
Intensity = parseResult.GetValue(intensityOption),
ReplaceExisting = parseResult.GetValue(replaceOption),
InPlace = parseResult.GetValue(inPlaceOption),
Overwrite = parseResult.GetValue(overwriteOption),
};
string? instrumentValue = parseResult.GetValue(instrumentOption);
if (instrumentValue is not null)
{
foreach (string name in instrumentValue.Split(',',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
options.Instruments.Add(Instruments[name]);
}
}
return Run(options);
});
var parseResult = root.Parse(args);
return parseResult.Invoke();
}
private static int Run(CliOptions options)
{
try
{
var inputs = GetInputs(options.InputPath);
if (inputs.Count == 0)
{
Console.Error.WriteLine("No MIDI files were found.");
return 1;
}
int failures = 0;
int generated = 0;
int skipped = 0;
foreach (string input in inputs)
{
try
{
var result = ProcessFile(input, options);
generated += result.GeneratedDifficultyCount;
skipped += result.SkippedDifficultyCount;
}
catch (Exception exception)
{
failures++;
Console.Error.WriteLine($"ERROR: {input}: {exception.Message}");
}
}
Console.WriteLine($"Completed {inputs.Count - failures}/{inputs.Count} file(s): " +
$"{generated} generated, {skipped} skipped, {failures} failed.");
return failures == 0 ? 0 : 1;
}
catch (Exception exception)
{
Console.Error.WriteLine($"ERROR: {exception.Message}");
return 1;
}
}
private static MidiDownchartExportResult ProcessFile(string inputPath, CliOptions options)
{
var source = MidFileLoader.LoadMidiFile(inputPath);
var result = MidiDownchartExporter.Generate(source, new MidiDownchartExportOptions
{
Intensity = options.Intensity,
ReplaceExisting = options.ReplaceExisting,
Instruments = options.Instruments.Count == 0 ? null : options.Instruments,
});
if (result.GeneratedDifficultyCount == 0)
{
Console.WriteLine($"Skipped {inputPath}: no difficulties needed generation.");
return result;
}
string outputPath = GetOutputPath(inputPath, options);
if (!options.InPlace && File.Exists(outputPath) && !options.Overwrite)
{
throw new IOException($"Output already exists: {outputPath}. Use --overwrite to replace it.");
}
string? directory = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
}
if (options.InPlace)
{
string temporaryPath = Path.Combine(
directory ?? ".",
$".{Path.GetFileName(inputPath)}.{Guid.NewGuid():N}.tmp");
try
{
result.Midi.Write(temporaryPath, true);
File.Move(temporaryPath, inputPath, true);
}
finally
{
if (File.Exists(temporaryPath))
{
File.Delete(temporaryPath);
}
}
}
else
{
result.Midi.Write(outputPath, options.Overwrite);
}
Console.WriteLine($"{inputPath} -> {outputPath}: " +
$"{result.GeneratedDifficultyCount} generated, {result.SkippedDifficultyCount} skipped.");
return result;
}
private static List<string> GetInputs(string inputPath)
{
if (File.Exists(inputPath))
{
return [Path.GetFullPath(inputPath)];
}
if (Directory.Exists(inputPath))
{
return Directory.EnumerateFiles(inputPath, "notes.mid", SearchOption.AllDirectories)
.Select(Path.GetFullPath)
.OrderBy(path => path, StringComparer.Ordinal)
.ToList();
}
throw new FileNotFoundException($"Input path does not exist: {inputPath}");
}
private static string GetOutputPath(string inputPath, CliOptions options)
{
if (options.InPlace)
{
return inputPath;
}
if (!string.IsNullOrEmpty(options.OutputPath))
{
if (File.Exists(options.InputPath))
{
return Path.GetFullPath(options.OutputPath);
}
string relative = Path.GetRelativePath(Path.GetFullPath(options.InputPath), inputPath);
string relativeDirectory = Path.GetDirectoryName(relative) ?? "";
return Path.Combine(Path.GetFullPath(options.OutputPath), relativeDirectory, "notes.generated.mid");
}
string directory = Path.GetDirectoryName(inputPath) ?? ".";
string fileName = Path.GetFileNameWithoutExtension(inputPath);
return Path.Combine(directory, $"{fileName}.generated.mid");
}
private sealed class CliOptions
{
public string InputPath { get; init; } = "";
public string? OutputPath { get; init; }
public double Intensity { get; init; } = 1.0;
public bool ReplaceExisting { get; init; }
public bool InPlace { get; init; }
public bool Overwrite { get; init; }
public HashSet<Instrument> Instruments { get; } = [];
}
}