okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-clean-step0' into f-clean-1abe32c7f3f

main
2.6 KiB63 linesraw
1"""Normalization: the golden files must be byte-identical on Windows, Linux and macOS and on every developer's machine.
2
3Done here: the scratch folder, the repository folder and the home folder become <ROOT>, <REPO>, <HOME>; every backslash in a path becomes a slash; the engine
4stub's executable suffix is dropped; random API keys, run ids and times become fixed words.  Nothing else is touched, so a real difference stays visible.
5"""
6
7from __future__ import annotations
8
9import re
10from pathlib import Path
11
12KEY = re.compile(r"\b(sk-[A-Za-z0-9_-]{8,}|strata-[A-Za-z0-9]{24,})\b")
13
14
15def _roots(world) -> list[tuple[str, str]]:
16    from .world import ROOT
17    pairs = []
18    for path, word in ((world.root, "<ROOT>"), (ROOT, "<REPO>")):
19        for form in {str(path), path.as_posix(), str(path).replace("\\", "/")}:
20            pairs.append((form, word))
21    pairs.sort(key=lambda p: -len(p[0]))                 # the longest first: <ROOT> sits inside no other, but be safe
22    return pairs
23
24
25def normalize(value, world):
26    pairs = _roots(world)
27
28    def text(s: str) -> str:
29        for form, word in pairs:
30            s = s.replace(form, word)
31            s = s.replace(form.replace("/", "\\"), word)
32        if "<" in s or "\\" in s:
33            s = re.sub(r"(<ROOT>|<REPO>)([^\s\"',;]*)", lambda m: m.group(1) + m.group(2).replace("\\", "/"), s)
34        s = re.sub(r"<ROOT>/(local/Strata|state/strata)/", "<ROOT>/<STATE>/", s)   # the per-user state folder is named by the host OS
35        s = KEY.sub("<KEY>", s)
36        s = re.sub(r"/strata-engine\.exe\b", "/strata-engine", s)
37        return s
38
39    def walk(v, key=None):
40        if isinstance(v, dict):
41            out = {}
42            for k, x in v.items():
43                if k in ("api_key",) and x:
44                    out[k] = "<KEY>"
45                elif k in ("created", "updated", "at", "stamp", "saved_at", "written_at", "ts", "time") and isinstance(x, (int, float)):
46                    out[k] = "<TIME>"
47                else:
48                    out[k] = walk(x, k)
49            return out
50        if isinstance(v, list):
51            return [walk(x) for x in v]
52        if isinstance(v, str):
53            return text(v)
54        return v
55
56    out = walk(value)
57    # the run config carries the argument list three times (args, and the stamps of what the launch derived and wrote); an identical copy is written as "=args"
58    cfg = out.get("config_file") if isinstance(out, dict) else None
59    if isinstance(cfg, dict):
60        for k in ("args_derived", "args_written"):
61            if k in cfg and cfg[k] == cfg.get("args"):
62                cfg[k] = "=args"
63    return out