-
-
Notifications
You must be signed in to change notification settings - Fork 254
/
CommandLineProcessor.cs
414 lines (364 loc) · 13.4 KB
/
CommandLineProcessor.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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace McMaster.Extensions.CommandLineUtils
{
internal sealed class CommandLineProcessor
{
private readonly CommandLineApplication _app;
private readonly IReadOnlyList<string> _parameters;
private readonly CommandLineApplication _initialCommand;
private readonly ParameterEnumerator _enumerator;
private CommandLineApplication _currentCommand;
private CommandArgumentEnumerator _currentCommandArguments;
public CommandLineProcessor(CommandLineApplication command, IReadOnlyList<string> parameters)
{
_app = command;
_parameters = parameters ?? new string[0];
_initialCommand = command;
_enumerator = new ParameterEnumerator(_parameters);
}
public CommandLineApplication Process()
{
_currentCommand = _initialCommand;
_currentCommandArguments = null;
while (_enumerator.MoveNext())
{
if (!ProcessNext())
{
return _currentCommand;
}
}
_enumerator.Reset();
return _currentCommand;
}
private bool ProcessNext()
{
switch (_enumerator.Current.Type)
{
case ParameterType.ArgumentSeparator:
if (!ProcessArgumentSeparator())
{
return false;
}
break;
case ParameterType.ShortOption:
case ParameterType.LongOption:
if (!ProcessOption())
{
return false;
}
break;
case ParameterType.ResponseFile:
if (!ProcessResponseFile())
{
return false;
}
break;
case ParameterType.CommandOrArgument:
if (!ProcessCommandOrArgument())
{
return false;
}
break;
default:
HandleUnexpectedArg("command or argument");
return false;
}
return true;
}
private bool ProcessResponseFile()
{
if (_currentCommand.ResponseFileHandling == ResponseFileHandling.Disabled)
{
return ProcessCommandOrArgument();
}
var arg = _enumerator.Current.Raw;
var path = arg.Substring(1);
var fullPath = Path.IsPathRooted(path)
? path
: Path.Combine(_currentCommand.WorkingDirectory, path);
try
{
var rspParams = ResponseFileParser.Parse(fullPath, _currentCommand.ResponseFileHandling);
_enumerator.InsertFromResponseFile(rspParams);
return true;
}
catch (Exception ex)
{
throw new CommandParsingException(_currentCommand, $"Could not parse the response file '{arg}'", ex);
}
}
private bool ProcessCommandOrArgument()
{
var arg = _enumerator.Current;
foreach (var subcommand in _currentCommand.Commands)
{
if (string.Equals(subcommand.Name, arg.Raw, StringComparison.OrdinalIgnoreCase))
{
_currentCommand = subcommand;
return true;
}
}
if (_currentCommandArguments == null)
{
_currentCommandArguments = new CommandArgumentEnumerator(_currentCommand.Arguments.GetEnumerator());
}
if (_currentCommandArguments.MoveNext())
{
_currentCommandArguments.Current.Values.Add(arg.Raw);
}
else
{
HandleUnexpectedArg("command or argument");
return false;
}
return true;
}
private bool ProcessOption()
{
CommandOption option;
var arg = _enumerator.Current;
if (arg.Type == ParameterType.ShortOption)
{
option = _currentCommand.GetOptions().SingleOrDefault(o => string.Equals(arg.Name, o.ShortName, StringComparison.Ordinal));
if (option == null)
{
option = _currentCommand.GetOptions().SingleOrDefault(o => string.Equals(arg.Name, o.SymbolName, StringComparison.Ordinal));
}
}
else
{
option = _currentCommand.GetOptions().SingleOrDefault(o => string.Equals(arg.Name, o.LongName, StringComparison.Ordinal));
}
if (option == null)
{
HandleUnexpectedArg("option");
return false;
}
// If we find a help/version option, show information and stop parsing
if (_currentCommand.OptionHelp == option)
{
_currentCommand.ShowHelp();
option.TryParse(null);
return false;
}
else if (_currentCommand.OptionVersion == option)
{
_currentCommand.ShowVersion();
option.TryParse(null);
return false;
}
if (arg.Value != null)
{
if (!option.TryParse(arg.Value))
{
_currentCommand.ShowHint();
throw new CommandParsingException(_currentCommand, $"Unexpected value '{arg.Value}' for option '{arg.Name}'");
}
}
else if (option.OptionType == CommandOptionType.NoValue
|| option.OptionType == CommandOptionType.SingleOrNoValue)
{
// No value is needed for this option
option.TryParse(null);
}
else
{
if (!_enumerator.MoveNext())
{
_currentCommand.ShowHint();
throw new CommandParsingException(_currentCommand, $"Missing value for option '{arg.Name}'");
}
if (_enumerator.Current.Type == ParameterType.ResponseFile
&& _currentCommand.ResponseFileHandling != ResponseFileHandling.Disabled)
{
if (!ProcessResponseFile())
{
return false;
}
if (!_enumerator.MoveNext())
{
_currentCommand.ShowHint();
throw new CommandParsingException(_currentCommand, $"Missing value for option '{arg.Name}'");
}
}
var nextArg = _enumerator.Current;
if (!option.TryParse(nextArg.Raw))
{
_currentCommand.ShowHint();
throw new CommandParsingException(_currentCommand, $"Unexpected value '{nextArg.Raw}' for option '{arg.Name}'");
}
}
return true;
}
private bool ProcessArgumentSeparator()
{
if (!_currentCommand.AllowArgumentSeparator)
{
HandleUnexpectedArg("option");
}
if (_enumerator.MoveNext())
{
AddRemainingArgumentValues();
}
return false;
}
private void HandleUnexpectedArg(string argTypeName)
{
if (_currentCommand.ThrowOnUnexpectedArgument)
{
_currentCommand.ShowHint();
throw new CommandParsingException(_currentCommand, $"Unrecognized {argTypeName} '{_enumerator.Current.Raw}'");
}
else
{
// All remaining arguments are stored for further use
AddRemainingArgumentValues();
}
}
private void AddRemainingArgumentValues()
{
do
{
_currentCommand.RemainingArguments.Add(_enumerator.Current.Raw);
} while (_enumerator.MoveNext());
}
private enum ParameterType
{
CommandOrArgument,
ShortOption,
LongOption,
ResponseFile,
ArgumentSeparator,
}
[DebuggerDisplay("{Raw} ({Type})")]
private sealed class Parameter
{
public Parameter(string raw, bool fromRspFile)
{
Raw = raw;
Type = GetType(raw, fromRspFile);
if (Type == ParameterType.LongOption || Type == ParameterType.ShortOption)
{
var parts = Raw.Split(new[] { ':', '=' }, 2);
if (parts.Length > 1)
{
Value = parts[1];
}
var sublen = Type == ParameterType.ShortOption
? 1
: 2;
Name = parts[0].Substring(sublen);
}
}
public string Raw { get; }
public string Name { get; }
public string Value { get; }
public ParameterType Type { get; }
private static ParameterType GetType(string raw, bool fromRspFile)
{
if (string.IsNullOrEmpty(raw) || raw == "-")
{
return ParameterType.CommandOrArgument;
}
else if (raw[0] == '@' && !fromRspFile)
{
// anything that starts with '@' might be a response file
// as long as we are not already parsing from a response file
return ParameterType.ResponseFile;
}
else if (raw[0] != '-')
{
// everything else that does not start with -
return ParameterType.CommandOrArgument;
}
else if (raw[1] != '-')
{
return ParameterType.ShortOption;
}
else if (raw.Length == 2)
{
return ParameterType.ArgumentSeparator;
}
return ParameterType.LongOption;
}
}
private sealed class ParameterEnumerator : IEnumerator<Parameter>
{
private readonly IEnumerator<string> _enumerator;
private Parameter _current;
private IEnumerator<string> _rspEnumerator;
public ParameterEnumerator(IReadOnlyList<string> parameters)
{
_enumerator = parameters.GetEnumerator();
}
public Parameter Current => _current;
object IEnumerator.Current => _current;
public void InsertFromResponseFile(IEnumerable<string> rspParams)
{
_rspEnumerator = rspParams.GetEnumerator();
}
public bool MoveNext()
{
if (_rspEnumerator != null)
{
if (_rspEnumerator.MoveNext())
{
_current = new Parameter(_rspEnumerator.Current, fromRspFile: true);
return true;
}
else
{
_rspEnumerator = null;
}
}
if (_enumerator.MoveNext())
{
_current = new Parameter(_enumerator.Current, fromRspFile: false);
return true;
}
return false;
}
public void Reset()
{
_current = null;
_rspEnumerator = null;
_enumerator.Reset();
}
public void Dispose()
{
_current = null;
_rspEnumerator = null;
_enumerator.Dispose();
}
}
private sealed class CommandArgumentEnumerator : IEnumerator<CommandArgument>
{
private readonly IEnumerator<CommandArgument> _enumerator;
public CommandArgumentEnumerator(IEnumerator<CommandArgument> enumerator)
{
_enumerator = enumerator;
}
public CommandArgument Current => _enumerator.Current;
object IEnumerator.Current => Current;
public void Dispose() => _enumerator.Dispose();
public bool MoveNext()
{
if (Current == null || !Current.MultipleValues)
{
return _enumerator.MoveNext();
}
// If current argument allows multiple values, we don't move forward and
// all later values will be added to current CommandArgument.Values
return true;
}
public void Reset() => _enumerator.Reset();
}
}
}