added CLI helper base
This commit is contained in:
parent
bd3402fc39
commit
f9aadbcbe9
58
src/lib/CLIAppBase.hx
Normal file
58
src/lib/CLIAppBase.hx
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
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<String, (Array<String>) -> Bool> = [];
|
||||||
|
private final _subcommandsAsync: Map<String, (Array<String>) -> Future<Bool>> = [];
|
||||||
|
private final _subcommandsSynopsis: Array<String> = [];
|
||||||
|
|
||||||
|
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<String>) -> Bool, synopsis: String = null) {
|
||||||
|
_subcommandsSync.set(command, callback);
|
||||||
|
_subcommandsSynopsis.push(command + " " + synopsis);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function registerAsyncSubcommand(command: String, callback: (Array<String>) -> Future<Bool>, synopsis: String = null) {
|
||||||
|
_subcommandsAsync.set(command, callback);
|
||||||
|
_subcommandsSynopsis.push(command + " " + synopsis);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function printHelp() {
|
||||||
|
handle.writeLine("Usage: <subcommand> [args]");
|
||||||
|
handle.writeLine("Subcommands:");
|
||||||
|
for (subcommand in _subcommandsSynopsis) {
|
||||||
|
handle.writeLine(" " + subcommand);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user