Move modules to CoreLoggerInstance

This commit is contained in:
JeremyStar™ 2024-04-08 21:30:24 +02:00
parent 39bc3f5872
commit 6bae282326
Signed by: JeremyStarTM
GPG key ID: E366BAEF67E4704D
6 changed files with 90 additions and 106 deletions

View file

@ -59,6 +59,9 @@ var custom_modules: Dictionary = {}
## Contains the node holding all custom modules as children.[br]
## [b]Danger: [i]Don't modify this.[/i][/b]
var custom_modules_node: Node
## The CORE Object's logger instance.
## [b]Danger: [i]Don't modify this.[/i][/b]
var loggeri: CoreLoggerInstance
# +++ initialization +++
## Handles the preinitialization part. Does stuff like checking the engine version, loading the config and loading all modules into memory.
@ -77,6 +80,7 @@ func _ready() -> void:
inject_modules()
custom_modules_node.name = "Custom Modules"
add_child(custom_modules_node)
loggeri = logger.get_instance(basepath + "src/core.gd")
## Initializes all built-in modules during the preinitialization phase.[br]
## [b]Danger: [i]Don't call this.[/i][/b]
@ -122,37 +126,37 @@ func complete_init(no_success_message: bool = false) -> void:
# Initialization complete
await get_tree().process_frame
if !no_success_message: logger.infof("core", "Initialized CORE successfully")
if !no_success_message: loggeri.info("Initialized CORE successfully")
# +++ custom module support +++
## Registers a new custom module.
func register_custom_module(module_name: String, module_origin: String, module_class: CoreBaseModule) -> bool:
logger.verbf("core", "Registering new custom module \"" + module_name + "\"")
loggeri.verb("Registering new custom module \"" + module_name + "\"")
if !config.custom_modules:
logger.errorf("core", "Registering module failed: Custom module support is disabled.")
loggeri.error("Registering module failed: Custom module support is disabled.")
return false
if custom_modules.has(module_name):
logger.errorf("core", "Registering module failed: A custom module with the name \"" + module_name + "\" already exists.")
loggeri.error("Registering module failed: A custom module with the name \"" + module_name + "\" already exists.")
return false
logger.diagf("core", "Updating variables")
loggeri.diag("Updating variables")
module_class.name = module_name
module_class.core = self
module_class.loggeri = logger.get_instance(module_origin)
logger.diagf("core", "Adding module to SceneTree")
loggeri.diag("Adding module to SceneTree")
custom_modules_node.add_child(module_class)
logger.diagf("core", "Merging module with custom_modules")
loggeri.diag("Merging module with custom_modules")
custom_modules.merge({ module_name: module_class })
logger.diagf("core", "Initializing custom module")
loggeri.diag("Initializing custom module")
module_class._initialize()
logger.diagf("core", "Updating custom module configuration")
loggeri.diag("Updating custom module configuration")
module_class._pull_config()
return true
## Unregisters a custom module, making it no longer available.
func unregister_custom_module(module_name: String) -> void:
logger.verbf("core", "Unregistering custom module \"" + module_name + "\"")
loggeri.verb("Unregistering custom module \"" + module_name + "\"")
if !custom_modules.has(module_name):
logger.errorf("core", "Unregistering module failed: A custom module with the name \"" + module_name + "\" does not exist.")
loggeri.error("Unregistering module failed: A custom module with the name \"" + module_name + "\" does not exist.")
return
var module: Node = get_custom_module(module_name)
await module._cleanup()
@ -164,9 +168,9 @@ func unregister_custom_module(module_name: String) -> void:
## Returns a registered custom module.[br]
## Please note that you can't get CORE's built-in modules with this function.
func get_custom_module(module_name: String) -> CoreBaseModule:
logger.diagf("core", "Getting custom module \"" + module_name + "\"")
loggeri.diag("Getting custom module \"" + module_name + "\"")
if !custom_modules.has(module_name):
logger.errorf("core", "Getting module failed: A custom module with the name \"" + module_name + "\" does not exist.")
loggeri.error("Getting module failed: A custom module with the name \"" + module_name + "\" does not exist.")
return null
return custom_modules[module_name]
@ -174,34 +178,34 @@ func get_custom_module(module_name: String) -> CoreBaseModule:
## Loads a (new) configuration object and applies it to all modules.
func reload_configuration(new_config: CoreConfiguration = CoreConfiguration.new()) -> void:
var initialized = config != null
if initialized: logger.verbf("core", "Reloading CORE's configuration")
if initialized: loggeri.verb("Reloading CORE's configuration")
if config != null: config.queue_free()
config = new_config
if is_devmode(): # Override configuration in development mode
config.logger_level = CoreTypes.LoggerLevel.VERB
if initialized: logger.verbf("core", "Overrode configuration (development mode)")
if initialized: loggeri.verb("Overrode configuration (development mode)")
if initialized: apply_configuration()
## Applies the a configuration.[br]
## [b]Danger: [i]Don't call this.[/i][/b]
func apply_configuration() -> void:
logger.verbf("core", "Applying configuration")
if is_devmode(): logger.warnf("core", "The CORE Framework is in development mode. Here be dragons!")
if config.headless: logger.warnf("core", "CORE is in headless mode. Certain modules will not work as expected.")
if loggeri != null: loggeri.verb("Applying configuration")
if is_devmode(): if loggeri != null: loggeri.warn("The CORE Framework is in development mode. Here be dragons!")
if config.headless: loggeri.warn("CORE is in headless mode. Certain modules will not work as expected.")
if !config.custom_modules:
logger.verbf("core", "Removing all custom modules (custom modules support is disabled)")
if loggeri != null: loggeri.verb("Removing all custom modules (custom modules support is disabled)")
for module in custom_modules: unregister_custom_module(module)
for module in modules: get(module)._pull_config()
if config.custom_modules:
for module in custom_modules:
logger.diagf("core", "Updating configuration for custom module \"" + module.name + "\"")
if loggeri != null: loggeri.diag("Updating configuration for custom module \"" + module.name + "\"")
module._pull_config()
# +++ etc ++
## Makes sure that CORE does not leak memory on shutdown/unload.[br]
## Unloads all custom modules, built-in modules, frees any of CORE's classes and lastly itself.
func cleanup() -> void:
logger.infof("core", "Cleaning up")
loggeri.info("Cleaning up")
config.queue_free()
var modules_reverse: Array[String] = modules.duplicate()
modules_reverse.reverse()
@ -247,7 +251,7 @@ func get_formatted_string(string: String) -> String:
CoreTypes.VersionType.ALPHA:
string = string.replace("%version_type%", "Alpha")
string = string.replace("%version_type_technical%", "a")
_: await logger.crashf("core", "Invalid version type " + str(version_type), true)
_: await loggeri.crash("Invalid version type " + str(version_type))
# Development mode
if is_devmode(): string = string.replace("%devmode%", "Enabled")
else: string = string.replace("%devmode%", "Disabled")

View file

@ -57,11 +57,11 @@ func _cleanup() -> void:
## [/codeblock]
## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b]
func awaited_request(url: String, parse_utf8: bool, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), data: String = "") -> Dictionary:
logger.verbf("erm", "Creating awaited request")
loggeri.verb("Creating awaited request")
if !await is_url_allowed(url): return {}
var id: int = create_request(url, method, headers, data)
start_request(id, parse_utf8)
logger.diagf("erm", "Waiting for request " + str(id) + " to finish")
loggeri.diag("Waiting for request " + str(id) + " to finish")
while !is_request_completed(id): await get_tree().create_timer(0.1, true).timeout
var dldata: Dictionary = list_complete[id]
list_complete.erase(id)
@ -96,7 +96,7 @@ func oneline_awaited_request(url: String, return_utf8: bool = true, ignore_http_
## [/codeblock]
## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b]
func batch_awaited_request(urls: PackedStringArray, parse_utf8: bool, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), data: String = "") -> Array[Dictionary]:
logger.verbf("erm", "Creating " + str(urls.size()) + " awaited request(s)")
loggeri.verb("Creating " + str(urls.size()) + " awaited request(s)")
var dldata: Array[Dictionary] = []
for url in urls:
if !await is_url_allowed(url): continue
@ -111,7 +111,7 @@ func batch_awaited_request(urls: PackedStringArray, parse_utf8: bool, method: HT
func _batch_awaited_request(url: String, parse_utf8: bool, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), data: String = "") -> int:
var id: int = create_request(url, method, headers, data)
start_request(id, parse_utf8)
logger.diagf("erm", "Waiting for request " + str(id) + " to finish")
loggeri.diag("Waiting for request " + str(id) + " to finish")
while !is_request_completed(id): await get_tree().create_timer(0.1, true).timeout
return id
@ -121,15 +121,15 @@ func _batch_awaited_request(url: String, parse_utf8: bool, method: HTTPClient.Me
func generate_id() -> int:
var id = randi()
if list_queue.has(id) or list_active.has(id):
logger.warnf("erm", "New download id '" + str(id) + "' is already taken")
loggeri.warn("New download id '" + str(id) + "' is already taken")
return generate_id()
logger.diagf("erm", "Generated new download id " + str(id))
loggeri.diag("Generated new download id " + str(id))
return id
## Creates a new request and stores it in the queue. Returns the download id.[br]
## [b]Warning: [i]You'll probably not need this. Only use this function when implementing your own downloading method.[/i][/b]
func create_request(url: String, method: HTTPClient.Method = HTTPClient.Method.METHOD_GET, headers: PackedStringArray = PackedStringArray([]), body: String = "") -> int:
logger.verbf("erm", "Creating new request\n-> URL: " + url + "\n-> Method: " + str(method) + "\nHeaders: " + str(headers.size()) + "\nBody size: " + str(body.length()) + " Characters")
loggeri.verb("Creating new request\n-> URL: " + url + "\n-> Method: " + str(method) + "\nHeaders: " + str(headers.size()) + "\nBody size: " + str(body.length()) + " Characters")
var id = generate_id()
list_queue.merge({ id: { "url": url, "method": method, "headers": headers, "body": body } })
return id
@ -138,16 +138,16 @@ func create_request(url: String, method: HTTPClient.Method = HTTPClient.Method.M
## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b][br]
## [b]Warning: [i]You'll probably not need this. Only use this function when implementing your own downloading method.[/i][/b]
func start_request(id: int, parse_utf8: bool) -> void:
logger.verbf("erm", "Starting request " + str(id))
loggeri.verb("Starting request " + str(id))
list_active.merge({ id: list_queue[id] })
list_queue.erase(id)
logger.diagf("erm", "Creating new HTTPRequest \"Request #" + str(id) + "\"")
loggeri.diag("Creating new HTTPRequest \"Request #" + str(id) + "\"")
var download: HTTPRequest = HTTPRequest.new()
download.name = "Request #" + str(id)
download.accept_gzip = true
download.use_threads = true
var lambda: Callable = func(result: int, http_code: int, headers: PackedStringArray, body: PackedByteArray, httprequest: HTTPRequest) -> void:
logger.verbf("erm", "Request " + str(id) + " completed\nResult: " + str(result) + "\nHTTP response code: " + str(http_code) + "\nHeaders: " + str(headers.size()) + "\nBody size: " + str(body.size()) + " Bytes // " + str(core.misc.byte2mib(body.size(), true)) + " MiB\nParse body as UTF-8: " + str(parse_utf8))
loggeri.verb("Request " + str(id) + " completed\nResult: " + str(result) + "\nHTTP response code: " + str(http_code) + "\nHeaders: " + str(headers.size()) + "\nBody size: " + str(body.size()) + " Bytes // " + str(core.misc.byte2mib(body.size(), true)) + " MiB\nParse body as UTF-8: " + str(parse_utf8))
list_complete.merge({ id: { "result": result, "http_code": http_code, "headers": headers, "body": body, "body_utf8": body.get_string_from_utf8() if parse_utf8 else "" } })
list_active.erase(id)
remove_child(httprequest)
@ -161,14 +161,14 @@ func is_url_allowed(url: String) -> bool:
if url.begins_with("http://"):
match(config_unsecure_requests):
CoreTypes.BlockadeLevel.BLOCK:
logger.errorf("erm", "Blocked unsecure url '" + url + "'")
loggeri.error("Blocked unsecure url '" + url + "'")
return false
CoreTypes.BlockadeLevel.WARN: logger.warnf("erm", "Requesting unsecure url '" + url + "'")
CoreTypes.BlockadeLevel.WARN: loggeri.warn("Requesting unsecure url '" + url + "'")
CoreTypes.BlockadeLevel.IGNORE: pass
_: await logger.crashf("erm", "Invalid BlockadeLevel '" + str(config_unsecure_requests) + "'")
_: await loggeri.crash("Invalid BlockadeLevel '" + str(config_unsecure_requests) + "'")
elif url.begins_with("https://"): pass
else:
logger.errorf("erm", "Invalid url '" + url + "'")
loggeri.error("Invalid url '" + url + "'")
return false
return true
@ -177,10 +177,10 @@ func is_request_completed(id: int) -> bool: return list_complete.has(id)
## Cleans the request queue.
func clean_queue() -> void:
logger.verbf("erm", "Cleaning request queue")
loggeri.verb("Cleaning request queue")
list_queue.clear()
## Cleans the completed requests list.
func clean_completed() -> void:
logger.verbf("erm", "Cleaning completed requests")
loggeri.verb("Cleaning completed requests")
list_complete.clear()

View file

@ -193,26 +193,6 @@ STACKTRACE
# Shutdown
await core.misc.quit_safely(69)
# Deprecated functions, will be removed soon
## Deprecated framework call
## @deprecated
func diagf(origin: String, message: String) -> void: _log(CoreTypes.LoggerLevel.DIAG, core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
## Deprecated framework call
## @deprecated
func verbf(origin: String, message: String) -> void: _log(CoreTypes.LoggerLevel.VERB, core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
## Deprecated framework call
## @deprecated
func infof(origin: String, message: String) -> void: _log(CoreTypes.LoggerLevel.INFO, core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
## Deprecated framework call
## @deprecated
func warnf(origin: String, message: String) -> void: _log(CoreTypes.LoggerLevel.WARN, core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
## Deprecated framework call
## @deprecated
func errorf(origin: String, message: String) -> void: _log(CoreTypes.LoggerLevel.ERROR, core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
## Deprecated framework call
## @deprecated
func crashf(origin: String, message: String) -> void: crash(core.basepath.replace("res://", "") + "src/" + origin + ".gd", message)
# +++ etc +++
## Checks if the specified log level is allowed by the current configuration.
func is_level_allowed(level: CoreTypes.LoggerLevel) -> bool:

View file

@ -72,10 +72,10 @@ func format_stringarray(array: Array[String], item_before: String = "", item_aft
var output: String = ""
if array.size() == 0:
logger.warnf("misc", "Unable to format a string with a size of 0")
loggeri.warn("Unable to format a string with a size of 0")
return ""
elif array.size() == 1:
logger.warnf("misc", "Unable to format a string with a size of 1")
loggeri.warn("Unable to format a string with a size of 1")
return array[0]
for item in array:
@ -129,7 +129,7 @@ func get_center(parent_size: Vector2, child_size: Vector2) -> Vector2:
## Using [method SceneTree.quit] directly may cause various issues.[br]
## [b]Note: [i]Using the [code]await[/code] keyword is required for this function.[/i][/b]
func quit_safely(exitcode: int = 0) -> void:
logger.infof("misc", "Shutting down (code " + str(exitcode) + ")")
loggeri.info("Shutting down (code " + str(exitcode) + ")")
await get_tree().create_timer(0.25).timeout
await core.cleanup()
get_tree().quit(exitcode)

View file

@ -59,19 +59,19 @@ func _cleanup() -> void:
func _pull_config() -> void:
if core.config.headless:
# Remove all scenes
if is_inside_tree(): logger.verbf("sms", "Removing all scenes (triggered by headless mode)")
if is_inside_tree(): loggeri.verb("Removing all scenes (triggered by headless mode)")
for scene in scenes: remove_scene(scene, true)
# +++ scene management +++
## Adds a scene to some scene collection.
func add_scene(sname: String, sclass: Node, type: CoreTypes.SceneType) -> bool:
if core.config.headless: return false
logger.verbf("sms", "Adding scene \"" + sname + "\" of type " + str(type))
loggeri.verb("Adding scene \"" + sname + "\" of type " + str(type))
if exists(sname) != CoreTypes.SceneType.NONE:
logger.errorf("sms", "Scene with name \"" + sname + "\" already exists")
loggeri.error("Scene with name \"" + sname + "\" already exists")
return false
if typeof(sclass) != TYPE_OBJECT or !sclass.is_class("Node"):
logger.errorf("sms", "Scene class \"" + sname + "\" is not of type Node")
loggeri.error("Scene class \"" + sname + "\" is not of type Node")
return false
sclass.name = sname
match(type):
@ -81,9 +81,9 @@ func add_scene(sname: String, sclass: Node, type: CoreTypes.SceneType) -> bool:
CoreTypes.SceneType.MAIN: scenes_main.add_child(sclass)
CoreTypes.SceneType.BACKGROUND: scenes_background.add_child(sclass)
CoreTypes.SceneType.NONE:
logger.errorf("sms", "CoreTypes.SceneType.NONE is not a valid scene type")
loggeri.error("CoreTypes.SceneType.NONE is not a valid scene type")
return false
_: await logger.crashf("sms", "Invalid SceneType " + str(type), true)
_: await loggeri.crash("Invalid SceneType " + str(type))
scenes.merge({ sname: { "type": type, "class": sclass } })
return true
@ -91,8 +91,8 @@ func add_scene(sname: String, sclass: Node, type: CoreTypes.SceneType) -> bool:
## [b]Danger: [i]Don't set [code]force_remove[/code] to [code]true[/code], thanks![/i][/b]
func remove_scene(sname: String, force_remove: bool = false) -> bool:
if core.config.headless and !force_remove: return false
if force_remove: await logger.crashf("sms", "force_remove = true is not allowed", true)
logger.verbf("sms", "Removing scene \"" + sname + "\"")
if force_remove: await loggeri.crash("force_remove = true is not allowed")
loggeri.verb("Removing scene \"" + sname + "\"")
match(exists(sname)):
CoreTypes.SceneType.DEBUG:
scenes_debug.remove_child(scenes[sname]["class"])
@ -110,9 +110,9 @@ func remove_scene(sname: String, force_remove: bool = false) -> bool:
scenes_background.remove_child(scenes[sname]["class"])
scenes[sname]["class"].queue_free()
CoreTypes.SceneType.NONE:
logger.errorf("sms", "Scene \"" + sname + "\" does not exist")
loggeri.error("Scene \"" + sname + "\" does not exist")
return false
_: await logger.crashf("sms", "Invalid SceneType " + str(exists(sname)), true)
_: await loggeri.crash("Invalid SceneType " + str(exists(sname)))
scenes.erase(sname)
return true
@ -128,8 +128,8 @@ func get_scene(sname: String) -> Node:
CoreTypes.SceneType.MENU: return scenes[sname]["class"]
CoreTypes.SceneType.MAIN: return scenes[sname]["class"]
CoreTypes.SceneType.BACKGROUND: return scenes[sname]["class"]
CoreTypes.SceneType.NONE: logger.errorf("sms", "Scene \"" + sname + "\" does not exist")
_: await logger.crashf("sms", "Invalid SceneType " + str(exists(sname)), true)
CoreTypes.SceneType.NONE: loggeri.error("Scene \"" + sname + "\" does not exist")
_: await loggeri.crash("Invalid SceneType " + str(exists(sname)))
return null
## Returns a scene collection node.[br]
@ -143,8 +143,8 @@ func get_scene_collection(type: CoreTypes.SceneType) -> Node:
CoreTypes.SceneType.MENU: return scenes_menu
CoreTypes.SceneType.MAIN: return scenes_main
CoreTypes.SceneType.BACKGROUND: return scenes_background
CoreTypes.SceneType.NONE: logger.errorf("sms", "No scene collection was found for CoreTypes.SceneType.NONE")
_: await logger.crashf("sms", "Invalid SceneType " + str(type), true)
CoreTypes.SceneType.NONE: loggeri.error("No scene collection was found for CoreTypes.SceneType.NONE")
_: await loggeri.crash("Invalid SceneType " + str(type))
return null
## Returns a list of all loaded scenes in some scene collection.

View file

@ -34,40 +34,40 @@ var storage_location: String = ""
## Opens a storage file into memory.
func open_storage(location: String, create_new: bool = true, sanity_check: bool = true, fail_on_sanity_check: bool = false) -> bool:
if is_open:
logger.errorf("storage", "Failed to open storage: A storage file is already open")
loggeri.error("Failed to open storage: A storage file is already open")
return false
logger.verbf("storage", "Opening storage file at \"" + location + "\"")
loggeri.verb("Opening storage file at \"" + location + "\"")
var file: FileAccess
if !FileAccess.file_exists(location):
if create_new:
file = FileAccess.open(location, FileAccess.WRITE)
if file == null:
await logger.crashf("storage", "Could not open storage file at \"" + location + "\": Failed with code " + str(FileAccess.get_open_error()))
await loggeri.crash("Could not open storage file at \"" + location + "\": Failed with code " + str(FileAccess.get_open_error()))
return false
file.store_string("{}")
file.close()
else:
logger.errorf("storage", "Failed to open storage: create_new is set to false")
loggeri.error("Failed to open storage: create_new is set to false")
return false
file = FileAccess.open(location, FileAccess.READ)
var storage_temp: Variant = file.get_as_text()
file.close()
storage_temp = JSON.parse_string(storage_temp)
if typeof(storage_temp) != TYPE_DICTIONARY:
logger.errorf("storage", "Failed to open storage: Parsed storage file is of type " + str(typeof(storage_temp)))
loggeri.error("Failed to open storage: Parsed storage file is of type " + str(typeof(storage_temp)))
return false
if sanity_check:
var check_result: Array[String] = perform_sanity_check(storage_temp)
if check_result.size() != 0:
if fail_on_sanity_check:
logger.errorf("storage", "Sanity check failed (stopping):")
loggeri.error("Sanity check failed (stopping):")
for error in check_result:
logger.errorf("storage", "-> " + error)
loggeri.error("-> " + error)
return false
else:
logger.warnf("storage", "Sanity check failed (continuing anyway):")
loggeri.warn("Sanity check failed (continuing anyway):")
for error in check_result:
logger.warnf("storage", "-> " + error)
loggeri.warn("-> " + error)
storage = storage_temp
storage_location = location
is_open = true
@ -76,9 +76,9 @@ func open_storage(location: String, create_new: bool = true, sanity_check: bool
## Closes the active storage file.
func close_storage() -> bool:
if !is_open:
logger.errorf("storage", "Failed to close storage: No storage file is open")
loggeri.error("Failed to close storage: No storage file is open")
return false
logger.verbf("storage", "Closing storage file")
loggeri.verb("Closing storage file")
storage = {}
is_open = false
return true
@ -86,13 +86,13 @@ func close_storage() -> bool:
## Saves the active storage file to disk.
func save_storage() -> bool:
if !is_open:
logger.errorf("storage", "Failed to save storage: No storage file is open")
loggeri.error("Failed to save storage: No storage file is open")
return false
var file: FileAccess = FileAccess.open(storage_location, FileAccess.WRITE)
if file == null:
await logger.crashf("storage", "Could not open storage file at \"" + storage_location + "\": Failed with code " + str(FileAccess.get_open_error()))
await loggeri.crash("Could not open storage file at \"" + storage_location + "\": Failed with code " + str(FileAccess.get_open_error()))
return false
logger.diagf("storage", "Writing storage file to disk")
loggeri.diag("Writing storage file to disk")
file.store_string(JSON.stringify(storage))
file.close()
return true
@ -101,9 +101,9 @@ func save_storage() -> bool:
## Removes all keys from the active storage file. The nuclear option basically.
func nuke_storage(autosave: bool = true) -> bool:
if !is_open:
logger.errorf("storage", "Failed to nuke storage: No storage file is open")
loggeri.error("Failed to nuke storage: No storage file is open")
return false
logger.warnf("storage", "Nuking storage")
loggeri.warn("Nuking storage")
storage = {}
if autosave: save_storage()
return true
@ -111,17 +111,17 @@ func nuke_storage(autosave: bool = true) -> bool:
## Returns a storage key. Can also return a default value if unset.
func get_key(key: String, default: Variant = null) -> Variant:
if !is_open:
logger.errorf("storage", "Failed to get key: No storage file is open")
loggeri.error("Failed to get key: No storage file is open")
return NAN
logger.diagf("storage", "Returning storage key \"" + key + "\" (default='" + str(default) + "')")
loggeri.diag("Returning storage key \"" + key + "\" (default='" + str(default) + "')")
return storage.get(key, default)
## Updates a storage key with the specified value.
func set_key(key: String, value: Variant, overwrite: bool = true, autosave: bool = true) -> bool:
if !is_open:
logger.errorf("storage", "Failed to set key: No storage file is open")
loggeri.error("Failed to set key: No storage file is open")
return false
logger.diagf("storage", "Updating storage key \"" + key + "\" with value '" + str(value) + "' (overwrite='" + str(overwrite) + "' autosave='" + str(autosave) + "'")
loggeri.diag("Updating storage key \"" + key + "\" with value '" + str(value) + "' (overwrite='" + str(overwrite) + "' autosave='" + str(autosave) + "'")
storage.merge({key: value}, overwrite)
if autosave: save_storage()
return true
@ -131,7 +131,7 @@ func del_key(key: String, autosave: bool = true) -> bool:
if !is_open:
logger.errof("storage", "Failed to delete key: No storage file is open")
return false
logger.diagf("storage", "Deleting storage key \"" + key + "\" (autosave='" + str(autosave) + "')")
loggeri.diag("Deleting storage key \"" + key + "\" (autosave='" + str(autosave) + "')")
storage.erase(key)
if autosave: save_storage()
return true
@ -141,30 +141,30 @@ func del_key(key: String, autosave: bool = true) -> bool:
## pass your modified [class Dictionary to [method safe_dict].
func get_dict() -> Dictionary:
if !is_open:
logger.errorf("storage", "Failed to get dictionary: No storage file is open")
loggeri.error("Failed to get dictionary: No storage file is open")
return {}
logger.verbf("storage", "Returning storage dictionary")
loggeri.verb("Returning storage dictionary")
return storage
# +++ raw manipulation +++
## Saves a arbitrary dictionary as a [param storage] [class Dictionary] with sanity checking ([code]sanity_check[/code] and [code]fail_on_sanity_check[/code]).
func save_dict(dict: Dictionary, sanity_check: bool = true, fail_on_sanity_check: bool = false, autosave: bool = true) -> bool:
if !is_open:
logger.errorf("storage", "Failed to save dictionary: No storage file is open")
loggeri.error("Failed to save dictionary: No storage file is open")
return false
logger.verbf("storage", "Saving custom dictionary as storage")
loggeri.verb("Saving custom dictionary as storage")
if sanity_check:
var check_result: Array[String] = perform_sanity_check(dict)
if check_result.size() != 0:
if fail_on_sanity_check:
logger.errorf("storage", "Sanity check failed (stopping):")
loggeri.error("Sanity check failed (stopping):")
for error in check_result:
logger.errorf("storage", "-> " + error)
loggeri.error("-> " + error)
return false
else:
logger.warnf("storage", "Sanity check failed (continuing anyway):")
loggeri.warn("Sanity check failed (continuing anyway):")
for error in check_result:
logger.warnf("storage", "-> " + error)
loggeri.warn("-> " + error)
storage = dict
if autosave: save_storage()
return true
@ -172,7 +172,7 @@ func save_dict(dict: Dictionary, sanity_check: bool = true, fail_on_sanity_check
# +++ etc +++
## Performs sanity checks on a [class Dictionary] to determine if it can be saved and loaded using this module.
func perform_sanity_check(storage_check: Dictionary) -> Array[String]:
logger.verbf("storage", "Performing a sanity check on some storage dictionary")
loggeri.verb("Performing a sanity check on some storage dictionary")
var errors: Array[String] = []
for key in storage_check:
if typeof(key) != TYPE_STRING:
@ -181,5 +181,5 @@ func perform_sanity_check(storage_check: Dictionary) -> Array[String]:
if typeof(storage_check[key]) != TYPE_NIL and typeof(storage_check[key]) != TYPE_STRING and typeof(storage_check[key]) != TYPE_INT and typeof(storage_check[key]) != TYPE_FLOAT and typeof(storage_check[key]) != TYPE_BOOL and typeof(storage_check[key]) != TYPE_ARRAY and typeof(storage_check[key]) != TYPE_DICTIONARY:
errors.append("The value of \"" + key + "\" is not null, a string, an integer, a float, boolean, array or dictionary (type '" + type_string(typeof(key)) + "')")
logger.verbf("storage", "Completed sanity check with " + str(errors.size()) + " errors")
loggeri.verb("Completed sanity check with " + str(errors.size()) + " errors")
return errors