Skip to content

Commit 1179388

Browse files
zaventhclaude
andcommitted
feat: add JSON, JSONC, and TOML 1.0 syntax checks
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 8ebde19 commit 1179388

4 files changed

Lines changed: 249 additions & 12 deletions

File tree

‎Dockerfile‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ RUN \
2929
apk add --no-cache bash build-base ruby ruby-dev git \
3030
lua5.3-dev luarocks5.3 \
3131
&& gem install --no-document etc mdl:0.18.1 \
32-
&& pip install --no-cache-dir yamllint==1.38.0 check-jsonschema==0.38.0 ruff==0.16.10 \
32+
&& pip install --no-cache-dir yamllint==1.38.0 check-jsonschema==0.38.0 ruff==0.16.10 tomli==2.3.1 \
3333
&& luarocks-5.3 install luacheck 1.2.0-1 \
3434
&& git config --global --add safe.directory /code \
3535
# smoke tests
@@ -42,6 +42,7 @@ RUN \
4242
&& actionlint -version \
4343
&& editorconfig-checker -version \
4444
&& ruff --version \
45+
&& python3 /usr/local/lib/lintorama/check_syntax.py toml /etc/lintorama/ruff/ruff.toml \
4546
# parse the bundled Ruff defaults (no project config at /, so Ruff falls back to them)
4647
&& XDG_CONFIG_HOME=/etc/lintorama ruff check --no-cache - </dev/null
4748

‎README.md‎

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,13 @@ and validators — [yamllint](https://github.com/adrienverge/yamllint),
2626
[editorconfig-checker](https://github.com/editorconfig-checker/editorconfig-checker)
2727
— behind one entrypoint, `lint-extras`. Point it at a Git repository and it runs
2828
the right check over every tracked YAML, shell, Lua, Dockerfile, Markdown, and
29-
GitHub Actions workflow file, lints the Python in supporting-script directories
30-
(`scripts/`, `build/`, `.claude/hooks/`), schema-validates common config files
31-
(CI pipelines, Docker Compose, GitHub issue forms and actions, Dependabot,
32-
Renovate, and more), and — when an `.editorconfig` is present — verifies every
33-
tracked file against it, then exits non-zero if any check fails. Dependency
34-
directories such as `node_modules/` and `vendor/` are never linted. It is built for CI pipelines: no per-project linter
29+
GitHub Actions workflow file, syntax-checks JSON, JSONC, and TOML, lints the
30+
Python in supporting-script directories (`scripts/`, `build/`, `.claude/hooks/`),
31+
schema-validates common config files (CI pipelines, Docker Compose, GitHub issue
32+
forms and actions, Dependabot, Renovate, and more), and — when an
33+
`.editorconfig` is present — verifies every tracked file against it, then exits
34+
non-zero if any check fails. Dependency directories such as `node_modules/` and
35+
`vendor/` are never linted. It is built for CI pipelines: no per-project linter
3536
installs, no juggling tool versions, no bespoke setup — just `docker run`.
3637

3738
In short: **one container image for polyglot static analysis and code-quality
@@ -53,8 +54,8 @@ checks in continuous integration.**
5354

5455
## Highlights
5556

56-
- **Nine checks, one image.** YAML, shell, Dockerfiles, Markdown, Lua, Python
57-
scripts, GitHub Actions workflows, schema-backed config files, and
57+
- **Nine linters, one image.** YAML, JSON, TOML, shell, Dockerfiles, Markdown,
58+
Lua, Python scripts, GitHub Actions workflows, schema-backed config files, and
5859
`.editorconfig` conformance are all covered by a single pull.
5960
- **Zero setup to start.** Sensible defaults work out of the box; every linter
6061
still honors its own config file when you want to tune it.
@@ -79,6 +80,7 @@ checks in continuous integration.**
7980
| [actionlint](https://github.com/rhysd/actionlint) | 1.7.12 | GitHub Actions workflows (`.github/workflows/*.yml`) |
8081
| [check-jsonschema](https://github.com/python-jsonschema/check-jsonschema) | 0.38.0 | Schema validation: CI pipelines, Docker Compose, GitHub issue forms and actions, Dependabot, Renovate, and [more](#schema-validated-files) |
8182
| [editorconfig-checker](https://github.com/editorconfig-checker/editorconfig-checker) | 4.0.1 | `.editorconfig` conformance (all tracked files) |
83+
| Built-in syntax check, using [tomli](https://github.com/hukkin/tomli) for TOML | 2.3.1 | [JSON, JSONC, and TOML](#json-and-toml) (`*.json`, `*.jsonc`, `*.toml`, `Pipfile`) |
8284

8385
Built on `python:3-alpine3.24`.
8486

@@ -176,6 +178,7 @@ repository. In order, it:
176178

177179
1. Runs `yamllint -s` (strict) over all tracked `*.yml` / `*.yaml` files, except generated lockfiles (`pnpm-lock.yaml`, `conda-lock.yml`).
178180
1. Schema-validates well-known config files against their published schemas with `check-jsonschema`, when present. See [Schema-validated files](#schema-validated-files).
181+
1. Syntax-checks all tracked JSON, JSONC, and TOML files, except generated lockfiles (`package-lock.json`, `npm-shrinkwrap.json`). See [JSON and TOML](#json-and-toml).
179182
1. Runs `actionlint` over all tracked `.github/workflows/*.yml` / `*.yaml` files (delegating embedded `run:` scripts to the bundled ShellCheck).
180183
1. If a `package.json` exists, requires a lockfile to accompany it: `package-lock.json`, `npm-shrinkwrap.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock`, or `bun.lockb`.
181184
1. Runs `shellcheck` over all tracked `*.sh` / `*.bash` files, plus extensionless files whose shebang names `sh`, `bash`, `dash`, or `ksh` (directly or through `env`), such as Git hooks. The generated `gradlew` and `mvnw` wrappers are skipped.
@@ -234,6 +237,34 @@ pre-commit hooks.
234237
Each `.yml` or `.yaml` name in the table matches both spellings, except Meltano
235238
and Mergify (`.yml` only) and Snapcraft (`.yaml` only).
236239

240+
### JSON and TOML
241+
242+
JSON files (`*.json`) must be strict [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259)
243+
JSON: no comments, trailing commas, `NaN` or `Infinity`, duplicate keys, or byte
244+
order mark. JSONC files may also use `//` and `/* */` comments, trailing commas,
245+
and a byte order mark, as TypeScript and VS Code allow. These files count as
246+
JSONC, at any depth, because the tools that read them accept comments:
247+
248+
- `*.jsonc`, `*.code-workspace`, `*.code-snippets`, and `.vscode/*.json`
249+
- `devcontainer.json` and `.devcontainer.json`
250+
- `tsconfig*.json` and `jsconfig*.json`, such as `tsconfig.build.json`
251+
- `deno.json`, `biome.json`, `turbo.json`, `wrangler.json`, and `typedoc.json`
252+
- `.eslintrc.json`, `.oxlintrc.json`, `.babelrc.json`, `babel.config.json`,
253+
`.markdownlint.json`, `cspell.json`, and `.cspell.json`
254+
- `appsettings*.json` (.NET)
255+
256+
A strict JSON file that would parse as JSONC gets a hint saying so.
257+
258+
TOML files (`*.toml` and Pipenv's `Pipfile`) must be valid
259+
[TOML 1.0](https://toml.io/en/v1.0.0), checked with
260+
[tomli](https://github.com/hukkin/tomli), which also rejects duplicate keys and
261+
tables. TOML 1.1 additions, such as trailing commas and line breaks in inline
262+
tables, are rejected: Python's `tomllib` (which reads `pyproject.toml`) and
263+
Gradle (which reads `libs.versions.toml`) only understand 1.0, and every 1.1
264+
reader accepts 1.0.
265+
266+
Each problem is reported as `path:line:column: message`.
267+
237268
## Options
238269

239270
`lint-extras` takes these command-line options:
@@ -301,7 +332,7 @@ Published to Docker Hub as
301332
| Tag | Meaning |
302333
| --- | --- |
303334
| `9.0.0` | Exact, immutable version |
304-
| `8` | Rolling major tag (recommended for most pipelines) |
335+
| `9` | Rolling major tag (recommended for most pipelines) |
305336
| `latest` | The most recent build |
306337

307338
Each tag is a multi-arch image for `linux/amd64` and `linux/arm64`; Docker picks
@@ -313,14 +344,15 @@ the right one for the host automatically.
313344
lintorama is a Docker image that bundles yamllint, ShellCheck, hadolint,
314345
markdownlint (mdl), luacheck, Ruff, actionlint, check-jsonschema, and
315346
editorconfig-checker behind a single command, `lint-extras`, for linting a Git
316-
repository in CI pipelines.
347+
repository in CI pipelines. It also syntax-checks JSON, JSONC, and TOML.
317348

318349
**Which linters does lintorama include?**
319350
Nine: yamllint (YAML), ShellCheck (shell scripts), hadolint (Dockerfiles),
320351
markdownlint / mdl (Markdown), luacheck (Lua), Ruff (Python scripts),
321352
actionlint (GitHub Actions workflows), check-jsonschema (schema validation for
322353
CI and tooling config), and editorconfig-checker (`.editorconfig` conformance).
323-
See [Bundled linters](#bundled-linters) for exact versions.
354+
A built-in check covers JSON, JSONC, and TOML syntax. See
355+
[Bundled linters](#bundled-linters) for exact versions.
324356

325357
**How do I run lintorama locally?**
326358
Run the [Quick start](#quick-start) command from the root of any Git repository

‎files/usr/local/bin/lint-extras‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,35 @@ schema_check vendor.taskfile -- \
164164
'Taskfile.yml' 'Taskfile.yaml' 'taskfile.yml' 'taskfile.yaml' \
165165
'Taskfile.dist.yml' 'Taskfile.dist.yaml' 'taskfile.dist.yml' 'taskfile.dist.yaml'
166166

167+
# syntax-check JSON, except generated lockfiles. JSON is held to RFC 8259 (no
168+
# comments, trailing commas, or duplicate keys) unless it's JSONC: *.jsonc, plus
169+
# the config files whose tools accept comments and trailing commas.
170+
check_syntax=/usr/local/lib/lintorama/check_syntax.py
171+
json_files=()
172+
jsonc_files=()
173+
while IFS= read -r f; do
174+
case "/$f" in
175+
*.jsonc|*.code-workspace|*.code-snippets|*/.vscode/*.json|*/devcontainer.json|*/.devcontainer.json|\
176+
*/tsconfig*.json|*/jsconfig*.json|*/deno.json|*/biome.json|*/turbo.json|*/wrangler.json|*/typedoc.json|\
177+
*/.eslintrc.json|*/.oxlintrc.json|*/.babelrc.json|*/babel.config.json|*/.markdownlint.json|\
178+
*/cspell.json|*/.cspell.json|*/appsettings*.json)
179+
jsonc_files+=("$f") ;;
180+
*) json_files+=("$f") ;;
181+
esac
182+
done < <(list_files '*.json' '*.jsonc' '*.code-workspace' '*.code-snippets' ':!:.agents/skills/*' \
183+
':(exclude,glob)**/package-lock.json' ':(exclude,glob)**/npm-shrinkwrap.json')
184+
[ ${#json_files[@]} -eq 0 ] || python3 "$check_syntax" json "${json_files[@]}"
185+
RESULT+=$?
186+
[ ${#jsonc_files[@]} -eq 0 ] || python3 "$check_syntax" jsonc "${jsonc_files[@]}"
187+
RESULT+=$?
188+
189+
# syntax-check TOML, including Pipenv's Pipfile. tomli is pinned to its v1.0 line:
190+
# Python's tomllib (pyproject.toml) and Gradle (libs.versions.toml) can't read
191+
# v1.1 additions such as trailing commas in inline tables.
192+
mapfile -t files < <(list_files '*.toml' ':(glob)**/Pipfile' ':!:.agents/skills/*')
193+
[ ${#files[@]} -eq 0 ] || python3 "$check_syntax" toml "${files[@]}"
194+
RESULT+=$?
195+
167196
# lint GitHub Actions workflows (run: steps are delegated to the bundled shellcheck)
168197
mapfile -t files < <(list_files '.github/workflows/*.yml' '.github/workflows/*.yaml')
169198
[ ${#files[@]} -eq 0 ] || actionlint "${files[@]}"
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
"""Syntax-check JSON, JSONC, and TOML files for lint-extras.
2+
3+
Usage: check_syntax.py {json,jsonc,toml} FILE...
4+
5+
Prints one `path:line:column: message` line per problem and exits 1 if any file
6+
fails. JSON is held to RFC 8259: no comments, trailing commas, NaN or Infinity,
7+
duplicate keys, or byte order mark. JSONC also allows // and /* */ comments,
8+
trailing commas, and a byte order mark, as TypeScript and VS Code do. TOML is
9+
held to v1.0, since Python's tomllib and Gradle can't read v1.1 additions.
10+
"""
11+
12+
import json
13+
import re
14+
import sys
15+
16+
import tomli
17+
18+
BOM = "\ufeff"
19+
20+
# A // or /* */ comment. The quantifiers can't backtrack, so a comment never ends
21+
# early at a "]" or reaches past its own "*/".
22+
COMMENT = r"//[^\n]*+|/\*[^*]*\*+(?:[^/*][^*]*\*+)*/"
23+
24+
# What has to be blanked out of JSONC to leave JSON. Strings are matched only so
25+
# that comment markers and commas inside them are left alone.
26+
JSONC_TOKEN = re.compile(
27+
rf"""
28+
(?P<string> "(?:[^"\\\n]|\\.)*" )
29+
| (?P<comment> {COMMENT} )
30+
| (?P<unclosed> /\* )
31+
| (?P<comma> ,(?=(?:\s|{COMMENT})*[\]}}]) )
32+
""",
33+
re.DOTALL | re.VERBOSE,
34+
)
35+
36+
# Strings, structural characters, and the non-standard constants Python accepts.
37+
JSON_TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|[{}\[\],]|-?Infinity|NaN')
38+
39+
40+
class SyntaxProblem(Exception):
41+
def __init__(self, pos, message):
42+
super().__init__(message)
43+
self.pos = pos
44+
self.message = message
45+
46+
47+
def location(text, pos):
48+
line = text.count("\n", 0, pos) + 1
49+
return line, pos - text.rfind("\n", 0, pos)
50+
51+
52+
def blank(match):
53+
return re.sub(r"[^\n]", " ", match.group())
54+
55+
56+
def strip_jsonc(text):
57+
"""Blank out comments and trailing commas, keeping every line and column."""
58+
59+
def replace(m):
60+
if m.group("unclosed"):
61+
raise SyntaxProblem(m.start(), "unterminated /* comment")
62+
return m.group() if m.group("string") else blank(m)
63+
64+
return JSONC_TOKEN.sub(replace, text)
65+
66+
67+
def suspects(text):
68+
"""Yield (pos, message) for duplicate keys and NaN/Infinity in parsed JSON."""
69+
stack = [] # one set of seen keys per open object, None per open array
70+
expect_key = False
71+
for m in JSON_TOKEN.finditer(text):
72+
tok = m.group()
73+
if tok[0] == '"':
74+
if expect_key:
75+
key = json.loads(tok)
76+
if key in stack[-1]:
77+
yield m.start(), f"duplicate key {tok}"
78+
stack[-1].add(key)
79+
expect_key = False
80+
elif tok == "{":
81+
stack.append(set())
82+
expect_key = True
83+
elif tok == "[":
84+
stack.append(None)
85+
elif tok in "}]":
86+
stack.pop()
87+
expect_key = False
88+
elif tok == ",":
89+
expect_key = stack[-1] is not None
90+
else:
91+
yield m.start(), f"{tok} is not valid JSON"
92+
93+
94+
def check_json(text, jsonc):
95+
if text.startswith(BOM):
96+
if not jsonc:
97+
yield 0, "byte order mark at start of file (not allowed in JSON)"
98+
text = " " + text[1:]
99+
if jsonc:
100+
text = strip_jsonc(text)
101+
102+
# Python's parser keeps the last of duplicate keys and accepts NaN and
103+
# Infinity, so note them here and locate them with a rescan.
104+
suspect = False
105+
106+
def object_pairs(pairs):
107+
nonlocal suspect
108+
suspect = suspect or len({key for key, _ in pairs}) != len(pairs)
109+
return pairs
110+
111+
def constant(name):
112+
nonlocal suspect
113+
suspect = True
114+
115+
try:
116+
json.loads(text, object_pairs_hook=object_pairs, parse_constant=constant)
117+
except json.JSONDecodeError as e:
118+
hint = ""
119+
if not jsonc:
120+
try:
121+
json.loads(strip_jsonc(text))
122+
hint = " (comments and trailing commas are allowed only in JSONC files)"
123+
except (ValueError, SyntaxProblem):
124+
pass
125+
yield e.pos, f"invalid {'JSONC' if jsonc else 'JSON'}: {e.msg}{hint}"
126+
return
127+
if suspect:
128+
yield from suspects(text)
129+
130+
131+
def check_toml(text):
132+
if text.startswith(BOM):
133+
yield 0, "byte order mark at start of file (not allowed in TOML)"
134+
text = " " + text[1:]
135+
try:
136+
tomli.loads(text)
137+
except tomli.TOMLDecodeError as e:
138+
yield e.pos, f"invalid TOML: {e.msg}"
139+
140+
141+
def check_file(path, kind):
142+
try:
143+
with open(path, "rb") as f:
144+
data = f.read()
145+
except OSError as e:
146+
print(f"{path}: {e.strerror}")
147+
return False
148+
try:
149+
text = data.decode("utf-8")
150+
except UnicodeDecodeError as e:
151+
text = data[: e.start].decode("utf-8")
152+
line, col = location(text, len(text))
153+
print(f"{path}:{line}:{col}: not valid UTF-8")
154+
return False
155+
try:
156+
problems = list(check_toml(text) if kind == "toml" else check_json(text, kind == "jsonc"))
157+
except SyntaxProblem as e:
158+
problems = [(e.pos, e.message)]
159+
for pos, message in problems:
160+
line, col = location(text, pos)
161+
print(f"{path}:{line}:{col}: {message}")
162+
return not problems
163+
164+
165+
def main(argv):
166+
if len(argv) < 1 or argv[0] not in ("json", "jsonc", "toml"):
167+
print(__doc__.strip(), file=sys.stderr)
168+
return 2
169+
kind, paths = argv[0], argv[1:]
170+
results = [check_file(path, kind) for path in paths]
171+
return 0 if all(results) else 1
172+
173+
174+
if __name__ == "__main__":
175+
sys.exit(main(sys.argv[1:]))

0 commit comments

Comments
 (0)