Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,36 @@ Array parsing has three special patterns.

For a regular `T[]`, if the value starts with `[`, it is parsed using `JsonSerializer.Deserialize`. Otherwise, it is parsed as comma-separated values. For example, `[1,2,3]` or `1,2,3` are allowed as values. To set an empty array, pass `[]`.

A `T[]` option can also be specified more than once. Each occurrence is parsed in the same way as above and the values are appended in order. For example, `--array 1 --array 2,3 --array [4,5]` will be bound to `[1, 2, 3, 4, 5]`. This does not apply to `[Argument]` parameters and `params T[]`.

```csharp
// cmd.exe -e FOO=1 -e BAR=2
ConsoleApp.Run(args, Commands.Run);

static class Commands
{
/// <param name="env">-e, Set environment variables.</param>
public static void Run(string[] env) => Console.WriteLine(string.Join(", ", env));
}
```

If the values themselves contain commas (for example `-p List=a,b`), comma-separated parsing gets in the way. In that case, you can create a [custom parser](#custom-value-converter) for `T[]` that does not split the value. Since each occurrence is appended, repeating the option still works.

```csharp
[AttributeUsage(AttributeTargets.Parameter)]
public class NoSplitAttribute : Attribute, IArgumentParser<string[]>
{
public static bool TryParse(ReadOnlySpan<char> s, out string[] result)
{
result = [s.ToString()];
return true;
}
}

// cmd.exe --p List=a,b --p X=1 -> ["List=a,b", "X=1"]
ConsoleApp.Run(args, ([NoSplit] string[] p) => { });
```

For `params T[]`, all subsequent arguments become the values of the array. For example, if there is an input like `--paramsArray foo bar baz`, it will be bound to a value like `["foo", "bar", "baz"]`.

### Object
Expand Down
4 changes: 4 additions & 0 deletions src/ConsoleAppFramework/Command.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,10 @@ public record class CommandParameter
public required string Description { get; init; }
public bool RequireCheckArgumentParsed => !(HasDefaultValue || IsParams || IsFlag);

// named option of T[] can be specified more than once(`-p a -p b`), each occurrence is appended.
// params T[] consumes all remaining arguments and [Argument] is positional so they are out of target.
public bool IsRepeatableArray => IsParsable && !IsParams && !IsArgument && Type.TypeSymbol is IArrayTypeSymbol { IsSZArray: true };

// increment = false when passed from [Argument]
public string BuildParseMethod(int argCount, string argumentName, bool increment)
{
Expand Down
12 changes: 12 additions & 0 deletions src/ConsoleAppFramework/ConsoleAppBaseCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,18 @@ static bool TrySplitParse<T>(ReadOnlySpan<char> s, out T[] result)
return true;
}

// array option specified more than once(`-p a -p b`), append to the previous values
static T[] ConcatArray<T>(T[] first, T[]? second)
{
if (second == null || second.Length == 0) return first;
if (first.Length == 0) return second;

var result = new T[first.Length + second.Length];
first.CopyTo(result, 0);
second.CopyTo(result, first.Length);
return result;
}

static void ValidateParameter(object? value, ParameterInfo parameter, ValidationContext validationContext, ref StringBuilder? errorMessages)
{
validationContext.DisplayName = parameter.Name ?? "";
Expand Down
20 changes: 18 additions & 2 deletions src/ConsoleAppFramework/Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ public void EmitRun(SourceBuilder sb, CommandWithId commandWithId, bool isRunAsy
}
using (sb.BeginBlock())
{
sb.AppendLine($"{parameter.BuildParseMethod(i, parameter.Name, increment: true)}");
EmitParseOption(sb, parameter, i);
if (parameter.RequireCheckArgumentParsed)
{
sb.AppendLine($"arg{i}Parsed = true;");
Expand All @@ -261,7 +261,7 @@ public void EmitRun(SourceBuilder sb, CommandWithId commandWithId, bool isRunAsy
}
using (sb.BeginBlock())
{
sb.AppendLine($"{parameter.BuildParseMethod(i, parameter.Name, increment: true)}");
EmitParseOption(sb, parameter, i);
if (parameter.RequireCheckArgumentParsed)
{
sb.AppendLine($"arg{i}Parsed = true;");
Expand Down Expand Up @@ -1136,6 +1136,22 @@ internal static ConsoleApp.ConsoleAppBuilder ToConsoleAppBuilder(this HostApplic
""");
}

// parse named option(--name or alias) to arg{i}
static void EmitParseOption(SourceBuilder sb, CommandParameter parameter, int i)
{
if (!parameter.IsRepeatableArray)
{
sb.AppendLine($"{parameter.BuildParseMethod(i, parameter.Name, increment: true)}");
return;
}

// array option can be specified more than once, keep the previous values and append to it.
// arg{i} is always null until parsed first(default value of the array parameter is only allowed null).
sb.AppendLine($"var prev{i} = arg{i};");
sb.AppendLine($"{parameter.BuildParseMethod(i, parameter.Name, increment: true)}");
sb.AppendLine($"if (prev{i} != null) arg{i} = ConcatArray(prev{i}, arg{i});");
}

string Join(string separator, params string?[] args)
{
var sb = new StringBuilder();
Expand Down
175 changes: 175 additions & 0 deletions tests/ConsoleAppFramework.GeneratorTests/ArrayParseTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,179 @@ public async Task JsonArray()
await verifier.Execute(code, args: "--ix [] --sx []", expected: "[][]");
await verifier.Execute(code, args: "--ix [1,2,3,4,5] --sx [\"a\",\"b\",\"c\",\"d\",\"e\"]", expected: "[1, 2, 3, 4, 5][a, b, c, d, e]");
}

[Test]
public async Task RepeatedOption()
{
var code = """
ConsoleApp.Run(args, (int[] ix, string[] sx) =>
{
Console.Write("[" + string.Join(", ", ix) + "]");
Console.Write("[" + string.Join(", ", sx) + "]");
});
""";
// single(unchanged)
await verifier.Execute(code, args: "--ix 1 --sx a", expected: "[1][a]");
// repeated
await verifier.Execute(code, args: "--ix 1 --ix 2 --ix 3 --sx a --sx b", expected: "[1, 2, 3][a, b]");
// interleaved
await verifier.Execute(code, args: "--ix 1 --sx a --ix 2 --sx b --ix 3", expected: "[1, 2, 3][a, b]");
// each occurrence is parsed as before(comma separated)
await verifier.Execute(code, args: "--ix 1,2 --ix 3 --sx a --sx b,c", expected: "[1, 2, 3][a, b, c]");
// each occurrence is parsed as before(json)
await verifier.Execute(code, args: "--ix [1,2] --ix 3 --ix [4,5] --sx [\"a\"] --sx b", expected: "[1, 2, 3, 4, 5][a, b]");
// empty array
await verifier.Execute(code, args: "--ix [] --ix 1 --sx a --sx []", expected: "[1][a]");
await verifier.Execute(code, args: "--ix [] --ix [] --sx [] --sx []", expected: "[][]");
// ignore-case(slow path) is mixed
await verifier.Execute(code, args: "--ix 1 --IX 2 --Ix 3 --SX a --sx b", expected: "[1, 2, 3][a, b]");
}

[Test]
public async Task RepeatedOptionAlias()
{
var code = """
ConsoleApp.Run(args, Commands.Run);

static class Commands
{
/// <param name="prop">-p, properties.</param>
public static void Run(string[] prop)
{
Console.Write("[" + string.Join(", ", prop) + "]");
}
}
""";
await verifier.Execute(code, args: "-p a --prop b -p c", expected: "[a, b, c]");
await verifier.Execute(code, args: "-P a --PROP b -p c,d", expected: "[a, b, c, d]");
}

[Test]
public async Task RepeatedOptionDefaultValue()
{
var code = """
ConsoleApp.Run(args, (string[]? sx = null, int x = 0) =>
{
Console.Write(sx == null ? "null" : "[" + string.Join(", ", sx) + "]");
});
""";
// keep default value when not specified
await verifier.Execute(code, args: "", expected: "null");
await verifier.Execute(code, args: "--x 10", expected: "null");
await verifier.Execute(code, args: "--sx a", expected: "[a]");
await verifier.Execute(code, args: "--sx a --x 10 --sx b", expected: "[a, b]");
}

[Test]
public async Task RepeatedOptionRequired()
{
var code = """
ConsoleApp.LogError = x => Console.Write(x);

ConsoleApp.Run(args, (int[] ix, int x = 0) =>
{
Console.Write("[" + string.Join(", ", ix) + "]");
});
""";
await verifier.Execute(code, args: "--ix 1 --x 10 --ix 2", expected: "[1, 2]");

var (stdout, exitCode) = verifier.Error(code, "--x 10");
await Assert.That(exitCode).IsEqualTo(1);
await Assert.That(stdout).Contains("Required argument 'ix' was not specified.");

// parse failed in second occurrence
(stdout, exitCode) = verifier.Error(code, "--ix 1 --ix foo");
await Assert.That(exitCode).IsEqualTo(1);
await Assert.That(stdout).Contains("Argument 'ix' failed to parse, provided value: foo");
}

[Test]
public async Task RepeatedOptionJsonElement()
{
// element type is not ISpanParsable, each occurrence is parsed as JSON
var code = """
ConsoleApp.Run(args, (MyItem[] items, MyEnum[] enums) =>
{
Console.Write("[" + string.Join<MyItem>(", ", items) + "]");
Console.Write("[" + string.Join(", ", enums) + "]");
});

public class MyItem
{
public int X { get; set; }

public override string ToString() => X.ToString();
}

public enum MyEnum
{
A, B, C
}
""";
await verifier.Execute(code, args: "--items [{\"X\":1}] --enums [0]", expected: "[1][A]");
await verifier.Execute(code, args: "--items [{\"X\":1}] --enums [0,1] --items [{\"X\":2},{\"X\":3}] --enums [2]", expected: "[1, 2, 3][A, B, C]");
}

[Test]
public async Task RepeatedOptionCustomParser()
{
// custom parser can disable comma separated parsing, each occurrence is appended as well
var code = """
ConsoleApp.Run(args, ([NoSplit] string[] p) =>
{
Console.Write(string.Join("|", p));
});

[AttributeUsage(AttributeTargets.Parameter)]
public class NoSplitAttribute : Attribute, IArgumentParser<string[]>
{
public static bool TryParse(ReadOnlySpan<char> s, out string[] result)
{
result = [s.ToString()];
return true;
}
}
""";
await verifier.Execute(code, args: "--p List=a,b", expected: "List=a,b");
await verifier.Execute(code, args: "--p List=a,b --p X=1 --p [1,2]", expected: "List=a,b|X=1|[1,2]");
}

[Test]
public async Task RepeatedOptionBuilder()
{
var code = """
var app = ConsoleApp.Create();
app.Add("", (int[] ix) => Console.Write("[" + string.Join(", ", ix) + "]"));
app.Add<MyCommands>();
app.Run(args);

public class MyCommands
{
public void Foo(string[] sx, int[]? ix = null)
{
Console.Write("[" + string.Join(", ", sx) + "]");
Console.Write(ix == null ? "null" : "[" + string.Join(", ", ix) + "]");
}
}
""";
await verifier.Execute(code, args: "--ix 1 --ix 2,3", expected: "[1, 2, 3]");
await verifier.Execute(code, args: "foo --sx a --sx b", expected: "[a, b]null");
await verifier.Execute(code, args: "foo --ix 1 --sx a --ix 2 --sx b", expected: "[a, b][1, 2]");
}

[Test]
public async Task ArgumentArrayIsNotRepeated()
{
// [Argument] is positional so each argument is bound to each parameter
var code = """
ConsoleApp.Run(args, ([Argument] int[] ix, [Argument] int[] iy, int[] iz) =>
{
Console.Write("[" + string.Join(", ", ix) + "]");
Console.Write("[" + string.Join(", ", iy) + "]");
Console.Write("[" + string.Join(", ", iz) + "]");
});
""";
await verifier.Execute(code, args: "1,2 3,4 --iz 5 --iz 6", expected: "[1, 2][3, 4][5, 6]");
await verifier.Execute(code, args: "--iz 5 1,2 --iz 6 3,4", expected: "[1, 2][3, 4][5, 6]");
}
}