Skip to content

Commit

Permalink
Code simplification with string interpolation and minor changes (#43)
Browse files Browse the repository at this point in the history
* Code simplification with string interpolation

* Version update
  • Loading branch information
masesdevelopers authored Nov 14, 2023
1 parent c3bdd77 commit 4fc0c01
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 60 deletions.
66 changes: 32 additions & 34 deletions src/net/CLIParser/ArgumentMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public enum ArgumentType
/// </summary>
KeyValue,
/// <summary>
/// Represents an argument whose value if the next argument
/// Represents an argument whose value is the next command-line argument
/// </summary>
Double
}
Expand Down Expand Up @@ -462,7 +462,7 @@ string IArgumentMetadataHelper.Parameter()
string description = Name;
if (!string.IsNullOrEmpty(ShortName))
{
description += string.Format(" ({0})", ShortName);
description += $" ({ShortName})";
}
return description;
}
Expand All @@ -480,11 +480,11 @@ string IArgumentMetadataHelper.DescriptionBuilder(int width)
if (!description.EndsWith(" ")) description += " ";
}

description += string.Format("The argument is {0}. ", IsMandatory ? "mandatory" : "optional");
description += $"The argument is {(IsMandatory ? "mandatory" : "optional")}. ";

if (Default != null)
{
description += string.Format("Default: {0}. ", Default);
description += $"Default: {Default}. ";
}
string range = null;
if (IsEnum)
Expand All @@ -504,7 +504,7 @@ string IArgumentMetadataHelper.DescriptionBuilder(int width)
case ArgumentValueType.Range:
if (MinValue != null && MaxValue != null)
{
range = string.Format("[{0}...{1}]", MinValue, MaxValue);
range = $"[{MinValue}...{MaxValue}]";
}
break;
case ArgumentValueType.Free:
Expand All @@ -515,20 +515,19 @@ string IArgumentMetadataHelper.DescriptionBuilder(int width)

switch (Type)
{
case ArgumentType.Single:
break;
case ArgumentType.KeyValue:
if (!string.IsNullOrEmpty(range))
{
description += string.Format("{0}{1}=<{2}>.", Helper.GetPrefix(), Name, range);
description += $"{Helper.GetPrefix()}{Name}=<{range}>.";
}
break;
case ArgumentType.Double:
if (!string.IsNullOrEmpty(range))
{
description += string.Format("{0}{1} <{2}>.", Helper.GetPrefix(), Name, range);
description += $"{Helper.GetPrefix()}{Name} <{range}>.";
}
break;
case ArgumentType.Single:
default:
break;
}
Expand All @@ -555,50 +554,48 @@ void IArgumentMetadataHelper.Check()
var dType = Default.GetType();
if (dType.GetInterface(typeof(System.Collections.IEnumerable).Name) != null)
{
var elemType = dType.GetElementType();
if (elemType == null) throw new ArgumentException(string.Format("Default type shall be an instance of {0}<{1}>.", typeof(System.Collections.IEnumerable).Name, DataType));
if (elemType != DataType) throw new ArgumentException(string.Format("Default type shall be equal to {0}.", DataType));
var elemType = dType.GetElementType() ?? throw new ArgumentException($"Default type shall be an instance of {typeof(System.Collections.IEnumerable).Name}<{DataType}>.");
if (elemType != DataType) throw new ArgumentException($"Default type shall be equal to {DataType}.");
}
else throw new ArgumentException(string.Format("Default type shall be an instance of {0}<{1}>.", typeof(System.Collections.IEnumerable).Name, DataType));
else throw new ArgumentException($"Default type shall be an instance of {typeof(System.Collections.IEnumerable).Name}<{DataType}>.");
}
else
{
if (Default.GetType() != DataType) throw new ArgumentException(string.Format("Default type shall be equal to {0}.", DataType));
if (Default.GetType() != DataType) throw new ArgumentException($"Default type shall be equal to {DataType}.");
}
}
switch (ValueType)
{
case ArgumentValueType.Free:
break;
case ArgumentValueType.Array:
if (ArrayValues == null || ArrayValues.Length == 0) throw new ArgumentException("Argument needs to set ArrayValues.");
foreach (var item in ArrayValues)
{
if (item.GetType() != DataType) throw new ArgumentException(string.Format("ArrayValues type shall be equal to {0}.", DataType));
if (item.GetType() != DataType) throw new ArgumentException($"ArrayValues type shall be equal to {DataType}.");
}
break;
case ArgumentValueType.Range:
if (MinValue == null && MaxValue == null) throw new ArgumentException("Argument needs to set both MinValue and MaxValue.");
if (!(DataType.IsValueType)) throw new ArgumentException(string.Format("DataType shall be a ValueType, found {0}.", DataType));
if (MinValue.GetType() != DataType) throw new ArgumentException(string.Format("MinValue type shall be equal to {0}.", DataType));
if (MaxValue.GetType() != DataType) throw new ArgumentException(string.Format("MaxValue type shall be equal to {0}.", DataType));
if (!(DataType.IsValueType)) throw new ArgumentException($"DataType shall be a ValueType, found {DataType}.");
if (MinValue.GetType() != DataType) throw new ArgumentException($"MinValue type shall be equal to {DataType}.");
if (MaxValue.GetType() != DataType) throw new ArgumentException("MaxValue type shall be equal to {DataType}.");
break;
case ArgumentValueType.Free:
default:
break;
}
if (Default != null) Helper.TestValue(Default);
}

bool checkParam(string stringToTest)
bool CheckParam(string stringToTest)
{
bool result = false;
bool result;
switch (Type)
{
case ArgumentType.KeyValue:
result = stringToTest.StartsWith(Helper.StartWith) || (!string.IsNullOrEmpty(Helper.ShortStartWith) ? stringToTest.StartsWith(Helper.ShortStartWith) : false);
result = stringToTest.StartsWith(Helper.StartWith) || (!string.IsNullOrEmpty(Helper.ShortStartWith) && stringToTest.StartsWith(Helper.ShortStartWith));
break;
default:
result = stringToTest == Helper.StartWith || (!string.IsNullOrEmpty(Helper.ShortStartWith) ? stringToTest == Helper.ShortStartWith : false);
result = stringToTest == Helper.StartWith || (!string.IsNullOrEmpty(Helper.ShortStartWith) && stringToTest == Helper.ShortStartWith);
break;
}
return result;
Expand All @@ -621,7 +618,7 @@ IArgumentMetadataParsed IArgumentMetadataHelper.Parse(IList<string> args)
args.RemoveAt(i);
return parsedData;
}
else if (checkParam(stringToTest))
else if (CheckParam(stringToTest))
{
ArgumentMetadataParsed parsedData = new ArgumentMetadataParsed(this)
{
Expand All @@ -638,7 +635,8 @@ IArgumentMetadataParsed IArgumentMetadataHelper.Parse(IList<string> args)
break;
case ArgumentType.KeyValue:
{
string value = args[i];
_ = args[i];
string value;
if (stringToTest.StartsWith(Helper.StartWith))
{
value = args[i].Substring(Helper.StartWith.Length);
Expand All @@ -649,7 +647,7 @@ IArgumentMetadataParsed IArgumentMetadataHelper.Parse(IList<string> args)
}
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(string.Format("Parameter {0} needs a value", Name));
throw new ArgumentException($"Parameter {Name} needs a value");
}
if (IsEnum)
{
Expand All @@ -660,7 +658,7 @@ IArgumentMetadataParsed IArgumentMetadataHelper.Parse(IList<string> args)
}
catch
{
throw new ArgumentException(string.Format("Argument {0} shall be in {1}: {2} was found.", Name, string.Join(", ", Enum.GetNames(DataType)), value));
throw new ArgumentException($"Argument {Name} shall be in {string.Join(", ", Enum.GetNames(DataType))}: {value} was found.");
}
}
else if (IsMultiValue)
Expand Down Expand Up @@ -697,7 +695,7 @@ IArgumentMetadataParsed IArgumentMetadataHelper.Parse(IList<string> args)
}
catch
{
throw new ArgumentException(string.Format("Argument {0} shall be in {1}: {2} was found.", Name, string.Join(", ", Enum.GetNames(DataType)), value));
throw new ArgumentException($"Argument {Name} shall be in {string.Join(", ", Enum.GetNames(DataType))}: {value} was found.");
}
}
else if (IsMultiValue)
Expand All @@ -720,7 +718,7 @@ IArgumentMetadataParsed IArgumentMetadataHelper.Parse(IList<string> args)
args.RemoveAt(i);
args.RemoveAt(i);
}
else throw new ArgumentException(string.Format("Parameter {0} needs a value", Name));
else throw new ArgumentException($"Parameter {Name} needs a value");
}
break;
default:
Expand All @@ -732,7 +730,7 @@ IArgumentMetadataParsed IArgumentMetadataHelper.Parse(IList<string> args)
else continue;
}

if (IsMandatory) throw new ArgumentException(string.Format("Parameter {0} is mandatory", Name));
if (IsMandatory) throw new ArgumentException($"Parameter {Name} is mandatory");

return new ArgumentMetadataParsed(this)
{
Expand All @@ -746,7 +744,7 @@ void IArgumentMetadataHelper.TestValue(object value)
{
if (!IsFlag && !Enum.IsDefined(DataType, value))
{
throw new ArgumentException(string.Format("Argument {0} shall be in {1}: {2} was found.", Name, string.Join(", ", Enum.GetNames(DataType)), value));
throw new ArgumentException($"Argument {Name} shall be in {string.Join(", ", Enum.GetNames(DataType))}: {value} was found.");
}
}
else
Expand All @@ -762,7 +760,7 @@ void IArgumentMetadataHelper.TestValue(object value)
}
if (!found)
{
throw new ArgumentException(string.Format("Argument {0} shall be in {1}, {2} was found.", Name, string.Join(", ", ArrayValues), value));
throw new ArgumentException($"Argument {Name} shall be in {string.Join(", ", ArrayValues)}, {value} was found.");
}
}
break;
Expand All @@ -772,7 +770,7 @@ void IArgumentMetadataHelper.TestValue(object value)
{
break;
}
else throw new ArgumentException(string.Format("Argument {0} shall be in {1} - {2}, {3} was found.", Name, MinValue, MaxValue, value));
else throw new ArgumentException($"Argument {Name} shall be in {MinValue} - {MaxValue}, {value} was found.");
}
case ArgumentValueType.Free:
default:
Expand Down
39 changes: 15 additions & 24 deletions src/net/CLIParser/CLIParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MASES.CLIParser
Expand Down Expand Up @@ -98,16 +99,9 @@ public static string ToString(this IArgumentMetadata metadata, params object[] v

switch (metadata.Type)
{
case ArgumentType.Single:
return $"{prefix}{metadata.Name}";
case ArgumentType.Double:
{
return $"{prefix}{metadata.Name} {valueStr}";
}
case ArgumentType.KeyValue:
{
return $"{prefix}{metadata.Name}{metadata.KeyValuePairSeparator}{valueStr}";
}
case ArgumentType.Single: return $"{prefix}{metadata.Name}";
case ArgumentType.Double: return $"{prefix}{metadata.Name} {valueStr}";
case ArgumentType.KeyValue: return $"{prefix}{metadata.Name}{metadata.KeyValuePairSeparator}{valueStr}";
default: throw new ArgumentException($"Parameter {metadata.Name} does not have a correct Type: {metadata.Type}");
}
}
Expand All @@ -119,7 +113,7 @@ public static string ToString(this IArgumentMetadata metadata, params object[] v
public static void Add(this IArgumentMetadata metadata)
{
IArgumentMetadataHelper helper = metadata as IArgumentMetadataHelper;
if (helper.Parser == null) throw new ArgumentException(string.Format("Parameter {0} does not have any associated Parser", metadata.Name));
if (helper.Parser == null) throw new ArgumentException($"Parameter {metadata.Name} does not have any associated Parser");
helper.Parser.Add(metadata);
}
/// <summary>
Expand Down Expand Up @@ -219,7 +213,7 @@ public static T Get<T>(this IEnumerable<IArgumentMetadataParsed> args, int index
public static T Get<T>(this IArgumentMetadataParsed arg)
{
if (arg == null) throw new ArgumentNullException("arg cannot be null.");
if (!typeof(T).IsAssignableFrom(arg.DataType)) throw new ArgumentException(string.Format("{0} is incomplatible wirh {1}.", typeof(T), arg.DataType));
if (!typeof(T).IsAssignableFrom(arg.DataType)) throw new ArgumentException($"{typeof(T)} is incomplatible wirh {arg.DataType}.");
if (arg.Value != null)
{
return (T)arg.Value;
Expand Down Expand Up @@ -257,7 +251,7 @@ public static IEnumerable<IArgumentMetadataParsed> Override(this IEnumerable<IAr
{
foreach (var item2 in newSrc.ToArray())
{
if (rawReplace ? true : item2.Exist && item.Override(item2))
if (rawReplace || item2.Exist && item.Override(item2))
{
newSrc.Remove(item2);
break;
Expand Down Expand Up @@ -436,7 +430,7 @@ public void Add(IArgumentMetadata metadata)
{
if (metadata == null) throw new ArgumentNullException("metadata cannot be null.");
if (string.IsNullOrEmpty(metadata.Name)) throw new ArgumentException("Parameter Name shall be set.");
if (arguments.ContainsKey(metadata.Name)) throw new ArgumentException(string.Format("Parameter {0} is duplicated", metadata.Name));
if (arguments.ContainsKey(metadata.Name)) throw new ArgumentException($"Parameter {metadata.Name} is duplicated");
IArgumentMetadataHelper helper = metadata as IArgumentMetadataHelper;
if (helper.Parser == null)
{
Expand All @@ -445,7 +439,7 @@ public void Add(IArgumentMetadata metadata)
}
if (!ReferenceEquals(helper.Parser, this))
{
throw new ArgumentException(string.Format("Parser mismatch: {0} is not associated to this parser instance.", metadata.Name));
throw new ArgumentException($"Parser mismatch: {metadata.Name} is not associated to this parser instance.");
}
helper.Check();
arguments.Add(metadata.Name, metadata);
Expand Down Expand Up @@ -480,7 +474,7 @@ public IEnumerable<IArgumentMetadataParsed> Parse(string[] args)
{
IArgumentMetadataParsed dataParsed = item.Parse(lstArgs);

if (parsedArgs.ContainsKey(dataParsed.Name)) throw new ArgumentException(string.Format("Parameter {0} is duplicated", dataParsed.Name));
if (parsedArgs.ContainsKey(dataParsed.Name)) throw new ArgumentException($"Parameter {dataParsed.Name} is duplicated");

if (dataParsed != null)
{
Expand All @@ -490,15 +484,12 @@ public IEnumerable<IArgumentMetadataParsed> Parse(string[] args)

if (Settings.CheckUnwanted && lstArgs.Count != 0)
{
throw new ArgumentException(string.Format("Parameter{0} {1} are not managed", lstArgs.Count == 1 ? string.Empty : "s", string.Join(", ", lstArgs)));
throw new ArgumentException($"Parameter {(lstArgs.Count == 1 ? string.Empty : "s")} {string.Join(", ", lstArgs)} are not managed");
}

foreach (var item in parsedArgs.Values)
{
if (item.CrossCheck != null)
{
item.CrossCheck(parsedArgs.Values);
}
item.CrossCheck?.Invoke(parsedArgs.Values);
}

UnparsedArgs = new List<string>(lstArgs).ToArray();
Expand All @@ -519,7 +510,7 @@ public IEnumerable<IArgumentMetadataParsed> Parse(IArgumentMetadataParsed arg)

IList<string> lstArgs = new List<string>(arg.Value as IEnumerable<string>);

foreach (IArgumentMetadataHelper item in Arguments)
foreach (IArgumentMetadataHelper item in Arguments.Cast<IArgumentMetadataHelper>())
{
IArgumentMetadataParsed dataParsed = item.Parse(lstArgs);

Expand Down Expand Up @@ -675,7 +666,7 @@ public IEnumerable<IArgumentMetadataParsed> NotExists(IEnumerable<IArgumentMetad
public int PaddingFromArguments()
{
int len = 0;
foreach (IArgumentMetadataHelper item in Arguments)
foreach (IArgumentMetadataHelper item in Arguments.Cast<IArgumentMetadataHelper>())
{
len = Math.Max(len, item.Parameter().Length);
}
Expand All @@ -697,7 +688,7 @@ public string HelpInfo(int? width = null)
catch { }
if (width.HasValue) newWidth = width.Value;
StringBuilder builder = new StringBuilder();
foreach (IArgumentMetadataHelper item in Arguments)
foreach (IArgumentMetadataHelper item in Arguments.Cast<IArgumentMetadataHelper>())
{
builder.AppendLine(item.DescriptionBuilder(newWidth));
}
Expand Down
2 changes: 1 addition & 1 deletion src/net/CLIParser/CLIParser.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<Owners>MASES s.r.l.</Owners>
<Authors>MASES s.r.l.</Authors>
<Company>MASES s.r.l.</Company>
<Version>3.1.2.0</Version>
<Version>3.2.0.0</Version>
<Product>CLIParser</Product>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
Expand Down
Loading

0 comments on commit 4fc0c01

Please sign in to comment.