|
| 1 | +// Copyright (c) Nate McMaster. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using McMaster.Extensions.CommandLineUtils; |
| 7 | + |
| 8 | +namespace SubcommandSample |
| 9 | +{ |
| 10 | + /// <summary> |
| 11 | + /// In this example, subcommands are defined using the builder API. |
| 12 | + /// Defining subcommands is possible by using the return value of app.Command(). |
| 13 | + /// </summary> |
| 14 | + class Npm |
| 15 | + { |
| 16 | + public static int Main(string[] args) |
| 17 | + { |
| 18 | + var app = new CommandLineApplication |
| 19 | + { |
| 20 | + Name = "fake-npm", |
| 21 | + Description = "A fake version of the node package manager", |
| 22 | + }; |
| 23 | + |
| 24 | + app.HelpOption(); |
| 25 | + app.Command("config", configCmd => |
| 26 | + { |
| 27 | + configCmd.HelpOption(); |
| 28 | + configCmd.OnExecute(() => |
| 29 | + { |
| 30 | + Console.WriteLine("Specify a subcommand"); |
| 31 | + configCmd.ShowHelp(); |
| 32 | + return 1; |
| 33 | + }); |
| 34 | + |
| 35 | + configCmd.Command("set", setCmd => |
| 36 | + { |
| 37 | + setCmd.HelpOption(); |
| 38 | + setCmd.Description = "Set config value"; |
| 39 | + var key = setCmd.Argument("key", "Name of the config").IsRequired(); |
| 40 | + var val = setCmd.Argument("value", "Value of the config").IsRequired(); |
| 41 | + setCmd.OnExecute(() => |
| 42 | + { |
| 43 | + Console.WriteLine($"Setting config {key.Value} = {val.Value}"); |
| 44 | + }); |
| 45 | + }); |
| 46 | + |
| 47 | + configCmd.Command("list", listCmd => |
| 48 | + { |
| 49 | + listCmd.HelpOption(); |
| 50 | + var json = listCmd.Option("--json", "Json output", CommandOptionType.NoValue); |
| 51 | + listCmd.OnExecute(() => |
| 52 | + { |
| 53 | + if (json.HasValue()) |
| 54 | + { |
| 55 | + Console.WriteLine("{\"dummy\": \"value\"}"); |
| 56 | + } |
| 57 | + else |
| 58 | + { |
| 59 | + Console.WriteLine("dummy = value"); |
| 60 | + } |
| 61 | + }); |
| 62 | + }); |
| 63 | + }); |
| 64 | + |
| 65 | + app.OnExecute(() => |
| 66 | + { |
| 67 | + Console.WriteLine("Specify a subcommand"); |
| 68 | + app.ShowHelp(); |
| 69 | + return 1; |
| 70 | + }); |
| 71 | + |
| 72 | + return app.Execute(args); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments