File size: 6,093 Bytes
d2badd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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 compute():
    svc = get(yaml_map("compose.yaml"), "services", "graph")
    assert "image" not in svc
    base = get(yaml_map(get(svc, "extends", "file")), "services", get(svc, "extends", "service"), "image")
    driver = resolve("${graph.client.version}", pom_properties("pom.xml"))
    return {"pin": image_version(base), "driver": driver}


TEMPLATE = json.loads(r'''
{
    "graph_present": true,
    "profiles": [
        {
            "engine": [
                "neo4j"
            ],
            "engine_version": "@pin@",
            "query_language": {
                "any_of": [
                    "cypher"
                ]
            },
            "driver": {
                "package": [
                    "neo4j-java-driver"
                ],
                "version": "@driver@"
            },
            "run_queries": {
                "accept": [
                    "bin/cypher",
                    "RunQuery",
                    "exec:java"
                ]
            }
        }
    ],
    "access": "read-only",
    "conflicts": [
        {
            "id": "version-conflict-surfaced",
            "text": "the reader is told that README.md and docs/architecture.md say Neo4j 2025.10 / 2025.10.1 while the image compose.yaml extends from compose.base.yaml is @pin@",
            "stale": [
                "(?<![\\d.])2025\\.10(?:\\.1)?(?![\\d.]*\\d)"
            ],
            "kept": [
                "@pin:re@"
            ],
            "sources": [
                "README",
                "architecture.md"
            ]
        }
    ],
    "texts": {
        "engine-version-pinned": "engine_version is @pin@: compose.yaml's graph service extends the neo4j service of compose.base.yaml, whose image is neo4j:@pin@-enterprise; the 2025.10 / 2025.10.1 in README.md and docs/architecture.md is prose"
    }
}
''')


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}))