ProcessCommandLineArguments() public static method

Expands environment variables (e.g. %TEMP%) and @files in a list of command-line arguments, and adds any options of the form "--opt" or "--opt=value" to a dictionary.
Two types of options are recognized, short (-s) and long (--long), and only one argument is supported per option. The documentation is above. You can choose whether to permit duplicate options or not. If you use a standard Dictionary{K,V} to hold the options, an exception will occur when this method calls Add() to add the duplicate. The exception is caught, the first ocurrance is kept, and a warning message is printed to MessageSink.Default. To allow duplicates, store options in a different data structure such as List(KeyValuePair(string, string)) or BMultiMap(string,string). DOS-style slash-options like /foo are not supported. Since Windows recognizes the forward slash as a path separator, forward-slash options can be recognized as paths. If you want to recognize them as options instead, you can preprocess the argument list, replacing every command that starts with "/" with a "--" command: for (int i = 0; args.Count > i; i++) if (args[i].StartsWith("/")) args[i] = "--" + args[i].Substring(1); Globs (e.g. *.txt) are not recognized or expanded, but environment variables are expanded when expandEnvVars is true. Quote marks are not processed. An argument of "--a", with quote marks, is not recognized as an option (these quote marks should be removed before calling this method, e.g. G.SplitCommandLineArguments handles this.)
public static ProcessCommandLineArguments ( IList args, string>.ICollection options, string atFolder, string>.IDictionary shortOptions = null, InvertibleSet twoArgOptions = null, int argLimit = 0xFFFF, bool expandEnvVars = true, bool caseSensitiveLongOpts = false ) : void
args IList The original arguments to process.
options string>.ICollection Any long options (arguments that start with "--") /// will be added to this dictionary, and removed from args. This /// parameter cannot be null. /// By default, long options are not case sensitive. In that case, the /// user's option name is converted to lower case. /// /// Long options are expected to have the form --ID or --ID=value, where ID /// matches the regex "[a-zA-Z_0-9-]+". If there is no "=" or ":", that's /// okay too. For example, --Id{foo} is equivalent to --Id={foo}; both yield /// in the name-value pair ("id", "{foo}"). If there is no value (no equals /// or colon), the value associated with the option is null.
atFolder string If a parameter has the form @filename, the folder /// specified by atFolder will be searched for an options text file with the /// user-specified filename, and the contents of the file will be expanded /// into the list of arguments (split using SplitCommandLineArguments). The /// expanded list can contain new @filenames, which are also processed. To /// search in the current directory, use "". The @filename may use an absolute /// path, which overrides this folder. To disable @filename expansion, set /// this parameter to null. Whether the feature is enabled or disabled, /// @filenames are not removed from args, in case you want to /// be aware of the filenames afterward.
shortOptions string>.IDictionary A map from one-letter options that start with /// "-" rather than "--", to the name of the corresponding long option (this /// option can be null to ignore all short options.) For example, if this /// contains ('a', "all"), and the input args contains "-a:foo", /// the pair ("all", "foo") will be added to options. If a value in /// this map is null, the key itself is used. Short options can be combined; /// for example -abc:foo is equivalent to -a -b -c:foo. Short /// options are always case-sensitive; to define an option that is not case /// sensitive, place two entries in the dictionary e.g. ('a', "all") and /// ('A', "all"). If the user specifies a short option letter that is not /// recognized, the entire command will be ignored and left in args. For /// example, if shortOptions contains only ('a', "all") but args /// contains "-ab=foo", the command is ignored and left in args. /// Rationale: -ab=foo might be a filename. /// /// On the other hand, if -a is a valid option then -a123 is also /// valid even when there is no option called '1'; the number "123" is /// treated as an argument to -a. Now, if '1' is a registered short option /// but '2' is not, then -a123 is equivalent to -a -1=23. ///
twoArgOptions InvertibleSet A set of options in which the argument can /// be separated by a space from the option. For example, if the input is /// "--out foo.txt" and you want to recognize "foo.txt" as the argument to /// "--out", add the string "out" to this set. If you want to treat all /// options this way, use InvertibleSet{string}.All. Note: /// If the input is "--out:foo bar", "foo" is recognized as the argument to /// "--out" and "bar" is left alone, i.e. it is treated as unrelated. /// Short options participate automatically. For example if "-f" means /// "--foo", and twoArgOptions contains "foo", then "-f arg" is interpreted /// like "--foo=arg". /// /// The argument will not be treated as an argument if it starts with a /// dash, e.g. in --foo -*, -* will not be treated as an /// argument to --foo, even if -* is not a registered option. ///
argLimit int A limit placed on the number of arguments when /// expanding @files. Such a file may refer to itself, and this is the only /// protection provided against infinite recursive expansion.
expandEnvVars bool If true, environment variable references /// such as %TEMP% are expanded by calling the standard method /// .
caseSensitiveLongOpts bool If true, long options are case- /// sensitive. By default, long options are not case sensitive.
return void
Exemplo n.º 1
0
        public void TestProcessCommandLineArguments2()
        {
            // Generate two options files, where the first refers to the second
            string       atFolder = Environment.ExpandEnvironmentVariables("%TEMP%");
            string       file1    = "test ProcessCmdLine 1.txt";
            string       file2    = "test ProcessCmdLine 2.txt";
            StreamWriter w        = new StreamWriter(Path.Combine(atFolder, file1));

            w.WriteLine("\"@" + file2 + "\" fox--jumps\n--over");
            w.Close();
            w = new StreamWriter(Path.Combine(atFolder, file2));
            w.WriteLine("these arguments are ignored (arg limit exceeded)");
            w.Close();

            // Expand command line and ensure that the arg limit is enforced
            List <string> args    = G.SplitCommandLineArguments("\"@" + file1 + "\" \"lazy dog\"");
            var           options = new DList <KeyValuePair <string, string> >();
            var           msgs    = new MessageHolder();

            using (MessageSink.SetDefault(msgs))
                UG.ProcessCommandLineArguments(args, options, atFolder, null, null, 5);

            ExpectList(args.AsListSource(), "@" + file1, "@" + file2, "fox--jumps", "lazy dog");
            ExpectList(options, P("over", null));
            ExpectList(msgs.List.Select(msg => msg.ToString()).AsListSource(),
                       "@test ProcessCmdLine 2.txt: Warning: Limit of 5 commands exceeded");
        }
Exemplo n.º 2
0
        public void TestProcessCommandLineArguments1()
        {
            string commandLine = "-abZ -ab123 and -a=Foo --Apple:No -b plantain --a %TEMP% @notExpanded --banana -Z --empty=";
            var    args        = G.SplitCommandLineArguments(commandLine);

            var shortOpts = new Dictionary <char, string> {
                { 'a', null }, { 'b', "banana" }
            };
            var twoArgOptions = new InvertibleSet <string>(new[] { "banana" });
            var options       = new DList <KeyValuePair <string, string> >();

            UG.ProcessCommandLineArguments(args, options, null, shortOpts, twoArgOptions, expandEnvVars: false);

            ExpectList(args.AsListSource(), "-abZ", "and", "%TEMP%", "@notExpanded", "-Z");
            ExpectList(options, P("a", null), P("banana", "123"), P("a", "Foo"), P("apple", "No"), P("banana", "plantain"), P("a", null), P("banana", null), P("empty", ""));
        }