Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 133 additions & 10 deletions pkgs/opencode-config-normalize/normalize.sh
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,146 @@ import json, re, sys, pathlib
path = pathlib.Path(sys.argv[1])
raw = path.read_text()

# Cheap JSONC -> JSON for the membership test only; we never write this back.
probe = re.sub(r'^\s*//.*$', '', raw, flags=re.M)
probe = re.sub(r',(\s*[}\]])', r'\1', probe)

def jsonc_to_json(text):
# String-aware JSONC -> JSON (#3179): strip // line comments and
# /* */ block comments plus trailing commas, but never touch the
# contents of string literals — "//", "/*", ",}" and ",]" inside a
# string value are data, not comments or trailing commas. Used for
# the membership probe and the pre-write verification only; the
# repaired output is still spliced from the original text, so
# comments in the user's file are preserved.
out = []
i, n = 0, len(text)
in_str = False
while i < n:
c = text[i]
if in_str:
out.append(c)
if c == '\\' and i + 1 < n:
out.append(text[i + 1])
i += 2
continue
if c == '"':
in_str = False
i += 1
continue
if c == '"':
in_str = True
out.append(c)
i += 1
continue
if c == '/' and text[i + 1:i + 2] == '/':
while i < n and text[i] != '\n':
i += 1
continue
if c == '/' and text[i + 1:i + 2] == '*':
end = text.find('*/', i + 2)
if end < 0:
raise ValueError('unterminated block comment')
i = end + 2
out.append(' ')
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
continue
out.append(c)
i += 1
s = ''.join(out)
out = []
i, n = 0, len(s)
in_str = False
while i < n:
c = s[i]
if in_str:
out.append(c)
if c == '\\' and i + 1 < n:
out.append(s[i + 1])
i += 2
continue
if c == '"':
in_str = False
i += 1
continue
if c == '"':
in_str = True
out.append(c)
i += 1
continue
if c == ',':
j = i + 1
while j < n and s[j] in ' \t\r\n':
j += 1
if j < n and s[j] in '}]':
i += 1
continue # trailing comma: drop it
out.append(c)
i += 1
return ''.join(out)

# JSONC -> JSON for the membership test only; we never write this back.
try:
doc = json.loads(probe)
doc = json.loads(jsonc_to_json(raw))
except Exception:
sys.exit(0) # unparseable: leave it alone rather than risk mangling it

changed = False
out = raw

# plugins -> plugin
def find_top_level_key(text, key):
# Index of the opening quote of the live top-level "key": token in
# text, skipping string contents and // /* */ comments (PR #4312
# review): a "key": lookalike inside a comment or a nested object
# must never be selected for a splice. Returns -1 when absent.
i, n = 0, len(text)
depth = 0
in_str = False
str_start = -1
while i < n:
c = text[i]
if in_str:
if c == '\\' and i + 1 < n:
i += 2
continue
if c == '"':
in_str = False
if depth == 1 and text[str_start + 1:i] == key:
j = i + 1
while j < n and text[j] in ' \t\r\n':
j += 1
if j < n and text[j] == ':':
return str_start
i += 1
continue
if c == '"':
in_str = True
str_start = i
i += 1
continue
if c == '/' and text[i + 1:i + 2] == '/':
while i < n and text[i] != '\n':
i += 1
continue
if c == '/' and text[i + 1:i + 2] == '*':
end = text.find('*/', i + 2)
if end < 0:
return -1
i = end + 2
continue
if c in '{[':
depth += 1
elif c in '}]':
depth -= 1
i += 1
return -1


# plugins -> plugin: rename the live top-level key only. A raw-text
# search can hit "plugins": inside an earlier comment and leave the
# live key unrepaired (PR #4312 review).
if 'plugins' in doc and 'plugin' not in doc:
out, n = re.subn(r'"plugins"(\s*):', r'"plugin"\1:', out, count=1)
changed = changed or bool(n)
at = find_top_level_key(out, 'plugins')
if at < 0:
sys.exit(1) # live key not locatable: leave the file untouched
out = out[:at] + '"plugin"' + out[at + len('"plugins"'):]
changed = True

# agents -> agent: fold the v2 `agents` map into `agent` (existing `agent`
# wins per key). The `agents` block is dropped only once the merged map has
Expand Down Expand Up @@ -105,10 +230,8 @@ if not changed:
# parsed document differs from the intended one. The intended document is
# `doc` with the renames/folds above applied; comparing the whole document
# is what proves no `agents` entry was dropped on the floor (#2364).
verify = re.sub(r'^\s*//.*$', '', out, flags=re.M)
verify = re.sub(r',(\s*[}\]])', r'\1', verify)
try:
parsed = json.loads(verify)
parsed = json.loads(jsonc_to_json(out))
except Exception:
sys.exit(1)

Expand Down
116 changes: 113 additions & 3 deletions pkgs/opencode-config-normalize/normalize_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,54 @@ parsed_doc() {
python3 - "$1" <<'PY'
import json, re, sys, pathlib
raw = pathlib.Path(sys.argv[1]).read_text()
probe = re.sub(r'^\s*//.*$', '', raw, flags=re.M)
probe = re.sub(r',(\s*[}\]])', r'\1', probe)
print(json.dumps(json.loads(probe), sort_keys=True))
# String-aware JSONC strip (mirrors normalize.sh jsonc_to_json, #3179):
# comments and trailing commas are removed only outside string literals.
out = []
i, n = 0, len(raw)
in_str = False
while i < n:
c = raw[i]
if in_str:
out.append(c)
if c == '\\' and i + 1 < n:
out.append(raw[i + 1]); i += 2; continue
if c == '"':
in_str = False
i += 1; continue
if c == '"':
in_str = True; out.append(c); i += 1; continue
if c == '/' and raw[i + 1:i + 2] == '/':
while i < n and raw[i] != '\n':
i += 1
continue
if c == '/' and raw[i + 1:i + 2] == '*':
end = raw.find('*/', i + 2)
i = n if end < 0 else end + 2
out.append(' '); continue
out.append(c); i += 1
s = ''.join(out)
out = []
i, n = 0, len(s)
in_str = False
while i < n:
c = s[i]
if in_str:
out.append(c)
if c == '\\' and i + 1 < n:
out.append(s[i + 1]); i += 2; continue
if c == '"':
in_str = False
i += 1; continue
if c == '"':
in_str = True; out.append(c); i += 1; continue
if c == ',':
j = i + 1
while j < n and s[j] in ' \t\r\n':
j += 1
if j < n and s[j] in '}]':
i += 1; continue
out.append(c); i += 1
print(json.dumps(json.loads(''.join(out)), sort_keys=True))
PY
}

Expand Down Expand Up @@ -148,6 +193,71 @@ cat > "$tmp/unrecognised.fixture" <<'EOF'
EOF
check unrecognised "$tmp/unrecognised.fixture" '' 1


# Case 7: inline // comments (#3179) — the old probe stripper removed
# only full-line comments, so this file failed to parse and every
# repair was silently skipped. Must repair exactly like its
# comment-free twin.
cat > "$tmp/inline-comments.fixture" <<'EOF'
{
"$schema": "https://opencode.ai/config.json", // schema URL
"plugins": ["opencode-plugin-x"], // v2 spelling, must rename
"model": "anthropic/claude-sonnet-4-5" // trailing note
}
EOF
check inline-comments "$tmp/inline-comments.fixture" \
'{"$schema":"https://opencode.ai/config.json","model":"anthropic/claude-sonnet-4-5","plugin":["opencode-plugin-x"]}' 0

# Case 8: /* */ block comments (#3179), standalone and inline.
cat > "$tmp/block-comments.fixture" <<'EOF'
{
/* written by OpenChamber 2.x */
"plugins": ["opencode-plugin-x", /* inline block */ "opencode-plugin-y"]
}
EOF
check block-comments "$tmp/block-comments.fixture" \
'{"plugin":["opencode-plugin-x","opencode-plugin-y"]}' 0

# Case 9: string lookalikes (#3179) — comment markers and ,} / ,]
# sequences inside string values are data and must survive verbatim,
# while a real trailing comma is still tolerated.
cat > "$tmp/string-lookalikes.fixture" <<'EOF'
{
"$schema": "https://opencode.ai/config.json",
"plugins": ["opencode-plugin-x"],
"note": "docs at https://example.com/a//b, markers /* not a comment */ and ,} ,] stay",
"list": [1, 2,]
}
EOF
check string-lookalikes "$tmp/string-lookalikes.fixture" \
'{"$schema":"https://opencode.ai/config.json","list":[1,2],"note":"docs at https://example.com/a//b, markers /* not a comment */ and ,} ,] stay","plugin":["opencode-plugin-x"]}' 0

# Case 10: unterminated block comment (PR #4312 review) — the stripper
# used to drop everything after the open /* and then repair and write
# the file anyway, leaving a still-invalid config behind. An
# unterminated comment is unparseable: leave the file byte-identical.
cat > "$tmp/unterminated-comment.fixture" <<'EOF'
{
"plugins": ["opencode-plugin-x"]
}
/* trailing note that never closes
EOF
check unterminated-comment "$tmp/unterminated-comment.fixture" '__UNPARSEABLE__' 0

# Case 11: "plugins": inside comments before the live key (PR #4312
# review) — the raw-text rename used to select the comment text first,
# leaving the live key unrepaired and the run failed. The live key is
# the one renamed; comments are preserved.
cat > "$tmp/comment-plugins-key.fixture" <<'EOF'
{
/* v2 spelling was "plugins": ["old"] — comment, do not touch */
// likewise "plugins": in a line comment is not a key
"plugins": ["opencode-plugin-x"]
}
EOF
check comment-plugins-key "$tmp/comment-plugins-key.fixture" \
'{"plugin":["opencode-plugin-x"]}' 0

if [ "$failures" -ne 0 ]; then
echo "normalize_test: $failures failure(s)"
exit 1
Expand Down