Is there an example on how to use the InvocationContext to return the exit code?
Does the invocation context param need to follow the handler's params? In my example, I have params that are optional.
rootCommand.SetHandler<string, string>(TestHandler, opt1, opt2);
public int TestHandler(string s1, string s2 = null) { ... }
There is no proper documentation yet about using InvocationContext to set an exit value¹, but the Beta 2 announcement https://github.com/dotnet/command-line-api/issues/1537 has some explanations with regard to this.
Does the invocation context param need to follow the handler's params?
I don't believe so, and the Beta 2 announcement https://github.com/dotnet/command-line-api/issues/1537 does not mention any requirements with regard to where such a parameter has to appear in the handler's method signature.
What happened when you tried it?
¹ Which is not automatically treated as the actual exit code of the program, but rather as the return value of the method invoked for processing of the commandline arguments by System.CommandLine (including the execution of the command handler). In other words, don't confuse InvocationContext.ExitCode with Environment.ExitCode.
If you include an InvocationContext parameter in your handler (which is valid in any position), then you can set the exit code by setting the InvocationContext.ExitCode property.
InvocationContext has been removed after 2.0 beta 4. Now you instead have to provide a method that returns int or Task<int>; either by overriding a method of CliAction, or by calling Command.SetAction.
Does this example help?
static int Main(string[] args)
{
var numOption = new Option<int>(name: "--num", description: "The number 42")
{
ArgumentHelpName = "number",
IsRequired = true
};
var rootCommand = new RootCommand("A program to verify you supplied option --num=42.")
{
numOption
};
rootCommand.SetHandler((context) =>
{
var num = context.ParseResult.GetValueForOption(numOption);
if (num != 42)
{
Console.Error.WriteLine($"Only 42 is permitted.");
context.ExitCode = 1;
return;
}
Console.WriteLine("Good job.");
});
return rootCommand.Invoke(args);
}