commandlineparser / commandline

The best C# command line parser that brings standardized *nix getopt style, for .NET. Includes F# support
MIT License
4.46k stars 473 forks source link
command-line dotnet dotnet-core

Build status NuGet NuGet NuGet Join the Gitter chat!

Command Line Parser Library for CLR and NetStandard

Note: the API surface has changed since v1.9.x and earlier. If you are looking for documentation on v1.9.x, please see stable-1.9.71.2

The Command Line Parser Library offers CLR applications a clean and concise API for manipulating command line arguments and related tasks, such as defining switches, options and verb commands. It allows you to display a help screen with a high degree of customization and a simple way to report syntax errors to the end user.

C:\Project> NuGet Install CommandLineParser

Nightly Build

Nightly version of the CommandLineParser can be downloaded from github Releases.

The Last new features and fixes, read changelog

NOTE: Mentioned F# Support is provided via CommandLineParser.FSharp package with FSharp dependencies.

This library provides hassle free command line parsing with a constantly updated API since 2005.

At a glance:

Getting Started with the Command Line Parser Library

You can utilize the parser library in several ways:

Quick Start Examples

  1. Create a class to define valid options, and to receive the parsed options.
  2. Call ParseArguments with the args string array.

C# Quick Start:

using System;
using CommandLine;

namespace QuickStart
{
    class Program
    {
        public class Options
        {
            [Option('v', "verbose", Required = false, HelpText = "Set output to verbose messages.")]
            public bool Verbose { get; set; }
        }

        static void Main(string[] args)
        {
            Parser.Default.ParseArguments<Options>(args)
                   .WithParsed<Options>(o =>
                   {
                       if (o.Verbose)
                       {
                           Console.WriteLine($"Verbose output enabled. Current Arguments: -v {o.Verbose}");
                           Console.WriteLine("Quick Start Example! App is in Verbose mode!");
                       }
                       else
                       {
                           Console.WriteLine($"Current Arguments: -v {o.Verbose}");
                           Console.WriteLine("Quick Start Example!");
                       }
                   });
        }
    }
}

C# Examples:

Click to expand! ```cs class Options { [Option('r', "read", Required = true, HelpText = "Input files to be processed.")] public IEnumerable InputFiles { get; set; } // Omitting long name, defaults to name of property, ie "--verbose" [Option( Default = false, HelpText = "Prints all messages to standard output.")] public bool Verbose { get; set; } [Option("stdin", Default = false, HelpText = "Read from stdin")] public bool stdin { get; set; } [Value(0, MetaName = "offset", HelpText = "File offset.")] public long? Offset { get; set; } } static void Main(string[] args) { CommandLine.Parser.Default.ParseArguments(args) .WithParsed(RunOptions) .WithNotParsed(HandleParseError); } static void RunOptions(Options opts) { //handle options } static void HandleParseError(IEnumerable errs) { //handle errors } ```

Demo to show IEnumerable options and other usage: Online Demo

F# Examples:

Click to expand! ```fsharp type options = { [] files : seq; [] verbose : bool; [] language : string; [] offset : int64 option; } let main argv = let result = CommandLine.Parser.Default.ParseArguments(argv) match result with | :? Parsed as parsed -> run parsed.Value | :? NotParsed as notParsed -> fail notParsed.Errors ```

VB.NET Example:

Click to expand! ```vb Class Options Public Property InputFiles As IEnumerable(Of String) ' Omitting long name, defaults to name of property, ie "--verbose" Public Property Verbose As Boolean Public Property Language As String Public Property Offset As Long? End Class Sub Main(ByVal args As String()) CommandLine.Parser.Default.ParseArguments(Of Options)(args) _ .WithParsed(Function(opts As Options) RunOptionsAndReturnExitCode(opts)) _ .WithNotParsed(Function(errs As IEnumerable(Of [Error])) 1) End Sub ```

For verbs:

  1. Create separate option classes for each verb. An options base class is supported.
  2. Call ParseArguments with all the verb attribute decorated options classes.
  3. Use MapResult to direct program flow to the verb that was parsed.

C# example:

Click to expand! ```csharp [Verb("add", HelpText = "Add file contents to the index.")] class AddOptions { //normal options here } [Verb("commit", HelpText = "Record changes to the repository.")] class CommitOptions { //commit options here } [Verb("clone", HelpText = "Clone a repository into a new directory.")] class CloneOptions { //clone options here } int Main(string[] args) { return CommandLine.Parser.Default.ParseArguments(args) .MapResult( (AddOptions opts) => RunAddAndReturnExitCode(opts), (CommitOptions opts) => RunCommitAndReturnExitCode(opts), (CloneOptions opts) => RunCloneAndReturnExitCode(opts), errs => 1); } ```

VB.NET example:

Click to expand! ```vb Public Class AddOptions 'Normal options here End Class Public Class CommitOptions 'Normal options here End Class Public Class CloneOptions 'Normal options here End Class Function Main(ByVal args As String()) As Integer Return CommandLine.Parser.Default.ParseArguments(Of AddOptions, CommitOptions, CloneOptions)(args) _ .MapResult( (Function(opts As AddOptions) RunAddAndReturnExitCode(opts)), (Function(opts As CommitOptions) RunCommitAndReturnExitCode(opts)), (Function(opts As CloneOptions) RunCloneAndReturnExitCode(opts)), (Function(errs As IEnumerable(Of [Error])) 1) ) End Function ```

F# Example:

Click to expand! ```fs open CommandLine [] type AddOptions = { // normal options here } [] type CommitOptions = { // normal options here } [] type CloneOptions = { // normal options here } [] let main args = let result = Parser.Default.ParseArguments args match result with | :? CommandLine.Parsed as command -> match command.Value with | :? AddOptions as opts -> RunAddAndReturnExitCode opts | :? CommitOptions as opts -> RunCommitAndReturnExitCode opts | :? CloneOptions as opts -> RunCloneAndReturnExitCode opts | :? CommandLine.NotParsed -> 1 ```

Release History

See the changelog

Contributors

First off, Thank you! All contributions are welcome.

Please consider sticking with the GNU getopt standard for command line parsing.

Additionally, for easiest diff compares, please follow the project's tabs settings. Utilizing the EditorConfig extension for Visual Studio/your favorite IDE is recommended.

And most importantly, please target the develop branch in your pull requests!

Main Contributors (alphabetical order):

Resources for newcomers:

Contacts: