mod_config.gd 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. class_name ModConfig
  2. extends Resource
  3. ##
  4. ## This Class is used to represent a configuration for a mod.[br]
  5. ## The Class provides functionality to initialize, validate, save, and remove a mod's configuration.
  6. ##
  7. ## @tutorial(Creating a Mod Config Schema with JSON-Schemas): https://wiki.godotmodding.com/guides/modding/config_json/
  8. const LOG_NAME := "ModLoader:ModConfig"
  9. ## Name of the config - must be unique
  10. var name: String
  11. ## The mod_id this config belongs to
  12. var mod_id: String
  13. ## The JSON-Schema this config uses for validation
  14. var schema: Dictionary
  15. ## The data this config holds
  16. var data: Dictionary
  17. ## The path where the JSON file for this config is stored
  18. var save_path: String
  19. ## False if any data is invalid
  20. var valid := false
  21. func _init(_mod_id: String, _data: Dictionary, _save_path: String, _schema: Dictionary = {}) -> void:
  22. name = _ModLoaderPath.get_file_name_from_path(_save_path, true, true)
  23. mod_id = _mod_id
  24. schema = ModLoaderStore.mod_data[_mod_id].manifest.config_schema if _schema.is_empty() else _schema
  25. data = _data
  26. save_path = _save_path
  27. var error_message := validate()
  28. if not error_message == "":
  29. ModLoaderLog.error("Mod Config for mod \"%s\" failed JSON Schema Validation with error message: \"%s\"" % [mod_id, error_message], LOG_NAME)
  30. return
  31. valid = true
  32. func get_data_as_string() -> String:
  33. return JSON.stringify(data)
  34. func get_schema_as_string() -> String:
  35. return JSON.stringify(schema)
  36. # Empty string if validation was successful
  37. func validate() -> String:
  38. var json_schema := JSONSchema.new()
  39. var error := json_schema.validate(get_data_as_string(), get_schema_as_string())
  40. if error.is_empty():
  41. valid = true
  42. else:
  43. valid = false
  44. return error
  45. # Runs the JSON-Schema validation and returns true if valid
  46. func is_valid() -> bool:
  47. if validate() == "":
  48. valid = true
  49. return true
  50. valid = false
  51. return false
  52. ## Saves the config data to the config file
  53. func save_to_file() -> bool:
  54. var is_success := _ModLoaderFile.save_dictionary_to_json_file(data, save_path)
  55. return is_success
  56. ## Removes the config file
  57. func remove_file() -> bool:
  58. var is_success := _ModLoaderFile.remove_file(save_path)
  59. return is_success