简体   繁体   中英

Get the actual option name in Mono.Options

I am using Mono.Options to parse command line flags in a CLI application.

For convenience, many options have several aliases, eg "o|opt|option" . Furthermore, Mono.Options allows one to specify an option using different prefixes, eg -o , /opt or --option .

Is there a reasonable way to retrieve the actual name that was supplied for an option during / after parsing? In my case, that would be "-o" , "/opt" or "--option" , depending on what the user has provided in the command line.

I did not find any reasonable way to do this via Mono.Options ' public interface. The best outcome would be to have the actual option name passed into the Action callback upon parsing, but it is just not there.

Mono.Options ' option prototype parsing mechanism is also non-public.

I ended up manually parsing the prototype and searching the command line arguments for any of the option aliases combined with all possible option prefixes ( - , -- , and / ):

public static string GetProvidedName(string flagPrototype, IEnumerable<string> commandLineArguments)
{
    IEnumerable<string> flagNames = flagPrototype
        .Split('|')
        .Select(value => value.Replace("=", string.Empty).Replace(":", string.Empty))
        .SelectMany(flagName => 
            new string[] 
            {
                $"-{flagName}",
                $"--{flagName}",
                $"/{flagName}"
            });

    return commandLineArguments.First(argument => flagNames.Contains(argument));
}

I hope it will be useful for someone looking to solve the same problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM