71 lines
2.4 KiB
GDScript
71 lines
2.4 KiB
GDScript
class_name CMD
|
|
|
|
|
|
var _parsed := false
|
|
|
|
## @type Dictionary[String, String|bool]
|
|
var command_line_arguments: Dictionary = {} setget set_command_line_arguments, get_command_line_arguments
|
|
|
|
|
|
## Removes the first element find from the `quotes` array from the start and end of a string
|
|
## Also removes any whitespace resulting from removing the quoting elements
|
|
static func unsurround(value: String, quotes := PoolStringArray(['"', "'"])) -> 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
|
|
|
|
|
|
## 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.
|
|
static func parse_cmd_arguments() -> Dictionary:
|
|
var arguments := {}
|
|
for arg in OS.get_cmdline_args():
|
|
var argument: String = arg.lstrip("--").to_lower()
|
|
if argument.find("=") > -1:
|
|
var arg_tuple := argument.split("=")
|
|
var key := arg_tuple[0]
|
|
var value := unsurround(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
|
|
|
|
|
|
func set_command_line_arguments(_arguments: Dictionary) -> void:
|
|
printerr("get_command_line_arguments is a read only value")
|
|
|
|
|
|
func get_command_line_arguments() -> Dictionary:
|
|
if not _parsed:
|
|
_parsed = true
|
|
command_line_arguments = parse_cmd_arguments()
|
|
return command_line_arguments
|
|
|
|
|
|
## Returns a single argument passed after `--` on the command line
|
|
## if the argument does not exist, `default` is returned instead
|
|
## _parse_cmd_arguments() has to be called first
|
|
func get_argument(name: String, default = null):
|
|
if get_command_line_arguments().has(name):
|
|
return get_command_line_arguments()[name]
|
|
return default
|
|
|
|
|
|
## Verifies an argument exists on the command line
|
|
## _parse_cmd_arguments() has to be called first
|
|
func has_argument(name: String) -> bool:
|
|
return get_command_line_arguments().has(name)
|