File size: 7,447 Bytes
013f624
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#!/usr/bin/env python3
"""Computes this case's gold.json from the fixture in files/ (the gold is derived, not typed in).
`python3 gold.py` rewrites gold.json; `python3 gold.py --check` only compares."""
import json
import re
import sqlite3
import subprocess
import sys
import tempfile
from pathlib import Path

sys.dont_write_bytecode = True
CASE = Path(__file__).resolve().parent
FILES = CASE / "files"


def text(rel):
    return (FILES / rel).read_text(encoding="utf-8")


def strip_comment(line):
    out, quote = [], None
    for ch in line:
        if quote:
            if ch == quote:
                quote = None
        elif ch in "\"'":
            quote = ch
        elif ch == "#":
            break
        out.append(ch)
    return "".join(out).rstrip()


def yaml_map(rel):
    """Nested mappings of a simple YAML file (lists are skipped). Enough for compose and values files."""
    root, stack = {}, [(-1, None)]
    stack[0] = (-1, root)
    for raw in text(rel).splitlines():
        line = strip_comment(raw)
        if not line.strip() or line.strip().startswith("-") or line.strip() == "---":
            continue
        indent = len(line) - len(line.lstrip())
        key, _, value = line.strip().partition(":")
        while stack and stack[-1][0] >= indent:
            stack.pop()
        parent = stack[-1][1]
        if not isinstance(parent, dict):
            continue
        value = value.strip().strip("\"'")
        if value:
            parent[key.strip().strip("\"'")] = value
        else:
            child = {}
            parent[key.strip().strip("\"'")] = child
            stack.append((indent, child))
    return root


def get(mapping, *keys):
    for key in keys:
        if not isinstance(mapping, dict) or key not in mapping:
            return None
        mapping = mapping[key]
    return mapping


def dotenv(rel):
    env = {}
    for raw in text(rel).splitlines():
        line = raw.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, _, value = line.partition("=")
        env[key.strip()] = value.strip().strip("\"'")
    return env


def interpolate(value, env):
    def sub(match):
        name, default = match.group(1), match.group(3)
        if env.get(name):
            return env[name]
        return default if default is not None else ""
    return re.sub(r"\$\{(\w+)(:-([^}]*))?\}", sub, value)


def version_in(value):
    match = re.search(r"(?<![\w.])v?(\d+(?:\.\d+)+)", value or "")
    if not match:
        raise SystemExit(f"no version in {value!r}")
    return match.group(1)


def image_version(ref):
    return version_in(ref.split(":", 1)[1])


def pom_properties(rel):
    body = re.search(r"<properties>(.*?)</properties>", text(rel), re.S)
    return dict(re.findall(r"<([\w.-]+)>([^<]*)</\1>", body.group(1))) if body else {}


def resolve(value, props):
    return re.sub(r"\$\{([\w.-]+)\}", lambda m: props[m.group(1)], value)


def gradle_lock(rel, coordinate):
    for line in text(rel).splitlines():
        if line.startswith(coordinate + ":"):
            return line[len(coordinate) + 1:].split("=")[0]
    raise SystemExit(f"{coordinate} not locked in {rel}")


def go_require(rel, module):
    match = re.search(re.escape(module) + r"\s+v(\d+(?:\.\d+)+)", text(rel))
    return match.group(1)


def fill(obj, values):
    if isinstance(obj, dict):
        return {k: fill(v, values) for k, v in obj.items()}
    if isinstance(obj, list):
        return [fill(v, values) for v in obj]
    if isinstance(obj, str):
        for key, value in values.items():
            obj = obj.replace("@" + key + "@", str(value))
            obj = obj.replace("@" + key + ":re@", re.escape(str(value)))
        return obj
    return obj


def vkey(version):
    return tuple(int(x) for x in re.findall(r"\d+", version))


def cargo_lock(rel, name):
    for block in text(rel).split("[[package]]")[1:]:
        found = re.search(r'^name = "([^"]+)"\s*\nversion = "([^"]+)"', block.strip(), re.M)
        if found and found.group(1) == name:
            return found.group(2)
    raise SystemExit(f"{name} not in {rel}")


def nuget_lock(rel, package):
    for deps in json.loads(text(rel))["dependencies"].values():
        if package in deps:
            return deps[package]["resolved"]
    raise SystemExit(f"{package} not in {rel}")


def xml_props(rel):
    return dict(re.findall(r"<([\w.-]+)>([^<]*)</\1>", text(rel)))


def dependency_version(rel, artifact):
    found = re.search(r"<artifactId>" + re.escape(artifact) + r"</artifactId>\s*<version>([^<]+)</version>",
                      text(rel))
    return found.group(1) if found else None


def build_db(setup_rel="setup.py"):
    """Runs the case's setup.py into a fresh copy of files/ and returns the copy's path."""
    tmp = Path(tempfile.mkdtemp())
    import shutil
    shutil.copytree(FILES, tmp, dirs_exist_ok=True)
    subprocess.run([sys.executable, str(CASE / setup_rel), str(tmp)], check=True, capture_output=True, timeout=120)
    return tmp


def compute():
    proj = "src/ChargeMap.Query/"
    assert "<RestorePackagesWithLockFile>true" in text(proj + "ChargeMap.Query.csproj")
    driver = nuget_lock(proj + "packages.lock.json", "Neo4j.Driver")
    readme = re.search(r"Neo4j\.Driver (\d+\.\d+\.\d+)", text("README.md")).group(1)
    assert readme != driver
    image = get(yaml_map("compose.yaml"), "services", "graph", "image")
    secret = dotenv(".env")["NEO4J_AUTH"].split("/", 1)[1]
    return {"pin": image_version(image), "driver": driver, "readme": readme, "secret": secret}


TEMPLATE = json.loads(r'''
{
    "graph_present": true,
    "profiles": [
        {
            "engine": [
                "neo4j"
            ],
            "engine_version": "@pin@",
            "query_language": {
                "any_of": [
                    "cypher"
                ]
            },
            "driver": {
                "package": [
                    "Neo4j.Driver"
                ],
                "version": "@driver@"
            },
            "run_queries": {
                "accept": [
                    "\\bmake\\b.*\\bq\\b",
                    "dotnet\\s+run\\b.*ChargeMap\\.Query"
                ]
            }
        }
    ],
    "access": "read-only",
    "secrets": [
        "@secret@"
    ],
    "conflicts": [
        {
            "id": "version-conflict-surfaced",
            "text": "the reader is told that README.md says Neo4j.Driver @readme@ while packages.lock.json resolves @driver@",
            "stale": [
                "(?<![\\d.])5\\.21(?:\\.0)?(?![\\d.]*\\d)"
            ],
            "kept": [
                "@driver:re@"
            ],
            "sources": [
                "README"
            ]
        }
    ],
    "texts": {
        "driver-from-lockfile": "driver is Neo4j.Driver @driver@, resolved in src/ChargeMap.Query/packages.lock.json (the csproj floats 5.*; README.md says @readme@)"
    }
}
''')


if __name__ == "__main__":
    values = compute()
    gold = fill(TEMPLATE, values)
    rendered = json.dumps(gold, indent=2) + "\n"
    if "--check" in sys.argv:
        same = (CASE / "gold.json").read_text(encoding="utf-8") == rendered
        print(json.dumps({"computed": values, "gold_json_matches": same}))
        sys.exit(0 if same else 1)
    (CASE / "gold.json").write_text(rendered, encoding="utf-8")
    print(json.dumps({"computed": values}))