throw CommandParsingException rather than crash on missing single value

This commit is contained in:
jonsequitur 2017-02-03 10:57:57 -08:00
parent f69f0ed266
commit 182c695275
3 changed files with 45 additions and 4 deletions

View file

@ -156,7 +156,10 @@ namespace Microsoft.DotNet.Cli.CommandLine
else if (isLongOption || arg.StartsWith("-"))
{
CommandOption option;
var result = ParseOption(isLongOption, command, args, ref index, out option);
if (result == ParseOptionResult.ShowHelp)
{
command.ShowHelp();
@ -285,14 +288,24 @@ namespace Microsoft.DotNet.Cli.CommandLine
else
{
index++;
arg = args[index];
if (!option.TryParse(arg))
if (index < args.Length)
{
arg = args[index];
if (!option.TryParse(arg))
{
command.ShowHint();
throw new CommandParsingException(
command,
String.Format(LocalizableStrings.UnexpectedValueForOptionError, arg, optionName));
}
}
else
{
command.ShowHint();
throw new CommandParsingException(
command,
String.Format(LocalizableStrings.UnexpectedValueForOptionError, arg, optionName));
String.Format(LocalizableStrings.OptionRequiresSingleValueWhichIsMissing, arg, optionName));
}
}
}

View file

@ -4,6 +4,8 @@ namespace Microsoft.DotNet.Cli.CommandLine
{
public const string LastArgumentMultiValueError = "The last argument '{0}' accepts multiple values. No more argument can be added.";
public const string OptionRequiresSingleValueWhichIsMissing = "Required value for option '{0}' was not provided.";
public const string UnexpectedValueForOptionError = "Unexpected value '{0}' for option '{1}'";
public const string UnexpectedArgumentError = "Unrecognized {0} '{1}'";

View file

@ -0,0 +1,26 @@
using System;
using FluentAssertions;
using Microsoft.DotNet.Cli.CommandLine;
using Xunit;
namespace Microsoft.DotNet.Tests
{
public class CommandLineApplicationTests
{
[Fact]
public void WhenAnOptionRequiresASingleValueThatIsNotSuppliedItThrowsCommandParsingException()
{
var app = new CommandLineApplication();
app.Option("-v|--verbosity", "be verbose", CommandOptionType.SingleValue);
Action execute = () => app.Execute("-v");
execute.ShouldThrow<CommandParsingException>()
.Which
.Message
.Should()
.Be("Required value for option '-v' was not provided.");
}
}
}