Default values for lists/arrays using Command Line Parser Library

PHeiberg picture PHeiberg · Mar 4, 2013 · Viewed 8k times · Source

Using Command Line Parser Library and having a list or array with a default value, the default value is printed as (Default: System.String[]). Is there any way to make it show the actual default values?

So with

[OptionList('l', "languages", Separator = ',', DefaultValue = new []{"eng"})]
public IList<string> Languages { get; set; }

the help text is printed as "(Default: System.String[]) ...". I'd like it to say "(Default: { "eng" })".

Answer

jay picture jay · Mar 5, 2013

HelpText suffered of using a generalized formatting function against DefaultValue.

The problem was (ref. to latest stable) in line 702 of HelpText.cs:

if (option.HasDefaultValue)
{
  option.HelpText = "(Default: {0}) ".FormatLocal(option.DefaultValue) + option.HelpText;
}

The current development branch (to my opinion usable) solves it with a new helper private method (covered also from a test perspective):

private static string FormatDefaultValue(object value)
{
    if (value is bool)
    {
        return value.ToLocalString().ToLowerInvariant();
    }

    if (value is string)
    {
        return value.ToLocalString();
    }

    var asEnumerable = value as IEnumerable;
    if (asEnumerable != null)
    {
        var builder = new StringBuilder();
        foreach (var item in asEnumerable)
        {
            builder.Append(item.ToLocalString());
            builder.Append(" ");
        }
        return builder.Length > 0 ? builder.ToString(0, builder.Length - 1) : string.Empty;
    }
    return value.ToLocalString();
}

To use the latest development branch:

git clone -b develop-1.9.8-beta https://github.com/gsscoder/commandline.git commandline-develop

For informations on its stability and how could change after first release, see here.

With this instructions should be easy also patch a fork of the current stable.