Skip to content

Instantly share code, notes, and snippets.

@llint
Created March 16, 2017 21:15
Show Gist options
  • Save llint/a361312e9ae01613b0f3ddfc39b3ccf2 to your computer and use it in GitHub Desktop.
Save llint/a361312e9ae01613b0f3ddfc39b3ccf2 to your computer and use it in GitHub Desktop.
CommandLineUtils Example
using System;
using System.Linq;
using Microsoft.Extensions.CommandLineUtils;
namespace CommandLineTest
{
class Program
{
public static void Main(params string[] args)
{
CommandLineApplication commandLineApplication =
new CommandLineApplication(throwOnUnexpectedArg: false);
commandLineApplication.Command("MyCommand",
(myCommand) =>
{
CommandArgument arguments = myCommand.Argument(
"arguments",
"Enter the full name of the person to be greeted.",
multipleValues: true);
CommandOption greeting = myCommand.Option(
"-$|-g |--greeting <greeting>",
"The greeting to display. The greeting supports"
+ " a format string where {fullname} will be "
+ "substituted with the full name.",
CommandOptionType.SingleValue);
CommandOption uppercase = myCommand.Option(
"-u | --uppercase", "Display the greeting in uppercase.",
CommandOptionType.NoValue);
myCommand.HelpOption("-? | -h | --help"); // help for MyCommand
myCommand.OnExecute(() =>
{
if (greeting.HasValue())
{
Console.WriteLine($"{(uppercase.HasValue() ? greeting.Value().ToUpper() : greeting.Value())}: {string.Join(", ", arguments.Values.Select(argument => uppercase.HasValue() ? argument.ToUpper() : argument))}");
}
return 0;
});
myCommand.Command("MySubCommand",
(mySubCommand) =>
{
var subArguments = mySubCommand.Argument(
"subArguments",
"MySubCommand arguments",
multipleValues: true);
var subOption = mySubCommand.Option(
"-o | --option <option>",
"MySubCommand option",
CommandOptionType.SingleValue);
mySubCommand.HelpOption("-? | -h | --help"); // help for MySubCommand
mySubCommand.OnExecute(() =>
{
if (subOption.HasValue())
{
Console.WriteLine($"{subOption.Value()}: {string.Join(", ", subArguments.Values)}");
}
return 0;
});
}
);
}
);
commandLineApplication.HelpOption("-x"); // top level help -- '-h | -? | --help would be consumed by 'dotnet run'
commandLineApplication.Execute(args);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment