TableTower/core/board_file_io.gd

58 lines
1.8 KiB
GDScript3
Raw Permalink Normal View History

class_name BoardFileIO
extends RefCounted
## Board files on disk: upgrading old file versions (migrate) and writing
## text safely through a temp file. TowerBoard hands this work to here.
## Upgrades a parsed file to TowerBoard.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(data: Dictionary) -> Dictionary:
var version: int = int(data.get("format_version", 1))
while version < TowerBoard.FORMAT_VERSION:
match version:
1:
data = _migrate_1_to_2(data)
_:
break
version += 1
data["format_version"] = version
return data
## Version 1 had no id or name; they are filled in by whoever imports the file.
static func _migrate_1_to_2(data: Dictionary) -> Dictionary:
data["format_version"] = 2
if not data.has("id"):
data["id"] = ""
if not data.has("name"):
data["name"] = ""
return data
## 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 file := FileAccess.open(tmp, FileAccess.WRITE)
if file == null:
return FileAccess.get_open_error()
file.store_string(text)
var write_error := file.get_error()
file.close()
if write_error != OK:
DirAccess.remove_absolute(tmp)
return write_error
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