Beispiel #1
0
 /// <summary>
 /// Add a default help switch "-help","-h","-?","/help"
 /// </summary>
 public Option AddHelpOption()
 {
     _help = AddBoolSwitch("-help", "Command line help");
     _help.AddAlias("-h");
     _help.AddAlias("-?");
     _help.AddAlias("/help");
     return(_help);
 }
Beispiel #2
0
        private static int SimpletMethod(params string[] args)
        {
            Console.WriteLine("test");

            var optionThatTakesInt = new Option <int>(
                name: "--int-option",
                description: "An option whose argument is parsed as an int",
                getDefaultValue: () => 42)
            {
                Arity    = ArgumentArity.ExactlyOne,
                IsHidden = false
            };

            optionThatTakesInt.AddAlias("-i");

            var optionThatTakesBool = new Option <bool>(
                "--bool-option",
                "An option whose argument is parsed as a bool")
            {
                Arity = ArgumentArity.ZeroOrOne,
            };

            optionThatTakesInt.AddAlias("-b");

            Console.WriteLine("rootcommand ctor");
            var rootCommand = new RootCommand();

            rootCommand.Description = "My sample app";
            rootCommand.AddOption(optionThatTakesInt);
            rootCommand.AddOption(optionThatTakesBool);

            Console.WriteLine("rootcommand created");

            rootCommand.Handler = CommandHandler.Create(() =>
            {
                Console.WriteLine($"The value for --int-option is: ");
            });

            // rootCommand.InvokeAsync(args).GetAwaiter().GetResult();

            rootCommand.Handler = CommandHandler.Create <int, bool>((intOption, boolOption) =>
            {
                Console.WriteLine($"The value for --int-option is: {intOption}");
                Console.WriteLine($"The value for --bool-option is: {boolOption}");
            });

            // rootCommand.InvokeAsync(args).GetAwaiter().GetResult();

            var parse   = new CommandLineBuilder(rootCommand).Build();
            var pr      = parse.Parse(args);
            var context = new InvocationContext(pr, new SystemConsole());

            rootCommand.Handler.InvokeAsync(context).GetAwaiter().GetResult();

            return(0);
        }
Beispiel #3
0
        public void AddCommand(Command rootCommand)
        {
            var cmd = new Command("BlockTrain", "Blocks someone, and everyone which follows them.");

            cmd.AddAlias("blocktrain");
            cmd.AddAlias("bt");

            var dryRunOption = new Option <bool>("--dryrun", "Does not actually make the changes");

            cmd.Add(dryRunOption);

            var targetOption = new Option <string>("--target", "Person to block");

            targetOption.AddAlias("-t");
            targetOption.Name     = "targetUsername";
            targetOption.Required = true;
            cmd.Add(targetOption);

            var logOption = new Option <bool>("--log", "Creates (or appends if the file exists) a log of all the " +
                                              "accounts impacted by the BlockTrain");

            logOption.Name = "log";
            logOption.AddAlias("-l");
            cmd.Add(logOption);

            var muteOption = new Option <bool>("--mute", "Rather than blocking, this command will mute the targets");

            muteOption.AddAlias("-m");
            cmd.Add(muteOption);

            cmd.Handler = CommandHandler.Create <bool, string, bool, bool>(this.Execute);
            rootCommand.Add(cmd);
        }
Beispiel #4
0
        public void AddCommand(Command rootCommand)
        {
            var cmd = new Command("Clean", "Scores everyone who follows the supplied user and if they do not meet a min-score they get blocked and unblocked which forces them to unfollow you.");

            cmd.AddAlias("clean");
            cmd.AddAlias("c");

            var dryRunOption = new Option <bool>("--dryrun", "Does not actually make the changes");

            cmd.Add(dryRunOption);

            var minScoreOption = new Option <double>(
                "--score",
                () => 0.85,
                "Sets the score for min kicking. Defaults to 0.85");

            minScoreOption.Name = "minscore";
            minScoreOption.AddAlias("-s");
            cmd.Add(minScoreOption);

            var logOption = new Option <bool>("--log", "Creates (or appends if the file exists) a log of all the " +
                                              "accounts impacted by the clean");

            logOption.Name = "log";
            logOption.AddAlias("-l");
            cmd.Add(logOption);

            cmd.Handler = CommandHandler.Create <bool, double, bool>(this.Execute);
            rootCommand.Add(cmd);
        }
Beispiel #5
0
        public IsNegative() : base("isnegative")
        {
            var optionNumber = new Option <int>("-number");

            optionNumber.AddAlias("-n");
            Add(optionNumber);
        }
        public static async Task Main(string[] args)
        {
            var option = new Option <string>("--savedir", "The directory to save downloaded images to.")
            {
                Name     = "savedir",
                Required = true
            };

            option.AddAlias("-s");

            var cmd = new RootCommand
            {
                option
            };

            cmd.Description = "Download the Bing daily image.";

            try
            {
                cmd.Handler = CommandHandler.Create <string>(DownloadBingDailyImage);
                await cmd.InvokeAsync(args);
            }
            catch (Exception ex)
            {
                File.WriteAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "bing-error.txt"), ex.ToString());
            }
        }
    public void ThrowIfInvalid_throws_if_there_are_duplicate_sibling_option_aliases_on_a_subcommand()
    {
        var option1 = new Option <string>("--dupe");
        var option2 = new Option <string>("--ok");

        option2.AddAlias("--dupe");

        var command = new RootCommand
        {
            new Command("subcommand")
            {
                option1,
                option2
            }
        };

        var config = new CommandLineConfiguration(command);

        var validate = () => config.ThrowIfInvalid();

        validate.Should()
        .Throw <CommandLineConfigurationException>()
        .Which
        .Message
        .Should()
        .Be("Duplicate alias '--dupe' found on command 'subcommand'.");
    }
Beispiel #8
0
        private void SetupOptions()
        {
            var path = new Option <string>("--data-source")
            {
                Description = "Path to the data",
                IsRequired  = true
            };

            path.AddAlias("--source");

            var output = new Option <OutputMode>("--output", () => OutputMode.Console)
            {
                Description = "Where to write the xml results to"
            };

            var auth = new Option <string>("--auth")
            {
                Description = "MongoDb credentials, ignored if output is not Mongo"
            };

            var mongo = new Option <string>("--mongo")
            {
                Description = "Comma separated list of mongo addresses"
            };

            AddOption(path);
            AddOption(output);
            AddOption(auth);
            AddOption(mongo);
        }
Beispiel #9
0
        public Command GetCommand()
        {
            var rv         = new Command(Attribute.Name, Attribute.Description);
            var cmdAliases = GetAliases();

            if (cmdAliases != null)
            {
                foreach (var alias in GetAliases())
                {
                    rv.AddAlias(alias);
                }
            }

            var oattr = OptionAttribute.GetOptionParameters(Method);

            foreach (var o in oattr)
            {
                var option  = new Option <object>(o.Attribute.Name, o.Attribute.Description); // TODO: determine if we need to supply type specific mappings
                var aliases = o.Attribute.Aliases?.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
                if (aliases != null)
                {
                    foreach (var a in aliases)
                    {
                        option.AddAlias(a);
                    }
                }
                if (o.Attribute.Required)
                {
                    option.IsRequired = true;
                }
                rv.AddOption(option);
            }
            rv.Handler = CommandHandler.Create(CreateDelegate(Method));
            return(rv);
        }
Beispiel #10
0
        public static async Task <int> Main(string[] args)
        {
            Option countOption = new Option("--count", "The number of classes to create", new Argument <int>(1));

            countOption.AddAlias("-c");

            Option outputOption = new Option("--output", "Where to output the files to", new Argument <string>(Environment.CurrentDirectory));

            outputOption.AddAlias("-o");

            Option namespaceOption = new Option("--namespace", "The namespace to use for the class file", new Argument <string>("Classes"));

            namespaceOption.AddAlias("-n");

            var command = new RootCommand();

            command.Description = "Creates a large number of C# classes";
            command.AddOption(countOption);
            command.AddOption(outputOption);
            command.AddOption(namespaceOption);

            command.Handler = CommandHandler.Create <int, string, string>((c, o, n) => CreateClasses(c, o, n));

            return(await command.InvokeAsync(args));
        }
        static void Main(string[] args)
        {
            var rootCommand = new RootCommand();

            {
                var fileCommand = new Command("file");
                rootCommand.AddCommand(fileCommand);
                var io = new Option <string>("--input", description: "The file to trim.");
                io.AddAlias("-i");
                fileCommand.AddOption(io);
                fileCommand.Handler = CommandHandler.Create <string>(async(string input) =>
                {
                    //Parse a file of markers into an in-out list for use with the automator.
                    var engine = new Engine(SmpteFrameRate.Smpte25, 10.0);
                    await engine.ParseMarkersFileAsync(input);
                });
            }
            {
                var directoryCommand = new Command("directory");
                rootCommand.AddCommand(directoryCommand);
                var io = new Option <string>("--input", description: "The file to trim.");
                io.AddAlias("-i");
                directoryCommand.AddOption(io);
                directoryCommand.Handler = CommandHandler.Create <string>(async(string input) =>
                {
                    foreach (var fi in new DirectoryInfo(input).GetFiles())
                    {
                        //Parse a file of markers into an in-out list for use with the automator.
                        var engine = new Engine(SmpteFrameRate.Smpte25, 15.0);
                        await engine.ParseMarkersFileAsync(fi.FullName);
                    }
                });
            }
            rootCommand.Invoke(args);
        }
Beispiel #12
0
        public IsNumber() : base("isnumber")
        {
            var optionNumber = new Option <string>("-number");

            optionNumber.AddAlias("-n");
            Add(optionNumber);
        }
Beispiel #13
0
        private Command SetupAnalyzeDirectoryCommand()
        {
            // Setup analyze-directory
            Command analyzeDirectoryCommand = new Command("analyze-directory");

            Option <DirectoryInfo> directoryOption = new Option <DirectoryInfo>(
                "--directory-path",
                "Directory to search for ARM templates (.json file extension)")
            {
                IsRequired = true
            };

            directoryOption.AddAlias("-d");

            analyzeDirectoryCommand.AddOption(directoryOption);

            Option <bool> recursiveOption = new Option <bool>(
                "--recursive",
                "Search directory and all subdirectories");

            recursiveOption.AddAlias("-r");

            analyzeDirectoryCommand.AddOption(recursiveOption);

            analyzeDirectoryCommand.AddOption(SetupOutputFileOption());

            analyzeDirectoryCommand.Handler = CommandHandler.Create <DirectoryInfo, bool>((directoryPath, recursive) =>
            {
                // TODO: This needs to call the library and pass in a list of templates
            });

            return(analyzeDirectoryCommand);
        }
Beispiel #14
0
        public RuntimeCommand() : base("runtime", "Installs the runtime on the robot")
        {
            TreatUnmatchedTokensAsErrors = true;
            downloadOption = new Option("--download");
            downloadOption.AddAlias("-d");
            downloadOption.Description    = "Download mono from internet";
            downloadOption.Argument.Arity = ArgumentArity.Zero;
            Add(downloadOption);

            installOption = new Option("--install");
            installOption.AddAlias("-i");
            installOption.Description    = "Install mono onto rio";
            installOption.Argument.Arity = ArgumentArity.Zero;
            Add(installOption);

            locationOption = new Option <string>("--location");
            locationOption.AddAlias("-l");
            locationOption.Description = "Point to a predownloaded mono location";
            //locationOption.ARgArity = ArgumentArity.ZeroOrOne;
            Add(locationOption);

            this.AddValidator(ValidateOneOptionSelected);

            Handler = CommandHandler.Create <int, string?, bool, bool, string?>(HandleCommand);
        }
        private static Command CreateSilentTokenAcquisitionCommand()
        {
            var silentCommand = new Command("silent", "Perform silent locally cached token acquisition")
            {
                Handler = CommandLineHost.GetCommandHandler <ClientApplicationBaseSilentCommandExecutor>()
            };

            var silentAccountOption = new Option <string>("--account")
            {
                Name        = nameof(SilentAcquireTokenOptions.AccountIdentifier),
                Description = "Previously acquired Account identifier",
                Argument    = { Name = "ACCOUNTID" }
            };

            silentAccountOption.AddAlias("-a");
            silentCommand.AddOption(silentAccountOption);

            var silentForceRefreshOption = new Option <bool>("--force-refresh")
            {
                Name        = nameof(SilentAcquireTokenOptions.ForceRefresh),
                Description = "Force access token refresh using cached refresh token",
            };

            silentCommand.AddOption(silentForceRefreshOption);

            silentCommand.AddOption(CreateAcquireTokenScopesOption());

            return(silentCommand);
        }
Beispiel #16
0
        public Sum() : base("sum")
        {
            var option = new Option <int[]>("-numbers");

            option.AddAlias("-n");
            Add(option);
        }
Beispiel #17
0
        public static async Task <int> Main(string[] args)
        {
            SetupConsoleEncoding();

            var rootCommand = new RootCommand();

            var interactiveCommand = new Command("interactive")
            {
                Handler = CommandHandler.Create <string, CancellationToken>(InteractiveCommand.Interactive)
            };

            interactiveCommand.AddAlias("i");
            var arg = new Option <string>("--project");

            arg.AddAlias("-p");
            interactiveCommand.Add(arg);
            rootCommand.Add(interactiveCommand);

            var studioCommand = new Command("studio")
            {
                Handler = CommandHandler.Create(StudioCommand.Studio)
            };

            studioCommand.AddAlias("s");
            rootCommand.Add(studioCommand);

            return(await rootCommand.InvokeAsync(args).ConfigureAwait(false));
        }
Beispiel #18
0
    public static Command InitCommand()
    {
        var command    = new Command("init", "initialize the Formfile.");
        var fileOption = new Option("--file", "A Stack or Deployment file")
        {
            Argument = new Argument <FileInfo>(() => new FileInfo("./stack.yaml")),
        };

        fileOption.AddAlias("-f");

        command.AddArgument(new Argument <bool>(defaultValue: () => false));
        command.AddAlias("i");
        command.AddOption(fileOption);

        command.Handler = CommandHandler.Create(
            async(FileInfo file) =>
        {
            Console.WriteLine($"Writing Geneisis Block ...");
            var result = await Init.Create(new string[] { file.FullName });
            if (!result.Success)
            {
                Console.WriteLine(result.Message);
            }
        });

        return(command);
    }
        private Option VerboseOption()
        {
            var option = new Option <bool>("--verbose", "More verbose output, including stack traces");

            option.AddAlias("-v");

            return(option);
        }
Beispiel #20
0
        public FlashcardVerifyCommand() : base("verify", "Verify ROM on Flashcard")
        {
            Option <FileInfo> uploadFileOption = new Option <FileInfo>("--input");

            uploadFileOption.AddAlias("-i");
            uploadFileOption.ExistingOnly().IsRequired = true;
            this.AddOption(uploadFileOption);
            this.Handler = CommandHandler.Create <GlobalOptions, SerialPortOptions, FileInfo, IConsole>(FlashcardVerifyHandler);
        }
Beispiel #21
0
        public Substract() : base("substract")
        {
            var optionNumber = new Option <int>("-number");

            optionNumber.AddAlias("-n");


            Add(optionNumber);
        }
Beispiel #22
0
        public void A_prefixed_alias_can_be_added_to_an_option()
        {
            var option = new Option("--apple");

            option.AddAlias("-a");

            option.HasAliasIgnorePrefix("a").Should().BeTrue();
            option.HasAlias("-a").Should().BeTrue();
        }
Beispiel #23
0
        public void RawAliases_is_aware_of_added_alias()
        {
            var option = new Option("--original");

            option.AddAlias("--added");

            option.Aliases.Should().Contain("--added");
            option.HasAlias("--added").Should().BeTrue();
        }
Beispiel #24
0
        private Option SetupOutputFileOption()
        {
            Option <FileInfo> outputFileOption = new Option <FileInfo>(
                "--output-path",
                "Redirect output to specified file in JSON format");

            outputFileOption.AddAlias("-o");

            return(outputFileOption);
        }
        public static Option <string> CreateConnectionStringOption()
        {
            var connectionStringOption = new Option <string>(
                name: "--connectionString",
                description: $"Force this command to use the specified connection string");

            connectionStringOption.AddAlias("-c");

            return(connectionStringOption);
        }
Beispiel #26
0
        public Option <VerbosityLevel> GetVerbosity()
        {
            Option <VerbosityLevel> opt = new Option <VerbosityLevel>("--verbosity");

            opt.Description = "Set the verbosity level.";
            opt.IsRequired  = false;
            opt.IsHidden    = false;
            opt.AddAlias("-v");
            return(opt);
        }
        public void When_an_option_alias_is_added_and_contains_whitespace_then_an_informative_error_is_returned(
            string alias)
        {
            var option = new Option("-x");

            Action addAlias = () => option.AddAlias(alias);

            addAlias.Should().Throw <ArgumentException>().Which.Message.Should()
            .Be($"Option alias cannot contain whitespace: \"{alias}\"");
        }
Beispiel #28
0
        public Option <DirectoryInfo> GetFolder()
        {
            Option <DirectoryInfo> opt = new Option <DirectoryInfo>("--folder");

            opt.Description = "";
            opt.IsRequired  = false;
            opt.IsHidden    = false;
            opt.AddAlias("-f");
            return(opt);
        }
Beispiel #29
0
        public Option <bool> GetCheck()
        {
            Option <bool> opt = new Option <bool>("--check");

            opt.Description = "Formats files without saving changes to disk. Terminates with a non-zero exit code if any files were formatted.";
            opt.IsRequired  = false;
            opt.IsHidden    = false;
            opt.AddAlias("-dry-run");
            return(opt);
        }
Beispiel #30
0
        public Option <IEnumerable <FileInfo> > GetFiles()
        {
            Option <IEnumerable <FileInfo> > opt = new Option <IEnumerable <FileInfo> >("--files");

            opt.Description = "A list of relative file or folder paths to include in formatting.All files are formatted if empty.";
            opt.IsRequired  = false;
            opt.IsHidden    = false;
            opt.AddAlias("-include");
            return(opt);
        }