cc-haxe/src/lib/CLIAppBase.hx

58 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 {
2023-07-30 13:55:22 +00:00
private var handle:ProcessHandle;
2023-04-14 12:35:54 +00:00
2023-07-30 13:55:22 +00:00
private final _subcommandsSync:Map<String, (Array<String>) -> Bool> = [];
private final _subcommandsAsync:Map<String, (Array<String>) -> Future<Bool>> = [];
private final _subcommandsSynopsis:Array<String> = [];
2023-04-14 12:35:54 +00:00
2023-07-30 13:55:22 +00:00
public function run(handle:ProcessHandle) {
2023-04-14 12:35:54 +00:00
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);
}
}
2023-07-30 13:55:22 +00:00
private function registerSyncSubcommand(command:String, callback:(Array<String>) -> Bool, synopsis:String = null) {
2023-04-14 12:35:54 +00:00
_subcommandsSync.set(command, callback);
2023-05-31 16:39:36 +00:00
_subcommandsSynopsis.push(command + " " + (synopsis ?? ""));
2023-04-14 12:35:54 +00:00
}
2023-07-30 13:55:22 +00:00
private function registerAsyncSubcommand(command:String, callback:(Array<String>) -> Future<Bool>, synopsis:String = null) {
2023-04-14 12:35:54 +00:00
_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);
}
}
}