Beispiel #1
0
        public void WithOptions(OptionParser opts)
        {
            opts.Header = "Search for PATTERN in each FILE or standard input.\n";
            opts.Header += "Example: grep -i \"hello world\" menu.h main.c";

            opts.Required.Arg<string>("PATTERN", "{0} is a .NET/Mono Regular Expression string.").Do(pattern => settings.Pattern = pattern);
            opts.Args<string>("FILE", "").Do(settings.Files.AddRange);

            opts.In("Regexp selection and interpretation", g =>
            {
                g.On("ignore-case", 'i', "ignore case distinctions").Do(() => settings.RegexOptions |= RegexOptions.IgnoreCase);
            });
            opts.In("Miscellaneous", g =>
            {
                g.On("no-messages", 's', "suppress error messages").Do(() => settings.SuppressErrorMessages = true);
                g.On("invert-match", 'v', "select non-matching lines").Do(() => settings.InvertMatch = true);
            });
            opts.In("Output control", g => {
                g.On("line-number", 'n', "print line number with output lines").Do(() => settings.Output.LineNumbers = true);
                g.On("with-filename", 'H', "print the filename for each match").Do(() => settings.Output.FileNames = true);
                g.On("no-filename", 'h', "print line number with output lines").Do(() => settings.Output.FileNames = false);
                g.On("files-without-match", 'L', "only print FILE names containing no match").Do(() => settings.Output.OnlyFileNames = OnlyFileNames.NonMatching);
                g.On("files-with-matches", 'l', "only print FILE names containing matches").Do(() => settings.Output.OnlyFileNames = OnlyFileNames.Matching);
            });

            opts.Footer = "With no FILE, or when FILE is -, read standard input.  If less than\n";
            opts.Footer += "two FILEs given, assume -h. Exit status is 0 if match, 1 if no match,\n";
            opts.Footer += "and 2 if trouble.";
        }
Beispiel #2
0
    public static void Main(string[] args)
    {
        OptionParser prs;

        Console.WriteLine("begin-parsing");
        // auto-calls .Dispose(). how neat.
        using (prs = new OptionParser())
        {
            /*
             * because CIL doesn't really let me properly check whether or not
             * a function takes an argument, every function takes an argument.
             * trying to wrap this in a OptionParser::Value is possible, but
             * is it worth it? C# already has stuff like int.Parse(), etc.
             */
            prs.on(new[] { "-v", "--verbose" }, "enable verbose messages", (string v) =>
            {
                Console.WriteLine("toggling verbose");
            });
            prs.on(new[] { "-o?", "--out=?" }, "write output to <val>", (string v) =>
            {
                Console.WriteLine("got value: {0}", v);
            });
            try
            {
                prs.parse(args);
            }
            catch (OptionParser.Error e)
            {
                Console.WriteLine("failed to parse: {0}", e);
            }
            var remainder = prs.positional();
            Console.WriteLine("positional: ({0}) {1}", remainder.Length, string.Join(" ", remainder));
        }
        Console.WriteLine("end-parsing");
    }
Beispiel #3
0
 public void WithOptions(OptionParser opts)
 {
     opts.Header = "Executes a COMMAND once for each line of input on STDIN.";
     opts.Required.Arg<string>("COMMAND", "{0} to execute.").Do(command => settings.Command = command);
     opts.Args<string>("ARGUMENTS", "Additional {0} to COMMAND. Use - to grab a line from STDIN.").Do(settings.Arguments.AddRange);
     opts.On("verbose", 'v', "Echo each execution of COMMAND on STDERR.").Do(() => settings.Verbose = true);
 }
Beispiel #4
0
 private static void CheckChoiceHasBeenGiven(Entity.Command command)
 {
     if (!OptionParser.HasOption("c", command))
     {
         throw new Exception("The choice must be defined using the option -c");
     }
 }
Beispiel #5
0
        /// <summary>
        /// Application entry point for schema synchronizations
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            try
            {
                AppOptions options = OptionParser.Parse <AppOptions>();
                // determine the number of threads to use while processing
                if (options.Threads == 0)
                {
                    options.Threads = Environment.ProcessorCount;
                }
                if (options.Timeout == 0)
                {
                    options.Timeout = 300;
                }
                if (options.UpdateInterval == 0)
                {
                    options.UpdateInterval = 10000;
                }

                options.Source.MaxPoolSize = options.Threads * 4;
                options.Target.MaxPoolSize = options.Threads * 4;
                options.Source.Timeout     = options.Timeout;
                options.Target.Timeout     = options.Timeout;

                // create the synchronizer
                var synchronizer = new SyncSchema(options);
                synchronizer.Sync();
            }
            catch (OptionParsingException e)
            {
                Console.Error.WriteLine(e.Message);
                AppOptions.Usage();
            }
        }
Beispiel #6
0
 private static void CheckSurveyIdIsGiven(Entity.Command command)
 {
     if (!OptionParser.HasOption("i", command))
     {
         throw new Exception("The survey ID must be defined using the option -i. You can find the ID by using the command \"/survey list -a\"");
     }
 }
Beispiel #7
0
        static void Main(string[] args)
        {
            var outputFile = string.Empty;
            var parser = new OptionParser
            {
                new Option
                {
                    ShortForm = "o",
                    LongForm = "output",
                    Required = true,
                    ActionWithParam = option => outputFile = option
                },
            };

            var inputs = parser.Parse(args);
            if (inputs.Length == 0)
                return;

            Console.WriteLine("Usage: compiler -o output.exe input.exe");
            Console.WriteLine(parser.GetUsage());

            //FIXME: make this use architecture etc
            //var assembly = AssemblyFactory.GetAssembly(inputs[0]);
            //var compiler = new AssemblyCompiler(new MethodCompilerStage(), new GccBuildStage(outputFile));
            //var context = new AssemblyCompilerContext(assembly, assembly.EntryPoint);
            //compiler.Compile(context);
        }
Beispiel #8
0
        public void TestMinMaxValues()
        {
            var options = new Dictionary <TokenType, List <Token> >
            {
                [TokenType.DecimalValues] = new List <Token>
                {
                    new Token(TokenType.Decimal, "-1.10", 0),
                    new Token(TokenType.Decimal, ".5", 0),
                    new Token(TokenType.Decimal, "1.5", 0)
                },
                [TokenType.IntValues] = new List <Token>
                {
                    new Token(TokenType.Number, "-10", 0),
                    new Token(TokenType.Number, "50", 0),
                    new Token(TokenType.Number, "101", 0)
                }
            };

            var(success, _) = OptionParser.TryParseOptions(new Command {
                Options = options
            }, out OptionsClassThree parsedOptions);
            Assert.IsTrue(success);
            Assert.AreEqual(0m, parsedOptions.DecimalValues[0]);
            Assert.AreEqual(.5m, parsedOptions.DecimalValues[1]);
            Assert.AreEqual(1m, parsedOptions.DecimalValues[2]);
            Assert.AreEqual(1, parsedOptions.IntValues[0]);
            Assert.AreEqual(50, parsedOptions.IntValues[1]);
            Assert.AreEqual(100, parsedOptions.IntValues[2]);
        }
Beispiel #9
0
        private static void Main(string[] args)
        {
            var parser = new OptionParser <Options>();

            if (!parser.TryParse(args, out var options))
            {
                return;
            }

            try
            {
                var table = new List <Entry>();
                if (!options.LocalOnly && new DefaultPublicIpResolver().TryResolve(out var publicIp))
                {
                    table.Add("Internet (Public)", publicIp, null);
                }

                var allInterfaces = NetworkInterface
                                    .GetAllNetworkInterfaces()
                                    .Where(i => i.OperationalStatus == OperationalStatus.Up)
                                    .ToArray();

                table.AddRange(allInterfaces.Where(i => i.NetworkInterfaceType == NetworkInterfaceType.Ethernet));
                table.AddRange(allInterfaces.Where(i => i.NetworkInterfaceType == NetworkInterfaceType.Wireless80211));
                table.AddRange(allInterfaces.Where(i => i.NetworkInterfaceType == NetworkInterfaceType.Loopback));

                table.WriteTable(Console.Out, options.ShowIpv6);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                parser.WriteUsage();
            }
        }
        public void Parse_IntValueAndParameterWithShortName_PropertiesAreSetCorrect()
        {
            const int expectedValue0 = 1234;
            const int expectedValue1 = 4321;

            var args = new[] { "hello", "-j", expectedValue1.ToString(), "-i", expectedValue0.ToString() };

            var parser = new OptionParser(typeof(TestOptionWithInt));

            // Act
            var option = parser.Parse(args) as TestOptionWithInt;

            // Assert
            option
            .Should()
            .NotBeNull();

            option !.IntValue
            .Should()
            .Be(expectedValue0);

            option.IntValue2
            .Should()
            .Be(expectedValue1);

            option.DefIntValue
            .Should()
            .Be(1357);
        }
        public void Parse_RequiredValueMissing_ThrowsException()
        {
            var args = Array.Empty <string>();

            var parser = new OptionParser(typeof(TestOptionWithValueOption));

            // Act
            Action act = () => parser.Parse(args);

            // Assert
            var exception = act
                            .Should()
                            .Throw <RequiredArgumentMissingException>()
                            .Which;

            exception.MissingProperty
            .Should()
            .BeSameAs(typeof(TestOptionWithValueOption).GetProperty(nameof(TestOptionWithValueOption.TestValue)));

            exception.ValueAttribute
            .Should()
            .BeEquivalentTo(new OptionValueAttribute(0)
            {
                IsRequired = true
            });
        }
        public void Parse_RequiredParameterMissing_ThrowsException()
        {
            const int expectedValue1 = 4321;

            var args = new[] { "hello", "-j", expectedValue1.ToString() };

            var parser = new OptionParser(typeof(TestOptionWithInt));

            // Act
            Action act = () => parser.Parse(args);

            // Assert
            var exception = act
                            .Should()
                            .Throw <RequiredArgumentMissingException>()
                            .Which;

            exception.MissingProperty
            .Should()
            .BeSameAs(typeof(TestOptionWithInt).GetProperty(nameof(TestOptionWithInt.IntValue)));

            exception.ParameterAttribute
            .Should()
            .BeEquivalentTo(new OptionParameterAttribute('i', "integer")
            {
                IsRequired = true
            });
        }
Beispiel #13
0
        static void Main(string[] aArgs)
        {
            Helper       helper    = new Helper(aArgs);
            OptionParser optParser = helper.OptionParser;

            OptionParser.OptionString option1 = new OptionParser.OptionString("-1", "--protocol", "UDP", "Protocol (UDP or TCP)", "PROTOCOL");
            OptionParser.OptionString option2 = new OptionParser.OptionString("-2", "--clientaddr", "127.0.0.1", "Client IP address", "CLIENTADDRESS");
            OptionParser.OptionInt    option3 = new OptionParser.OptionInt("-3", "--clientport", 51936, "Client port", "CLIENTPORT");
            OptionParser.OptionString option4 = new OptionParser.OptionString("-4", "--serveraddr", "127.0.0.1", "Server IP address", "SERVERADDRESS");
            OptionParser.OptionInt    option5 = new OptionParser.OptionInt("-5", "--serverport", 51936, "Server port", "SERVERPORT");
            OptionParser.OptionInt    option6 = new OptionParser.OptionInt("-6", "--size", 4, "Size of each packet (bytes)", "PACKETSIZE");
            OptionParser.OptionInt    option7 = new OptionParser.OptionInt("-7", "--total", 20, "Total number of packets to send", "PACKETTOTAL");
            OptionParser.OptionInt    option8 = new OptionParser.OptionInt("-8", "--delay", 0, "Delay between packets (0.1ms steps)", "PACKETDELAY");
            optParser.AddOption(option1);
            optParser.AddOption(option2);
            optParser.AddOption(option3);
            optParser.AddOption(option4);
            optParser.AddOption(option5);
            optParser.AddOption(option6);
            optParser.AddOption(option7);
            helper.ProcessCommandLine();

            Client test = new Client(option1.Value, option2.Value, option3.Value, option4.Value, option5.Value, option6.Value, option7.Value, option8.Value);

            // run the test ...
            test.ClientServerTest();
            helper.Dispose();
        }
 public void ShortOptionRun_WithSecondOptionRequiringArgument_ThrowsException()
 {
     var parser = new OptionParser {
         Definitions = NoneOptionalRequiredArguments
     };
     var results = parser.Parse(new[] { "-ac" }).ToArray();
 }
 public void ShortSlashOptionRequiringArgument_WithoutArgument_ThrowsException()
 {
     var parser = new OptionParser {
         Definitions = SingleRequiredArgument
     };
     var results = parser.Parse(new[] { "/a" }).ToArray();
 }
Beispiel #16
0
 public void WithOptions(OptionParser opts)
 {
     opts.Header = "Executes a COMMAND once for each line of input on STDIN.";
     opts.Required.Arg <string>("COMMAND", "{0} to execute.").Do(command => settings.Command = command);
     opts.Args <string>("ARGUMENTS", "Additional {0} to COMMAND. Use - to grab a line from STDIN.").Do(settings.Arguments.AddRange);
     opts.On("verbose", 'v', "Echo each execution of COMMAND on STDERR.").Do(() => settings.Verbose = true);
 }
Beispiel #17
0
        public void WithOptions(OptionParser opts)
        {
            opts.Header  = "Search for PATTERN in each FILE or standard input.\n";
            opts.Header += "Example: grep -i \"hello world\" menu.h main.c";

            opts.Required.Arg <string>("PATTERN", "{0} is a .NET/Mono Regular Expression string.").Do(pattern => settings.Pattern = pattern);
            opts.Args <string>("FILE", "").Do(settings.Files.AddRange);

            opts.In("Regexp selection and interpretation", g =>
            {
                g.On("ignore-case", 'i', "ignore case distinctions").Do(() => settings.RegexOptions |= RegexOptions.IgnoreCase);
            });
            opts.In("Miscellaneous", g =>
            {
                g.On("no-messages", 's', "suppress error messages").Do(() => settings.SuppressErrorMessages = true);
                g.On("invert-match", 'v', "select non-matching lines").Do(() => settings.InvertMatch        = true);
            });
            opts.In("Output control", g => {
                g.On("line-number", 'n', "print line number with output lines").Do(() => settings.Output.LineNumbers = true);
                g.On("with-filename", 'H', "print the filename for each match").Do(() => settings.Output.FileNames   = true);
                g.On("no-filename", 'h', "print line number with output lines").Do(() => settings.Output.FileNames   = false);
                g.On("files-without-match", 'L', "only print FILE names containing no match").Do(() => settings.Output.OnlyFileNames = OnlyFileNames.NonMatching);
                g.On("files-with-matches", 'l', "only print FILE names containing matches").Do(() => settings.Output.OnlyFileNames   = OnlyFileNames.Matching);
            });

            opts.Footer  = "With no FILE, or when FILE is -, read standard input.  If less than\n";
            opts.Footer += "two FILEs given, assume -h. Exit status is 0 if match, 1 if no match,\n";
            opts.Footer += "and 2 if trouble.";
        }
 public void UnknownLongSlashOption_ThrowsException()
 {
     var parser = new OptionParser {
         Definitions = SingleRequiredArgument
     };
     var results = parser.Parse(new[] { "/long" }).ToArray();
 }
        public async Task <int> ExecuteAsync(string[] args)
        {
            Ensure.NotNull(args, nameof(args));

            var(groupCommandIsExecuted, groupCommandResult) = await TryExecuteGroupCommandAsync(args);

            if (groupCommandIsExecuted)
            {
                return(groupCommandResult?.ReturnCode ?? _context.DefaultErrorReturnCode);
            }

            var(commandIsExecuted, commandResult) = await TryExecuteCommandAsync(args);

            if (commandIsExecuted)
            {
                return(commandResult?.ReturnCode ?? _context.DefaultErrorReturnCode);
            }

            if (_context.DefaultCommand == null)
            {
                return(_context.DefaultErrorReturnCode);
            }

            var defaultOptions = new OptionParser(_context.DefaultCommand.OptionsType).Parse(args);

            var defaultCommandResult = await _context.DefaultCommand.ExecuteAsync(defaultOptions);

            return(defaultCommandResult.ReturnCode);
        }
Beispiel #20
0
        public static ProcessResultArray <Clip> Apply(Command command, params Clip[] clips)
        {
            (var success, var msg) = OptionParser.TryParseOptions(command, out ScanOptions options);
            if (!success)
            {
                return(new ProcessResultArray <Clip>(msg));
            }
            var processedClips = new Clip[clips.Length];

            for (var c = 0; c < clips.Length; c++)
            {
                var     clip          = clips[c];
                var     processedClip = new Clip(options.Window * options.Count, clip.IsLooping);
                decimal delta         = clip.Length / options.Count,
                        curPos        = 0;

                for (int i = 0; i < options.Count; i++)
                {
                    processedClip.Notes.AddRange(ClipUtilities.GetSplitNotesInRangeAtPosition(curPos, curPos + options.Window, clip.Notes, options.Window * i));
                    curPos += delta;
                }
                processedClips[c] = processedClip;
            }

            return(new ProcessResultArray <Clip>(processedClips));
        }
Beispiel #21
0
 private static void CheckSurveyIdIsGiven(Entity.Command command)
 {
     if (OptionParser.CountOptions("i", command) != 1)
     {
         throw new Exception("You must specify the ID");
     }
 }
 public void ShortOptionRun_WithSecondOptionUnknown_ThrowsException()
 {
     var parser = new OptionParser {
         Definitions = SingleNoneArgument
     };
     var results = parser.Parse(new[] { "-an" }).ToArray();
 }
Beispiel #23
0
    public static SpecSharpOptions ParseCommandLineArguments(MetadataHostEnvironment hostEnvironment, IEnumerable <string> arguments)
    {
        OptionParser parser = new OptionParser(hostEnvironment);

        parser.ParseCommandLineArguments(arguments, true);
        return(parser.options);
    }
Beispiel #24
0
        private (string Name, string Author, List <EngineOption> Options) ParseUciHeader(string uciHeader)
        {
            string idName   = null;
            string idAuthor = null;
            var    options  = new List <EngineOption>();
            var    lines    = uciHeader.Split('\n');

            foreach (var l in lines)
            {
                if (l.StartsWith("id name"))
                {
                    idName = string.Join(' ', l.Split(' ').Skip(2));
                }
                else if (l.StartsWith("id author"))
                {
                    idAuthor = string.Join(' ', l.Split(' ').Skip(2));
                }
                else if (l.StartsWith("option"))
                {
                    options.Add(OptionParser.ParseOptionLine(l));
                }
            }

            return(idName, idAuthor, options);
        }
 public void LongOptionRequiringArgument_WithoutArgument_ThrowsException()
 {
     var parser = new OptionParser {
         Definitions = SingleRequiredArgument
     };
     var results = parser.Parse(new[] { "--aardvark" }).ToArray();
 }
 public void LongSlashOptionNoneArgument_WithEqualsArgument_ThrowsException()
 {
     var parser = new OptionParser {
         Definitions = SingleNoneArgument
     };
     var results = parser.Parse(new[] { "/aardvark=animal" }).ToArray();
 }
 public void ShortSlashOptionNoneArgument_WithEmptyEqualsArgument_ThrowsException()
 {
     var parser = new OptionParser {
         Definitions = SingleNoneArgument
     };
     var results = parser.Parse(new[] { "/a=" }).ToArray();
 }
        public void SimpleParameters_WithoutParameter_IsParsed()
        {
            var parameters = new SimpleParameters();

            OptionParser.Parse(new[] { "/f" }, parameters);
            Assert.IsTrue(parameters.Flag);
        }
 public void ShortOptionNoneArgument_WithEmptyColonArgument_ThrowsException()
 {
     var parser = new OptionParser {
         Definitions = SingleNoneArgument
     };
     var results = parser.Parse(new[] { "-a:" }).ToArray();
 }
        public void SimpleParameters_WithParsedParameter_IsParsed()
        {
            var parameters = new SimpleParameters();

            OptionParser.Parse(new[] { "13" }, parameters);
            Assert.AreEqual(14, parameters.FirstPositionalArgument);
        }
        public void SimpleParameters_WithSingleParameter_IsParsed()
        {
            var parameters = new SimpleParameters();

            OptionParser.Parse(new[] { "--Animal", "horse" }, parameters);
            Assert.AreEqual("horse", parameters.Animal);
        }
 public void JustASlash_ThrowsException()
 {
     var parser = new OptionParser {
         Definitions = SingleRequiredArgument
     };
     var results = parser.Parse(new[] { "/", "a" }).ToArray();
 }
 public void ShortOptionRun_WithColonArgument_ThrowsException()
 {
     var parser = new OptionParser {
         Definitions = SingleNoneArgument
     };
     var results = parser.Parse(new[] { "-aardvark:animal" }).ToArray();
 }
Beispiel #34
0
        static void Main(string[] args)
        {
            OptionParser parser = new OptionParser();
            var setting = parser.Parse(args);

            SignHost.SignPath(setting);

            System.Console.ReadLine();
        }
Beispiel #35
0
        public void WithOptions(OptionParser opts)
        {
            opts.Header = "Copy standard input to each FILE, and also to standard output.";

            opts.Args<string>("FILE", "").Do(settings.Files.AddRange);

            opts.On("append", 'a', "Append to the given FILEs, do not overwrite").Do(() => settings.FileMode = FileMode.Append);

            opts.Footer = "With no FILE, or when a FILE is -, copy again to standard output.";
        }
Beispiel #36
0
        public void WithOptions(OptionParser opts)
        {
            opts.Header = "Summarize disk usage of each FILE, recursively for directories.";

            opts.Args<string>("FILE", "").Do(files => { });

            opts.Footer = "Display values are in units of the first available SIZE from --block-size,\n";
            opts.Footer += "and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables.\n";
            opts.Footer += "Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set).\n";
            opts.Footer += "\n";
            opts.Footer += "SIZE may be (or may be an integer optionally followed by) one of following:\n";
            opts.Footer += "KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n";
        }
Beispiel #37
0
        /*  ALIAS
            GNU Options
                -d=DIR, --dir=DIR
                    Install the script into directory DIR, rather than
                    searching for a suitable directory in $PATH.
                -m, --manpage
                    Display the manpage for the alias script given as the
                    single argument. The alias can be an absolute pathname, or
                    the name of a script in $PATH. If the argument isn't an
                    alias script, or if multiple arguments are given, then all
                    arguments are passed to the system 'man' command. This
                    allows you to alias your man command like this:
                    alias man='0alias --manpage'
                -r, --resolve
                    Print the interface URI for the given alias script to stdout

            GNU Standard Options
                -h, --help
                    Show the built-in help text.
                -V, --version
                    Display version information.
        */
        static void Main(string[] args)
        {
            // Set parser
            OptionParser parser = new OptionParser();
            parser.ProgramInfo.Name = "Alias";
            parser.ProgramInfo.Version = "1.3.2.1";

            // Add reqired option, which has reqired parameter
            OptionValue<string> dir = new OptionValue<string>();
            parser.AddOption(
                new Option(new string[] { "-d", "--dir" },
                    "Install the script into directory DIR, rather than searching for a suitable directory in $PATH.",
                    new StoreAction<string>(dir)
                ) { Required = true, ParametersRequired = true}
            );

            // Add option, which has not any parameter
            OptionValue<bool> manpage = new OptionValue<bool>(false);
            parser.AddOption(
                new Option(new string[] { "-m", "--manpage" },
                    "Display the manpage for the alias script given as the single argument.",
                    new StoreConstAction<bool>(manpage, true)
                ) { ParametersCount = 0 }
            );

            // Add option, which has not any parameter
            OptionValue<bool> resolve = new OptionValue<bool>(false);
            parser.AddOption(
                new Option(new string[] { "-r", "--resolve" },
                    "Print the interface URI for the given alias script to stdout.",
                    new StoreConstAction<bool>(resolve, true)
                ) { ParametersCount = 0 }
            );

            try
            {
                // Run options parser (for example with args: --dir ./rootdir/nextdir/ -r)
                IList<string> remainingArgs = parser.ParseArguments(args);
                Console.WriteLine("dir: {0}", dir.Value);
                Console.WriteLine("manpage: {0}", manpage.Value);
                Console.WriteLine("resolve: {0}", resolve.Value);
            }
            catch (ParseException exception)
            {
                // User control the exception
                System.Console.WriteLine("exception: " + exception.Message);
            }
        }
 /// <summary>
 /// Formats a help message about using options to an output stream.
 /// Write a general usage pattern and a description of each option
 /// (<see cref="Option.Names"/>, <see cref="Option.HelpText"/>
 /// </summary>
 /// <param name="writer">output stream</param>
 /// <param name="options">information about the options</param>
 /// <param name="programInfo">information about the program</param>
 public void FormatHelp(
     System.IO.TextWriter writer,
     IList<Option> options,
     OptionParser.ProgramInformation programInfo)
 {
     string usageLine = String.Format(programInfo.UsageFormat, programInfo.Name);
     writer.WriteLine("Usage: {0}", usageLine);
     writer.WriteLine();
     writer.WriteLine("Options:");
     foreach (Option option in options)
     {
         // TODO: print the meta variable if needed (or do that in
         // a more sophisticated HelpFormatter)
         writer.WriteLine("  {0} {1}",
             String.Join(", ", option.Names.ToArray()), option.HelpText);
     }
 }
Beispiel #39
0
        public void WithOptions(OptionParser opts)
        {
            opts.Required.Arg<string>("URL", "").Do(settings.Urls.Add);

            opts.In("Logging and input file", g =>
            {
                g.On("output-file", 'o', "log messages to {0}").WithArg<string>("FILE").Do(filename => settings.Logging.WriteTo = filename);
                g.On("append-output", 'a', "append messages to {0}").WithArg<string>("FILE").Do(filename => settings.Logging.AppendTo = filename);
                g.On("quiet", 'q', "quiet (no output)").Do(() => { settings.Quiet = true;});
                g.On("debug", 'd', "print lots of debugging information").Do(() => settings.Logging.Debug = true);
            });

            opts.In("Download", g => {
                g.On("tries", 't', "set number of retries to {0} (0 - unlimited)").WithArg<int>("NUMBER").Do(retries => {});
                g.On("output-document", 'O', "write documents to {0}").WithArg<string>("FILE").Do(filename => settings.Download.OutputDocument = filename);
                g.On("no-clobber", 'n', "skip downloads that would download to existing files").Do(() => {});
                g.On("continue", 'c', "resume getting a partially-downloaded file").Do(() => {});
                g.On("progress", "select progress gauge {0}")
                    .WithArg<ProgressType>("TYPE")
                    .WithParseErrorMessage("--{0}: Invalid progress type '{1}'.\nValid choices are: None, Bar, Dot")
                    .Do(type => settings.Download.ProgressType = type);
                g.On("timestamping", 'N', "don't re-retrieve files unless newer than local").Do(() => {});
                g.On("server-response", 'S', "print server response").Do(() => {});
                g.On("spider", "don't download anything").Do(() => {});
                g.On("timeout", 'T', "set all timeout values to {0}").WithArg<int>("SECONDS").Do(timeout => {});
                g.On("user", "set both ftp and http user to {0}").WithArg<string>("USER").Do(user => {});
                g.On("password", "set both ftp and http password to {0}").WithArg<string>("PASSWORD").Do(password => {});
                g.On("ask-password", "prompt for passwords").Do(() => {});
            });

            opts.In("HTTP options", g =>
            {
                g.On("http-user", "set http user to {0}").WithArg<string>("USER").Do(user => {});
                g.On("http-password", "set http password to {0}").WithArg<string>("PASSWORD").Do(password => {});
                g.On("ask-password", "prompt for passwords").Do(() => {});
                g.On("referer", "include `Referer: {0}' header in HTTP request").WithArg<string>("URL").Do(refererUrl => {});
                g.On("header", "insert {0} among the headers sent").WithArg<string>("STRING").Do(header => {});
                g.On("user-agent", 'U', "identify as {0} instead of Wget/VERSION").WithArg<string>("AGENT").Do(userAgent => {});
                g.On("post-data", "use the POST method; send {0} as the data").WithArg<string>("STRING").Do(postData => {});
                g.On("post-file", "use the POST method; send contents of {0}").WithArg<string>("FILE").Do(postDataFile => {});
            });
        }
Beispiel #40
0
        public void WithOptions(OptionParser opts)
        {
            opts.Header = "Search for PATTERN and replace with REPLACE in each FILE or standard input.\n";
            opts.Header += "Example: sed 'hello world' 'goodbye world' menu.h main.c";

            opts.Required.Arg<string>("PATTERN", "{0} is a .NET/Mono Regular Expression string.").Do(pattern => settings.Pattern = pattern);
            opts.Required.Arg<string>("REPLACE", "").Do(replace => settings.Replace = replace);
            opts.Args<string>("FILE", "").Do(settings.Files.AddRange);

            opts.In("Regexp selection and interpretation", g =>
            {
                g.On("ignore-case", 'i', "ignore case distinctions").Do(() => settings.RegexOptions |= RegexOptions.IgnoreCase);
            });
            opts.In("Miscellaneous", g =>
            {
                g.On("no-messages", 's', "suppress error messages").Do(() => settings.SuppressErrorMessages = true);
            });

            opts.Footer = "With no FILE, or when FILE is -, read standard input.\n";
            opts.Footer += "Exit status is 0 on success and 2 if trouble.";
        }
Beispiel #41
0
        public void WithOptions(OptionParser opts)
        {
            opts.Header = "Show information about the file system on which each FILE resides,\nor all file systems by deafult.";

            opts.Args<string>("FILE", "").Do(files => { });

            opts.On("block-size", 'B', "use SIZE-byte blocks").WithArg<int>("SIZE").Do(arg => { customBlockSize = true; blockSize = arg; });
            opts.On("human-readable", 'h', "print sizes in human readable format (e.g., 1K 234M 2G)").Do(() => humanReadable = true);
            opts.On("si", 'H', "likewise, but use powers of 1000 not 1024").Do(() => humanReadableWithSi = true);
            opts.On("portability", 'P', "use the POSIX output format").Do(() => posixFormat = true);
            opts.On("type", 't', "limit listing to file systems of type TYPE").WithArg<string>("TYPE").Do(arg => limitToType = arg);
            opts.On("print-type", 'T', "print file system type").Do(() => printFileSystemType = true);
            opts.On("exclude-type", 'x', "limit listing to file systems not of type TYPE").WithArg<string>("TYPE").Do(arg => excludeType = arg);

            opts.Footer = "Display values are in units of the first available SIZE from --block-size,\n";
            opts.Footer += "and the DF_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables.\n";
            opts.Footer += "Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set).\n";
            opts.Footer += "\n";
            opts.Footer += "SIZE may be (or may be an integer optionally followed by) one of following:\n";
            opts.Footer += "KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n";
        }
Beispiel #42
0
        static int Main(string[] args)
        {
            var opts = new OptionParser();
            opts.On("help", "display this help and exit").Do(() =>
            {
                opts.WriteUsage(Console.Out);
                Environment.Exit(0);
            });
            opts.On("version", 'V', "print version information and exit").Do(() =>
            {
                opts.WriteVersionInfo(Console.Out);
                Environment.Exit(0);
            });

            try
            {
                var commandType = App.Commands
                   .SingleOrDefault(NamedAsExecutable)
                   ?? typeof(UnknownCommand);

                var command = ((ICommand)Activator.CreateInstance(commandType));

                command.WithOptions(opts);
                opts.Parse(args);
                return command.Execute();
            }
            catch (OptionParserException ex)
            {
                Console.Error.WriteLine(ex.Message);
                opts.WriteUsageHeader(Console.Error);
                Console.Error.WriteLine("\nTry `{0} --help' for more options.", App.CommandName);
                return 2;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                return 1;
            }
        }
 /// <summary>
 /// Executes the callback action ignoring any option parameters.
 /// </summary>
 /// <param name="parameters">The list of option parameters which is
 /// ignored, however.</param>
 /// <param name="parserState">Current state of the option parser.
 /// </param>
 public void Execute(IList<string> parameters, OptionParser.State parserState)
 {
     callback_(parserState);
 }
 /// <summary>
 /// Formats program version string to an output stream.
 /// </summary>
 /// <param name="writer">The output writer.</param>
 /// <param name="programInfo">The information about the program.</param>
 public void FormatVersion(
     System.IO.TextWriter writer,
     OptionParser.ProgramInformation programInfo)
 {
     writer.WriteLine(String.Format("{0} {1}", programInfo.Name, programInfo.Version));
 }
Beispiel #45
0
 public void WithOptions(OptionParser opts)
 {
 }
Beispiel #46
0
        /*  TIME
            GNU Options
                -f FORMAT, --format=FORMAT
                    Specify output format, possibly overriding the format
                    specified in the environment variable TIME.
                -p, --portability
                    Use the portable output format.
                -o FILE, --output=FILE
                    Do not send the results to stderr, but overwrite the
                    specified file.
                -a, --append
                    (Used together with -o.) Do not overwrite but append.
                -v, --verbose
                    Give very verbose output about all the program knows about.

            GNU Standard Options
                -h --help
                    Print a usage message on standard output and exit
                    successfully.
                -V, --version
                    Print version information on standard output, then exit
                    successfully.
                --
                    Terminate option list.
        */
        static void Main(string[] args)
        {
            // Set parser
            OptionParser parser = new OptionParser();
            parser.ProgramInfo.Name = "Time";
            parser.ProgramInfo.Version = "3.14";

            // Add option, which has reqired parameter and meta variable "TIME"
            OptionValue<string> format = new OptionValue<string>("DD.MM.YYYY");
            parser.AddOption(
                new Option(new string[] { "-f", "--format" },
                    "Specify output format, possibly overriding the format specified in the environment variable TIME.",
                    new StoreAction<string>(format)
                ) { ParametersRequired = true }
            );

            // Add option, which has not any parameter
            OptionValue<bool> portability = new OptionValue<bool>(false);
            parser.AddOption(
                new Option(new string[] { "-p", "--portability" },
                    "Use the portable output format.",
                    new StoreConstAction<bool>(portability, true)
                ) { ParametersCount = 0 }
            );

            // Add option, which has reqired parameter
            OptionValue<string> output = new OptionValue<string>();
            parser.AddOption(
                new Option(new string[] { "-o", "--output" },
                    "Do not send the results to stderr, but overwrite the specified file.",
                    new StoreAction<string>(output)
                ) { ParametersRequired = true}
            );

            // Add option, which has not any parameter
            OptionValue<bool> append = new OptionValue<bool>(false);
            parser.AddOption(
                new Option(new string[] { "-a", "--append" },
                    "(Used together with -o.) Do not overwrite but append.",
                    new StoreConstAction<bool>(append, true)
                ) { ParametersCount = 0 }
            );

            // Add option, which has not any parameter
            OptionValue<bool> verbose = new OptionValue<bool>(false);
            parser.AddOption(
                new Option(new string[] { "-v", "--verbose" },
                    "Give very verbose output about all the program knows about.",
                    new StoreConstAction<bool>(verbose, true)
                ) { ParametersCount = 0 }
            );

            try
            {
                // Run options parser (for example with args: -f YYYY.MM.DDD -p -o ./outputfile -a -v)
                IList<string> remainingArgs = parser.ParseArguments(args);
                Console.WriteLine("format: {0}", format.Value);
                Console.WriteLine("portability: {0}", portability.Value);
                Console.WriteLine("output: {0}", output.Value);
                Console.WriteLine("append: {0}", append.Value);
                Console.WriteLine("verbose: {0}", verbose.Value);
            }
            catch (ParseException exception)
            {
                // User control the exception
                System.Console.WriteLine("exception: " + exception.ToString());
            }
        }