• Stars
    star
    118
  • Rank 298,527 (Top 6 %)
  • Language
    C#
  • License
    MIT License
  • Created over 7 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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);
    }
}

More Repositories

1

Soulseek.NET

A .NET Standard client library for the Soulseek network.
C#
168
star
2

ILMergeGUI

Unofficial fork of ILMergeGUI from CodePlex (https://ilmergegui.codeplex.com/)
C#
73
star
3

NLog.xLogger

A C# .NET class library that extends NLog.Logger to provide additional functionality for tracing the entry and exit, arbitrary checkpoints, exceptions and stack traces within methods.
C#
34
star
4

SWoT

A web application for designing, tracking, and reporting progress on workouts. Written in JavaScript with React, Redux, Material UI, and hosted by a serverless AWS backend.
JavaScript
15
star
5

B2MML.NET

A C# .NET class library containing an implementation of the MESA International standards B2MML and BatchML.
C#
13
star
6

slack-desktop-dark-theme

My Frankensteined CSS to add a dark theme to the Slack desktop app, based on slack-black-theme.
CSS
13
star
7

Utility.CommandLine.Progress

A C# .NET class library containing tools for displaying progress in console applications.
C#
11
star
8

brainz

A lightweight MusicBrainz CLI in Go.
Go
8
star
9

Utility.OperationResult

A C# .NET class library designed to represent the result of an operation. Includes a result code and a list of messages generated during the operation.
C#
7
star
10

NLog.RealtimeLogger

A C# .NET class library that works in conjunction with the NLog 'MethodCall' logging target to expose log messages via an event in real time.
C#
7
star
11

KPI-ML.NET

A C# .NET class library containing an implementation of the MESA International standard KPI-ML.
C#
5
star
12

Utility.BigFont

A C# .NET class library for transforming strings into large, stylized characters.
C#
4
star
13

AWSPricingExplorer

A microservice for the AWS Pricing Api, written in JavaScript with Express, React, and blueprintjs.
JavaScript
4
star
14

B2MML4j

A Java package containing an implementation of the MESA International standards B2MML and BatchML.
Java
4
star
15

FileHistorian

A C# .NET application to keep track of changes to a filesystem.
C#
3
star
16

Functal

Decompiled source from the Functal library (https://functal.com/)
C#
3
star
17

Utility.PGPSignatureTools

A C# .NET class library for signing and verifying data using PGP encryption.
C#
3
star
18

SeedboxSync

A Java console application for syncing files with a seedbox account via FTP.
Java
2
star
19

CalcuPlate

A cross-platform mobile application for calculating barbell plate configurations, written in React Native.
JavaScript
2
star
20

HMACAuth

HMAC authentication for ASP.NET
C#
2
star
21

MTS-2.0-Documentation

Design documentation for a next-gen (circa 2005) mIRC theming standard
HTML
2
star
22

backend-seed

A backend application project seed in C# .NET.
JavaScript
2
star
23

SWoT-Backend

JavaScript
1
star
24

Archivist

A simple Golang application for tracking changes to files and directories on a system.
Go
1
star
25

deployments

Testing GitHub deployments APIs
HTML
1
star
26

Socks5.NET

A quick implementation of a SOCKS5 proxy client through TcpClient
C#
1
star
27

LazyCsv

Experimenting with an on-demand CSV parser
C#
1
star
28

react-sandbox

JavaScript
1
star
29

KPI-ML4j

A Java package containing an implementation of the MESA International standard KPI-ML.
Java
1
star
30

2opt.NET.WinForms

Crappy Windows forms application for visualizing 2opt.NET results.
C#
1
star
31

ServerlessTask

1
star
32

Governor

Proof of concept for a multi-tier bandwidth limiting algorithm
C#
1
star
33

FileWatcher

A quick and simple implementation of Microsoft's FileSystemWatcher to track and monitor changes to files on my computer.
C#
1
star
34

Scorecard

A proof of concept for a generic scorecard application
C#
1
star
35

stig-service

A service to track STIGs
JavaScript
1
star
36

SqlBulkCopyBenchmark

.NET Core console application for testing performance aspects of SqlBulkCopy against indexed and non-indexed tables
C#
1
star
37

sfn-syncex

A node.js script for synchronous execution of an AWS Step Function
JavaScript
1
star
38

SQLite-Benchmarks

Benchmarking various SQLite use cases
C#
1
star
39

DotnetCoreWorker

Experimenting with IHostedService
C#
1
star
40

pd-cci-test

1
star
41

github-action

Proof of concept for a custom GitHub action
JavaScript
1
star
42

SpanBenchmark

A quick .NET Core 2.1 application to examine the performance of the new Span<T>
C#
1
star
43

use-github-action

Uses the custom action created in the `github-action` repo
1
star
44

cypress-test

JavaScript
1
star
45

Channels

Playing around with .NET's Channel<T>
C#
1
star
46

Battleship

A simple Battleship game written in Java in 2005.
Java
1
star
47

rails-blog

Repository for the 'Getting Started with Rails' tutorial.
Ruby
1
star
48

slack-desktop-patcher

A console application to patch the Slack (4.x) desktop application to load custom CSS, written in Go.
Go
1
star
49

2opt.NET

An implementation of the 2-opt algorithm in .NET Core 2.
C#
1
star
50

circleci-test-report

Proof of concept for fetching test data from the CircleCI API during a workflow run
JavaScript
1
star
51

HTTPSStreaming

A proof of concept for concurrent file streaming over HTTPS
C#
1
star
52

Serverless

JavaScript
1
star
53

graphql-sandbox

Playing around with GraphQL
JavaScript
1
star
54

ColloquialTypeName

C# method to return a colloquial or "pretty" name for a given Type
C#
1
star
55

Sokoban

A Sokoban game written in VB6, made in 2002.
Visual Basic
1
star
56

apm-sandbox

Sandbox for testing APM with Prometheus, Grafana and Loki
C#
1
star
57

Kodi-StereoSnitch

A Python script which searches a directory of files for Kodi metadata and reports any files with a stereo (two channel) audio track.
Python
1
star
58

frisbee

Free ESB
Java
1
star
59

dotnetAPM

Quick WebAPI for testing APM with AppMetrics and Prometheus
C#
1
star
60

FunWithWebApi

C#
1
star
61

lets-code-ci-session-2

Let's Code: Unit Testing and Continuous Integration Part 2: C# .NET
C#
1
star
62

DotNetCore-Lambda

A quick .NET Core 2.1 Web API implementation for AWS Lambda
C#
1
star
63

circleci-insights-summary

Fetches Insights Summary data from Circle CI
JavaScript
1
star
64

VSTSTest

Testing VSTS build pipelines originating from GitHub
TypeScript
1
star
65

Utility.Extensions.Configuration.Yaml

A C# .NET Class Library containing an IConfigurationSource for Yaml files.
C#
1
star
66

WCFApi

A simple .NET 3.5 console application demonstrating how to host a RESTful API with WCF
C#
1
star
67

aws-lambda-express-bare-bones

A bare-bones, bare minimum implementation of an AWS Lambda script using Express.js
JavaScript
1
star
68

backstage

Trying out Backstage: https://backstage.io/
TypeScript
1
star
69

serverless-todo

A serverless AWS todo app for QC Coders.
JavaScript
1
star
70

OnAir

C#
1
star
71

lets-code-ci-session-1

Let's Code: Unit Testing and Continuous Integration Part 1: JavaScript
JavaScript
1
star
72

ServerlessExpress

JavaScript
1
star
73

dump-urself

A .NET console application that dumps its own memory using dotnet-dump
C#
1
star
74

nodets

TypeScript
1
star
75

MetadataBenchmark

Benchmarking music file metadata libraries
C#
1
star
76

dagger

Testing Dagger (dagger.io)
JavaScript
1
star
77

Utility.EnvironmentVariables

A C# .NET Class Library containing tools for populating properties from environment variables.
C#
1
star
78

ConsoleService.NET

A C# .NET project template for a Windows service application which also runs as a console application in user mode and/or on non-Windows platforms.
C#
1
star