All Projects → jpdillingham → Utility.CommandLine.Arguments

jpdillingham / Utility.CommandLine.Arguments

Licence: MIT License
A C# .NET class library containing tools for parsing the command line arguments of console applications.

Programming Languages

C#
18002 projects
shell
77523 projects

Projects that are alternatives of or similar to Utility.CommandLine.Arguments

Picocli
Picocli is a modern framework for building powerful, user-friendly, GraalVM-enabled command line apps with ease. It supports colors, autocompletion, subcommands, and more. In 1 source file so apps can include as source & avoid adding a dependency. Written in Java, usable from Groovy, Kotlin, Scala, etc.
Stars: ✭ 3,286 (+3029.52%)
Mutual labels:  commandline, command-line-parser
cmdr
POSIX-compliant command-line UI (CLI) parser and Hierarchical-configuration operations
Stars: ✭ 94 (-10.48%)
Mutual labels:  commandline, command-line-parser
CommandLineParser.Core
💻 A simple, light-weight and strongly typed Command Line Parser made in .NET Standard!
Stars: ✭ 32 (-69.52%)
Mutual labels:  commandline, command-line-parser
commandeer
Take command of your command line in Nim
Stars: ✭ 84 (-20%)
Mutual labels:  commandline, command-line-parser
simplecli
The simplest way to parse cli arguments in golang
Stars: ✭ 15 (-85.71%)
Mutual labels:  commandline
hacker
Hack on your project easily. A liftoff proof-of-concept.
Stars: ✭ 21 (-80%)
Mutual labels:  flags
discord-message-handler
Message and command handler for discord.js bots and applications
Stars: ✭ 19 (-81.9%)
Mutual labels:  command-line-parser
note-keeper
📓 A tiny bash tool for taking and organizing notes.
Stars: ✭ 58 (-44.76%)
Mutual labels:  commandline
nice
Highly customizable and idiomatic Go CLI app framework 👌
Stars: ✭ 198 (+88.57%)
Mutual labels:  commandline
debayer
Debayer raw images automatically, with the option of outputting scene-linear aces exrs.
Stars: ✭ 26 (-75.24%)
Mutual labels:  commandline
react-flagkit
🇺🇦 React wrapper for FlagKit Flag Icons
Stars: ✭ 21 (-80%)
Mutual labels:  flags
vt100
💻 VT100 Terminal Package
Stars: ✭ 19 (-81.9%)
Mutual labels:  commandline
cotp
Trustworthy, encrypted, command-line TOTP/HOTP authenticator app with import functionality.
Stars: ✭ 45 (-57.14%)
Mutual labels:  commandline
flagg
Barebones subcommand handling
Stars: ✭ 55 (-47.62%)
Mutual labels:  flags
argum
Parse incoming arguments in to structure
Stars: ✭ 18 (-82.86%)
Mutual labels:  flags
select-run
A CLI tool to interactively search & select one or many package.json npm scripts to run
Stars: ✭ 29 (-72.38%)
Mutual labels:  commandline
Data-Scientist-In-Python
This repository contains notes and projects of Data scientist track from dataquest course work.
Stars: ✭ 23 (-78.1%)
Mutual labels:  commandline
swift-commandlinekit
Framework supporting the development of command-line tools in Swift on macOS and Linux. The framework supports managing command-line arguments, provides lightweight functions to deal with escape sequences, and defines an API for reading strings from the terminal.
Stars: ✭ 38 (-63.81%)
Mutual labels:  flags
pflag
Generic PHP command line flags parse library
Stars: ✭ 14 (-86.67%)
Mutual labels:  flags
prettyBenching
🦕 A small lib to make your Deno benchmarking progress and results look pretty
Stars: ✭ 23 (-78.1%)
Mutual labels:  commandline

Utility.CommandLine.Arguments

Build status Build Status codecov Quality Gate Status NuGet version License: MIT

A C# .NET Class Library containing tools for parsing the command line arguments of console applications.

Why?

I needed a solution for parsing command line arguments and didn't like the existing options.

Installation

Install from the NuGet gallery GUI or with the Package Manager Console using the following command:

Install-Package Utility.CommandLine.Arguments

The code is also designed to be incorporated into your project as a single source file (Arguments.cs).

Quick Start

Create private static properties in the class containing your Main() and mark them with the Argument attribute, assigning short and long names. Invoke the Arguments.Populate() method within Main(), then implement the rest of your logic.

The library will populate your properties with the values specified in the command line arguments.

internal class Program
{
    // [Argument(short name (char), long name (string), help text)]
    [Argument('b', "myBool", "a boolean value")]
    private static bool Bool { get; set; }

    [Argument('f', "someFloat")]
    private static double Double { get; set; }

    [Argument('i', "anInteger")]
    private static int Int { get; set; }

    [Argument('s', "aString")]
    private static string[] String { get; set; }

    [Operands]
    private static string[] Operands { get; set; }

    private static void Main(string[] args)
    {
        Arguments.Populate();

        Console.WriteLine("Bool: " + Bool);
        Console.WriteLine("Int: " + Int);
        Console.WriteLine("Double: " + Double);

        foreach (string s in String)
        {
            Console.WriteLine("String: " + s);
        }

        foreach (string operand in Operands) 
        {
            Console.WriteLine("\r\n Operand:" + operand);
        }
    }
}

Grammar

The grammar supported by this library is designed to follow the guidelines set forth in the publication The Open Group Base Specifications Issue 7, specifically the content of Chapter 12, Utility Conventions, located here.

Each argument is treated as a key-value pair, regardless of whether a value is present. The general format is as follows:

<-|--|/>argument-name<=|:| >["|']value['|"] [--] [operand] ... [operand]

The key-value pair may begin with a single hyphen, a pair of hyphen, or a forward slash. Single and double dashes indicate the use of short or long names, respectively, which are covered below. The forward slash may represent either a sort or long name but does not allow for the grouping of parameterless arguments (e.g. /abc is not equivalent to -abc, but rather --abc).

The argument name may be a single character when using short names, or any alphanumeric sequence not including spaces if using long names.

The value delimiter may be an equals sign, a colon, or a space.

Values may be any alphanumeric sequence, however if a value contains a space it must be enclosed in either single or double quotes.

Any word, or phrase enclosed in single or double quotes, will be parsed as an operand. The official specification requires operands to appear last, however this library will parse them in any position.

A double-hyphen -- not enclosed in single or double quotes and appearing with whitespace on either side designates the end of the argument list and beginning of the explicit operand list. Anything appearing after this delimiter is treated as an operand, even if it begins with a hyphen, double-hyphen or forward slash.

Short Names

Short names consist of a single character, and arguments without parameters may be grouped. A grouping may be terminated with a single argument containing a parameter. Arguments using short names must be preceded by a single dash.

Examples

Single argument with a parameter: -a foo

Key Value
a foo

Two parameterless arguments: -ab

Key Value
a
b

Three arguments; two parameterless followed by a third argument with a parameter: -abc bar

Key Value
a
b
c bar

Long Names

Long names can consist of any alphanumeric string not containing a space. Arguments using long names must be preceded by two dashes.

Examples

Single argument with a parameter: --foo bar

Key Value
foo bar

Two parameterless arguments: --foo --bar

Key Value
foo
bar

Two arguments with parameters: --foo bar --hello world

Key Value
foo bar
hello world

Mixed Naming

Any combination of short and long names are supported.

Example

-abc foo --hello world /new="slashes are ok too"

Key Value
a
b
c foo
hello world
new slashes are ok too

Multiple Values

Arguments can accept multiple values, and when parsed a List<object> is returned if more than one value is specified. When using the Populate() method the underlying property for an argument accepting multiple values must be an array or List, otherwise an InvalidCastException is thrown.

Example

--list 1 --list 2 --list 3

Key Value
list 1,2,3

Operands

Any text in the string that doesn't match the argument-value format is considered an operand. Any text which appears after a double-hyphen -- not enclosed in single or double quotes and with spaces on either side is treated as an operand regardless of whether it matches the argument-value format.

Example

-a foo bar "hello world" -b -- -explicit operand

Key Value
a foo
b

Operands

  1. bar
  2. "hello world"
  3. -explicit
  4. operand

Parsing

Argument key-value pairs can be parsed from any string using the Parse(string) method. This method returns a Dictionary<string, object> containing all argument-value pairs.

If the string parameter is omitted, the value of Environment.CommandLine is used.

Note that passing the args variable, or the result of String.Join() on args, will prevent the library from property handling quoted strings. There are generally very few instance in which Environment.CommandLine should not be used.

Example

Dictionary<string, object> args = Arguments.Parse("-ab --foo bar");

The example above would result in a dictionary args containing:

Key Value
a
b
foo bar

Note that boolean values should be checked with Dictionary.ContainsKey("name"); the result will indicate whether the argument was encountered in the command line arguments. All other values are retrieved with Dictionary["key"].

Populating

The Populate() method uses reflection to populate private static properties in the target Type with the argument values matching properties marked with the Argument attribute.

The list of operands is placed into a single property marked with the Operands attribute. This property must be of type string[] or List<string>.

Creating Target Properties

Use the Argument attribute to designate properties to be populated. The constructor of Argument accepts a char, a string, and an additional string, representing the short and long names of the argument, and help text, respectively.

Note that the name of the property doesn't matter; only the attribute values are used to match an argument key to a property.

The Type of the property does matter; the code attempts to convert argument values from string to the specified Type, and if the conversion fails an ArgumentException is thrown.

Properties can accept lists of parameters, as long as they are backed by an array or List<>. Specifying multiple parameters for an argument backed by an atomic Type (e.g. not an array or List) will result in an InvalidCastException.

The Operands property accepts no parameters. If the property type is not string[] or List<string>, an InvalidCastException will be thrown.

Examples

[Argument('f', "foo", "some help text")]
private static string Foo { get; set; }

[Argument('n', "number")]
private static integer MyNumber { get; set; }

[Argument('b', "bool")]
private static bool TrueOrFalse { get; set; }

[Argument('l', "list")]
private static string[] List { get; set; }

[Operands]
private static List<string> Operands { get; set; }

Given the argument string -bf "bar" --number=5 --list 1 --list 2, the resulting property values would be as follows:

Property Value
Foo bar
MyNumber 5
TrueOrFalse true
List 1,2

Obtaining Help

A collection of ArgumentHelp containing the short and long names and help text for each argument property can be fetched with GetArgumentHelp():

private static void ShowHelp()
{
    var helpAttributes = Arguments.GetArgumentHelp(typeof(Program));

    Console.WriteLine("Short\tLong\tFunction");
    Console.WriteLine("-----\t----\t--------");

    foreach (var item in helpAttributes)
    {
        var result = item.ShortName + "\t" + item.LongName + "\t" + item.HelpText;
        Console.WriteLine(result);
    }
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].