cc-haxe/src/lib/CLIAppBase.hx

59 lines
1.7 KiB
Haxe
Raw Normal View History

2023-04-14 12:35:54 +00:00
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);
2023-05-31 16:39:36 +00:00
_subcommandsSynopsis.push(command + " " + (synopsis ?? ""));
2023-04-14 12:35:54 +00:00
}
private function registerAsyncSubcommand(command: String, callback: (Array<String>) -> Future<Bool>, synopsis: String = null) {
_subcommandsAsync.set(command, callback);
2023-05-31 16:39:36 +00:00
_subcommandsSynopsis.push(command + " " + (synopsis ?? ""));
2023-04-14 12:35:54 +00:00
}
private function printHelp() {
handle.writeLine("Usage: <subcommand> [args]");
handle.writeLine("Subcommands:");
for (subcommand in _subcommandsSynopsis) {
handle.writeLine(" " + subcommand);
}
}
}