Add collection storage: LibraryStore, StateStore, format version 2
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
60c2d03147
commit
6f29e9373d
8 changed files with 704 additions and 17 deletions
176
core/library_store.gd
Normal file
176
core/library_store.gd
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
class_name LibraryStore
|
||||
extends RefCounted
|
||||
## The saved collections: one JSON file per collection in <root>/collections/.
|
||||
## The file name is the collection id. Local state (decks, variables, history)
|
||||
## lives in the paired StateStore and is dropped when a collection is deleted.
|
||||
|
||||
const LEGACY_NAME := "My Tables"
|
||||
|
||||
## Folder that contains collections/. Default user://.
|
||||
var root: String
|
||||
var state: StateStore
|
||||
## Messages about files that couldn't be read or written (most recent last).
|
||||
var errors: PackedStringArray = []
|
||||
|
||||
|
||||
func _init(p_root: String = "user://", p_state: StateStore = null) -> void:
|
||||
root = p_root
|
||||
state = p_state if p_state else StateStore.new(p_root)
|
||||
|
||||
|
||||
func collections_dir() -> String:
|
||||
return root.path_join("collections")
|
||||
|
||||
|
||||
func path_for(id: String) -> String:
|
||||
return collections_dir().path_join(id + ".json")
|
||||
|
||||
|
||||
## True for ids that are safe to use as a file name.
|
||||
static func is_valid_id(id: String) -> bool:
|
||||
if id == "":
|
||||
return false
|
||||
for c in id:
|
||||
if not (c in "abcdefghijklmnopqrstuvwxyz0123456789-_"):
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
## Lowercase letters, digits and dashes; "collection" if nothing is left.
|
||||
static func slugify(text: String) -> String:
|
||||
var out := ""
|
||||
for c in text.to_lower():
|
||||
if c in "abcdefghijklmnopqrstuvwxyz0123456789":
|
||||
out += c
|
||||
elif not out.ends_with("-"):
|
||||
out += "-"
|
||||
out = out.trim_prefix("-").trim_suffix("-")
|
||||
return out if out != "" else "collection"
|
||||
|
||||
|
||||
func exists(id: String) -> bool:
|
||||
return is_valid_id(id) and FileAccess.file_exists(path_for(id))
|
||||
|
||||
|
||||
## [{id, name}] sorted by name. Unreadable files are skipped and noted in errors.
|
||||
func list() -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
var dir := DirAccess.open(collections_dir())
|
||||
if dir == null:
|
||||
return out
|
||||
for fname in dir.get_files():
|
||||
if fname.get_extension() != "json":
|
||||
continue
|
||||
var id := fname.get_basename()
|
||||
if not is_valid_id(id):
|
||||
continue
|
||||
var b := load_collection(id)
|
||||
if b:
|
||||
out.append({"id": id, "name": b.name})
|
||||
out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
|
||||
return str(a["name"]).naturalnocasecmp_to(str(b["name"])) < 0)
|
||||
return out
|
||||
|
||||
|
||||
## Loads a collection, or returns null (and records why in errors) if it's
|
||||
## missing or unreadable. The id always comes from the file name.
|
||||
func load_collection(id: String) -> TowerBoard:
|
||||
if not exists(id):
|
||||
return _fail("No collection '%s'." % id)
|
||||
var b := TowerBoard.new()
|
||||
if not b.load_json(FileAccess.get_file_as_string(path_for(id))):
|
||||
return _fail("Collection file %s is unreadable or not a collection." % path_for(id))
|
||||
b.id = id
|
||||
if b.name == "":
|
||||
b.name = id
|
||||
return b
|
||||
|
||||
|
||||
## Saves a collection under its id. Returns false (and records why) on failure.
|
||||
func save(board: TowerBoard) -> bool:
|
||||
if not is_valid_id(board.id):
|
||||
_fail("Can't save a collection with id '%s'." % board.id)
|
||||
return false
|
||||
var err := TowerBoard.write_text_atomic(path_for(board.id), board.to_json())
|
||||
if err != OK:
|
||||
_fail("Couldn't save %s: %s" % [path_for(board.id), error_string(err)])
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
## Makes and saves an empty collection with a unique id taken from the name.
|
||||
func create(coll_name: String) -> TowerBoard:
|
||||
var b := TowerBoard.new()
|
||||
b.name = coll_name.strip_edges() if coll_name.strip_edges() != "" else "Untitled"
|
||||
b.id = unique_id(slugify(b.name))
|
||||
save(b)
|
||||
return b
|
||||
|
||||
|
||||
## Changes the display name only; the id (and so the file and state) stays.
|
||||
func rename(id: String, new_name: String) -> bool:
|
||||
var b := load_collection(id)
|
||||
if b == null or new_name.strip_edges() == "":
|
||||
return false
|
||||
b.name = new_name.strip_edges()
|
||||
return save(b)
|
||||
|
||||
|
||||
## Copies a collection (tables only; local state isn't copied). Returns the copy or null.
|
||||
func duplicate(id: String, new_name: String) -> TowerBoard:
|
||||
var b := load_collection(id)
|
||||
if b == null:
|
||||
return null
|
||||
b.name = new_name.strip_edges() if new_name.strip_edges() != "" else b.name + " copy"
|
||||
b.id = unique_id(slugify(b.name))
|
||||
return b if save(b) else null
|
||||
|
||||
|
||||
## Deletes the file and the collection's local state.
|
||||
func delete(id: String) -> bool:
|
||||
if not exists(id):
|
||||
return false
|
||||
if DirAccess.remove_absolute(path_for(id)) != OK:
|
||||
_fail("Couldn't delete %s." % path_for(id))
|
||||
return false
|
||||
state.forget_collection(id)
|
||||
state.save()
|
||||
return true
|
||||
|
||||
|
||||
## base, or base-2, base-3 ... whichever isn't taken.
|
||||
func unique_id(base: String) -> String:
|
||||
var id := base
|
||||
var n := 2
|
||||
while exists(id):
|
||||
id = "%s-%d" % [base, n]
|
||||
n += 1
|
||||
return id
|
||||
|
||||
|
||||
## First run: if the old single-board file exists and there are no collections,
|
||||
## imports it as a collection and renames the old file to board.json.bak.
|
||||
## Returns the imported collection, or null if nothing was migrated.
|
||||
func migrate_legacy(legacy_path: String = "") -> TowerBoard:
|
||||
if legacy_path == "":
|
||||
legacy_path = root.path_join("board.json")
|
||||
if not FileAccess.file_exists(legacy_path) or not list().is_empty():
|
||||
return null
|
||||
var b := TowerBoard.load_saved(legacy_path)
|
||||
if b == null:
|
||||
_fail("Old board file %s is unreadable; leaving it alone." % legacy_path)
|
||||
return null
|
||||
b.name = LEGACY_NAME
|
||||
b.id = unique_id(slugify(LEGACY_NAME))
|
||||
if not save(b):
|
||||
return null
|
||||
DirAccess.remove_absolute(legacy_path + ".bak")
|
||||
if DirAccess.rename_absolute(legacy_path, legacy_path + ".bak") != OK:
|
||||
_fail("Imported %s but couldn't rename it to .bak." % legacy_path)
|
||||
return b
|
||||
|
||||
|
||||
func _fail(message: String) -> TowerBoard:
|
||||
errors.append(message)
|
||||
push_warning(message)
|
||||
return null
|
||||
1
core/library_store.gd.uid
Normal file
1
core/library_store.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://c0pij64vq2ydy
|
||||
204
core/state_store.gd
Normal file
204
core/state_store.gd
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
class_name StateStore
|
||||
extends RefCounted
|
||||
## Local state that is never exported: Card mode decks, persistent variables,
|
||||
## roll history and small settings. Everything is keyed by collection and table
|
||||
## ids, so renaming a collection or table doesn't break it.
|
||||
##
|
||||
## Stored as one file, <root>/state/state.json. Mutators only mark the store
|
||||
## dirty (cheap); call save() to write, which does nothing if nothing changed.
|
||||
## Decks are opaque Dictionaries (whatever DeckState.to_dict() produces).
|
||||
|
||||
const FORMAT_VERSION := 1
|
||||
const HISTORY_CAP := 50
|
||||
|
||||
## Folder that contains state/. Default user://.
|
||||
var root: String
|
||||
var _data: Dictionary = {}
|
||||
var _loaded := false
|
||||
var _dirty := false
|
||||
|
||||
|
||||
func _init(p_root: String = "user://") -> void:
|
||||
root = p_root
|
||||
|
||||
|
||||
func state_path() -> String:
|
||||
return root.path_join("state/state.json")
|
||||
|
||||
|
||||
# ---------- Decks ----------
|
||||
|
||||
func get_deck(cid: String, tid: String) -> Dictionary:
|
||||
var by_c: Dictionary = _section("decks").get(cid, {})
|
||||
var d: Variant = by_c.get(tid, {})
|
||||
return (d as Dictionary).duplicate(true) if d is Dictionary else {}
|
||||
|
||||
|
||||
func set_deck(cid: String, tid: String, deck: Dictionary) -> void:
|
||||
_bucket("decks", cid)[tid] = deck.duplicate(true)
|
||||
_dirty = true
|
||||
|
||||
|
||||
## Reshuffle: forgets the deck so the next draw starts a fresh one.
|
||||
func clear_deck(cid: String, tid: String) -> void:
|
||||
var by_c: Dictionary = _section("decks").get(cid, {})
|
||||
if by_c.erase(tid):
|
||||
_dirty = true
|
||||
|
||||
|
||||
# ---------- Persistent variables ----------
|
||||
# {name: {"value": String, "source": table_id}}
|
||||
|
||||
func get_variables(cid: String) -> Dictionary:
|
||||
var v: Variant = _section("variables").get(cid, {})
|
||||
return (v as Dictionary).duplicate(true) if v is Dictionary else {}
|
||||
|
||||
|
||||
func set_variable(cid: String, var_name: String, value: String, source: String = "") -> void:
|
||||
_bucket("variables", cid)[var_name] = {"value": value, "source": source}
|
||||
_dirty = true
|
||||
|
||||
|
||||
func clear_variable(cid: String, var_name: String) -> void:
|
||||
var by_c: Dictionary = _section("variables").get(cid, {})
|
||||
if by_c.erase(var_name):
|
||||
_dirty = true
|
||||
|
||||
|
||||
func clear_variables(cid: String) -> void:
|
||||
if _section("variables").erase(cid):
|
||||
_dirty = true
|
||||
|
||||
|
||||
# ---------- History ----------
|
||||
# One global list, most recent first, capped at HISTORY_CAP. Callers put a
|
||||
# "collection" id in each record; get_history(cid) filters by it.
|
||||
|
||||
func add_history(record: Dictionary) -> void:
|
||||
var list: Array = _section_list("history")
|
||||
list.push_front(record.duplicate(true))
|
||||
if list.size() > HISTORY_CAP:
|
||||
list.resize(HISTORY_CAP)
|
||||
_dirty = true
|
||||
|
||||
|
||||
## All records, or only those whose "collection" is cid when cid isn't empty.
|
||||
func get_history(cid: String = "") -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
for r in _section_list("history"):
|
||||
if r is Dictionary and (cid == "" or str((r as Dictionary).get("collection", "")) == cid):
|
||||
out.append((r as Dictionary).duplicate(true))
|
||||
return out
|
||||
|
||||
|
||||
## Clears all history, or only a collection's records when cid isn't empty.
|
||||
func clear_history(cid: String = "") -> void:
|
||||
var list: Array = _section_list("history")
|
||||
if cid == "":
|
||||
list.clear()
|
||||
else:
|
||||
for i in range(list.size() - 1, -1, -1):
|
||||
if list[i] is Dictionary and str((list[i] as Dictionary).get("collection", "")) == cid:
|
||||
list.remove_at(i)
|
||||
_dirty = true
|
||||
|
||||
|
||||
# ---------- Settings ----------
|
||||
|
||||
func get_setting(key: String, default: Variant = null) -> Variant:
|
||||
return _section("settings").get(key, default)
|
||||
|
||||
|
||||
func set_setting(key: String, value: Variant) -> void:
|
||||
var s := _section("settings")
|
||||
if not s.has(key) or s[key] != value:
|
||||
s[key] = value
|
||||
_dirty = true
|
||||
|
||||
|
||||
# ---------- Forgetting ----------
|
||||
|
||||
## Drops everything stored for a collection (decks, variables, its history).
|
||||
func forget_collection(cid: String) -> void:
|
||||
_section("decks").erase(cid)
|
||||
_section("variables").erase(cid)
|
||||
clear_history(cid)
|
||||
if str(_section("settings").get("last_collection", "")) == cid:
|
||||
_section("settings").erase("last_collection")
|
||||
_dirty = true
|
||||
|
||||
|
||||
## Drops a table's deck and the variables it set.
|
||||
func forget_table(cid: String, tid: String) -> void:
|
||||
clear_deck(cid, tid)
|
||||
var vars: Dictionary = _section("variables").get(cid, {})
|
||||
for k in vars.keys():
|
||||
var v: Variant = vars[k]
|
||||
if v is Dictionary and str((v as Dictionary).get("source", "")) == tid:
|
||||
vars.erase(k)
|
||||
_dirty = true
|
||||
|
||||
|
||||
# ---------- Saving ----------
|
||||
|
||||
func is_dirty() -> bool:
|
||||
return _dirty
|
||||
|
||||
|
||||
## Writes the file if anything changed. Returns false only on a write error.
|
||||
func save() -> bool:
|
||||
if not _loaded or not _dirty:
|
||||
return true
|
||||
var out := _data.duplicate()
|
||||
out["format_version"] = FORMAT_VERSION
|
||||
var err := TowerBoard.write_text_atomic(state_path(), JSON.stringify(out, " "))
|
||||
if err != OK:
|
||||
push_warning("Couldn't save local state to %s: %s" % [state_path(), error_string(err)])
|
||||
return false
|
||||
_dirty = false
|
||||
return true
|
||||
|
||||
|
||||
## Re-reads the file, dropping unsaved changes. A corrupt file is moved aside to
|
||||
## state.json.corrupt and the store starts empty.
|
||||
func reload() -> void:
|
||||
_loaded = true
|
||||
_dirty = false
|
||||
_data = {}
|
||||
var path := state_path()
|
||||
if not FileAccess.file_exists(path):
|
||||
return
|
||||
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(path))
|
||||
if parsed is Dictionary:
|
||||
_data = parsed
|
||||
return
|
||||
push_warning("Local state file %s is unreadable; starting fresh (old copy kept as .corrupt)." % path)
|
||||
DirAccess.rename_absolute(path, path + ".corrupt")
|
||||
|
||||
|
||||
# ---------- Internals ----------
|
||||
|
||||
func _ensure() -> void:
|
||||
if not _loaded:
|
||||
reload()
|
||||
|
||||
|
||||
func _section(key: String) -> Dictionary:
|
||||
_ensure()
|
||||
if not (_data.get(key) is Dictionary):
|
||||
_data[key] = {}
|
||||
return _data[key]
|
||||
|
||||
|
||||
func _section_list(key: String) -> Array:
|
||||
_ensure()
|
||||
if not (_data.get(key) is Array):
|
||||
_data[key] = []
|
||||
return _data[key]
|
||||
|
||||
|
||||
func _bucket(section: String, cid: String) -> Dictionary:
|
||||
var s := _section(section)
|
||||
if not (s.get(cid) is Dictionary):
|
||||
s[cid] = {}
|
||||
return s[cid]
|
||||
1
core/state_store.gd.uid
Normal file
1
core/state_store.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bhci5uoa7vbhp
|
||||
|
|
@ -1,13 +1,18 @@
|
|||
class_name TowerBoard
|
||||
extends RefCounted
|
||||
## Every table on the board, plus loading and saving as JSON.
|
||||
## A collection: every table on the board, plus loading and saving as JSON.
|
||||
## Files carry a format_version; older versions are upgraded by migrate().
|
||||
|
||||
const SAVE_PATH := "user://board.json"
|
||||
const FORMAT_VERSION := 1
|
||||
const SAVE_PATH := "user://board.json" # The single-board file of format version 1.
|
||||
const FORMAT_VERSION := 2
|
||||
|
||||
static var _counter: int = 0
|
||||
static var _salt: String = ""
|
||||
|
||||
## Stable slug used as the file name and as the key for local state.
|
||||
var id: String = ""
|
||||
## Display name; free to change.
|
||||
var name: String = ""
|
||||
var tables: Array[RollTable] = []
|
||||
|
||||
|
||||
|
|
@ -35,40 +40,105 @@ func remove_table(id: String) -> void:
|
|||
e.pipes.erase(id)
|
||||
|
||||
|
||||
## Upgrades a parsed file to FORMAT_VERSION, one version step at a time.
|
||||
## To add a version, bump FORMAT_VERSION and add a _migrate_N_to_N1 step here.
|
||||
static func migrate(d: Dictionary) -> Dictionary:
|
||||
var v: int = int(d.get("format_version", 1))
|
||||
while v < FORMAT_VERSION:
|
||||
match v:
|
||||
1:
|
||||
d = _migrate_1_to_2(d)
|
||||
_:
|
||||
break
|
||||
v += 1
|
||||
d["format_version"] = v
|
||||
return d
|
||||
|
||||
|
||||
## Version 1 had no id or name; they are filled in by whoever imports the file.
|
||||
static func _migrate_1_to_2(d: Dictionary) -> Dictionary:
|
||||
d["format_version"] = 2
|
||||
if not d.has("id"):
|
||||
d["id"] = ""
|
||||
if not d.has("name"):
|
||||
d["name"] = ""
|
||||
return d
|
||||
|
||||
|
||||
func to_dict() -> Dictionary:
|
||||
var list: Array = []
|
||||
for t in tables:
|
||||
list.append(t.to_dict())
|
||||
return {"format_version": FORMAT_VERSION, "tables": list}
|
||||
return {"format_version": FORMAT_VERSION, "id": id, "name": name, "tables": list}
|
||||
|
||||
|
||||
func to_json() -> String:
|
||||
return JSON.stringify(to_dict(), " ")
|
||||
|
||||
|
||||
## Replaces the board's tables from JSON text. Returns false if the text isn't a board.
|
||||
## Replaces the board's tables (and id/name, when the text has them) from JSON
|
||||
## text of any known version. Returns false if the text isn't a board.
|
||||
func load_json(text: String) -> bool:
|
||||
var parsed: Variant = JSON.parse_string(text)
|
||||
if not (parsed is Dictionary) or not (parsed.get("tables") is Array):
|
||||
return false
|
||||
return load_dict(parsed as Dictionary)
|
||||
|
||||
|
||||
## Same as load_json for an already parsed Dictionary.
|
||||
func load_dict(src: Dictionary) -> bool:
|
||||
if not (src.get("tables") is Array):
|
||||
return false
|
||||
var d: Dictionary = migrate(src.duplicate())
|
||||
var loaded: Array[RollTable] = []
|
||||
for td in parsed["tables"]:
|
||||
for td in d["tables"]:
|
||||
if td is Dictionary:
|
||||
loaded.append(RollTable.from_dict(td))
|
||||
tables = loaded
|
||||
if str(d.get("id", "")) != "":
|
||||
id = str(d["id"])
|
||||
if str(d.get("name", "")) != "":
|
||||
name = str(d["name"])
|
||||
return true
|
||||
|
||||
|
||||
## Writes text to path via a temp file and a rename, so a crash can't leave a
|
||||
## half-written file. Creates the folder if needed.
|
||||
static func write_text_atomic(path: String, text: String) -> Error:
|
||||
var dir := path.get_base_dir()
|
||||
if not DirAccess.dir_exists_absolute(dir):
|
||||
var mk := DirAccess.make_dir_recursive_absolute(dir)
|
||||
if mk != OK:
|
||||
return mk
|
||||
var tmp := path + ".tmp"
|
||||
var f := FileAccess.open(tmp, FileAccess.WRITE)
|
||||
if f == null:
|
||||
return FileAccess.get_open_error()
|
||||
f.store_string(text)
|
||||
var werr := f.get_error()
|
||||
f.close()
|
||||
if werr != OK:
|
||||
DirAccess.remove_absolute(tmp)
|
||||
return werr
|
||||
var err := DirAccess.rename_absolute(tmp, path)
|
||||
if err != OK and FileAccess.file_exists(path):
|
||||
# Some platforms won't rename over an existing file.
|
||||
DirAccess.remove_absolute(path)
|
||||
err = DirAccess.rename_absolute(tmp, path)
|
||||
if err != OK:
|
||||
DirAccess.remove_absolute(tmp)
|
||||
return err
|
||||
|
||||
|
||||
func save(path: String = SAVE_PATH) -> bool:
|
||||
var f := FileAccess.open(path, FileAccess.WRITE)
|
||||
if f == null:
|
||||
push_warning("Couldn't save the board to %s: %s" % [path, error_string(FileAccess.get_open_error())])
|
||||
var err := write_text_atomic(path, to_json())
|
||||
if err != OK:
|
||||
push_warning("Couldn't save the board to %s: %s" % [path, error_string(err)])
|
||||
return false
|
||||
f.store_string(to_json())
|
||||
return true
|
||||
|
||||
|
||||
## Loads the saved board, or returns null if there isn't a usable one.
|
||||
## Loads a board file, or returns null if there isn't a usable one.
|
||||
static func load_saved(path: String = SAVE_PATH) -> TowerBoard:
|
||||
if not FileAccess.file_exists(path):
|
||||
return null
|
||||
|
|
|
|||
204
tests/test_storage.gd
Normal file
204
tests/test_storage.gd
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
extends SceneTree
|
||||
## Headless checks for collections, LibraryStore and StateStore.
|
||||
## Run: godot --headless --path . -s res://tests/test_storage.gd
|
||||
|
||||
const ROOT := "user://test_storage_tmp"
|
||||
|
||||
var _failures := 0
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
_wipe(ROOT)
|
||||
_test_versions()
|
||||
_test_library()
|
||||
_test_migration()
|
||||
_test_corrupt()
|
||||
_test_state()
|
||||
_wipe(ROOT)
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
func _test_versions() -> void:
|
||||
var sample := SampleBoard.create()
|
||||
var v1 := JSON.stringify({"format_version": 1, "tables": sample.to_dict()["tables"]})
|
||||
var b := TowerBoard.new()
|
||||
_check(b.load_json(v1), "v1 text loads")
|
||||
_check(b.tables.size() == sample.tables.size(), "v1 keeps every table")
|
||||
_check(b.id == "" and b.name == "", "v1 has no id or name")
|
||||
var d := b.to_dict()
|
||||
_check(int(d["format_version"]) == 2, "saving writes format_version 2")
|
||||
var b2 := TowerBoard.new()
|
||||
b2.id = "x"
|
||||
b2.name = "X"
|
||||
b2.tables = b.tables
|
||||
var b3 := TowerBoard.new()
|
||||
_check(b3.load_json(b2.to_json()), "v2 text loads")
|
||||
_check(b3.id == "x" and b3.name == "X", "v2 round-trips id and name")
|
||||
_check(not TowerBoard.new().load_json("not json"), "garbage is rejected")
|
||||
_check(TowerBoard.migrate({"format_version": 1, "tables": []})["format_version"] == 2, "migrate steps 1 to 2")
|
||||
|
||||
|
||||
func _test_library() -> void:
|
||||
var root := ROOT + "/lib"
|
||||
var lib := LibraryStore.new(root)
|
||||
_check(lib.list().is_empty(), "empty library lists nothing")
|
||||
var a := lib.create("Fantasy Loot")
|
||||
_check(a.id == "fantasy-loot", "slug id from name")
|
||||
var a2 := lib.create("Fantasy Loot")
|
||||
_check(a2.id == "fantasy-loot-2", "duplicate names get unique ids")
|
||||
_check(LibraryStore.slugify(" !! ") == "collection", "empty slug falls back")
|
||||
_check(lib.exists("fantasy-loot") and not lib.exists("nope") and not lib.exists("../x"), "exists")
|
||||
|
||||
a.tables = SampleBoard.create().tables
|
||||
_check(lib.save(a), "save succeeds")
|
||||
var back := lib.load_collection("fantasy-loot")
|
||||
_check(back != null and back.tables.size() == a.tables.size() and back.name == "Fantasy Loot", "load round trip")
|
||||
|
||||
_check(lib.rename("fantasy-loot", "Dark Loot"), "rename succeeds")
|
||||
_check(lib.load_collection("fantasy-loot").name == "Dark Loot", "rename keeps id, changes name")
|
||||
|
||||
var copy := lib.duplicate("fantasy-loot", "Dark Loot Copy")
|
||||
_check(copy != null and copy.id == "dark-loot-copy" and copy.tables.size() == a.tables.size(), "duplicate copies tables")
|
||||
var names: Array = []
|
||||
for e in lib.list():
|
||||
names.append(e["name"])
|
||||
_check(names == ["Dark Loot", "Dark Loot Copy", "Fantasy Loot"], "list sorted by name: %s" % str(names))
|
||||
|
||||
# No temp files left behind by saves.
|
||||
var leftovers := 0
|
||||
for f in DirAccess.get_files_at(lib.collections_dir()):
|
||||
if not f.ends_with(".json"):
|
||||
leftovers += 1
|
||||
_check(leftovers == 0, "atomic save leaves no temp files")
|
||||
|
||||
# Delete removes the file and its state.
|
||||
lib.state.set_deck("fantasy-loot", "loot", {"drawn": [1]})
|
||||
lib.state.set_variable("fantasy-loot", "weapon", "Dagger", "loot")
|
||||
lib.state.add_history({"collection": "fantasy-loot", "root": "loot"})
|
||||
lib.state.add_history({"collection": "dark-loot-copy", "root": "loot"})
|
||||
lib.state.set_setting("last_collection", "fantasy-loot")
|
||||
_check(lib.delete("fantasy-loot"), "delete succeeds")
|
||||
_check(not lib.exists("fantasy-loot"), "deleted file is gone")
|
||||
_check(lib.state.get_deck("fantasy-loot", "loot").is_empty(), "delete drops decks")
|
||||
_check(lib.state.get_variables("fantasy-loot").is_empty(), "delete drops variables")
|
||||
_check(lib.state.get_history("fantasy-loot").is_empty() and lib.state.get_history().size() == 1, "delete drops only its history")
|
||||
_check(lib.state.get_setting("last_collection") == null, "delete clears last_collection if it pointed there")
|
||||
_check(not lib.delete("fantasy-loot"), "deleting twice returns false")
|
||||
_check(lib.load_collection("fantasy-loot") == null, "loading a missing collection returns null")
|
||||
|
||||
|
||||
func _test_migration() -> void:
|
||||
var root := ROOT + "/mig"
|
||||
DirAccess.make_dir_recursive_absolute(root)
|
||||
var legacy := root + "/board.json"
|
||||
var sample := SampleBoard.create()
|
||||
var f := FileAccess.open(legacy, FileAccess.WRITE)
|
||||
f.store_string(JSON.stringify({"format_version": 1, "tables": sample.to_dict()["tables"]}))
|
||||
f.close()
|
||||
var lib := LibraryStore.new(root)
|
||||
var b := lib.migrate_legacy()
|
||||
_check(b != null and b.name == "My Tables" and b.id == "my-tables", "legacy board imported as My Tables")
|
||||
_check(lib.load_collection("my-tables").tables.size() == sample.tables.size(), "imported tables are saved")
|
||||
_check(not FileAccess.file_exists(legacy) and FileAccess.file_exists(legacy + ".bak"), "old file renamed to .bak")
|
||||
_check(lib.migrate_legacy() == null, "migration is a no-op once done")
|
||||
|
||||
# Not run when collections already exist.
|
||||
var f2 := FileAccess.open(legacy, FileAccess.WRITE)
|
||||
f2.store_string(JSON.stringify({"format_version": 1, "tables": sample.to_dict()["tables"]}))
|
||||
f2.close()
|
||||
_check(lib.migrate_legacy() == null and FileAccess.file_exists(legacy), "no migration when collections exist")
|
||||
|
||||
|
||||
func _test_corrupt() -> void:
|
||||
var root := ROOT + "/bad"
|
||||
var lib := LibraryStore.new(root)
|
||||
lib.create("Good")
|
||||
var f := FileAccess.open(lib.path_for("broken"), FileAccess.WRITE)
|
||||
f.store_string("{ this is not json")
|
||||
f.close()
|
||||
var f2 := FileAccess.open(lib.path_for("wrongshape"), FileAccess.WRITE)
|
||||
f2.store_string("[1, 2, 3]")
|
||||
f2.close()
|
||||
_check(lib.load_collection("broken") == null, "corrupt collection loads as null")
|
||||
var ids: Array = []
|
||||
for e in lib.list():
|
||||
ids.append(e["id"])
|
||||
_check(ids == ["good"], "list skips unreadable files: %s" % str(ids))
|
||||
_check(not lib.errors.is_empty(), "errors are recorded")
|
||||
|
||||
# Corrupt legacy file is left alone.
|
||||
var legacy := root + "/board.json"
|
||||
var f3 := FileAccess.open(legacy, FileAccess.WRITE)
|
||||
f3.store_string("nope")
|
||||
f3.close()
|
||||
var lib2 := LibraryStore.new(root + "/empty")
|
||||
_check(lib2.migrate_legacy(legacy) == null and FileAccess.file_exists(legacy), "corrupt legacy file is not touched")
|
||||
|
||||
# Corrupt state file starts fresh.
|
||||
var st := StateStore.new(root)
|
||||
DirAccess.make_dir_recursive_absolute(root + "/state")
|
||||
var f4 := FileAccess.open(st.state_path(), FileAccess.WRITE)
|
||||
f4.store_string("garbage")
|
||||
f4.close()
|
||||
_check(st.get_variables("c").is_empty(), "corrupt state file reads as empty")
|
||||
st.set_setting("k", 1)
|
||||
_check(st.save() and FileAccess.file_exists(st.state_path() + ".corrupt"), "corrupt state moved aside, new one saved")
|
||||
|
||||
|
||||
func _test_state() -> void:
|
||||
var root := ROOT + "/state"
|
||||
var st := StateStore.new(root)
|
||||
_check(st.save() and not FileAccess.file_exists(st.state_path()), "saving an untouched store writes nothing")
|
||||
st.set_deck("c1", "t1", {"drawn": [3, 5], "n": 10})
|
||||
st.set_deck("c1", "t2", {"drawn": []})
|
||||
st.set_variable("c1", "weapon", "Dagger", "t1")
|
||||
st.set_variable("c1", "armor", "Plate", "t2")
|
||||
st.set_setting("last_collection", "c1")
|
||||
for i in 60:
|
||||
st.add_history({"collection": "c1", "n": i})
|
||||
_check(st.is_dirty(), "mutation sets dirty")
|
||||
_check(st.save() and not st.is_dirty(), "save clears dirty")
|
||||
_check(not FileAccess.file_exists(st.state_path() + ".tmp"), "no temp file after state save")
|
||||
|
||||
var st2 := StateStore.new(root)
|
||||
var deck := st2.get_deck("c1", "t1")
|
||||
_check(deck.get("n") == 10.0 and (deck["drawn"] as Array).size() == 2, "deck round trip")
|
||||
_check(st2.get_deck("c1", "nope").is_empty() and st2.get_deck("zz", "t1").is_empty(), "missing deck is empty")
|
||||
_check(st2.get_variables("c1")["weapon"] == {"value": "Dagger", "source": "t1"}, "variable round trip")
|
||||
_check(st2.get_setting("last_collection") == "c1" and st2.get_setting("none", "d") == "d", "settings round trip")
|
||||
var h := st2.get_history()
|
||||
_check(h.size() == StateStore.HISTORY_CAP, "history capped at 50 (got %d)" % h.size())
|
||||
_check(h[0]["n"] == 59.0 and h[49]["n"] == 10.0, "history is most recent first")
|
||||
|
||||
st2.clear_variable("c1", "weapon")
|
||||
_check(not st2.get_variables("c1").has("weapon") and st2.get_variables("c1").has("armor"), "clear one variable")
|
||||
st2.forget_table("c1", "t2")
|
||||
_check(st2.get_deck("c1", "t2").is_empty() and not st2.get_variables("c1").has("armor"), "forget_table drops deck and its variables")
|
||||
_check(not st2.get_deck("c1", "t1").is_empty(), "forget_table leaves other tables")
|
||||
st2.clear_deck("c1", "t1")
|
||||
_check(st2.get_deck("c1", "t1").is_empty(), "clear_deck")
|
||||
st2.set_variable("c1", "a", "1")
|
||||
st2.clear_variables("c1")
|
||||
_check(st2.get_variables("c1").is_empty(), "clear all variables")
|
||||
st2.clear_history()
|
||||
_check(st2.get_history().is_empty(), "clear_history")
|
||||
st2.save()
|
||||
var st3 := StateStore.new(root)
|
||||
_check(st3.get_history().is_empty() and st3.get_deck("c1", "t1").is_empty(), "cleared state persists")
|
||||
|
||||
|
||||
func _wipe(path: String) -> void:
|
||||
if not DirAccess.dir_exists_absolute(path):
|
||||
return
|
||||
for d in DirAccess.get_directories_at(path):
|
||||
_wipe(path.path_join(d))
|
||||
for f in DirAccess.get_files_at(path):
|
||||
DirAccess.remove_absolute(path.path_join(f))
|
||||
DirAccess.remove_absolute(path)
|
||||
|
||||
|
||||
func _check(ok: bool, what: String) -> void:
|
||||
if not ok:
|
||||
_failures += 1
|
||||
print(" ✗ ", what)
|
||||
1
tests/test_storage.gd.uid
Normal file
1
tests/test_storage.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://d10dfnkj6mc2y
|
||||
42
ui/main.gd
42
ui/main.gd
|
|
@ -13,6 +13,8 @@ const HINTS := {
|
|||
}
|
||||
|
||||
var data: TowerBoard
|
||||
var library: LibraryStore
|
||||
var state: StateStore
|
||||
var mode: Mode = Mode.PLAY
|
||||
var cards: Dictionary = {} # table id -> TableCard
|
||||
var lit_entries: Dictionary = {} # "tid:eid" -> true
|
||||
|
|
@ -49,9 +51,11 @@ func _ready() -> void:
|
|||
if args.has("--sample") or _arg_value(args, "--screenshot") != "":
|
||||
_saving_enabled = false
|
||||
if _saving_enabled:
|
||||
data = TowerBoard.load_saved()
|
||||
_open_library()
|
||||
if data == null:
|
||||
data = SampleBoard.create()
|
||||
data.id = "fantasy-loot"
|
||||
data.name = "Fantasy Loot"
|
||||
|
||||
_build_ui()
|
||||
_rebuild_cards()
|
||||
|
|
@ -65,8 +69,35 @@ func _ready() -> void:
|
|||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
if _saving_enabled and data:
|
||||
data.save()
|
||||
_save_now()
|
||||
|
||||
|
||||
## Migrates the old board.json if needed, then opens the last collection (or the
|
||||
## first one, or a new "Fantasy Loot" made from the sample tables).
|
||||
func _open_library() -> void:
|
||||
state = StateStore.new()
|
||||
library = LibraryStore.new("user://", state)
|
||||
library.migrate_legacy()
|
||||
var last := str(state.get_setting("last_collection", ""))
|
||||
if last != "":
|
||||
data = library.load_collection(last)
|
||||
if data == null:
|
||||
for entry in library.list():
|
||||
data = library.load_collection(str(entry["id"]))
|
||||
if data:
|
||||
break
|
||||
if data == null:
|
||||
data = library.create("Fantasy Loot")
|
||||
data.tables = SampleBoard.create().tables
|
||||
library.save(data)
|
||||
state.set_setting("last_collection", data.id)
|
||||
|
||||
|
||||
func _save_now() -> void:
|
||||
if _saving_enabled and data and library:
|
||||
library.save(data)
|
||||
state.set_setting("last_collection", data.id)
|
||||
state.save()
|
||||
|
||||
|
||||
# ---------- UI ----------
|
||||
|
|
@ -90,8 +121,7 @@ func _build_ui() -> void:
|
|||
_save_timer.one_shot = true
|
||||
_save_timer.wait_time = SAVE_DELAY
|
||||
_save_timer.timeout.connect(func() -> void:
|
||||
if _saving_enabled:
|
||||
data.save()
|
||||
_save_now()
|
||||
)
|
||||
add_child(_save_timer)
|
||||
resized.connect(_place_toast)
|
||||
|
|
@ -348,7 +378,7 @@ func add_table() -> void:
|
|||
|
||||
func reset_sample() -> void:
|
||||
var snap := _snapshot()
|
||||
data = SampleBoard.create()
|
||||
data.tables = SampleBoard.create().tables
|
||||
lit_entries.clear()
|
||||
lit_pipes.clear()
|
||||
_rebuild_cards()
|
||||
|
|
|
|||
Loading…
Reference in a new issue