Coder Social home page Coder Social logo

commandlineparser / commandline Goto Github PK

View Code? Open in Web Editor NEW
4.5K 74.0 471.0 11.54 MB

The best C# command line parser that brings standardized *nix getopt style, for .NET. Includes F# support

License: MIT License

C# 100.00%
command-line dotnet dotnet-core

commandline's Introduction

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:

  • Compatible with .NET Framework 4.0+, Mono 2.1+ Profile, .NET Standard 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(...) and three overload methods.
  • Automatic or one line help screen generator: HelpText.AutoBuild(...).
  • Supports --help, --version, version and help [verb] by default with customization.
  • 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) for reference and value types.
  • Verbs can be array of types collected from Plugins or IoC container.
  • Define verb commands similar to git commit -a.
  • Support default verb.
  • Support Mutable and Immutable types.
  • Support HelpText localization.
  • Support ordering of options in HelpText.
  • Support Mutually Exclusive Options and Option groups.
  • Support named and value options.
  • Support Asynchronous programming with async and await.
  • Unparsing support: CommandLine.Parser.Default.FormatCommandLine<T>(T options).
  • CommandLineParser.FSharp package is F#-friendly with support for option<'a>, see demo. NOTE: This is a separate NuGet package.
  • Include wiki documentation with lot of examples ready to run online.
  • Support Source Link and symbolic nuget package snupkg.
  • Tested in Windows, Linux Ubuntu 18.04 and Mac OS.
  • Most of features applies with a CoC philosophy.
  • C# demo: source here.

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!
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(
	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<Options>(args)
    .WithParsed(RunOptions)
    .WithNotParsed(HandleParseError);
}
static void RunOptions(Options opts)
{
  //handle options
}
static void HandleParseError(IEnumerable<Error> errs)
{
  //handle errors
}

Demo to show IEnumerable options and other usage: Online Demo

F# Examples:

Click to expand!
type options = {
  [<Option('r', "read", Required = true, HelpText = "Input files.")>] files : seq<string>;
  [<Option(HelpText = "Prints all messages to standard output.")>] verbose : bool;
  [<Option(Default = "русский", 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 Example:

Click to expand!
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(Default:="中文",
	HelpText:="Content language.")>
	Public Property Language As String

	<CommandLine.Value(0, MetaName:="offset",
	HelpText:="File offset.")>
	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!
[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<AddOptions, CommitOptions, CloneOptions>(args)
	.MapResult(
	  (AddOptions opts) => RunAddAndReturnExitCode(opts),
	  (CommitOptions opts) => RunCommitAndReturnExitCode(opts),
	  (CloneOptions opts) => RunCloneAndReturnExitCode(opts),
	  errs => 1);
}

VB.NET example:

Click to expand!
<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 CommitOptions
    'Normal options here
End Class
<CommandLine.Verb("clone", HelpText:="Clone a repository into a new directory.")>
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!
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

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):

  • Alexander Fast (@mizipzor)
  • Dan Nemec (@nemec)
  • Eric Newton (@ericnewton76)
  • Kevin Moore (@gimmemoore)
  • Moh-Hassan (@moh-hassan)
  • 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
  • Moh-Hassan

commandline's People

Contributors

0xced avatar alexanderfast avatar anthonylangsworth avatar athari avatar e673 avatar ericnewton76 avatar gbritton1 avatar gimmemoore avatar gsscoder avatar hadzhiyski avatar jeremymeng avatar johnjaylward avatar joseangelmt avatar kapsir avatar kendfrey avatar lmmarsano avatar lythix avatar moh-hassan avatar neilmacmullen avatar nemec avatar peterpitterling avatar qmfrederik avatar regme avatar rmunn avatar smbecker avatar thilas avatar tkouba avatar tynar avatar viktorhofer avatar zii-dmg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

commandline's Issues

Parser.ParserSettings.MutuallyExclusive=true - does not work as stated in the documentation

Issue by coyot
Tuesday Nov 19, 2013 at 14:26 GMT
Originally opened as gsscoder/commandline#109


According to the https://github.com/gsscoder/commandline/wiki/Mutually-Exclusive-Options

this works like that:

;; permitted
$ app --enablejavascript --documentroot ~/var/local/website

;; denied
$ app --anonymouslogin --enablejavascript

BUT based on my research - this works exactly OPPOSITE! You are able to set values from DIFFERENT sets, not set values which are in the same "mutually exclusive set" - this is correct name, but this does not work as described...

Ability to display usage without concrete example with AutoHelp

Issue by kensykora
Thursday Oct 01, 2015 at 14:39 GMT
Originally opened as gsscoder/commandline#247


I am wanting to display help options for my verb class that doesn't include a concrete example. Currently this isn't supported, at least as far as I can tell.

e.g.,

USAGE: push-registration register platform token [tags1 tags2 ... tagn] [-c connectionString] [-h hubName]
<Example Name>:
  push-registration register ios abc123 tag1 tag2

Currently that first line is what I can't figure out what the best way is to spit that out with autohelp

Parsing question

Issue by Sirais
Friday Aug 07, 2015 at 10:35 GMT
Originally opened as gsscoder/commandline#221


in the Wiki at
https://github.com/gsscoder/commandline/wiki/Quickstart
is the quickstart example to parse the commandline args into n Object using the following
example. still the same as the "old" lib i was using.
...
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options))
...
now it seems to be completely different way and currently Blindsighted or something. but i cant see how i can parse the commandline into an Object anymore.
any hints ?

Defining sets of valid option values

Issue by bergbria
Monday Sep 28, 2015 at 17:27 GMT
Originally opened as gsscoder/commandline#245


I'd like to create an option where there is a known, restricted set of valid values which cannot be expressed in C# as the name of an enum. For example, the set might look like {8.0, 8.1, 9.0}. Is there any way to express this using this library?

If not, what would be the best way to add support for this? A custom attribute for enum fields, another parameter for the Option attribute?

Support For Dynamic Options

Issue by issafram
Wednesday Aug 28, 2013 at 14:46 GMT
Originally opened as gsscoder/commandline#96


I have an application that will have 1 to many different arguments being passed in. The argument names will always be different depending on configuration (dynamic). So I will never know the name of the argument names as the designer of the application.

Does this library support something like that? It is great for parsing but it requires the options parameter to be defined. I have tried using an ExpandoObject but I don't think it works properly because attributes are required on the properties.

Is there a way to implement multiple level verbs?

Issue by akfish
Thursday Oct 31, 2013 at 19:48 GMT
Originally opened as gsscoder/commandline#107


I am trying to make an app with multiple level of verbs, something like:

app repo list
app repo add
app account list

What I tried is:

    class Options
    {
        #region Global Options
        //...
        #endregion

        #region Help
        //..
        #endregion

        #region Verbs
        [VerbOption("account", HelpText = "Manage mail accounts")]
        public AccountOptions AccountVerb { get; set; }

        [VerbOption("repo", HelpText = "Manage repositories")]
        public RepoOptions RepoVerb { get; set; }
        #endregion
    }

In each verb, nested a sub verb:

    class AccountOptions : IOptions
    {
        [VerbOption("add", HelpText = "Add an account")]
        public AddOption AddVerb { get; set; }

        //And so on....

        public class AddOption : IOptions
        {
        }
        //And so on....

    }

main:

    class Program
    {
        static void Main(string[] args)
        {
            string theVerb = null;
            IOptions theOptions = null;

            var options = new Options();
            if (CommandLine.Parser.Default.ParseArguments(args, options, (verb, subOptions) =>
            {
                theVerb = verb;
                if (verb != null)
                    theOptions = subOptions as IOptions;
            }))
            {
                theOptions.Execute(options);
            }
            else
            {
                Console.Error.WriteLine("Command line parsing error.");
            }
        }
    }

I was able to get first level of verbs to working (e.g. app repo, app account, as the documents said. But the second level ones (app account list, app account add) didn't.

So is there a way to do this? Thanks.

Can a verb have a child verb?

Issue by sgrassie
Friday Jul 17, 2015 at 10:56 GMT
Originally opened as gsscoder/commandline#201


I'd like to allow the following scenarios:

$ app verb -t
$ app verb childverb -u
$ app verb otherchildverb -z

Where -u and -z are both specific to the respective child verbs. Is the documentation in the wiki for this still valid, or has it changed in 2.0+?

Added multiple tokenizers implementing new ITokenizer interface

Issue by Ehryk
Saturday Aug 01, 2015 at 06:05 GMT
Originally opened as gsscoder/commandline#212


Persuant to issue #108, I have renamed the default tokenizer to TokenizerGetOpt, and added TokenizerWindows (currently just '/', '//' variant of TokenizerGetOpt), and TokenizerHybrid (allowing both '-','/' and '--','//' together). I also added a ITokenizer interface to set a standard for possibly other tokenizers.

Because static classes cannot implement interfaces, the tokenizers are no longer static and must be instantiated before use (which is now done so using TokenizerGetOpt).


Ehryk included the following code: https://github.com/gsscoder/commandline/pull/212/commits

When using ValueOptionAttributes, setting a property as Required always fails

Issue by wags1999
Thursday Oct 17, 2013 at 19:14 GMT
Originally opened as gsscoder/commandline#104


In version 1.9.71.2, when using ValueOptionAttributes to define order-specific parameters (I'm using this for backwards compatibility), if I set any properties as Required, the parsing thinks it fails. This is because in OptionMap.cs, in EnforceRequiredRule, the option.IsDefined has never been set in the Parser.DoParseArgumentsCore() and subsequent valueMapper.MapValueItem() methods.

Why does DefaultValue *always* overwrite the property if that option is not provided?

Issue by nemec
Friday Apr 12, 2013 at 21:29 GMT
Originally opened as gsscoder/commandline#81


I would expect the default value to not be used unless the option was provided but without a value. Otherwise, it kind of duplicates the functionality of the constructor (but more limited since Attributes may only contain constant values).

For example, when parsing the following class:

public class Config
{
    [Option('v', DefaultValue = "Other")]
    public string Value { get; set; }

    public Config()
    {
        Value = "Initial";
    }
}

I would expect the following:

  • Program.exe > Value == Initial
  • Program.exe -v > Value == Other
  • Program.exe -v Overwrite > Value == Overwrite

Specifying that an Option requires another Option

Issue by st1led
Tuesday Apr 09, 2013 at 09:55 GMT
Originally opened as gsscoder/commandline#76


Hi everybody, is there a way in CommandLine (I guess in a way similar to what is done with mutually exclusive properties) to specify that an option requires another option to be set? This is a short example:

        [Option('v', "verbose",
            Required = false,
            DefaultValue = false,
            HelpText = "Prints log messages.")]
        public bool Verbose { get; set; }

        [Option('o', "optional-operation",
            Required = false,
            DefaultValue = false,
            HelpText = "Performs an operation (a.k.a. \"does something\") in the code.")]
        public bool PerformOperation { get; set; }

        [Option('t', "time-limit",
            Required = false,
            DefaultValue = false,
            HelpText = "Requires option -o. Specifies a time limit for the optional operation")]
        public int OperationTimeLimit { get; set; }

In this scenario, one would want to allow command line arguments like -o and -vot but not -vt or -t for instance, since in the latter the option -t is specified without -o. Is this currently possible in CommandLine?

Regards,
Stefano

Backslash in argument value escapes quotation mark

Issue by wpeti
Thursday Sep 10, 2015 at 15:04 GMT
Originally opened as gsscoder/commandline#240


I hope I'm not using the library in the right way, but i just came across this issue:
I have an option class with a property called "Path", designed to be used as input container of folder or file paths. In case the user is trying to pass a value to this option by using the --Path= argument he/she experiences errors sometime. The cause of this is that they sometime pass on directory paths with a backslash in the end, like so: --Path="c:\test folder". In this unfortunate case the ending quotation mark is not recognized by the parser library and it parses the faulty "c:\test " argument value into my options object.
I'm not an expert of this library and I haven't checked every line of it's code (so far) but would say it's a bug which doesn't have any workaround implemented at the moment.

Stackable ValueOption and Option

Issue by netxph
Tuesday Jun 16, 2015 at 09:28 GMT
Originally opened as gsscoder/commandline#163


I'd like to mimic this...

app.exe -type SomeType
app.exe SomeType
[ValueOption(0)]
[Option('t', "typeName", Required=true)]
public string TypeName { get; set; }

Having this option gives parsing error on app.exe SomeType. Any suggestions recommendations?

Prohibited values

Issue by raymondb1
Wednesday May 14, 2014 at 15:24 GMT
Originally opened as gsscoder/commandline#128


Hi there,

Can I specify that certain parameter values are invalid? Something to the same effect of:

        private string _server = null;
        [Option('s', "server", Required = true, HelpText = "Some text here")]
        public virtual string Server
        {
            get { return _server; }
            set {   if (string.Compare("localhost", value, true) == 0)
                    {
                        _server = null;
                        throw new ArgumentException("Localhost is not accepted as a server name.");
                    }

                }
        }

Of course, I can validate after parsing is complete, but I had to do it in many places. Is there a better way?

Thanks!

Project is not dead!

Issue by gsscoder
Thursday May 28, 2015 at 18:24 GMT
Originally opened as gsscoder/commandline#152


I apologize for not being able to coordinate issues, pull requests and for not replying to all emails.
I was very engaged in various heavy and challenging projects around Europe.

I next days (or may be weeks) I'll try to catch up with everything...

For now I repeat what I've said to few (of many, sorry) emails I've replied: please use the consolidated code base of latest stable on branch stable-1.9.71.2.

At the moment I can't make any preview for the future: maybe the new pre-release 2.0.0.0 (actual master branch) will be discarded, maybe not or maybe both versions will go ahead together. As always suggestions are welcome.

EDIT

  • I've to check ISSUEs but there's good chance that for an intermediate period stable-1.9.72.2 could evolve in its path.
  • But there's no doubt that pre-release 2.0 will stabilize, becoming the official branch. I'm working to make it happen.

EDIT 2

  • All PRs that can be merged to trunk as been merged.
  • Now I can review ISSUEs.

Regards,
Giacomo Stelluti Scala

Option to convert Arguments object back into args string

Issue by issacg
Wednesday Dec 18, 2013 at 10:09 GMT
Originally opened as gsscoder/commandline#114


Hi

In my use-case, I needed to (occasionally) construct command line parameters for another instance of my process, and overloaded my class' ToString method to do so. I'd love to contribute the code back, but not sure if it's something that's needed, or where the best place in the library would be to put it.

I've included the code here, and if there is interest, and someone would give me some basic guidance as to where the correct place to add this to the library would be, I'd be happy to make a pull request (time permitting ;))

class MyArguments {
        // Add some option-properties

        public override string ToString()
        {
            string res = "";
            // Get a list of all properties with OptionAttribute
            var props = this.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(OptionAttribute)));
            // Now search the list to extract the attribute data
            foreach (PropertyInfo prop in props)
            {
                object[] attrs = prop.GetCustomAttributes(true);
                foreach (object attr in attrs)
                {
                    OptionAttribute oa = attr as OptionAttribute;
                    if (oa != null)
                    {
                        // We found an OptionAttribute!
                        Type t = prop.GetType();
                        var data = prop.GetValue(this, null);
                        // Check if value is "default(t)" or not
                        if (data != (t.IsValueType ? Activator.CreateInstance(t) : null))
                        {
                            // Only print out non-empty parameters
                            res += "--" + oa.LongName + " " + data.ToString() + " ";
                        }
                    }
                }
            }
            return res;
        }
}

Ability to use HelpText.AutoBuild() without parser results

Issue by zii-dmg
Thursday Jun 20, 2013 at 07:27 GMT
Originally opened as gsscoder/commandline#88


Using commit e00dd9f.

Sometimes Parser.ParseArguments throws exceptions (for example, InvalidOperationException: "Sequence contains more than one matching element") and ParseResult doesn't created, but I still need to show help usage to user. Without ParserResult I can't do this easily.

Or maybe I doesn't understand how to use help usage auto generation on exceptions.

Fixed issue where it was treating 'help' as the verb that usage info was...

Issue by tombatron
Thursday Apr 04, 2013 at 01:55 GMT
Originally opened as gsscoder/commandline#74


... requested for.

Let's say that I have an application called 'example' that has a verb called 'dothing'. If I entered the following on the console:

example help dothing

The usage text displayed isn't for the verb specified but the default usage text.


tombatron included the following code: https://github.com/gsscoder/commandline/pull/74/commits

Is there any way to display a custom usage for a verb with no options?

Issue by kolbasov
Friday Jan 31, 2014 at 11:12 GMT
Originally opened as gsscoder/commandline#116


When I try to get a help for a verb with no options using version 2.0.0.0:

app.exe help verb

I get the following:

App 1.0.0.0
Copyright (c) 2014

  --help    Display this help screen.

That makes sense since the verb has no options. However, it would be helpful to have something like GetUsage from the version 1.9 for printing more descriptive message. Is it possible in version 2.0.0.0?

Added Windows Style LongName ("/") to Options along with the required…

Issue by Rusk85
Saturday Aug 15, 2015 at 22:02 GMT
Originally opened as gsscoder/commandline#224


… unit tests. I have refrained from altering the core logic. Instead I added two overloaded methods for Parser.ParseArguments(...) with an additional optional parameter "useWinStyleOptions" which is set to true per default. From there on I simply check all arguments for the win style flag ("/") and replace them with the stock double dashes ("--"). The result I pass to the original ParseArguments-Methods.

While as a personal preference I take unix style options over windows style options every day but there is a remote service I am using that is among other things capable of executing applications. I cant easily change the service - its fairly old and written in vb.net - but I checked the implementation. Turns out its capable of interpreting windows style options and passing that to the application it starts. So there you go.

There might be others in a similar situation to whom this could be a possible solution.

Please review the code.


Rusk85 included the following code: https://github.com/gsscoder/commandline/pull/224/commits

Parsing key-value pairs

Issue by mr-miles
Wednesday Mar 26, 2014 at 18:36 GMT
Originally opened as gsscoder/commandline#122


Is it possible to use the parser to populate key-value pairs?

So something like "myapp.exe -v:a=x -v:b=y -v:c=z" would populate a property v which is a Dictionary<string, string> with (a,x), (b,y), (c,z) values?

I want to use the parser to specify replacements to be made on a text file

Great package by the way!

Help Wanted: review of wiki and other docs for grammar correctness

Issue by gsscoder
Sunday Jul 12, 2015 at 17:21 GMT
Originally opened as gsscoder/commandline#196


If anyone find bad English forms and grammatical issues, please fix it!

Actual priority:

  1. Wiki - Latest Version Info: https://github.com/gsscoder/commandline/wiki/Latest-Version
  2. README.md - https://github.com/gsscoder/commandline/blob/master/README.md
  3. Main Wiki: https://github.com/gsscoder/commandline/wiki

For point 3 we can wait a more stable version of 2.0, when info about previous stable will be replaced.

Displaying help text with fluent syntax?

Issue by jawn
Wednesday Aug 12, 2015 at 08:58 GMT
Originally opened as gsscoder/commandline#223


Using the latest nuget of the version 2.0 pre-release, I can display help text like this:

var results = Parser.Default.ParseArguments<Options>(args)
  .WithParsed(opts => /* handle options here */)

if (results.Tag == ParserResultType.NotParsed)
{
  var helpText = HelpText.AutoBuild(results);
  Console.WriteLine(helpText);
}

Is there a way to do this within the fluent syntax?

Something like
var results = Parser.Default.ParseArguments(args)
.WithNotParsed(opts => Console.WriteLine(HelpText.AutoBuild()));
.WithParsed(opts => /* handle options here */)

Since AutoBuild() requires results, this can't be called within the fluent syntax. That's already logged as #88, however I would like to know whether a different solution is available.

Default value?

Issue by ekkis
Monday Sep 16, 2013 at 21:49 GMT
Originally opened as gsscoder/commandline#100


I've defined an option like this:

[Option('s', HelpText = "Save name", DefaultValue="Main")]
public string SaveName { get; set; }

but when I run my programme as:

c:> test ./file-to-munch.txt -s

I get a failure of ParseArgumentsStrict. what have I done wrong?

Refactoring test project

Issue by gsscoder
Saturday Jul 11, 2015 at 17:13 GMT
Originally opened as gsscoder/commandline#195


Has anyone some neat idea to re-organize test code?

I'd like to programmatically create it with https://github.com/AutoFixture/AutoFixture. Has anyone do it before?

I've also some more extreme idea, like porting test code to F# using https://github.com/mausch/Fuchu and https://code.google.com/p/unquote/.

(Maybe I'll start some experiment in a dev branch).

cc/ @mizipzor @nemec @gimmemoore

HELP: Plus/Minus argument parsing; i.e. -optimize[+|-]

Issue by sushihangover
Friday Jun 12, 2015 at 16:09 GMT
Originally opened as gsscoder/commandline#158


I am looking for a little assistance in seeing if I can parse plus/minus (inclusion/negation) arguments with 'commandline'.

i.e. Argument options like:

  • someexecutable -optimize+ -unsafe-
  • -optimize[+|-]
  • -unsafe[+|-]
  • -warnaserror[+|-]

Maybe I am just missing something or I have not had enough coffee, but this one is stumping me.

Add Attribute to Specify a Verb's Action

Issue by austinwagner
Friday Jul 10, 2015 at 20:17 GMT
Originally opened as gsscoder/commandline#194


The current method of using verbs seems more verbose than it needs to be.

I would like to suggest an attribute that can be applied to a method within option classes marked as verbs that contain the code to execute when the verb is invoked.

[Verb("dosomething")]
class DoSomethingOptions
{
    [Option("foo")]
    public string Foo { get; set; }

    [VerbAction]
    public int Run()
    {
        Console.WriteLine(this.Foo)
    }
}

This could simplify the call to ParseArguments down to something along the lines of Parser.Default.ParseArguments<DoSomethingOptions, DoSomethingElseOptions>(args).Run()

Auto help question

Issue by AndrewSav
Tuesday Sep 22, 2015 at 22:37 GMT
Originally opened as gsscoder/commandline#242


This is regarding 2.0

  1. Is it possible to suppress displaying version/copyright stuff (I can display them myself, thank you very much) but retain the rest?
  2. If I remove AssemblyCopyright attribute CommandLine just crashes. I'm not sure if it's intended behaviour?

Missing ValueList attribute

Issue by ekkis
Monday Sep 16, 2013 at 22:07 GMT
Originally opened as gsscoder/commandline#101


to help me with other issues I posted, I decided to pull in the whole project into my solution. upon compilation I get the error that ValueListAttribute cannot be found. indeed it's not there... I don't see another project I should also add... what next?

Support for a App.config settings

Issue by apla
Thursday Jun 18, 2015 at 11:06 GMT
Originally opened as gsscoder/commandline#165


I'm trying to couple commandline Options class with ConfigurationManager.AppSettings to make configuration persistent. For now (with stable version 1.9.x) I ended with such piece of code:

public Options (string[] args) {

    // TODO: redesign without reflections
    var pis = this.GetType().GetProperties().Where(prop => prop.IsDefined(typeof(OptionAttribute), false));
    foreach (var pi in pis) {
        var optAttr = pi.GetCustomAttributes(typeof(OptionAttribute), false).FirstOrDefault() as OptionAttribute;
        if (optAttr == null)
            continue;
        optAttr.DefaultValue = optAttr.DefaultValue ?? ConfigurationManager.AppSettings[optAttr.LongName];
    }

    // here we use CommandLine to initialize this class
    using (var parser = new CommandLine.Parser(settings => { settings.HelpWriter = Console.Error; settings.IgnoreUnknownArguments = false; }))
...

Maybe you can propose better way to enumerate properties?

Accepting ONLY fixes PR until stable release

Issue by gsscoder
Saturday Aug 01, 2015 at 06:20 GMT
Originally opened as gsscoder/commandline#213


As you can see I've recently promoted the library from alpha to beta.

Please be patient if I'll not accept enhancement PR until it becomes stable.

As a developer you know that adding complexity will delay the consolidation of a stable code base, a solid prerequisite for proceeding with future changes.

Obviously I'll accept any fix, or better everyone is encouraged to submit fixes or also new tests to cover untested parts.

A good practice is always open issue, discuss and than submit a PR.

Thanks everyone!

cc/ @nemec @Thilas @mizipzor @gimmemoore

Added the ability to use \n and/or \r in HelpText

Issue by rupe120
Monday Jun 22, 2015 at 19:41 GMT
Originally opened as gsscoder/commandline#169


It would be helpful to be able to create more than one paragraph in the HelpText, for the instances where there is supplemental / conditional information to add.

I have a scenario where depending on the list of options supplied, a given option may have slightly different behavior and/or be required or not.

It tends to be helpful if the user can see clear separation between the default functionality of an option, and additional scenarios.


rupe120 included the following code: https://github.com/gsscoder/commandline/pull/169/commits

Verb option help is not rendering Enum value options

Issue by kensykora
Thursday Oct 01, 2015 at 14:32 GMT
Originally opened as gsscoder/commandline#246


When I create a verb object with a verb that has an enum value option, the help for the verb is not rendering. See example here: https://gist.github.com/kensykora/f486cdf239a823390409

Basically, any enum that's a positional parameter doesn't show up in autobuild help. It'd also be nice if the enum displayed it's string value rather than the int value, maybe even used the System.ComponentModel.DescriptionAttribute option?

HelpText.AutoBuild ignores word after last dot in AssemblyTitleAttribute

Issue by eakoning
Wednesday Jul 15, 2015 at 14:24 GMT
Originally opened as gsscoder/commandline#199


I'm using CommandLine version 1.9.71.2
If i specify an AssemblyTitleAttribute with a dotted name (and I version my tool 1.10.1.* through the AssemblyVersionAttribute) in the project's AssemblyInfo.cs file, e.g.

[assembly: AssemblyTitle("my.favorite.tool")]

the Copyright and Heading properties on HelpText when using the AutoBuild show
my.favorite 1.10.1.27342

Changing the assembly title to

[assembly: AssemblyTitle("my.great.fantastic.favorite.tool")]

changes Copyright and Heading properties to
my.great.fantastic.favorite 1.10.1.27342

It always leaves out the word after the last dot.

When I leave out the AssemblyTitleAttribute all together, the HelpText falls back to the text specified in the AssemblyProductAttribute and that seems to be working fine.

AddPreOptionsLine() incorrectly wrapping when adding multi-line string (like in the wiki example "Handling Parsing Errors")

Issue by turch
Wednesday Mar 13, 2013 at 21:07 GMT
Originally opened as gsscoder/commandline#69


Using the sample code in https://github.com/gsscoder/commandline/wiki/Display-A-Help-Screen section "Handling Parsing Errors" to print errors:

RenderParsingErrorsText() returns a string with linebreaks if there are multiple errors. When passed to Add<>OptionsLine, it is wrapped every 80 characters regardless of newlines, causing incorrect wrapping.

[ParserState]
public IParserState LastParserState { get; set; }

[Option('a', "qwe", Required = true)]
public string a { get; set; }

[Option('b', "asd", Required = true)]
public double b { get; set; }

[Option('c', "zxc", Required = true)]
public bool c { get; set; }

[HelpOption]
public string GetUsage()
{
    var help = new HelpText();
    // ...
    if (this.LastParserState.Errors.Count > 0)
    {
        var errors = help.RenderParsingErrorsText(this, 2); // indent with two spaces
        if (!string.IsNullOrEmpty(errors))
        {
            help.AddPreOptionsLine(string.Concat("\n", "ERROR(S):"));
            help.AddPreOptionsLine(errors);
        }
    }
    // ...
    return help;

}
>foo.exe

ERROR(S):
  -a/--qwe required option is missing.
  -b/--asd required option is 
missing.
  -c/--zxc required option is missing.

As you can see, the second error line gets incorrectly wrapped.

HelpText.AutoBuild fails on Linux

Issue by aggieben
Wednesday Oct 14, 2015 at 02:03 GMT
Originally opened as gsscoder/commandline#256


Here's the output when I try to run my command with --help:

sbAppDev@sb-docker:~/proj/cm-core/src/Cm.Util$ dnx cmutil dbm --help
info    : [Cm.Util] Running cmutil 1.0.0-beta in /home/sbAppDev/proj/cm-core/src/Cm.Util
info    : [Cm.Util] LogLevel configured to Information
System.InvalidOperationException: CopyrightInfo::Default requires that you define AssemblyCopyrightAttribute or AssemblyCompanyAttribute.
  at CSharpx.MaybeExtensions.FromJustOrFail[AssemblyCompanyAttribute] (CSharpx.Maybe`1 maybe, System.Exception exceptionToThrow) [0x00000] in <filename unknown>:0
  at CommandLine.Text.CopyrightInfo.get_Default () [0x00000] in <filename unknown>:0
  at CommandLine.Text.HelpText.AutoBuild[Object] (CommandLine.ParserResult`1 parserResult, System.Func`2 onError, System.Func`2 onExample, Boolean verbsIndex) [0x00000] in <filename unknown>:0
  at CommandLine.Text.HelpText.AutoBuild[Object] (CommandLine.ParserResult`1 parserResult) [0x00000] in <filename unknown>:0
  at CommandLine.Parser+<>c__DisplayClass17_0`1[System.Object].<DisplayHelp>b__1 (IEnumerable`1 _, System.IO.TextWriter writer) [0x00000] in <filename unknown>:0
  at CSharpx.MaybeExtensions.Do[IEnumerable`1,TextWriter] (CSharpx.Maybe`1 maybe, System.Action`2 action) [0x00000] in <filename unknown>:0
  at CommandLine.Parser+<>c__DisplayClass17_0`1[System.Object].<DisplayHelp>b__0 (IEnumerable`1 errors) [0x00000] in <filename unknown>:0
  at CommandLine.ParserResultExtensions.WithNotParsed[Object] (CommandLine.ParserResult`1 result, System.Action`1 action) [0x00000] in <filename unknown>:0
  at CommandLine.Parser.DisplayHelp[Object] (CommandLine.ParserResult`1 parserResult, System.IO.TextWriter helpWriter) [0x00000] in <filename unknown>:0
  at CommandLine.Parser.MakeParserResult[Object] (CommandLine.ParserResult`1 parserResult, CommandLine.ParserSettings settings) [0x00000] in <filename unknown>:0
  at CommandLine.Parser.ParseArguments (IEnumerable`1 args, System.Type[] types) [0x00000] in <filename unknown>:0
  at CommandLine.ParserExtensions.ParseArguments[SupervisorCommand,MigrationsCommand] (CommandLine.Parser parser, IEnumerable`1 args) [0x00000] in <filename unknown>:0
  at Cm.Util.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
  at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
  at Microsoft.Dnx.Runtime.Common.EntryPointExecutor.Execute (System.Reflection.Assembly assembly, System.String[] args, IServiceProvider serviceProvider) [0x00000] in <filename unknown>:0
  at Microsoft.Dnx.ApplicationHost.Program.ExecuteMain (Microsoft.Dnx.Runtime.DefaultHost host, System.String applicationName, System.String[] args) [0x00000] in <filename unknown>:0
  at Microsoft.Dnx.ApplicationHost.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
  at Microsoft.Dnx.Runtime.Common.EntryPointExecutor.Execute (System.Reflection.Assembly assembly, System.String[] args, IServiceProvider serviceProvider) [0x00000] in <filename unknown>:0
  at Microsoft.Dnx.Host.Bootstrapper.RunAsync (System.Collections.Generic.List`1 args, IRuntimeEnvironment env, System.Runtime.Versioning.FrameworkName targetFramework) [0x00000] in <filename unknown>:0

Exact same code and dnx version works fine on Windows desktop CLR.

Stack:
Mono 4.0.4 (Stable 4.0.4.1/5ab4c0d)
dnx 1.0.0-beta7 Mono/Linux/x64

Issues with sub options

Issue by wadewegner
Thursday Oct 01, 2015 at 18:07 GMT
Originally opened as gsscoder/commandline#249


I'm having an issue with the parser not figuring out my sub-options.

Here's the code in Main:

var invokedVerb = "";
var invokedVerbInstance = new object();

var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options,
    (verb, subOptions) =>
    {
        // if parsing succeeds the verb name and correct instance
        // will be passed to onVerbCommand delegate (string,object)
        invokedVerb = verb;
        if (!string.IsNullOrEmpty(invokedVerb))
        invokedVerbInstance = subOptions;
    }))
{
    Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
}

This is pretty much right from the wiki.

My options are defined as this:

class Options
{
    public Options()
    {
        CpVerb = new CPSubOptions { };
    }

    [VerbOption("cp", HelpText = "Interact with cp.")]
    public CPSubOptions CpVerb { get; set; }

    [HelpVerbOption]
    public string GetUsage(string verb)
    {
        return HelpText.AutoBuild(this, verb);
    }
}

class CPSubOptions
{
    [Option('n', "name", HelpText = "Get details name.")]
    public string Name { get; set; }
}

When I run with cp as the args, it works and the parser determines that CPSubOptions is the subOptions and invokedVerbInstance is set appropriately.

However, when I run with cp --name blah or cp -n blah, the subOptions is null, so it's not parsed properly.

Any help?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.