-
Notifications
You must be signed in to change notification settings - Fork 385
/
StringExtensions.cs
502 lines (433 loc) · 17.7 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
// 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 RemovePrefix(this string alias)
{
int prefixLength = GetPrefixLength(alias);
return prefixLength > 0
? alias.Substring(prefixLength)
: alias;
}
private static int GetPrefixLength(this string alias)
{
if (alias[0] == '-')
{
return alias.Length > 1 && alias[1] == '-'
? 2
: 1;
}
if (alias[0] == '/')
{
return 1;
}
return 0;
}
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,
CommandLineConfiguration configuration,
bool inferRootCommand,
out List<Token> tokens,
out List<string>? errors)
{
const int FirstArgIsNotRootCommand = -1;
List<string>? errorList = null;
var currentCommand = configuration.RootCommand;
var foundDoubleDash = false;
var foundEndOfDirectives = !configuration.EnableDirectives;
var tokenList = new List<Token>(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] == ']')
{
tokenList.Add(Directive(arg));
continue;
}
if (!configuration.RootCommand.HasAlias(arg))
{
foundEndOfDirectives = true;
}
}
if (configuration.EnableTokenReplacement &&
configuration.TokenReplacer 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 TokenType.Option:
tokenList.Add(Option(arg, (Option)token.Symbol!));
break;
case TokenType.Command:
Command cmd = (Command)token.Symbol!;
if (cmd != currentCommand)
{
if (cmd != configuration.RootCommand)
{
knownTokens = cmd.ValidTokens();
}
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 == TokenType.Option)
{
tokenList.Add(Option(first, (Option)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));
}
Token Argument(string value) => new(value, TokenType.Argument, default, i);
Token CommandArgument(string value, Command command) => new(value, TokenType.Argument, command, i);
Token OptionArgument(string value, Option option) => new(value, TokenType.Argument, option, i);
Token Command(string value, Command cmd) => new(value, TokenType.Command, cmd, i);
Token Option(string value, Option option) => new(value, TokenType.Option, option, i);
Token DoubleDash() => new("--", TokenType.DoubleDash, default, i);
Token Directive(string value) => new(value, TokenType.Directive, default, 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 Token(alias.Slice(i + 1).ToString(), TokenType.Argument, default, argumentIndex));
return true;
}
pCandidate[1] = alias[i];
if (!knownTokens.TryGetValue(candidate, out Token? found))
{
if (tokensBefore != tokenList.Count && tokenList[tokenList.Count - 1].Type == TokenType.Option)
{
// Invalid_char_in_bundle_causes_rest_to_be_interpreted_as_value
tokenList.Add(new Token(alias.Slice(i).ToString(), TokenType.Argument, default, argumentIndex));
return true;
}
return false;
}
tokenList.Add(new Token(found.Value, found.Type, found.Symbol, argumentIndex));
if (i != alias.Length - 1 && ((Option)found.Symbol!).IsGreedy)
{
int index = i + 1;
if (alias[index] == ':' || alias[index] == '=')
{
index++; // Last_bundled_option_can_accept_argument_with_colon_separator
}
tokenList.Add(new Token(alias.Slice(index).ToString(), TokenType.Argument, default, argumentIndex));
return true;
}
}
}
}
return true;
}
bool PreviousTokenIsAnOptionExpectingAnArgument(out Option? option)
{
if (tokenList.Count > 1)
{
var token = tokenList[tokenList.Count - 1];
if (token.Type == TokenType.Option)
{
if (token.Symbol is Option { IsGreedy: true } opt)
{
option = opt;
return true;
}
}
}
option = null;
return false;
}
}
private static bool FirstArgumentIsRootCommand(IReadOnlyList<string> args, Command rootCommand, bool inferRootCommand)
{
if (args.Count > 0)
{
if (inferRootCommand && args[0] == RootCommand.ExecutablePath)
{
return true;
}
try
{
var potentialRootCommand = Path.GetFileName(args[0]);
if (rootCommand.HasAlias(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,
LocalizationResources localizationResources,
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 CommandLineStringSplitter.Instance.Split(arg))
{
yield return word;
}
}
}
private static Dictionary<string, Token> ValidTokens(this Command command)
{
Dictionary<string, Token> tokens = new(StringComparer.Ordinal);
foreach (string commandAlias in command.Aliases)
{
tokens.Add(
commandAlias,
new Token(commandAlias, TokenType.Command, command, Token.ImplicitPosition));
}
if (command.HasSubcommands)
{
var subCommands = command.Subcommands;
for (int childIndex = 0; childIndex < subCommands.Count; childIndex++)
{
Command cmd = subCommands[childIndex];
foreach (string childAlias in cmd.Aliases)
{
tokens.Add(childAlias, new Token(childAlias, TokenType.Command, cmd, Token.ImplicitPosition));
}
}
}
if (command.HasOptions)
{
var options = command.Options;
for (int childIndex = 0; childIndex < options.Count; childIndex++)
{
Option option = options[childIndex];
foreach (string childAlias in option.Aliases)
{
if (!option.IsGlobal || !tokens.ContainsKey(childAlias))
{
tokens.Add(childAlias, new Token(childAlias, TokenType.Option, option, Token.ImplicitPosition));
}
}
}
}
Command? current = command;
while (current is not null)
{
Command? parentCommand = null;
ParentNode? parent = current.FirstParent;
while (parent is not null)
{
if ((parentCommand = parent.Symbol as Command) is not null)
{
if (parentCommand.HasOptions)
{
for (var i = 0; i < parentCommand.Options.Count; i++)
{
Option option = parentCommand.Options[i];
if (option.IsGlobal)
{
foreach (var childAlias in option.Aliases)
{
if (!tokens.ContainsKey(childAlias))
{
tokens.Add(childAlias, new Token(childAlias, TokenType.Option, option, Token.ImplicitPosition));
}
}
}
}
}
break;
}
parent = parent.Next;
}
current = parentCommand;
}
return tokens;
}
}
}