cc-haxe/src/lib/CLIAppBase.hx

69 lines
2.1 KiB
Haxe
Raw Normal View History

2023-04-14 12:35:54 +00:00
package lib;
import lib.args.CLIArgs;
import lib.args.ArgType;
2024-03-13 09:39:22 +00:00
import kernel.ps.IProcess;
2023-04-14 12:35:54 +00:00
import kernel.ps.ProcessHandle;
using tink.CoreApi;
2024-03-13 09:39:22 +00:00
abstract class CLIAppBase implements IProcess {
2023-07-30 13:55:22 +00:00
private var handle:ProcessHandle;
2023-04-14 12:35:54 +00:00
private final _subcommandsSync:Map<String, (CLIArgs) -> Bool> = [];
private final _subcommandsAsync:Map<String, (CLIArgs) -> Future<Bool>> = [];
private final _subcommandsArgs:Map<String, Array<ArgType>> = [];
2023-04-14 12:35:54 +00:00
2023-08-02 14:31:40 +00:00
public final 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 argParser = new CLIArgs(_subcommandsArgs.get(subcommand));
if (!argParser.parse(args)) {
handle.writeLine(argParser.getError());
return handle.close(false);
}
return handle.close(_subcommandsSync[subcommand](argParser));
2023-04-14 12:35:54 +00:00
} else if (_subcommandsAsync.exists(subcommand)) {
var argParser = new CLIArgs(_subcommandsArgs.get(subcommand));
if (!argParser.parse(args)) {
handle.writeLine(argParser.getError());
return handle.close(false);
}
_subcommandsAsync[subcommand](argParser).handle(handle.close);
2023-04-14 12:35:54 +00:00
} else {
handle.writeLine("Unknown subcommand: " + subcommand);
printHelp();
return handle.close(false);
}
}
private function registerSyncSubcommand(command:String, callback:(CLIArgs) -> Bool, args:Array<ArgType> = null) {
2023-04-14 12:35:54 +00:00
_subcommandsSync.set(command, callback);
_subcommandsArgs.set(command, args ?? []);
2023-04-14 12:35:54 +00:00
}
private function registerAsyncSubcommand(command:String, callback:(CLIArgs) -> Future<Bool>, args:Array<ArgType> = null) {
2023-04-14 12:35:54 +00:00
_subcommandsAsync.set(command, callback);
_subcommandsArgs.set(command, args ?? []);
2023-04-14 12:35:54 +00:00
}
private function printHelp() {
handle.writeLine("Usage: <subcommand> [args]");
handle.writeLine("Subcommands:");
for (k => v in this._subcommandsArgs) {
handle.writeLine(' $k ${CLIArgs.getSynopsis(v)}');
2023-04-14 12:35:54 +00:00
}
}
}