Skip to content

Commit

Permalink
Fixed ValidateOptionsType
Browse files Browse the repository at this point in the history
  • Loading branch information
Paolo Iommarini committed Aug 1, 2022
1 parent 867ac68 commit 907e3a1
Showing 1 changed file with 17 additions and 15 deletions.
32 changes: 17 additions & 15 deletions CmdLineArgsParser/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ public Parser(ParserSettings settings = null)
if (!property.Property.CanWrite)
throw new Exception($"Readonly property '{property.Property.Name}'");

if (string.IsNullOrEmpty(property.Option.Name))
throw new Exception($"Missing option name for property '{property.Property.Name}'");
ValidateName(property, names, shortNames);

if (opt.Verb) {
if (verb != null)
Expand All @@ -86,18 +85,6 @@ public Parser(ParserSettings settings = null)
verb = property;
}

if (string.IsNullOrEmpty(opt.Name) && !opt.Verb)
throw new Exception($"Empty option name for property '{property.Property.Name}'");
if (opt.Name.Contains(" ") || opt.Name.StartsWith("-"))
throw new Exception($"Invalid option name '{opt.Name}'");

if (names.Contains(opt.Name.ToLower())) {
throw new Exception($"Duplicated option name '{opt.Name}'");
}
if (shortNames.Contains(opt.ShortName)) {
throw new Exception($"Duplicated option short name '{opt.ShortName}'");
}

// Bool options cannot be required
if (property.Property.PropertyType.IsAssignableFrom(typeof(bool)) && property.Option.Required) {
throw new Exception($"Bool option '{opt.Name}' cannot be required");
Expand All @@ -114,10 +101,25 @@ public Parser(ParserSettings settings = null)

names.Add(opt.Name.ToLower());
if (opt.ShortName != '\0')
shortNames.Add(opt.ShortName);
shortNames.Add(char.ToLower(opt.ShortName));
}
}

private void ValidateName(OptionProperty property, HashSet<string> usedNames, HashSet<char> usedShortNames)
{
if (string.IsNullOrEmpty(property.Option.Name))
throw new Exception($"Missing option name for property '{property.Property.Name}'");
if (string.IsNullOrEmpty(property.Option.Name))
throw new Exception($"Empty option name for property '{property.Property.Name}'");
if (property.Option.Name.Contains(" ") || property.Option.Name.StartsWith("-"))
throw new Exception($"Invalid option name '{property.Option.Name}'");

if (usedNames.Contains(property.Option.Name.ToLower()))
throw new Exception($"Duplicated option name '{property.Option.Name}'");
if (usedShortNames.Contains(char.ToLower(property.Option.ShortName)))
throw new Exception($"Duplicated option short name '{property.Option.ShortName}'");
}

private void ValidateValidValues(OptionProperty property, string[] validValues)
{
if (validValues?.Length > 0) {
Expand Down

0 comments on commit 907e3a1

Please sign in to comment.