wow-state 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wow_state/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """Stdlib-only parser, reader, discovery, and archiver for WoWState SavedVariables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "1.1.0"
6
+
7
+ from .discovery import discover_sv_files, resolve_sv_path # noqa: E402
8
+ from .parser import ( # noqa: E402
9
+ DB_GLOBAL_NAMES,
10
+ LuaSyntaxError,
11
+ LuaTableParser,
12
+ SVError,
13
+ find_db_table,
14
+ normalize_arrays,
15
+ read_sv,
16
+ sanitize_for_json,
17
+ strip_bootstrap,
18
+ )
19
+ from .reader import ( # noqa: E402
20
+ AI_SECTIONS,
21
+ build_ai_snapshot,
22
+ format_summary,
23
+ select_character,
24
+ )
25
+
26
+ __all__ = [
27
+ "__version__",
28
+ "AI_SECTIONS",
29
+ "DB_GLOBAL_NAMES",
30
+ "SVError",
31
+ "LuaSyntaxError",
32
+ "LuaTableParser",
33
+ "read_sv",
34
+ "strip_bootstrap",
35
+ "normalize_arrays",
36
+ "sanitize_for_json",
37
+ "find_db_table",
38
+ "discover_sv_files",
39
+ "resolve_sv_path",
40
+ "build_ai_snapshot",
41
+ "format_summary",
42
+ "select_character",
43
+ ]
wow_state/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Entry point for `python3 -m wow_state`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from .reader import main
8
+
9
+ if __name__ == "__main__":
10
+ sys.exit(main())
wow_state/archive.py ADDED
@@ -0,0 +1,168 @@
1
+ """Archive changed WoWState SavedVariables snapshots with JSON sidecars."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import datetime as _dt
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ from . import __version__
14
+ from .discovery import resolve_sv_path
15
+ from .parser import (
16
+ LuaTableParser,
17
+ SVError,
18
+ normalize_arrays,
19
+ sanitize_for_json,
20
+ strip_bootstrap,
21
+ )
22
+
23
+ HASH_NAME = ".last_hash"
24
+
25
+
26
+ def _log(msg: str) -> None:
27
+ stamp = _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
28
+ print(f"[{stamp}] {msg}", flush=True)
29
+
30
+
31
+ def _sha256_bytes(data: bytes) -> str:
32
+ return hashlib.sha256(data).hexdigest()
33
+
34
+
35
+ def _tmp_for(path: Path) -> Path:
36
+ return path.with_name(f".{path.name}.{os.getpid()}.tmp")
37
+
38
+
39
+ def _atomic_write_bytes(path: Path, data: bytes, mtime: float | None = None) -> None:
40
+ tmp = _tmp_for(path)
41
+ try:
42
+ with open(tmp, "wb") as fh:
43
+ fh.write(data)
44
+ fh.flush()
45
+ os.fsync(fh.fileno())
46
+ if mtime is not None:
47
+ os.utime(tmp, (mtime, mtime))
48
+ os.replace(tmp, path)
49
+ finally:
50
+ try:
51
+ tmp.unlink(missing_ok=True)
52
+ except OSError:
53
+ pass
54
+
55
+
56
+ def _render_json_sidecar(clean_text: str, arrays: bool = False) -> str:
57
+ doc = LuaTableParser(clean_text).parse_document()
58
+ if not doc:
59
+ raise SVError("SavedVariables file contains no Lua assignments")
60
+ payload = normalize_arrays(doc) if arrays else doc
61
+ payload = sanitize_for_json(payload)
62
+ return json.dumps(payload, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
63
+
64
+
65
+ def archive_snapshot(
66
+ source: Path,
67
+ dest: Path,
68
+ prefix: str = "WoWState",
69
+ arrays: bool = False,
70
+ ) -> int:
71
+ """Archive a changed SavedVariables snapshot into dest with a JSON sidecar."""
72
+ if not source.is_file():
73
+ _log(
74
+ f"no snapshot yet: {source} not found "
75
+ "(waiting for the first in-game flush)"
76
+ )
77
+ return 0
78
+
79
+ raw_text = source.read_text(encoding="utf-8", errors="replace")
80
+ clean_text = strip_bootstrap(raw_text)
81
+ if not clean_text.strip():
82
+ raise SVError(f"SavedVariables file is empty: {source}")
83
+
84
+ clean_bytes = clean_text.encode("utf-8")
85
+ digest = _sha256_bytes(clean_bytes)
86
+ hash_path = dest / HASH_NAME
87
+ if hash_path.is_file():
88
+ try:
89
+ prior = hash_path.read_text(encoding="utf-8").strip()
90
+ except OSError:
91
+ prior = None
92
+ if prior == digest:
93
+ _log(f"unchanged: {source} (sha256 {digest}) already archived")
94
+ return 0
95
+
96
+ # Parse before creating any output file so broken input never touches history.
97
+ json_payload = _render_json_sidecar(clean_text, arrays=arrays)
98
+
99
+ dest.mkdir(parents=True, exist_ok=True)
100
+ mtime = source.stat().st_mtime
101
+ stamp = _dt.datetime.fromtimestamp(mtime).strftime("%Y%m%d-%H%M%S")
102
+ stamp_text = _dt.datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M:%S")
103
+
104
+ candidate = dest / f"{prefix}-{stamp}.lua"
105
+ n = 1
106
+ while candidate.exists():
107
+ if _sha256_bytes(candidate.read_bytes()) == digest:
108
+ break
109
+ n += 1
110
+ candidate = dest / f"{prefix}-{stamp}-{n}.lua"
111
+ archive = candidate
112
+
113
+ created = not archive.exists()
114
+ if created:
115
+ _atomic_write_bytes(archive, clean_bytes, mtime=mtime)
116
+
117
+ json_path = archive.with_suffix(".json")
118
+ _atomic_write_bytes(json_path, json_payload.encode("utf-8"))
119
+
120
+ # Write .last_hash LAST so partial failures never mark unarchived state as seen.
121
+ _atomic_write_bytes(hash_path, (digest + "\n").encode("ascii"))
122
+
123
+ verb = "archived" if created else "reused"
124
+ _log(
125
+ f"{verb} {archive.name} + {json_path.name} "
126
+ f"(sha256 {digest}, source mtime {stamp_text})"
127
+ )
128
+ return 0
129
+
130
+
131
+ def main(argv: list[str] | None = None) -> int:
132
+ default_dest = os.environ.get("WOW_STATE_HISTORY_DIR", "history")
133
+ ap = argparse.ArgumentParser(
134
+ prog="wow-state-archive",
135
+ description="Archive changed WoWState SavedVariables snapshots + JSON sidecars.",
136
+ )
137
+ ap.add_argument(
138
+ "-V", "--version", action="version", version=f"%(prog)s {__version__}",
139
+ )
140
+ ap.add_argument(
141
+ "--source", default=None,
142
+ help="SavedVariables .lua file (default: WOW_STATE_SV or auto-discover)",
143
+ )
144
+ ap.add_argument(
145
+ "--dest", default=default_dest,
146
+ help=f"history folder (default: {default_dest})",
147
+ )
148
+ ap.add_argument(
149
+ "--prefix", default="WoWState",
150
+ help="archive filename prefix (default: WoWState)",
151
+ )
152
+ ap.add_argument(
153
+ "--arrays", action="store_true",
154
+ help="normalize contiguous 1-based Lua tables into JSON arrays in sidecars",
155
+ )
156
+ args = ap.parse_args(argv)
157
+
158
+ try:
159
+ source = resolve_sv_path(args.source)
160
+ dest = Path(args.dest).expanduser()
161
+ return archive_snapshot(source, dest, prefix=args.prefix, arrays=args.arrays)
162
+ except (OSError, SVError, ValueError) as exc:
163
+ print(f"wow-state-archive: {exc}", file=sys.stderr, flush=True)
164
+ return 1
165
+
166
+
167
+ if __name__ == "__main__":
168
+ sys.exit(main())
wow_state/discovery.py ADDED
@@ -0,0 +1,125 @@
1
+ """Discover World of Warcraft SavedVariables files across standard platforms."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import glob
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from .parser import SVError
11
+
12
+ SV_FILENAMES = ("WoWState.lua",)
13
+
14
+ WOW_FLAVORS = (
15
+ "_retail_",
16
+ "_classic_",
17
+ "_classic_era_",
18
+ "_classic_ptr_",
19
+ "_forever_",
20
+ "_ptr_",
21
+ "_beta_",
22
+ )
23
+
24
+
25
+ def _candidate_wow_roots(extra_roots: list[Path] | None = None) -> list[Path]:
26
+ roots: list[Path] = []
27
+ env_wow = os.environ.get("WOW_DIR")
28
+ if env_wow:
29
+ roots.append(Path(env_wow).expanduser())
30
+ if extra_roots:
31
+ roots.extend(p.expanduser() for p in extra_roots)
32
+
33
+ home = Path.home()
34
+ roots.extend([
35
+ Path("/Applications/World of Warcraft"),
36
+ home / "Applications" / "World of Warcraft",
37
+ home / "Games" / "World of Warcraft",
38
+ home / "Games" / "battlenet" / "drive_c" / "Program Files (x86)" / "World of Warcraft",
39
+ Path("C:/Program Files (x86)/World of Warcraft"),
40
+ Path("C:/Program Files/World of Warcraft"),
41
+ ])
42
+
43
+ for pattern in (
44
+ "/Volumes/*/Games/World of Warcraft",
45
+ str(home / ".local/share/Steam/steamapps/compatdata/*/pfx/drive_c/Program Files (x86)/World of Warcraft"),
46
+ ):
47
+ for match in sorted(glob.glob(pattern)):
48
+ roots.append(Path(match))
49
+
50
+ # Deduplicate while preserving priority order.
51
+ unique: list[Path] = []
52
+ seen: set[str] = set()
53
+ for root in roots:
54
+ key = str(root)
55
+ if key not in seen:
56
+ seen.add(key)
57
+ unique.append(root)
58
+ return unique
59
+
60
+
61
+ def discover_sv_files(extra_roots: list[Path] | None = None) -> list[Path]:
62
+ """Find WoWState SavedVariables files, newest first."""
63
+ found: list[tuple[float, Path]] = []
64
+ seen: set[Path] = set()
65
+
66
+ for root in _candidate_wow_roots(extra_roots):
67
+ try:
68
+ if not root.is_dir():
69
+ continue
70
+ except OSError:
71
+ continue
72
+
73
+ for flavor in WOW_FLAVORS:
74
+ acct_dir = root / flavor / "WTF" / "Account"
75
+ try:
76
+ if not acct_dir.is_dir():
77
+ continue
78
+ accounts = list(acct_dir.iterdir())
79
+ except OSError:
80
+ continue
81
+
82
+ for acct in accounts:
83
+ try:
84
+ if not acct.is_dir():
85
+ continue
86
+ except OSError:
87
+ continue
88
+ sv_dir = acct / "SavedVariables"
89
+ for filename in SV_FILENAMES:
90
+ candidate = sv_dir / filename
91
+ try:
92
+ if candidate.is_file():
93
+ resolved = candidate.resolve()
94
+ if resolved not in seen:
95
+ seen.add(resolved)
96
+ found.append((candidate.stat().st_mtime, candidate))
97
+ except OSError:
98
+ continue
99
+
100
+ found.sort(key=lambda item: item[0], reverse=True)
101
+ return [item[1] for item in found]
102
+
103
+
104
+ def resolve_sv_path(explicit: str | None = None) -> Path:
105
+ """Resolve the SavedVariables file path from CLI arg, env vars, or discovery."""
106
+ if explicit:
107
+ return Path(explicit).expanduser()
108
+
109
+ env_sv = os.environ.get("WOW_STATE_SV")
110
+ if env_sv:
111
+ return Path(env_sv).expanduser()
112
+
113
+ discovered = discover_sv_files()
114
+ if discovered:
115
+ if len(discovered) > 1:
116
+ print(
117
+ f"Note: multiple SavedVariables found; using newest: {discovered[0]}",
118
+ file=sys.stderr,
119
+ )
120
+ return discovered[0]
121
+
122
+ raise SVError(
123
+ "No WoWState SavedVariables file found. Pass a file path, set "
124
+ "WOW_STATE_SV, or log out / /reload in-game so WoW writes WoWState.lua."
125
+ )