Skip to content

Instantly share code, notes, and snippets.

@jsmarble jsmarble/Argument.cs
Last active Apr 26, 2016

Embed
What would you like to do?
argument-parser
public class Argument
{
public Argument(string prefix)
: this(prefix, null)
{
}
public Argument(string prefix, IEnumerable<string> values)
{
this.Values = new List<string>();
this.Prefix = prefix;
if (values != null)
this.Values.AddRange(values);
}
public string Prefix { get; private set; }
public List<string> Values { get; private set; }
}
public class ArgumentList : List<Argument>
{
public ArgumentList()
{
}
public ArgumentList(IEnumerable<Argument> collection) : base(collection)
{
}
public List<Argument> Find(params string[] prefixes)
{
return this.Where(x => prefixes.Contains(x.Prefix, StringComparer.CurrentCultureIgnoreCase)).ToList();
}
public string GetValue(params string[] prefixes)
{
return Find(prefixes).FirstOrDefault()?.Values.FirstOrDefault();
}
}
public class ArgumentParser
{
public static readonly char[] ArgumentPrefixes;
static ArgumentParser()
{
ArgumentParser.ArgumentPrefixes = BuildArgumentPrefixes();
}
public ArgumentList Parse(string[] args)
{
ArgumentList results = new ArgumentList();
Argument currentArg = null;
Argument blankArg = new Argument("");
foreach (string arg in args)
{
if (ValueIsArgPrefix(arg))
{
var a = arg.TrimStart(ArgumentParser.ArgumentPrefixes);
currentArg = results.Find(a).FirstOrDefault();
if (currentArg == null)
{
currentArg = new Argument(a);
results.Add(currentArg);
}
}
else
{
Argument a = currentArg ?? blankArg;
a.Values.Add(arg);
currentArg = null;
}
}
if (blankArg.Values.Count > 0)
results.Add(blankArg);
return results;
}
private static bool ValueIsArgPrefix(string value)
{
if (string.IsNullOrEmpty(value))
return false;
return ArgumentParser.ArgumentPrefixes.Any(c => value[0] == c);
}
private static char[] BuildArgumentPrefixes()
{
return new char[] { '-', '/' };
}
}
@jsmarble

This comment has been minimized.

Copy link
Owner Author

commented Apr 26, 2016

Argument Parser

Description

A set of C# classes for intelligently parsing command line arguments into a usable collection of arguments and values.

Usage

ArgumentParser

The main class used is ArgumentParser. Instantiate an instance of ArgumentParser then call the Parse() function, passing in string[] args. The result of the function is an ArgumentList object, containing Argument objects representing the arguments passed. The ArgumentParser combines arguments with the same prefixes and aggregates the values. ArgumentParser will also include a "blank" argument, containing the values that were not prefixed with an argument, if any exist.

ArgumentParser supports arguments using either - or / prefixes for arguments. It also supports -- with full argument names. Arguments may be specified without any values as well.

Examples

Arguments: "--user bob -p"
Result (visualized in JSON):
[ {"prefix":"user", "values": [ "bob" ]}, {"prefix":"p", "values": []} ]

Arguments: "-a sha1 File1.txt -a sha256 File2.txt -o output.txt"
Result (visualized in JSON):
[ {"prefix":"a", "values": [ "sha1", "sha256" ]}, {"prefix":"o", "values": [ "output.txt" ]}, {"prefix":"", "values": [ "File1.txt", "File2.txt" ]} ]

ArgumentList

ArgumentList also contains a Find() method to help find arguments. It supports passing multiple argument and will return an ArgumentList with just the desired arguments. Omit the argument prefix for the desired arguments.

Examples
var args = parser.Parse(argsString);
var userNames = args?.Find("u", "user")?.SelectMany(x => x.Values);

License

MIT License

Copyright (c) [2016] [jsmarble]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.