Created
December 7, 2018 20:31
-
-
Save cocowalla/5b2b23348e482f900927cd46181821ab to your computer and use it in GitHub Desktop.
Subcommands with Oakton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Lamar; | |
using Oakton; | |
using MyApp.Commands; | |
namespace MyApp | |
{ | |
internal class Program | |
{ | |
private static readonly string[] Commands = { "volume", "container", "etc" }; | |
private static async Task<int> Main(string[] args) | |
{ | |
// Check a valid top-level command was specified | |
if (args.Length == 0 || !Commands.Contains(args[0]) || args[0] == "help" || args[0] == "--help") | |
ShowHelp(); | |
var command = args[0]; | |
// Now we have the command, we only need any remaining arguments | |
args = args.Skip(1).ToArray(); | |
var container = Bootstrapper.Initialize(); | |
CommandExecutor executor; | |
switch (command) | |
{ | |
case "volume": | |
executor = GetVolumeCommand(container); | |
break; | |
case "container": | |
executor = GetContainerCommand(container); | |
break; | |
default: | |
ShowHelp(); | |
return 1; | |
} | |
return await executor.ExecuteAsync(args); | |
} | |
private static CommandExecutor GetVolumeCommand(IContainer container) | |
{ | |
var executor = CommandExecutor.For(x => | |
{ | |
x.RegisterCommand<ListVolumeCommand>(); | |
x.RegisterCommand<CreateVolumeCommand>(); | |
x.RegisterCommand<RemoveVolumeCommand>(); | |
}, new LamarCommandCreator(container)); | |
return executor; | |
} | |
private static CommandExecutor GetContainerCommand(IContainer container) | |
{ | |
var executor = CommandExecutor.For(x => | |
{ | |
x.RegisterCommand<ListContainerCommand>(); | |
x.RegisterCommand<CreateContainerCommand>(); | |
x.RegisterCommand<RemoveContainerCommand>(); | |
}, new LamarCommandCreator(container)); | |
return executor; | |
} | |
private static void ShowHelp() | |
{ | |
ConsoleWriter.Write("Help text here"); | |
Environment.Exit(1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment