Skip to content

ericnewton76/commandline

 
 

Repository files navigation

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

or

C:\Project> paket install CommandLineParser

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

At a glance:

  • Compatible with .NET Framework 4.0+, Mono 2.1+ Profile, and .Net Core
  • Doesn't depend on other packages (No dependencies beyond standard base libraries)
  • One line parsing using default singleton: CommandLine.Parser.Default.ParseArguments(...).
  • Automatic or one line help screen generator: HelpText.AutoBuild(...).
  • Supports --help, --version, version and help [verb] by default.
  • Map to sequences (via IEnumerable<T> and similar) and scalar types, including Enums and Nullable<T>.
  • You can also map to every type with a constructor that accepts a string (like System.Uri).
  • Plug-In friendly architecture as explained here.
  • Define verb commands similar to git commit -a.
  • Unparsing support: CommandLine.Parser.Default.FormatCommandLine<T>(T options).
  • F#-friendly with support for option<'a>, see demo.
  • Most of features applies with a CoC philosophy.
  • C# demo: source here.

Used by several open source projects and by various commercial products: See the wiki for listing

Getting Started with the Command Line Parser Library

You can utilize the parser library in several ways:

  • Install via Nuget/Paket
  • Integrate directly into your project by copying the .cs files into your project.
  • ILMerge during your build process.

See more details in the wiki for direct integrations

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# Examples:

internal class Options {
  [Option('r',"read", 
	Required = true,
	HelpText = "Input files to be processed.")]
  public IEnumerable<string> InputFiles { get; set; }

  // Omitting long name, defaults to name of property, ie "--verbose"
  [Option(
	DefaultValue = false,
	HelpText = "Prints all messages to standard output.")]
  public bool Verbose { get; set; }
  
  [Option("stdin",
	DefaultValue = false
	HelpText = "Read from stdin")]
   public bool stdin { get; set; }

  [Value(0, MetaName = "offset",
	HelpText = "File offset.")]
  public long? Offset { get; set; }
}

static int Main(string[] args) {
  var options = new Options();
  var isValid = CommandLine.Parser.Default.ParseArgumentsStrict(args, options);

F# Examples:

type options = {
  [<Option('r', "read", Required = true, HelpText = "Input files.")>] files : seq<string>;
  [<Option(HelpText = "Prints all messages to standard output.")>] verbose : bool;
  [<Option(DefaultValue = "русский", HelpText = "Content language.")>] language : string;
  [<Value(0, MetaName="offset", HelpText = "File offset.")>] offset : int64 option;
}

let main argv =
  let result = CommandLine.Parser.Default.ParseArguments<options>(argv)
  match result with
  | :? Parsed<options> as parsed -> run parsed.Value
  | :? NotParsed<options> as notParsed -> fail notParsed.Errors

VB.Net:

Class Options
	<CommandLine.Option('r', "read", Required := true,
	HelpText:="Input files to be processed.")>
	Public Property InputFiles As IEnumerable(Of String)

	' Omitting long name, defaults to name of property, ie "--verbose"
	<CommandLine.Option(
	HelpText:="Prints all messages to standard output.")>
	Public Property Verbose As Boolean

	<CommandLine.Option(DefaultValue:="中文",
	HelpText:="Content language.")>
	Public Property Language As String

	<CommandLine.Value(0, MetaName:="offset",
	HelpText:="File offset.")>
	Public Property Offset As Long?
End Class

'TODO

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:

[Verb("add", HelpText = "Add file contents to the index.")]
class AddOptions {
  //normal options here
}
[Verb("commit", HelpText = "Record changes to the repository.")]
class CommitOptions {
  //normal options here
}
[Verb("clone", HelpText = "Clone a repository into a new directory.")]
class CloneOptions {
  //normal options here
}

int Main(string[] args) {
  return CommandLine.Parser.Default.ParseArguments<AddOptions, CommitOptions, CloneOptions>(args)
	.MapResult(
	  (AddOptions opts) => RunAddAndReturnExitCode(opts),
	  (CommitOptions opts) => RunCommitAndReturnExitCode(opts),
	  (CloneOptions opts) => RunCloneAndReturnExitCode(opts),
	  errs => 1);
}

VB.Net example:

<CommandLine.Verb("add", HelpText:="Add file contents to the index.")>
Public Class AddOptions
	'Normal options here
End Class
<CommandLine.Verb("commit", HelpText:="Record changes to the repository.")>
Public Class AddOptions
	'Normal options here
End Class
<CommandLine.Verb("clone", HelpText:="Clone a repository into a new directory.")>
Public Class AddOptions
	'Normal options here
End Class

Public Shared Sub Main()
	'TODO
End Sub

F# Example:

open CommandLine

[<Verb("add", HelpText = "Add file contents to the index.")>]
type AddOptions = {
  // normal options here
}
[<Verb("commit", HelpText = "Record changes to the repository.")>]
type CommitOptions = {
  // normal options here
}
[<Verb("clone", HelpText = "Clone a repository into a new directory.")>]
type CloneOptions = {
  // normal options here
}

[<EntryPoint>]
let main args =
  let result = Parser.Default.ParseArguments<AddOptions, CommitOptions, CloneOptions> args
  match result with
  | :? CommandLine.Parsed<obj> as command ->
	match command.Value with
	| :? AddOptions as opts -> RunAddAndReturnExitCode opts
	| :? CommitOptions as opts -> RunCommitAndReturnExitCode opts
	| :? CloneOptions as opts -> RunCloneAndReturnExitCode opts
  | :? CommandLine.NotParsed<obj> -> 1

For additional examples, check the wiki for additional examples

Acknowledgements:

Jet Brains ReSharper

Thanks to JetBrains for providing an open source license for ReSharper.

Contibutors

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!

For more info, see the wiki for details about contributing and for building the project.

Main Contributors (alphabetical order):

  • Alexander Fast (@mizipzor)
  • Dan Nemec (@nemec)
  • Kevin Moore (@gimmemoore)
  • Steven Evans
  • Thomas Démoulins (@Thilas)

Resources for newcomers:

Contacts:

  • Giacomo Stelluti Scala
    • gsscoder AT gmail DOT com (use this for everything that is not available via GitHub features)
    • GitHub: gsscoder
    • Blog
    • Twitter
  • Dan Nemec
  • Eric Newton

About

C# command line parser for .NET with F# support

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 99.4%
  • Other 0.6%