Class CommandLine
Performs common operations on application a DOS or Linux command line.
Namespace: Neon.Common
Assembly: Neon.Common.dll
Syntax
public sealed class CommandLine
Remarks
Command lines may consist of zero or more items. Items that begin with the dash (-) character are considered to be command line options. Items that begin with an at sign (@) can be considered to be response files, and all other items are considered to be command line arguments.
note
The "-" and "--" items (without an option name are considered arguments, not options.
The static ExpandFiles(string[]) method can be used to process response files specified in a command line. Response files are specified by prepending a '@' character to the name of a text file and then treating each line of the file as a command line item.
The static ExpandWildcards(string) method can be used to expand file names with wildcard characters into the set of actual files that match the pattern.
The CommandLine class can also handles parsing of items as command line options.
--<option name>[=<value>]
You can also use single or double quotes around option values that
include spaces or other special characters:
--<option name>[='<value>']
--<option name>[="<value>"]
will be parsed into name/value pairs and will be available for lookup via the string keyed indexer. Options that specify no value will be assigned an empty string value.
note
Command line option names are case sensitive.
The class will also make all command line items available via the integer keyed indexer which will return items based on their position on the command line and also via the Items property. Command line items that are not command, are available via the Arguments property. Options can be looked up via the GetOption(string, string) and GetOptionValues(string) overrides.
CommandLine also supports the definition of long and short forms of options with optional default values using the DefineOption(params string[]) method. This associates one or more option names with an optional default value.
You can use this easily implement the short and long forms of options as well as to centralize the specification of option default values.
var commandLine = new CommandLine(args);
commandLine.DefineOption("-q", "--quiet");
commandLine.DefineOption("-k", "--key").Default = "none";
// These calls both return the option value for "-q" or "--quiet".
// Since no default value was set, the default value will be the
// empty string.
commandLine.GetOption("-q");
commandLine.GetOption("--quiet");
// These calls both return the option value for "-k" or "--key".
// The default value will be "none".
commandLine.GetOption("-k");
commandLine.GetOption("--key");
note
This class assumes that the position of command line options doesn't matter, which is somewhat simplistic. In particular, the Shift(int, string) method actually relocates all of the options to the beginning of the shifted command line.
Constructors
CommandLine(params object[])
Constructs an instance optionally expanding any response files specified in the arguments passed.
Declaration
public CommandLine(params object[] args)
Parameters
Type | Name | Description |
---|---|---|
object[] | args | The optional command line arguments. |
Properties
Arguments
Returns the array of command line values (items that are not command line options).
Declaration
public string[] Arguments { get; }
Property Value
Type | Description |
---|---|
string[] |
HasHelpOption
Determines if the --help command line option is present.
Declaration
public bool HasHelpOption { get; }
Property Value
Type | Description |
---|---|
bool |
|
this[int]
Returns an item from the command line based on its position.
Declaration
public string this[int index] { get; }
Parameters
Type | Name | Description |
---|---|---|
int | index | The zero-based position of the desired argument. |
Property Value
Type | Description |
---|---|
string | The argument string. |
Items
Returns the array of command line arguments (including both command line options and values).
Declaration
public string[] Items { get; }
Property Value
Type | Description |
---|---|
string[] |
Options
Returns the command line options as a dictionary of option name/value tuples.
Declaration
public Dictionary<string, string> Options { get; }
Property Value
Type | Description |
---|---|
Dictionary<string, string> |
Original
Returns the original unshifted command line.
Declaration
public CommandLine Original { get; }
Property Value
Type | Description |
---|---|
CommandLine |
Methods
DefineOption(params string[])
Adds an option definition to the command line and returns the definition so its default value may be set if desired.
Declaration
public CommandLine.OptionDefinition DefineOption(params string[] names)
Parameters
Type | Name | Description |
---|---|---|
string[] | names | The option names (e.g. the short and long form). |
Returns
Type | Description |
---|---|
CommandLine.OptionDefinition |
Remarks
You can use this easily implement the short and long forms of options as well as to centralize the specification of option default values.
var commandLine = new CommandLine(args);
commandLine.DefineOption("-q", "--quiet");
commandLine.DefineOption("-k", "--key").Default = "none";
// These calls both return the option value for "-q" or "--quiet".
// Since no default value was set, the default value will be the
// empty string.
commandLine.GetOption("-q");
commandLine.GetOption("--quiet");
// These calls both return the option value for "-k" or "--key".
// The default value will be "none".
commandLine.GetOption("-k");
commandLine.GetOption("--key");
ExpandFiles(string[])
Expands the command line by processing items beginning with '@' as input files.
Declaration
public static string[] ExpandFiles(string[] args)
Parameters
Type | Name | Description |
---|---|---|
string[] | args | The command line arguments. |
Returns
Type | Description |
---|---|
string[] | The set of expanded items. |
Remarks
Command line items will be assumed to specify a text file name after the '@'. This file will be read and each non-empty line of text will be inserted as a command line parameter.
Lines of text whose first non-whitespace character is a pound sign (#) will be ignored as comments.
Command line parameters may also span multiple lines by beginning the parameter with a line of text begininning with "{{" and finishing it with a line of text containing "}}". In this case, the command line parameter will be set to the text between the {{...}} with any CRLF sequences replaced by a single space.
Here's an example:
# This is a comment and will be ignored
-param1=aaa
-param2=bbb
{{
-param3=hello
world
}}
This will be parsed as three command line parameters: -param1=aaa, -param2=bbb, and -param3=hello world
Exceptions
Type | Condition |
---|---|
IOException | Thrown if there's a problem opening an "@" input file. |
FormatException | Thrown if there's an error parsing an "@" input file. |
ExpandWildcards(string)
Checks the argument passed for wildcards and expands them into the appopriate set of matching file names.
Declaration
public static string[] ExpandWildcards(string path)
Parameters
Type | Name | Description |
---|---|---|
string | path | The file path potentially including wildcards. |
Returns
Type | Description |
---|---|
string[] | The set of matching file names. |
Format(params object[])
Formats an array of objects into a form suitable for passing to a process on the command line by adding double quotes around any values with embedded spaces.
Declaration
public static string Format(params object[] args)
Parameters
Type | Name | Description |
---|---|---|
object[] | args | The arguments to be formatted. |
Returns
Type | Description |
---|---|
string | the formatted string. |
Exceptions
Type | Condition |
---|---|
FormatException | Thrown if any of the arguments contain double quote or any other invalid characters. |
GetArguments(int)
Enumerates the command line arguments beginning at the specified index.
Declaration
public IEnumerable<string> GetArguments(int startIndex = 0)
Parameters
Type | Name | Description |
---|---|---|
int | startIndex | The index of the first argument to be returned. |
Returns
Type | Description |
---|---|
IEnumerable<string> | The enumerated arguments. |
GetFlag(string)
Determines whether an option is present on the command line.
Declaration
public bool GetFlag(string optionName)
Parameters
Type | Name | Description |
---|---|---|
string | optionName | The case sensitive option name (including the leading dashes (-). |
Returns
Type | Description |
---|---|
bool | The option value if present, the specified default value otherwise. |
GetOption(string, string)
Returns the value associated with a command line option if the option was present on the command line otherwise, the specified default value will be returned.
Declaration
public string GetOption(string optionName, string def = null)
Parameters
Type | Name | Description |
---|---|---|
string | optionName | The case sensitive option name (including the leading dashes (-). |
string | def | The default value. |
Returns
Type | Description |
---|---|
string | The option value if present, the specified default value otherwise. |
Remarks
If the optionName
was included in a previous DefineOption(params string[])
call, then all aliases for the option will be searched. If the option is not
present on the command line and def
is null
, then the default
defined default value will be returned otherwise def
will override
the definition.
GetOptionValues(string)
Returns all of the values a command line option that appears multiple times in the command.
Declaration
public string[] GetOptionValues(string optionName)
Parameters
Type | Name | Description |
---|---|---|
string | optionName | The case sensitive option name (including the leading dashes (-). |
Returns
Type | Description |
---|---|
string[] | The array of values found sorted in the same order thney appear in the command line. |
Remarks
note
Only command line options that actually specify a value using the colon (=) syntax are returned by this method.
If the optionName
was included in a previous DefineOption(params string[])
call, then all aliases for the option will be searched.
HasOption(string)
Determines if an option was present on the command line.
Declaration
public bool HasOption(string optionName)
Parameters
Type | Name | Description |
---|---|---|
string | optionName | The case sensitive option name (including the leading dashes (-). |
Returns
Type | Description |
---|---|
bool |
|
Remarks
If the optionName
was included in a previous DefineOption(params string[])
call, then all aliases for the option will be searched.
Parse(string)
Parses the argument string passed into a CommandLine instance, dealing with quoted parameters, etc.
Declaration
public static CommandLine Parse(string input)
Parameters
Type | Name | Description |
---|---|---|
string | input | The argument string. |
Returns
Type | Description |
---|---|
CommandLine | The parsed CommandLine. |
Preprocess(Dictionary<string, string>, Regex)
Preprocesses the command line by using PreprocessReader to replace any environment variable, profile, or secret references in the command line arguments, like:
$(env:VARIABLE) | Replaced with the environment VARIABLE |
$(profile:VALUE) | Replaced with the profile VALUE |
${password:SECRET} | Replaced with the password field of the SECRET |
${password:SECRET:SOURCE} | Replaced with the password field of the SECRET obtained from SOURCE |
${password:SECRET[PROPERTY]} | Replaced with the PROPERTY field of the SECRET |
${password:SECRET[PROPERTY]:SOURCE} | Replaced with the PROPERTY field of the SECRET obtained from SOURCE |
note
IMORTANT: You'll probably need to surround variable references with single quotes on Linux to prevent Bash from interpreting these as Bash variables.
note
IMPORTANT: You must register an IProfileClient implementation with ServiceContainer for this to work.
Declaration
public CommandLine Preprocess(Dictionary<string, string> variables = null, Regex variableRegex = null)
Parameters
Type | Name | Description |
---|---|---|
Dictionary<string, string> | variables | Optionally specifies variables to be incuded in the preprocessing. |
Regex | variableRegex | Optionally specifies the regular expression that will be used to locate and process any variable references. This defaults to CurlyVariableExpansionRegex but may be set to any expressions supported by PreprocessReader. |
Returns
Type | Description |
---|---|
CommandLine | A new CommandLine including any changes. |
Shift(int, string)
Returns a new CommandLine which includes all of the command line options and the arguments starting at the position passed to the end of the command line, essentially shifting arguments to the left.
Declaration
public CommandLine Shift(int position, string splitter = "--")
Parameters
Type | Name | Description |
---|---|---|
int | position | The index of the first argument to be included in the result. |
string | splitter | The optional argument used to ensure that we're only shifting the left
side of a command line. This defaults to "--" but may be set to
|
Returns
Type | Description |
---|---|
CommandLine | The new CommandLine. |
Split(string, bool)
Splits the command line into two parts, the command line to the left of the first specified item (defaults to "--") and the command line to the right of it.
Declaration
public (CommandLine Left, CommandLine Right) Split(string splitter = "--", bool addSplitterToRight = false)
Parameters
Type | Name | Description |
---|---|---|
string | splitter | The split item (defaults to "--"). |
bool | addSplitterToRight | Optionally specifies that the split item should be included in the right command line returned. |
Returns
Type | Description |
---|---|
(CommandLine Left, CommandLine Right) | A tuple with Left and Right properties. |
Remarks
note
The Left command line will return with a copy of the original option definitions.
note
If there is no split item present, then Right will be null
.
StartsWithArgs(params string[])
Determines whether the command line starts with the specified arguments.
Declaration
public bool StartsWithArgs(params string[] args)
Parameters
Type | Name | Description |
---|---|---|
string[] | args | The non- |
Returns
Type | Description |
---|---|
bool |
|
Remarks
note
The argument comparison is case sensitive.
ToFormatted(string, bool, bool, Redactor)
Converts the command line into a nicely formatted (potentially multi-line) string suitable for including in logs.
Declaration
public string ToFormatted(string programName, bool withBars = false, bool withLineContinuation = false, CommandLine.Redactor redactor = null)
Parameters
Type | Name | Description |
---|---|---|
string | programName | Specifies the program name. |
bool | withBars | Optionally include bars above and below the formatted command. |
bool | withLineContinuation | Optionally include line continuation characters appropriate for the current operating system. |
CommandLine.Redactor | redactor | Optionally passed as a redactor. See CommandLine.Redactor. |
Returns
Type | Description |
---|---|
string | The formatted string. |
ToString()
Renders the command line as a string suitable for presenting to a process or a command line shell. Arguments that include spaces will be enclosed in double quotes.
Declaration
public override string ToString()
Returns
Type | Description |
---|---|
string | The command line string. |
Overrides
Exceptions
Type | Condition |
---|---|
InvalidOperationException | Thrown if a command line argument includes both single and double quotes. |