-
Notifications
You must be signed in to change notification settings - Fork 393
/
Copy pathStringExtensions.cs
529 lines (456 loc) · 19.6 KB
/
StringExtensions.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace System.CommandLine.Parsing
{
internal static class StringExtensions
{
internal static bool ContainsCaseInsensitive(
this string source,
string value) =>
source.IndexOfCaseInsensitive(value) >= 0;
internal static int IndexOfCaseInsensitive(
this string source,
string value) =>
CultureInfo.InvariantCulture
.CompareInfo
.IndexOf(source,
value,
CompareOptions.OrdinalIgnoreCase);
internal static (string? Prefix, string Alias) SplitPrefix(this string rawAlias)
{
if (rawAlias[0] == '/')
{
return ("/", rawAlias.Substring(1));
}
else if (rawAlias[0] == '-')
{
if (rawAlias.Length > 1 && rawAlias[1] == '-')
{
return ("--", rawAlias.Substring(2));
}
return ("-", rawAlias.Substring(1));
}
return (null, rawAlias);
}
// this method is not returning a Value Tuple or a dedicated type to avoid JITting
internal static void Tokenize(
this IReadOnlyList<string> args,
CliConfiguration configuration,
bool inferRootCommand,
out List<CliToken> tokens,
out List<string>? errors)
{
const int FirstArgIsNotRootCommand = -1;
List<string>? errorList = null;
var currentCommand = configuration.RootCommand;
var foundDoubleDash = false;
var foundEndOfDirectives = false;
var tokenList = new List<CliToken>(args.Count);
var knownTokens = configuration.RootCommand.ValidTokens();
int i = FirstArgumentIsRootCommand(args, configuration.RootCommand, inferRootCommand)
? 0
: FirstArgIsNotRootCommand;
for (; i < args.Count; i++)
{
var arg = i == FirstArgIsNotRootCommand
? configuration.RootCommand.Name
: args[i];
if (foundDoubleDash)
{
tokenList.Add(CommandArgument(arg, currentCommand!));
continue;
}
if (!foundDoubleDash &&
arg == "--")
{
tokenList.Add(DoubleDash());
foundDoubleDash = true;
continue;
}
if (!foundEndOfDirectives)
{
if (arg.Length > 2 &&
arg[0] == '[' &&
arg[1] != ']' &&
arg[1] != ':' &&
arg[arg.Length - 1] == ']')
{
int colonIndex = arg.AsSpan().IndexOf(':');
string directiveName = colonIndex > 0
? arg.Substring(1, colonIndex - 1) // [name:value]
: arg.Substring(1, arg.Length - 2); // [name] is a legal directive
CliDirective? directive;
if (knownTokens.TryGetValue($"[{directiveName}]", out var directiveToken))
{
directive = (CliDirective)directiveToken.Symbol!;
}
else
{
directive = null;
}
tokenList.Add(Directive(arg, directive));
continue;
}
if (!configuration.RootCommand.EqualsNameOrAlias(arg))
{
foundEndOfDirectives = true;
}
}
if (configuration.ResponseFileTokenReplacer is { } replacer &&
arg.GetReplaceableTokenValue() is { } value)
{
if (replacer(
value,
out var newTokens,
out var error))
{
if (newTokens is not null && newTokens.Count > 0)
{
List<string> listWithReplacedTokens = args.ToList();
listWithReplacedTokens.InsertRange(i + 1, newTokens);
args = listWithReplacedTokens;
}
continue;
}
else if (!string.IsNullOrWhiteSpace(error))
{
(errorList ??= new()).Add(error!);
continue;
}
}
if (knownTokens.TryGetValue(arg, out var token))
{
if (PreviousTokenIsAnOptionExpectingAnArgument(out var option))
{
tokenList.Add(OptionArgument(arg, option!));
}
else
{
switch (token.Type)
{
case CliTokenType.Option:
if (token?.Symbol?.CaseSensitive ?? false)
{
// If the option is case sensitive, we need to make sure that the match was sensitive
if(!arg.Equals(token.Value, StringComparison.Ordinal))
{
// it doesn't match, so we need to keep going
break;
}
}
tokenList.Add(Option(arg, (CliOption)token.Symbol!));
break;
case CliTokenType.Command:
if (token?.Symbol?.CaseSensitive ?? false)
{
// If the option is case sensitive, we need to make sure that the match was sensitive
if (!arg.Equals(token.Value, StringComparison.Ordinal))
{
// it doesn't match, so we need to keep going
break;
}
}
CliCommand cmd = (CliCommand)token.Symbol!;
if (cmd != currentCommand)
{
if (cmd != configuration.RootCommand)
{
knownTokens = cmd.ValidTokens(); // config contains Directives, they are allowed only for RootCommand
}
currentCommand = cmd;
tokenList.Add(Command(arg, cmd));
}
else
{
tokenList.Add(Argument(arg));
}
break;
}
}
}
else if (arg.TrySplitIntoSubtokens(out var first, out var rest) &&
knownTokens.TryGetValue(first, out var subtoken) &&
subtoken.Type == CliTokenType.Option)
{
tokenList.Add(Option(first, (CliOption)subtoken.Symbol!));
if (rest is not null)
{
tokenList.Add(Argument(rest));
}
}
else if (!configuration.EnablePosixBundling ||
!CanBeUnbundled(arg) ||
!TryUnbundle(arg.AsSpan(1), i))
{
tokenList.Add(Argument(arg));
}
CliToken Argument(string value) => new(value, CliTokenType.Argument, default, i);
CliToken CommandArgument(string value, CliCommand command) => new(value, CliTokenType.Argument, command, i);
CliToken OptionArgument(string value, CliOption option) => new(value, CliTokenType.Argument, option, i);
CliToken Command(string value, CliCommand cmd) => new(value, CliTokenType.Command, cmd, i);
CliToken Option(string value, CliOption option) => new(value, CliTokenType.Option, option, i);
CliToken DoubleDash() => new("--", CliTokenType.DoubleDash, default, i);
CliToken Directive(string value, CliDirective? directive) => new(value, CliTokenType.Directive, directive, i);
}
tokens = tokenList;
errors = errorList;
bool CanBeUnbundled(string arg)
=> arg.Length > 2
&& arg[0] == '-'
&& arg[1] != '-'// don't check for "--" prefixed args
&& arg[2] != ':' && arg[2] != '=' // handled by TrySplitIntoSubtokens
&& !PreviousTokenIsAnOptionExpectingAnArgument(out _);
bool TryUnbundle(ReadOnlySpan<char> alias, int argumentIndex)
{
int tokensBefore = tokenList.Count;
string candidate = new('-', 2); // mutable string used to avoid allocations
unsafe
{
fixed (char* pCandidate = candidate)
{
for (int i = 0; i < alias.Length; i++)
{
if (alias[i] == ':' || alias[i] == '=')
{
tokenList.Add(new CliToken(alias.Slice(i + 1).ToString(), CliTokenType.Argument, default, argumentIndex));
return true;
}
pCandidate[1] = alias[i];
if (!knownTokens.TryGetValue(candidate, out CliToken? found))
{
if (tokensBefore != tokenList.Count && tokenList[tokenList.Count - 1].Type == CliTokenType.Option)
{
// Invalid_char_in_bundle_causes_rest_to_be_interpreted_as_value
tokenList.Add(new CliToken(alias.Slice(i).ToString(), CliTokenType.Argument, default, argumentIndex));
return true;
}
return false;
}
tokenList.Add(new CliToken(found.Value, found.Type, found.Symbol, argumentIndex));
if (i != alias.Length - 1 && ((CliOption)found.Symbol!).Greedy)
{
int index = i + 1;
if (alias[index] == ':' || alias[index] == '=')
{
index++; // Last_bundled_option_can_accept_argument_with_colon_separator
}
tokenList.Add(new CliToken(alias.Slice(index).ToString(), CliTokenType.Argument, default, argumentIndex));
return true;
}
}
}
}
return true;
}
bool PreviousTokenIsAnOptionExpectingAnArgument(out CliOption? option)
{
if (tokenList.Count > 1)
{
var token = tokenList[tokenList.Count - 1];
if (token.Type == CliTokenType.Option)
{
if (token.Symbol is CliOption { Greedy: true } opt)
{
option = opt;
return true;
}
}
}
option = null;
return false;
}
}
private static bool FirstArgumentIsRootCommand(IReadOnlyList<string> args, CliCommand rootCommand, bool inferRootCommand)
{
if (args.Count > 0)
{
if (inferRootCommand && args[0] == CliRootCommand.ExecutablePath)
{
return true;
}
try
{
var potentialRootCommand = Path.GetFileName(args[0]);
if (rootCommand.EqualsNameOrAlias(potentialRootCommand))
{
return true;
}
}
catch (ArgumentException)
{
// possible exception for illegal characters in path on .NET Framework
}
}
return false;
}
private static string? GetReplaceableTokenValue(this string arg) =>
arg.Length > 1 && arg[0] == '@'
? arg.Substring(1)
: null;
internal static bool TrySplitIntoSubtokens(
this string arg,
out string first,
out string? rest)
{
var i = arg.AsSpan().IndexOfAny(':', '=');
if (i >= 0)
{
first = arg.Substring(0, i);
rest = arg.Substring(i + 1);
if (rest.Length == 0)
{
rest = null;
}
return true;
}
first = arg;
rest = null;
return false;
}
internal static bool TryReadResponseFile(
string filePath,
out IReadOnlyList<string>? newTokens,
out string? error)
{
try
{
newTokens = ExpandResponseFile(filePath).ToArray();
error = null;
return true;
}
catch (FileNotFoundException)
{
error = LocalizationResources.ResponseFileNotFound(filePath);
}
catch (IOException e)
{
error = LocalizationResources.ErrorReadingResponseFile(filePath, e);
}
newTokens = null;
return false;
static IEnumerable<string> ExpandResponseFile(string filePath)
{
var lines = File.ReadAllLines(filePath);
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i];
foreach (var p in SplitLine(line))
{
if (p.GetReplaceableTokenValue() is { } path)
{
foreach (var q in ExpandResponseFile(path))
{
yield return q;
}
}
else
{
yield return p;
}
}
}
}
static IEnumerable<string> SplitLine(string line)
{
var arg = line.Trim();
if (arg.Length == 0 || arg[0] == '#')
{
yield break;
}
foreach (var word in CliParser.SplitCommandLine(arg))
{
yield return word;
}
}
}
private static Dictionary<string, CliToken> ValidTokens(this CliCommand command)
{
Dictionary<string, CliToken> tokens = new(command.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);
if (command is CliRootCommand { Directives: IList<CliDirective> directives })
{
for (int i = 0; i < directives.Count; i++)
{
var directive = directives[i];
var tokenString = $"[{directive.Name}]";
tokens[tokenString] = new CliToken(tokenString, CliTokenType.Directive, directive, CliToken.ImplicitPosition);
}
}
AddCommandTokens(tokens, command);
if (command.HasSubcommands)
{
var subCommands = command.Subcommands;
for (int i = 0; i < subCommands.Count; i++)
{
AddCommandTokens(tokens, subCommands[i]);
}
}
if (command.HasOptions)
{
var options = command.Options;
for (int i = 0; i < options.Count; i++)
{
AddOptionTokens(tokens, options[i]);
}
}
CliCommand? current = command;
while (current is not null)
{
CliCommand? parentCommand = null;
SymbolNode? parent = current.FirstParent;
while (parent is not null)
{
if ((parentCommand = parent.Symbol as CliCommand) is not null)
{
if (parentCommand.HasOptions)
{
for (var i = 0; i < parentCommand.Options.Count; i++)
{
CliOption option = parentCommand.Options[i];
if (option.Recursive)
{
AddOptionTokens(tokens, option);
}
}
}
break;
}
parent = parent.Next;
}
current = parentCommand;
}
return tokens;
static void AddCommandTokens(Dictionary<string, CliToken> tokens, CliCommand cmd)
{
tokens.Add(cmd.Name, new CliToken(cmd.Name, CliTokenType.Command, cmd, CliToken.ImplicitPosition));
if (cmd._aliases is not null)
{
foreach (string childAlias in cmd._aliases)
{
tokens.Add(childAlias, new CliToken(childAlias, CliTokenType.Command, cmd, CliToken.ImplicitPosition));
}
}
}
static void AddOptionTokens(Dictionary<string, CliToken> tokens, CliOption option)
{
if (!tokens.ContainsKey(option.Name))
{
tokens.Add(option.Name, new CliToken(option.Name, CliTokenType.Option, option, CliToken.ImplicitPosition));
}
if (option._aliases is not null)
{
foreach (string childAlias in option._aliases)
{
if (!tokens.ContainsKey(childAlias))
{
tokens.Add(childAlias, new CliToken(childAlias, CliTokenType.Option, option, CliToken.ImplicitPosition));
}
}
}
}
}
}
}