Completed the command line parser, then decided while adding result validation to the unit tests that the parser should be greedy (and accept option initiators within option names) - I don't like the way the parser code turned out anyway, so I'll rewrite soon

git-svn-id: file:///srv/devel/repo-conversion/nusu@107 d2e56fa2-650e-0410-a79f-9358c0239efd
This commit is contained in:
Markus Ewald 2008-12-11 20:15:21 +00:00
parent ffba112786
commit 9c40abe10a
6 changed files with 676 additions and 148 deletions

13
Documents/CommandLine.txt Normal file
View File

@ -0,0 +1,13 @@
 /*
struct CommandLine {
[Option]
bool? Option;
[Option]
int? Width;
[Option]
TypeCode Code;
[Values]
string[] Values;
}
*/

View File

@ -246,6 +246,7 @@
</Compile> </Compile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Content Include="Documents\CommandLine.txt" />
<Content Include="Documents\Nuclex.Support.txt" /> <Content Include="Documents\Nuclex.Support.txt" />
<Content Include="Documents\Request Framework.txt" /> <Content Include="Documents\Request Framework.txt" />
</ItemGroup> </ItemGroup>

View File

@ -20,28 +20,114 @@ License along with this library
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
namespace Nuclex.Support.Parsing { namespace Nuclex.Support.Parsing {
partial class CommandLine { partial class CommandLine {
/// <summary>Option that can be specified on an application's command line</summary> /// <summary>Option being specified on an application's command line</summary>
public struct Option { public class Option {
/// <summary>Initializes a new option with only a name</summary>
/// <param name="raw">
/// String segment containing the entire option as it was given on the command line
/// </param>
/// <param name="nameStart">Absolute index the option name starts at</param>
/// <param name="nameLength">Number of characters in the option name</param>
/// <returns>The newly created option</returns>
internal Option(
StringSegment raw,
int nameStart, int nameLength
)
: this(raw, nameStart, nameLength, -1, -1) { }
/// <summary>Creates a new option with a name and an assigned value</summary>
/// <param name="raw">
/// String segment containing the entire option as it was given on the command line
/// </param>
/// <param name="nameStart">Absolute index the option name starts at</param>
/// <param name="nameLength">Number of characters in the option name</param>
/// <param name="valueStart">Absolute index the value starts at</param>
/// <param name="valueLength">Number of characters in the value</param>
/// <returns>The newly created option</returns>
internal Option(
StringSegment raw,
int nameStart, int nameLength,
int valueStart, int valueLength
) {
this.raw = raw;
this.nameStart = nameStart;
this.nameLength = nameLength;
this.valueStart = valueStart;
this.valueLength = valueLength;
Debug.Assert(this.nameStart != -1, "Name start index must not be -1");
Debug.Assert(this.nameLength != -1, "Name length must not be -1");
}
/// <summary>Contains the raw string the command line argument was parsed from</summary> /// <summary>Contains the raw string the command line argument was parsed from</summary>
public string Raw; // TODO: ToString() instead public string Raw {
/* get { return this.raw.ToString(); }
/// <summary>Method used to specify the argument (either '-', '--' or '/')</summary> }
public string Method;
*/ /// <summary>Characters used to initiate this option</summary>
/// <summary>Name of the command line argument</summary> public string Initiator {
public string Name; get {
/// <summary>Value that has been assigned to the command line argument</summary> return this.raw.Text.Substring(
public string Value; this.raw.Offset, this.nameStart - this.raw.Offset
/* );
/// <summary>Method used to assign the value (either '=', ':' or ' ')</summary> }
public string Assignment; }
*/
/// <summary>Name of the command line option</summary>
public string Name {
get {
return this.raw.Text.Substring(this.nameStart, this.nameLength);
}
}
/// <summary>Characters used to associate a value to this option</summary>
public string Associator {
get {
int associatorStart = this.nameStart + this.nameLength;
if(this.valueStart == -1) {
int characterCount = (this.raw.Offset + this.raw.Count) - associatorStart;
if(characterCount == 0) {
return null;
}
}
return this.raw.Text.Substring(associatorStart, 1);
}
}
/// <summary>Name of the command line option</summary>
public string Value {
get {
if(this.valueStart == -1) {
return null;
} else {
return this.raw.Text.Substring(this.valueStart, this.valueLength);
}
}
}
/// <summary>
/// Contains the entire option as it was specified on the command line
/// </summary>
private StringSegment raw;
/// <summary>Absolute index in the raw string the option name starts at</summary>
private int nameStart;
/// <summary>Number of characters in the option name</summary>
private int nameLength;
/// <summary>Absolute index in the raw string the value starts at</summary>
private int valueStart;
/// <summary>Number of characters in the value</summary>
private int valueLength;
} }
} }

View File

@ -21,6 +21,7 @@ License along with this library
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
namespace Nuclex.Support.Parsing { namespace Nuclex.Support.Parsing {
@ -30,16 +31,20 @@ namespace Nuclex.Support.Parsing {
private class Parser { private class Parser {
/// <summary>Initializes a new command line parser</summary> /// <summary>Initializes a new command line parser</summary>
private Parser() { /// <param name="windowsMode">Whether the / character initiates an argument</param>
private Parser(bool windowsMode) {
this.windowsMode = windowsMode;
this.commandLine = new CommandLine(); this.commandLine = new CommandLine();
} }
/// <summary>Parses a string containing command line arguments</summary> /// <summary>Parses a string containing command line arguments</summary>
/// <param name="commandLineString">String that will be parsed</param> /// <param name="commandLineString">String that will be parsed</param>
/// <param name="windowsMode">Whether the / character initiates an argument</param>
/// <returns>The parsed command line arguments from the string</returns> /// <returns>The parsed command line arguments from the string</returns>
public static CommandLine Parse(string commandLineString) { public static CommandLine Parse(string commandLineString, bool windowsMode) {
Parser theParser = new Parser(); Console.WriteLine("Parsing '" + commandLineString + "'");
theParser.parse(commandLineString); Parser theParser = new Parser(windowsMode);
theParser.parseFullCommandLine(commandLineString);
return theParser.commandLine; return theParser.commandLine;
} }
@ -50,7 +55,7 @@ namespace Nuclex.Support.Parsing {
/// <param name="commandLineString"> /// <param name="commandLineString">
/// String containing the command line arguments that will be parsed /// String containing the command line arguments that will be parsed
/// </param> /// </param>
private void parse(string commandLineString) { private void parseFullCommandLine(string commandLineString) {
if(commandLineString == null) { if(commandLineString == null) {
return; return;
} }
@ -69,7 +74,8 @@ namespace Nuclex.Support.Parsing {
// Parse the chunk of characters at this location and advance the index // Parse the chunk of characters at this location and advance the index
// to the next location after the chunk of characters // to the next location after the chunk of characters
index += parseCharacterChunk(commandLineString, index); parseChunk(commandLineString, ref index);
} }
} }
@ -82,7 +88,7 @@ namespace Nuclex.Support.Parsing {
/// </param> /// </param>
/// <param name="index">Index in the string at which to begin parsing</param> /// <param name="index">Index in the string at which to begin parsing</param>
/// <returns>The number of characters that were consumed</returns> /// <returns>The number of characters that were consumed</returns>
private int parseCharacterChunk(string commandLineString, int index) { private void parseChunk(string commandLineString, ref int index) {
int startIndex = index; int startIndex = index;
char currentCharacter = commandLineString[index]; char currentCharacter = commandLineString[index];
@ -94,45 +100,47 @@ namespace Nuclex.Support.Parsing {
// Does the string end here? Stop parsing. // Does the string end here? Stop parsing.
if(index >= commandLineString.Length) { if(index >= commandLineString.Length) {
addValue("-"); this.commandLine.addValue(new StringSegment(commandLineString, startIndex, 1));
break; break;
} }
// Does another '-' follow? Might be a unix style option or a loose "--" // Does another '-' follow? Might be a unix style option or a loose "--"
if(commandLineString[index] == '-') { if(commandLineString[index] == '-') {
++index; ++index;
index += parsePotentialOption(commandLineString, startIndex, index);
} else { // Nope, it's a normal option or a loose '-'
index += parsePotentialOption(commandLineString, startIndex, index);
} }
parsePotentialOption(commandLineString, startIndex, ref index);
break; break;
} }
// Windows style argument using '/' as its initiator // Windows style argument using '/' as its initiator
case '/': { case '/': {
// The '/ character is only used to initiate argument on windows and can be
// toggled off. The application decides, whether this is done depending on the
// operating system or whether uniform behavior across platforms is desired.
if(!this.windowsMode) {
goto default;
}
++index; ++index;
index += parsePotentialOption(commandLineString, startIndex, index); parsePotentialOption(commandLineString, startIndex, ref index);
break; break;
} }
// Quoted loose value // Quoted loose value
case '"': { case '"': {
StringSegment value = parseQuotedValue(commandLineString, index); parseQuotedValue(commandLineString, ref index);
index += value.Count + 1;
break; break;
} }
// Unquoted loose value // Unquoted loose value
default: { default: {
StringSegment value = parseNakedValue(commandLineString, index); parseNakedValue(commandLineString, ref index);
index += value.Count;
break; break;
} }
} }
return index - startIndex;
} }
/// <summary>Parses a potential command line option</summary> /// <summary>Parses a potential command line option</summary>
@ -144,111 +152,226 @@ namespace Nuclex.Support.Parsing {
/// Index at which the option name is supposed start (if it's an actual option) /// Index at which the option name is supposed start (if it's an actual option)
/// </param> /// </param>
/// <returns>The number of characters consumed</returns> /// <returns>The number of characters consumed</returns>
private int parsePotentialOption( private void parsePotentialOption(
string commandLineString, int initiatorStartIndex, int index string commandLineString, int initiatorStartIndex, ref int index
) { ) {
// If the string ends here this can only be considered as a loose value // If the string ends here this can only be considered as a loose value
if(index >= commandLineString.Length) { if(index == commandLineString.Length) {
addValue(commandLineString.Substring(initiatorStartIndex)); this.commandLine.addValue(
return 0; new StringSegment(
commandLineString,
initiatorStartIndex,
commandLineString.Length - initiatorStartIndex
)
);
return;
} }
int nameStartIndex = index;
// Look for the first character that ends the option. If it is not an actual option, // Look for the first character that ends the option. If it is not an actual option,
// the very first character might be the end // the very first character might be the end
int nameEndIndex = commandLineString.IndexOfAny(OptionNameEndingCharacters, index); index = commandLineString.IndexOfAny(OptionNameEndingCharacters, nameStartIndex);
if(nameEndIndex == -1) { if(index == -1) {
nameEndIndex = commandLineString.Length; index = commandLineString.Length;
} }
// If the first character of the supposed option is not valid for an option, // If the first character of the supposed option is not valid for an option name,
// we have to consider this to be a loose value // we have to consider this to be a loose value
if(nameEndIndex == index) { if(index == nameStartIndex) {
// Parse normal unquoted value index = commandLineString.IndexOfAny(WhitespaceCharacters, index);
//parseNakedValue(commandLineString, initiatorStartIndex).Count; if(index == -1) {
/* index = commandLineString.Length;
int endIndex = commandLineString.IndexOfAny(WhitespaceCharacters, index);
if(endIndex == -1) {
addValue(commandLineString.Substring(initiatorStartIndex));
return commandLineString.Length - index;
} else {
addValue(
commandLineString.Substring(initiatorStartIndex, endIndex - initiatorStartIndex)
);
return endIndex - index;
} }
*/
commandLine.addValue(
new StringSegment(
commandLineString, initiatorStartIndex, index - initiatorStartIndex
)
);
return;
} }
Console.WriteLine( parseOptionAssignment(
"Argument name: " + commandLineString.Substring(index, nameEndIndex - index) commandLineString, initiatorStartIndex, nameStartIndex, ref index
); );
// TODO: Parse argument value (if provided) here!!
return nameEndIndex - index;
} }
static readonly char[] OptionNameEndingCharacters = new char[] { /// <summary>Parses the value assignment in a command line option</summary>
' ', '\t', '=', ':', '/', '-', '+', '"' /// <param name="commandLineString">String containing the command line arguments</param>
}; /// <param name="initiatorStartIndex">
/// Position of the character that started the option
/// </param>
/// <param name="nameStartIndex">
/// Position of the first character in the option's name
/// </param>
/// <param name="index">Index at which the option name ended</param>
private void parseOptionAssignment(
string commandLineString, int initiatorStartIndex, int nameStartIndex, ref int index
) {
int nameEndIndex = index;
int valueStartIndex;
int valueEndIndex;
if(index == commandLineString.Length) {
valueStartIndex = -1;
valueEndIndex = -1;
} else {
char currentCharacter = commandLineString[index];
bool isAssignment =
(currentCharacter == ':') ||
(currentCharacter == '=');
// Does the string end after the suspected assignment character?
bool argumentEndReached = ((index + 1) == commandLineString.Length);
if(isAssignment) {
parseOptionValue(commandLineString, initiatorStartIndex, nameStartIndex, ref index);
return;
} else {
bool isModifier =
(currentCharacter == '+') ||
(currentCharacter == '-');
if(isModifier) {
valueStartIndex = index;
++index;
valueEndIndex = index;
} else {
valueStartIndex = -1;
valueEndIndex = -1;
}
}
}
int argumentLength = index - initiatorStartIndex;
this.commandLine.addOption(
new Option(
new StringSegment(commandLineString, initiatorStartIndex, argumentLength),
nameStartIndex, nameEndIndex - nameStartIndex,
valueStartIndex, valueEndIndex - valueStartIndex
)
);
}
/// <summary>Parses the value assignment in a command line option</summary>
/// <param name="commandLineString">String containing the command line arguments</param>
/// <param name="initiatorStartIndex">
/// Position of the character that started the option
/// </param>
/// <param name="nameStartIndex">
/// Position of the first character in the option's name
/// </param>
/// <param name="index">Index at which the option name ended</param>
private void parseOptionValue(
string commandLineString, int initiatorStartIndex, int nameStartIndex, ref int index
) {
int nameEndIndex = index;
int valueStartIndex, valueEndIndex;
// Does the string end after the suspected assignment character?
bool argumentEndReached = ((index + 1) == commandLineString.Length);
if(argumentEndReached) {
++index;
valueStartIndex = -1;
valueEndIndex = -1;
} else {
char nextCharacter = commandLineString[index + 1];
// Is this a quoted assignment
if(nextCharacter == '"') {
index += 2;
valueStartIndex = index;
index = commandLineString.IndexOf('"', index);
if(index == -1) {
index = commandLineString.Length;
valueEndIndex = index;
} else {
valueEndIndex = index;
++index;
}
} else { // Nope, assuming unquoted assignment or empty assignment
++index;
valueStartIndex = index;
index = commandLineString.IndexOfAny(WhitespaceCharacters, index);
if(index == -1) {
index = commandLineString.Length;
valueEndIndex = index;
} else {
if(index == valueStartIndex) {
valueStartIndex = -1;
valueEndIndex = -1;
} else {
valueEndIndex = index;
}
}
}
}
int argumentLength = index - initiatorStartIndex;
this.commandLine.addOption(
new Option(
new StringSegment(commandLineString, initiatorStartIndex, argumentLength),
nameStartIndex, nameEndIndex - nameStartIndex,
valueStartIndex, valueEndIndex - valueStartIndex
)
);
}
/// <summary>Parses a quoted value from the input string</summary> /// <summary>Parses a quoted value from the input string</summary>
/// <param name="commandLineString">String the quoted value is parsed from</param> /// <param name="commandLineString">String the quoted value is parsed from</param>
/// <param name="index">Index at which the quoted value begins</param> /// <param name="index">Index at which the quoted value begins</param>
/// <returns>A string segment containing the parsed quoted value</returns> private void parseQuotedValue(string commandLineString, ref int index) {
/// <remarks>
/// The returned string segment does not include the quotes.
/// </remarks>
private static StringSegment parseQuotedValue(string commandLineString, int index) {
char quoteCharacter = commandLineString[index]; char quoteCharacter = commandLineString[index];
++index; int startIndex = index + 1;
int endIndex = commandLineString.IndexOf(quoteCharacter, index); // Search for the closing quote
if(endIndex == -1) { index = commandLineString.IndexOf(quoteCharacter, startIndex);
endIndex = commandLineString.Length; if(index == -1) {
index = commandLineString.Length; // value ends at string end
commandLine.addValue(
new StringSegment(commandLineString, startIndex, index - startIndex)
);
} else { // A closing quote was found
commandLine.addValue(
new StringSegment(commandLineString, startIndex, index - startIndex)
);
++index; // Skip the closing quote
} }
// TODO: We don't skip the closing quote, the callee would have to detect it himself
return new StringSegment(commandLineString, index, endIndex - index);
} }
/// <summary>Parses a plain, unquoted value from the input string</summary> /// <summary>Parses a plain, unquoted value from the input string</summary>
/// <param name="commandLineString">String containing the value to be parsed</param> /// <param name="commandLineString">String containing the value to be parsed</param>
/// <param name="index">Index at which the value begins</param> /// <param name="index">Index at which the value begins</param>
/// <returns>A string segment containing the parsed value</returns> private void parseNakedValue(string commandLineString, ref int index) {
private static StringSegment parseNakedValue(string commandLineString, int index) { int startIndex = index;
int endIndex = commandLineString.IndexOfAny(WhitespaceCharacters, index);
if(endIndex == -1) { index = commandLineString.IndexOfAny(WhitespaceCharacters, index);
endIndex = commandLineString.Length; if(index == -1) {
index = commandLineString.Length;
} }
return new StringSegment(commandLineString, index, endIndex - index); commandLine.addValue(
} new StringSegment(commandLineString, startIndex, index - startIndex)
);
/// <summary>
/// Determines whether the specified character is valid as the first character
/// in an option
/// </summary>
/// <param name="character">Character that will be tested for validity</param>
/// <returns>True if the character is valid as the first character in an option</returns>
private static bool isValidFirstCharacterInOption(char character) {
const string InvalidCharacters = " \t=:/-+\"";
return (InvalidCharacters.IndexOf(character) == -1);
}
private void addValue(string value) {
Console.WriteLine("Added Value: '" + value + "'");
} }
/// <summary>Characters which end an option name when they are encountered</summary>
private static readonly char[] OptionNameEndingCharacters = new char[] {
' ', '\t', '=', ':', '/', '-', '+', '"'
};
/// <summary>Characters the parser considers to be whitespace</summary> /// <summary>Characters the parser considers to be whitespace</summary>
private static readonly char[] WhitespaceCharacters = new char[] { ' ', '\t' }; private static readonly char[] WhitespaceCharacters = new char[] { ' ', '\t' };
/// <summary>Command line currently being built by the parser</summary> /// <summary>Command line currently being built by the parser</summary>
private CommandLine commandLine; private CommandLine commandLine;
/// <summary>Whether the '/' character initiates an argument</summary>
private bool windowsMode;
} }

View File

@ -31,34 +31,218 @@ namespace Nuclex.Support.Parsing {
/// <summary>Ensures that the command line parser is working properly</summary> /// <summary>Ensures that the command line parser is working properly</summary>
[TestFixture] [TestFixture]
public class CommandLineTest { public class CommandLineTest {
/* #region class OptionTest
struct CommandLine {
[Option] /// <summary>Unit test for the command line option class</summary>
bool? Option; [TestFixture]
[Option] public class OptionTest {
int? Width;
[Option] /// <summary>
TypeCode Code; /// Verifies that the name of a command line option without a value can be extracted
[Values] /// </summary>
string[] Values; [Test]
public void TestNameExtraction() {
CommandLine.Option option = new CommandLine.Option(
new StringSegment("--test"), 2, 4
);
Assert.AreEqual("--test", option.Raw);
Assert.AreEqual("--", option.Initiator);
Assert.AreEqual("test", option.Name);
Assert.IsNull(option.Associator);
Assert.IsNull(option.Value);
}
/// <summary>
/// Verifies that the name of a command line option without a value can be extracted
/// when the option is contained in a substring of a larger string
/// </summary>
[Test]
public void TestNameExtractionFromSubstring() {
CommandLine.Option option = new CommandLine.Option(
new StringSegment("||--test||", 2, 6), 4, 4
);
Assert.AreEqual("--test", option.Raw);
Assert.AreEqual("--", option.Initiator);
Assert.AreEqual("test", option.Name);
Assert.IsNull(option.Associator);
Assert.IsNull(option.Value);
}
/// <summary>
/// Varifies that the name and value of a command line option can be extracted
/// </summary>
[Test]
public void TestValueExtraction() {
CommandLine.Option option = new CommandLine.Option(
new StringSegment("--test=123"), 2, 4, 7, 3
);
Assert.AreEqual("--test=123", option.Raw);
Assert.AreEqual("--", option.Initiator);
Assert.AreEqual("test", option.Name);
Assert.AreEqual("=", option.Associator);
Assert.AreEqual("123", option.Value);
}
/// <summary>
/// Varifies that the name and value of a command line option can be extracted
/// when the option is contained in a substring of a larger string
/// </summary>
[Test]
public void TestValueExtractionFromSubstring() {
CommandLine.Option option = new CommandLine.Option(
new StringSegment("||--test=123||", 2, 10), 4, 4, 9, 3
);
Assert.AreEqual("--test=123", option.Raw);
Assert.AreEqual("--", option.Initiator);
Assert.AreEqual("test", option.Name);
Assert.AreEqual("=", option.Associator);
Assert.AreEqual("123", option.Value);
}
/// <summary>
/// Varifies that the name and value of a command line option can be extracted
/// when the option is assigned a quoted value
/// </summary>
[Test]
public void TestQuotedValueExtraction() {
CommandLine.Option option = new CommandLine.Option(
new StringSegment("--test=\"123\"", 0, 12), 2, 4, 8, 3
);
Assert.AreEqual("--test=\"123\"", option.Raw);
Assert.AreEqual("--", option.Initiator);
Assert.AreEqual("test", option.Name);
Assert.AreEqual("=", option.Associator);
Assert.AreEqual("123", option.Value);
}
/// <summary>
/// Varifies that the associator of a command line option with an open ended value
/// assignment can be retrieved
/// </summary>
[Test]
public void TestValuelessAssociatorRetrieval() {
CommandLine.Option option = new CommandLine.Option(
new StringSegment("--test="), 2, 4
);
Assert.AreEqual("--test=", option.Raw);
Assert.AreEqual("--", option.Initiator);
Assert.AreEqual("test", option.Name);
Assert.AreEqual("=", option.Associator);
Assert.IsNull(option.Value);
}
/// <summary>
/// Varifies that the associator of a command line option with an open ended value
/// assignment can be retrieved when the option is contained in a substring of
/// a larger string
/// </summary>
[Test]
public void TestValuelessAssociatorRetrievalFromSubstring() {
CommandLine.Option option = new CommandLine.Option(
new StringSegment("||--test=||", 2, 7), 4, 4//, 9, -1
);
Assert.AreEqual("--test=", option.Raw);
Assert.AreEqual("--", option.Initiator);
Assert.AreEqual("test", option.Name);
Assert.AreEqual("=", option.Associator);
Assert.IsNull(option.Value);
}
} }
*/
/// <summary>Validates that a single argument without quotes can be parsed</summary> #endregion // class OptionTest
/// <summary>
/// Validates that the parser can handle an argument initiator without an obvious name
/// </summary>
[Test] [Test]
public void TestParseSingleNakedArgument() { public void TestParseAmbiguousNameResolution() {
CommandLine.Parse("Hello"); CommandLine commandLine = CommandLine.Parse("--:test");
Assert.AreEqual(0, commandLine.Values.Count);
Assert.AreEqual(1, commandLine.Options.Count);
Assert.AreEqual("-", commandLine.Options[0].Name);
Assert.AreEqual("test", commandLine.Options[0].Value);
} }
/// <summary> /// <summary>
/// Validates that the parser can handle a single argument initator without /// Validates that the parser can handle multiple lone argument initators without
/// a following argument /// a following argument
/// </summary> /// </summary>
[Test] [Test]
public void TestParseLoneArgumentInitiator() { public void TestParseArgumentInitiatorAtEnd() {
CommandLine.Parse("/"); CommandLine commandLine = CommandLine.Parse("-hello:-world -");
CommandLine.Parse("-");
CommandLine.Parse("--"); Assert.AreEqual(1, commandLine.Values.Count);
Assert.AreEqual(1, commandLine.Options.Count);
Assert.AreEqual("hello", commandLine.Options[0].Name);
Assert.AreEqual("-world", commandLine.Options[0].Value);
Assert.AreEqual("-", commandLine.Values[0]);
}
/// <summary>Validates that quoted arguments can be parsed</summary>
[Test]
public void TestParseQuotedOption() {
CommandLine commandLine = CommandLine.Parse("hello -world --this -is=\"a test\"");
Assert.AreEqual(1, commandLine.Values.Count);
Assert.AreEqual(3, commandLine.Options.Count);
Assert.AreEqual("hello", commandLine.Values[0]);
Assert.AreEqual("world", commandLine.Options[0].Name);
Assert.AreEqual("this", commandLine.Options[1].Name);
Assert.AreEqual("is", commandLine.Options[2].Name);
Assert.AreEqual("a test", commandLine.Options[2].Value);
}
/// <summary>Validates that null can be parsed</summary>
[Test]
public void TestParseNull() {
CommandLine commandLine = CommandLine.Parse(null);
Assert.AreEqual(0, commandLine.Values.Count);
Assert.AreEqual(0, commandLine.Options.Count);
}
/// <summary>Validates that a single argument without quotes can be parsed</summary>
[Test]
public void TestParseSingleNakedValue() {
CommandLine commandLine = CommandLine.Parse("hello");
Assert.AreEqual(1, commandLine.Values.Count);
Assert.AreEqual(0, commandLine.Options.Count);
Assert.AreEqual("hello", commandLine.Values[0]);
}
/// <summary>
/// Validates that the parser can handle a quoted argument that's missing
/// the closing quote
/// </summary>
[Test]
public void TestParseQuotedArgumentWithoutClosingQuote() {
CommandLine commandLine = CommandLine.Parse("\"Quoted argument");
Assert.AreEqual(1, commandLine.Values.Count);
Assert.AreEqual(0, commandLine.Options.Count);
Assert.AreEqual("Quoted argument", commandLine.Values[0]);
}
/// <summary>
/// Validates that the parser can handle an command line consisting of only spaces
/// </summary>
[Test]
public void TestParseSpacesOnly() {
CommandLine commandLine = CommandLine.Parse(" \t ");
Assert.AreEqual(0, commandLine.Values.Count);
Assert.AreEqual(0, commandLine.Options.Count);
} }
/// <summary> /// <summary>
@ -67,49 +251,110 @@ namespace Nuclex.Support.Parsing {
/// </summary> /// </summary>
[Test] [Test]
public void TestParseMultipleLoneArgumentInitiators() { public void TestParseMultipleLoneArgumentInitiators() {
CommandLine.Parse("/ // /"); CommandLine commandLine = CommandLine.Parse("--- --");
CommandLine.Parse("- -- -");
CommandLine.Parse("-- --- --"); Assert.AreEqual(0, commandLine.Values.Count);
Assert.AreEqual(2, commandLine.Options.Count);
Assert.AreEqual("-", commandLine.Options[1].Name);
Assert.AreEqual("-", commandLine.Options[2].Name);
} }
/// <summary> /// <summary>
/// Validates that the parser can handle multiple lone argument initators without /// Verifies that the parser correctly handles options with embedded option initiators
/// a following argument
/// </summary> /// </summary>
[Test] [Test]
public void TestParseArgumentInitiatorsWithInvalidNames() { public void TestParseOptionWithEmbeddedInitiator() {
CommandLine.Parse("/=:"); CommandLine commandLine = CommandLine.Parse("-hello/world=123 -test-case");
CommandLine.Parse("-/=");
CommandLine.Parse("--:/"); Assert.AreEqual(0, commandLine.Values.Count);
Assert.AreEqual(2, commandLine.Options.Count);
Assert.AreEqual("hello/world", commandLine.Options[0].Name);
Assert.AreEqual("test-case", commandLine.Options[1].Name);
} }
/// <summary> /// <summary>
/// Validates that the parser can handle an command line consisting of only spaces /// Validates that arguments and values without spaces inbetween can be parsed
/// </summary> /// </summary>
[Test] [Test]
public void TestParseSpacesOnly() { public void TestParseOptionAndValueWithoutSpaces() {
CommandLine.Parse(" \t "); CommandLine commandLine = CommandLine.Parse("\"value\"-option\"value\"");
Assert.AreEqual(2, commandLine.Values.Count);
Assert.AreEqual(1, commandLine.Options.Count);
Assert.AreEqual("value", commandLine.Values[0]);
Assert.AreEqual("option", commandLine.Options[0].Name);
Assert.AreEqual("value", commandLine.Values[1]);
} }
/// <summary> /// <summary>
/// Validates that the parser can handle a quoted argument that's missing /// Validates that options with modifiers at the end of the command line
/// the closing quote /// are parsed successfully
/// </summary> /// </summary>
[Test] [Test]
public void TestParseQuoteArgumentWithoutClosingQuote() { public void TestParseOptionWithModifierAtEnd() {
CommandLine.Parse("\"Quoted argument"); CommandLine commandLine = CommandLine.Parse("--test-value- -test+");
Assert.AreEqual(0, commandLine.Values.Count);
Assert.AreEqual(2, commandLine.Options.Count);
Assert.AreEqual("test-value", commandLine.Options[0].Name);
Assert.AreEqual("test", commandLine.Options[1].Name);
} }
/// <summary>Validates that normal arguments can be parsed</summary> /// <summary>
/// Validates that options with values assigned to them are parsed successfully
/// </summary>
[Test] [Test]
public void TestParseOptions() { public void TestParseOptionWithAssignment() {
CommandLine.Parse("Hello -World /This --Is \"a test\""); CommandLine commandLine = CommandLine.Parse("-hello:123 -world=321");
Assert.AreEqual(0, commandLine.Values.Count);
Assert.AreEqual(2, commandLine.Options.Count);
Assert.AreEqual("hello", commandLine.Options[0].Name);
Assert.AreEqual("123", commandLine.Options[0].Value);
Assert.AreEqual("world", commandLine.Options[1].Name);
Assert.AreEqual("321", commandLine.Options[1].Value);
} }
/// <summary>Validates that null can be parsed</summary> /// <summary>
/// Validates that options with an empty value at the end of the command line
/// string are parsed successfully
/// </summary>
[Test] [Test]
public void TestParseNull() { public void TestParseOptionAtEndOfString() {
Assert.IsNotNull(CommandLine.Parse(null)); CommandLine commandLine = CommandLine.Parse("--test:");
Assert.AreEqual(0, commandLine.Values.Count);
Assert.AreEqual(1, commandLine.Options.Count);
Assert.AreEqual("test", commandLine.Options[0].Name);
}
/// <summary>
/// Verifies that the parser can recognize windows command line options if
/// configured to windows mode
/// </summary>
[Test]
public void TestWindowsOptionInitiator() {
CommandLine commandLine = CommandLine.Parse("/hello //world", true);
Assert.AreEqual(1, commandLine.Values.Count);
Assert.AreEqual(2, commandLine.Options.Count);
Assert.AreEqual("hello", commandLine.Options[0].Name);
Assert.AreEqual("/", commandLine.Options[0].Value);
Assert.AreEqual("world", commandLine.Options[1].Name);
}
/// <summary>
/// Verifies that the parser ignores windows command line options if
/// configured to non-windows mode
/// </summary>
[Test]
public void TestNonWindowsOptionValues() {
CommandLine commandLine = CommandLine.Parse("/hello //world", false);
Assert.AreEqual(2, commandLine.Values.Count);
Assert.AreEqual(0, commandLine.Options.Count);
Assert.AreEqual("/hello", commandLine.Values[0]);
Assert.AreEqual("//world", commandLine.Values[1]);
} }
} }

View File

@ -20,7 +20,9 @@ License along with this library
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.IO;
using Nuclex.Support.Collections;
namespace Nuclex.Support.Parsing { namespace Nuclex.Support.Parsing {
@ -55,7 +57,14 @@ namespace Nuclex.Support.Parsing {
/// </description> /// </description>
/// </item> /// </item>
/// <item> /// <item>
/// <term>Option / Argument</term> /// <term>Argument</term>
/// <description>
/// Either an option or a loose value (see below) that being specified on
/// the command line
/// </description>
/// </item>
/// <item>
/// <term>Option</term>
/// <description> /// <description>
/// Can be specified on the command line and typically alters the behavior /// Can be specified on the command line and typically alters the behavior
/// of the application or changes a setting. For example, '--normalize' or /// of the application or changes a setting. For example, '--normalize' or
@ -80,15 +89,66 @@ namespace Nuclex.Support.Parsing {
public partial class CommandLine { public partial class CommandLine {
/// <summary>Initializes a new command line</summary> /// <summary>Initializes a new command line</summary>
public CommandLine() { } public CommandLine() {
this.options = new List<Option>();
this.values = new List<string>();
}
/// <summary>Parses the command line arguments from the provided string</summary> /// <summary>Parses the command line arguments from the provided string</summary>
/// <param name="commandLineString">String containing the command line arguments</param> /// <param name="commandLineString">String containing the command line arguments</param>
/// <returns>The parsed command line</returns> /// <returns>The parsed command line</returns>
public static CommandLine Parse(string commandLineString) { public static CommandLine Parse(string commandLineString) {
return Parser.Parse(commandLineString); bool windowsMode = (Path.DirectorySeparatorChar != '/');
return Parser.Parse(commandLineString, windowsMode);
} }
/// <summary>Parses the command line arguments from the provided string</summary>
/// <param name="commandLineString">String containing the command line arguments</param>
/// <param name="windowsMode">Whether the / character initiates an argument</param>
/// <returns>The parsed command line</returns>
public static CommandLine Parse(string commandLineString, bool windowsMode) {
return Parser.Parse(commandLineString, windowsMode);
}
#region To Be Removed
/// <summary>Adds a loose value to the command line</summary>
/// <param name="value">Value taht will be added</param>
internal void addValue(StringSegment value) {
Console.WriteLine("Discovered loose value: '" + value.ToString() + "'");
this.values.Add(value.ToString());
}
/// <summary>Adds an option to the command line</summary>
/// <param name="option">Option that will be added</param>
internal void addOption(Option option) {
Console.WriteLine("Discovered option: '" + option.Raw.ToString() + "'");
Console.WriteLine(" Name: '" + option.Name + "'");
if(option.Value != null) {
Console.WriteLine(" Value: '" + option.Value + "'");
}
this.options.Add(option);
}
#endregion // To Be Removed
/// <summary>Options that were specified on the command line</summary>
public IList<Option> Options {
get { return this.options; }
}
/// <summary>Loose values that were given on the command line</summary>
public IList<string> Values {
get { return this.values; }
}
/// <summary>Options that were specified on the command line</summary>
private List<Option> options;
/// <summary>Loose values that were given on the command line</summary>
private List<string> values;
} }
} // namespace Nuclex.Support.Parsing } // namespace Nuclex.Support.Parsing