package lib; import kernel.ps.Process; import kernel.ps.ProcessHandle; using tink.CoreApi; abstract class CLIAppBase implements Process { private var handle: ProcessHandle; private final _subcommandsSync: Map) -> Bool> = []; private final _subcommandsAsync: Map) -> Future> = []; private final _subcommandsSynopsis: Array = []; public function run(handle: ProcessHandle){ this.handle = handle; var subcommand = handle.args[0]; if (subcommand == null || subcommand == "") { handle.writeLine("No subcommand specified"); printHelp(); return handle.close(false); } var args = handle.args.slice(1); if (_subcommandsSync.exists(subcommand)) { var result = _subcommandsSync[subcommand](args); return handle.close(result); } else if (_subcommandsAsync.exists(subcommand)) { _subcommandsAsync[subcommand](args).handle(handle.close); } else { handle.writeLine("Unknown subcommand: " + subcommand); printHelp(); return handle.close(false); } } private function registerSyncSubcommand(command: String, callback: (Array) -> Bool, synopsis: String = null) { _subcommandsSync.set(command, callback); _subcommandsSynopsis.push(command + " " + synopsis); } private function registerAsyncSubcommand(command: String, callback: (Array) -> Future, synopsis: String = null) { _subcommandsAsync.set(command, callback); _subcommandsSynopsis.push(command + " " + synopsis); } private function printHelp() { handle.writeLine("Usage: [args]"); handle.writeLine("Subcommands:"); for (subcommand in _subcommandsSynopsis) { handle.writeLine(" " + subcommand); } } }