rat-times/scripts/cmd.gd

44 lines
1.5 KiB
GDScript3
Raw Permalink Normal View History

2023-03-03 21:44:32 +00:00
class_name CMD
## Returns a dictionary of all arguments passed after `--` on the command line
## arguments take one of 2 forms:
## - `--arg` which is a boolean (using `--no-arg` for `false` is possible)
## - `--arg=value`. If the value is quoted with `"` or `'`, this function will
## unsurround the string
## This function does no evaluation and does not attempt to guess the type of
## arguments. You will receive either bools, or strings.
2023-03-04 14:07:03 +00:00
var command_line_arguments: Dictionary = (func () -> Dictionary:
2023-03-03 21:44:32 +00:00
var unsurround := func unsurround(value: String, quotes := PackedStringArray(['"', "'"])) -> String:
for quote_str in quotes:
if value.begins_with(quote_str) \
and value.ends_with(quote_str) \
and value[value.length() - 2] != "\\":
return value.trim_prefix(quote_str).trim_suffix(quote_str).strip_edges()
return value
var arguments := {}
for argument in OS.get_cmdline_user_args():
argument = argument.lstrip("--").to_lower()
if argument.find("=") > -1:
var arg_tuple := argument.split("=")
var key := arg_tuple[0]
var value:String = unsurround.call(arg_tuple[1])
arguments[key] = value
else:
var key := argument
var value := true
if argument.begins_with("no-"):
value = false
key = argument.lstrip("no-")
arguments[key] = value
return arguments).call()
func get_argument(name: String, default: Variant = null) -> Variant:
if command_line_arguments.has(name):
return command_line_arguments[name]
return default
func has_argument(name: String) -> bool:
return command_line_arguments.has(name)