wow-state 1.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brian Sunter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,10 @@
1
+ include LICENSE README.md pyproject.toml
2
+ recursive-include src *.py
3
+ recursive-include tests *.py *.lua
4
+ prune history
5
+ prune dist
6
+ prune WoWState
7
+ prune extras
8
+ prune scripts
9
+ prune .agents
10
+ global-exclude *.pyc __pycache__ .DS_Store
@@ -0,0 +1,161 @@
1
+ Metadata-Version: 2.4
2
+ Name: wow-state
3
+ Version: 1.1.0
4
+ Summary: Read, query, and archive World of Warcraft character state snapshots exported by WoWState
5
+ Author: Brian Sunter
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/briansunter/wow-state
8
+ Project-URL: Repository, https://github.com/briansunter/wow-state
9
+ Project-URL: Issues, https://github.com/briansunter/wow-state/issues
10
+ Keywords: world-of-warcraft,wow,addon,savedvariables,lua,cli,ai,agent
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Games/Entertainment :: Role-Playing
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Dynamic: license-file
26
+
27
+ # WoWState
28
+
29
+ **WoWState** (`wow-state`) is a lightweight, zero-UI World of Warcraft addon and stdlib-only Python toolkit that exports your full character state to `SavedVariables` (`WoWStateDB`) so external tools, scripts, and AI assistants can inspect and archive it outside the game.
30
+
31
+ **Downloads & Directories:** [PyPI](https://pypi.org/project/wow-state/) · [CurseForge](https://www.curseforge.com/wow/addons/wowstate) · [Wago Addons](https://addons.wago.io/addons/wowstate) · [WoWInterface](https://www.wowinterface.com/downloads/info27347-WoWState.html) · [GitHub Releases](https://github.com/briansunter/wow-state/releases/latest)
32
+
33
+ ## Features
34
+
35
+ - **Full character snapshot**: identity, `/played` time, location/coordinates/instance, item level, secondary/tertiary/ranged/resistance/weapon/movement stats, combat ratings, weapon & profession skills, spellbook, talents & Retail spec/loadouts, action bars, equipped gear (with per-slot iLvl), carried bags, bank/Reagent/Warband contents, active & completed quests, reputations, currencies, buffs/debuffs, macros, mounts/achievements, PvP stats/ratings, instance lockouts/Mythic+/Great Vault, and active pet state.
36
+ - **Self-healing & resilient**: every collector section runs inside `xpcall`; `Collect()` is `pcall`-guarded with re-entrancy protection, scheduled timers, and a 30s/180s `OnUpdate` watchdog.
37
+ - **Keep-last-good merge**: torn-down logout or early-login collects never overwrite populated character sections with empty/zeroed state, and restricted/secret client values are safely ignored.
38
+ - **Multi-flavor TOC support**: ships with a multi-flavor `## Interface:` manifest for Retail (`Mainline`), Mists of Pandaria Classic (`Mists`), Cataclysm Classic (`Cata`), TBC Classic (`TBC`), Classic Era (`Vanilla`), and custom `16001` builds.
39
+ - **Zero-dependency Python CLI & archiver**: parses WoW's Lua `SavedVariables` (including `\ddd` UTF-8 byte escapes and long strings) using only Python's standard library, with auto-discovery, `--summary`, `--section`, `--arrays`, and idempotent snapshot archiving with JSON sidecars.
40
+ - **Project-local AI skill**: includes `.agents/skills/wow-state/` so coding assistants in this repo know how to discover, query, and interpret character snapshots.
41
+
42
+ ## Installation
43
+
44
+ ### 1. Install the WoW Addon
45
+
46
+ #### Option A: Addon Manager / Directory
47
+ Install **WoWState** directly from:
48
+ - **CurseForge**: https://www.curseforge.com/wow/addons/wowstate
49
+ - **Wago Addons**: https://addons.wago.io/addons/wowstate
50
+ - **WoWInterface**: https://www.wowinterface.com/downloads/info27347-WoWState.html
51
+
52
+ #### Option B: Release ZIP (manual install)
53
+ Download `WoWState-<version>.zip` from [GitHub Releases](https://github.com/briansunter/wow-state/releases/latest) and extract the `WoWState/` folder into your `Interface/AddOns/` directory.
54
+
55
+ #### Option C: Install from source
56
+ ```sh
57
+ sh scripts/install.sh
58
+ ```
59
+
60
+ Or specify your AddOns directory explicitly:
61
+ ```sh
62
+ sh scripts/install.sh --addons "/path/to/World of Warcraft/_retail_/Interface/AddOns"
63
+ ```
64
+
65
+ ### 2. Run or Install the Python CLI
66
+
67
+ `wow-state` uses only the Python 3.10+ standard library. Run it directly with `uvx` (zero install):
68
+
69
+ ```sh
70
+ uvx wow-state
71
+ uvx wow-state --only character,stats,equipment
72
+ ```
73
+
74
+ Or install `wow-state` and `wow-state-archive` from PyPI:
75
+
76
+ ```sh
77
+ pip install wow-state
78
+ # or: uv tool install wow-state / pipx install wow-state
79
+ ```
80
+
81
+ Or run directly from a source checkout:
82
+ ```sh
83
+ PYTHONPATH=src python3 -m wow_state
84
+ ```
85
+
86
+ ## In-Game Slash Commands
87
+
88
+ - `/wowstate` or `/wstate` — refresh the character snapshot immediately (flushes to disk on `/reload` or logout)
89
+ - `/wowstate status` — print addon version, load count, collect counts, and last collect status
90
+ - `/wowstate help` — show slash command usage
91
+
92
+ ## Python CLI Usage
93
+
94
+ ### Inspect SavedVariables (`wow-state`)
95
+
96
+ ```sh
97
+ # Print a compact AI-ready JSON digest for the latest character (default)
98
+ wow-state
99
+ wow-state --only character,stats,equipment
100
+ wow-state --character "Lyra" --indent 2
101
+ wow-state --all
102
+
103
+ # Discover SavedVariables files or list characters
104
+ wow-state --discover
105
+ wow-state --list
106
+
107
+ # Print a compact human-readable summary
108
+ wow-state --summary
109
+ wow-state --summary --character "Lyra"
110
+ wow-state --summary --all
111
+
112
+ # Query a single raw section as clean JSON arrays
113
+ wow-state --section inventory
114
+ wow-state --section equipment
115
+ wow-state --section questLog
116
+
117
+ # Dump the entire raw parsed SavedVariables file as JSON
118
+ wow-state --raw path/to/SavedVariables/WoWState.lua
119
+ ```
120
+
121
+ Environment variables:
122
+ - `WOW_STATE_SV`: explicit path to `WoWState.lua`
123
+ - `WOW_DIR`: additional World of Warcraft root directory to scan during `--discover`
124
+
125
+ ### Archive Snapshot History (`wow-state-archive`)
126
+
127
+ World of Warcraft overwrites `SavedVariables/WoWState.lua` on every `/reload` or logout. Archive changed snapshots along with validated `.json` sidecars:
128
+
129
+ ```sh
130
+ wow-state-archive --dest ./history
131
+ ```
132
+
133
+ The archiver hashes only the Lua data portion (ignoring any optional bootstrap carrier), writes atomically, and skips unchanged files.
134
+
135
+ ## AI Skill
136
+
137
+ This repository includes a project-local AI skill at [`.agents/skills/wow-state/SKILL.md`](.agents/skills/wow-state/SKILL.md) with schema documentation at [`.agents/skills/wow-state/references/schema.md`](.agents/skills/wow-state/references/schema.md).
138
+
139
+ ## Packaging & Extras
140
+
141
+ - **Package addon ZIP**: `sh scripts/package.sh` writes `dist/WoWState-<version>.zip` (with `WoWState*.toc`, `WoWState.lua`, and `LICENSE`) and prints its SHA-256 checksum. Also includes `.pkgmeta` and `BigWigsMods/packager` automation in [`.github/workflows/release.yml`](.github/workflows/release.yml) (set optional `CF_API_KEY`, `WAGO_API_TOKEN`, and `WOWI_API_TOKEN` repository secrets to publish to CurseForge, Wago Addons, and WoWInterface on `v*` tag pushes).
142
+ - **macOS `launchd` templates**: see [`extras/launchd/README.md`](extras/launchd/README.md) for scheduled background archiving.
143
+ - **Custom-client SavedVariables carrier**: see [`extras/sv-carrier/README.md`](extras/sv-carrier/README.md) (only needed for private/custom clients that pin addon files after first load).
144
+
145
+ ## Development & Testing
146
+
147
+ ```sh
148
+ # Run the Lua test harness under both LuaJIT (Lua 5.1) and Lua 5.4
149
+ luajit tests/lua/harness.lua
150
+ lua tests/lua/harness.lua
151
+
152
+ # Run the Python test suite
153
+ python3 -m pytest -v
154
+
155
+ # Lint shell scripts
156
+ shellcheck scripts/*.sh extras/sv-carrier/*.sh extras/launchd/*.sh
157
+ ```
158
+
159
+ ## License
160
+
161
+ MIT License — see [LICENSE](LICENSE).
@@ -0,0 +1,135 @@
1
+ # WoWState
2
+
3
+ **WoWState** (`wow-state`) is a lightweight, zero-UI World of Warcraft addon and stdlib-only Python toolkit that exports your full character state to `SavedVariables` (`WoWStateDB`) so external tools, scripts, and AI assistants can inspect and archive it outside the game.
4
+
5
+ **Downloads & Directories:** [PyPI](https://pypi.org/project/wow-state/) · [CurseForge](https://www.curseforge.com/wow/addons/wowstate) · [Wago Addons](https://addons.wago.io/addons/wowstate) · [WoWInterface](https://www.wowinterface.com/downloads/info27347-WoWState.html) · [GitHub Releases](https://github.com/briansunter/wow-state/releases/latest)
6
+
7
+ ## Features
8
+
9
+ - **Full character snapshot**: identity, `/played` time, location/coordinates/instance, item level, secondary/tertiary/ranged/resistance/weapon/movement stats, combat ratings, weapon & profession skills, spellbook, talents & Retail spec/loadouts, action bars, equipped gear (with per-slot iLvl), carried bags, bank/Reagent/Warband contents, active & completed quests, reputations, currencies, buffs/debuffs, macros, mounts/achievements, PvP stats/ratings, instance lockouts/Mythic+/Great Vault, and active pet state.
10
+ - **Self-healing & resilient**: every collector section runs inside `xpcall`; `Collect()` is `pcall`-guarded with re-entrancy protection, scheduled timers, and a 30s/180s `OnUpdate` watchdog.
11
+ - **Keep-last-good merge**: torn-down logout or early-login collects never overwrite populated character sections with empty/zeroed state, and restricted/secret client values are safely ignored.
12
+ - **Multi-flavor TOC support**: ships with a multi-flavor `## Interface:` manifest for Retail (`Mainline`), Mists of Pandaria Classic (`Mists`), Cataclysm Classic (`Cata`), TBC Classic (`TBC`), Classic Era (`Vanilla`), and custom `16001` builds.
13
+ - **Zero-dependency Python CLI & archiver**: parses WoW's Lua `SavedVariables` (including `\ddd` UTF-8 byte escapes and long strings) using only Python's standard library, with auto-discovery, `--summary`, `--section`, `--arrays`, and idempotent snapshot archiving with JSON sidecars.
14
+ - **Project-local AI skill**: includes `.agents/skills/wow-state/` so coding assistants in this repo know how to discover, query, and interpret character snapshots.
15
+
16
+ ## Installation
17
+
18
+ ### 1. Install the WoW Addon
19
+
20
+ #### Option A: Addon Manager / Directory
21
+ Install **WoWState** directly from:
22
+ - **CurseForge**: https://www.curseforge.com/wow/addons/wowstate
23
+ - **Wago Addons**: https://addons.wago.io/addons/wowstate
24
+ - **WoWInterface**: https://www.wowinterface.com/downloads/info27347-WoWState.html
25
+
26
+ #### Option B: Release ZIP (manual install)
27
+ Download `WoWState-<version>.zip` from [GitHub Releases](https://github.com/briansunter/wow-state/releases/latest) and extract the `WoWState/` folder into your `Interface/AddOns/` directory.
28
+
29
+ #### Option C: Install from source
30
+ ```sh
31
+ sh scripts/install.sh
32
+ ```
33
+
34
+ Or specify your AddOns directory explicitly:
35
+ ```sh
36
+ sh scripts/install.sh --addons "/path/to/World of Warcraft/_retail_/Interface/AddOns"
37
+ ```
38
+
39
+ ### 2. Run or Install the Python CLI
40
+
41
+ `wow-state` uses only the Python 3.10+ standard library. Run it directly with `uvx` (zero install):
42
+
43
+ ```sh
44
+ uvx wow-state
45
+ uvx wow-state --only character,stats,equipment
46
+ ```
47
+
48
+ Or install `wow-state` and `wow-state-archive` from PyPI:
49
+
50
+ ```sh
51
+ pip install wow-state
52
+ # or: uv tool install wow-state / pipx install wow-state
53
+ ```
54
+
55
+ Or run directly from a source checkout:
56
+ ```sh
57
+ PYTHONPATH=src python3 -m wow_state
58
+ ```
59
+
60
+ ## In-Game Slash Commands
61
+
62
+ - `/wowstate` or `/wstate` — refresh the character snapshot immediately (flushes to disk on `/reload` or logout)
63
+ - `/wowstate status` — print addon version, load count, collect counts, and last collect status
64
+ - `/wowstate help` — show slash command usage
65
+
66
+ ## Python CLI Usage
67
+
68
+ ### Inspect SavedVariables (`wow-state`)
69
+
70
+ ```sh
71
+ # Print a compact AI-ready JSON digest for the latest character (default)
72
+ wow-state
73
+ wow-state --only character,stats,equipment
74
+ wow-state --character "Lyra" --indent 2
75
+ wow-state --all
76
+
77
+ # Discover SavedVariables files or list characters
78
+ wow-state --discover
79
+ wow-state --list
80
+
81
+ # Print a compact human-readable summary
82
+ wow-state --summary
83
+ wow-state --summary --character "Lyra"
84
+ wow-state --summary --all
85
+
86
+ # Query a single raw section as clean JSON arrays
87
+ wow-state --section inventory
88
+ wow-state --section equipment
89
+ wow-state --section questLog
90
+
91
+ # Dump the entire raw parsed SavedVariables file as JSON
92
+ wow-state --raw path/to/SavedVariables/WoWState.lua
93
+ ```
94
+
95
+ Environment variables:
96
+ - `WOW_STATE_SV`: explicit path to `WoWState.lua`
97
+ - `WOW_DIR`: additional World of Warcraft root directory to scan during `--discover`
98
+
99
+ ### Archive Snapshot History (`wow-state-archive`)
100
+
101
+ World of Warcraft overwrites `SavedVariables/WoWState.lua` on every `/reload` or logout. Archive changed snapshots along with validated `.json` sidecars:
102
+
103
+ ```sh
104
+ wow-state-archive --dest ./history
105
+ ```
106
+
107
+ The archiver hashes only the Lua data portion (ignoring any optional bootstrap carrier), writes atomically, and skips unchanged files.
108
+
109
+ ## AI Skill
110
+
111
+ This repository includes a project-local AI skill at [`.agents/skills/wow-state/SKILL.md`](.agents/skills/wow-state/SKILL.md) with schema documentation at [`.agents/skills/wow-state/references/schema.md`](.agents/skills/wow-state/references/schema.md).
112
+
113
+ ## Packaging & Extras
114
+
115
+ - **Package addon ZIP**: `sh scripts/package.sh` writes `dist/WoWState-<version>.zip` (with `WoWState*.toc`, `WoWState.lua`, and `LICENSE`) and prints its SHA-256 checksum. Also includes `.pkgmeta` and `BigWigsMods/packager` automation in [`.github/workflows/release.yml`](.github/workflows/release.yml) (set optional `CF_API_KEY`, `WAGO_API_TOKEN`, and `WOWI_API_TOKEN` repository secrets to publish to CurseForge, Wago Addons, and WoWInterface on `v*` tag pushes).
116
+ - **macOS `launchd` templates**: see [`extras/launchd/README.md`](extras/launchd/README.md) for scheduled background archiving.
117
+ - **Custom-client SavedVariables carrier**: see [`extras/sv-carrier/README.md`](extras/sv-carrier/README.md) (only needed for private/custom clients that pin addon files after first load).
118
+
119
+ ## Development & Testing
120
+
121
+ ```sh
122
+ # Run the Lua test harness under both LuaJIT (Lua 5.1) and Lua 5.4
123
+ luajit tests/lua/harness.lua
124
+ lua tests/lua/harness.lua
125
+
126
+ # Run the Python test suite
127
+ python3 -m pytest -v
128
+
129
+ # Lint shell scripts
130
+ shellcheck scripts/*.sh extras/sv-carrier/*.sh extras/launchd/*.sh
131
+ ```
132
+
133
+ ## License
134
+
135
+ MIT License — see [LICENSE](LICENSE).
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "wow-state"
7
+ version = "1.1.0"
8
+ description = "Read, query, and archive World of Warcraft character state snapshots exported by WoWState"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [
14
+ { name = "Brian Sunter" },
15
+ ]
16
+ keywords = ["world-of-warcraft", "wow", "addon", "savedvariables", "lua", "cli", "ai", "agent"]
17
+ classifiers = [
18
+ "Development Status :: 5 - Production/Stable",
19
+ "Environment :: Console",
20
+ "Intended Audience :: End Users/Desktop",
21
+ "Intended Audience :: Developers",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Topic :: Games/Entertainment :: Role-Playing",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/briansunter/wow-state"
33
+ Repository = "https://github.com/briansunter/wow-state"
34
+ Issues = "https://github.com/briansunter/wow-state/issues"
35
+
36
+ [project.scripts]
37
+ wow-state = "wow_state.reader:main"
38
+ wow-state-archive = "wow_state.archive:main"
39
+
40
+ [tool.setuptools.packages.find]
41
+ where = ["src"]
42
+
43
+ [tool.pytest.ini_options]
44
+ pythonpath = ["src"]
45
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]
@@ -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())
@@ -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())