Skip to main content

greengate_runtime/hooks/
lint_json_yaml.rs

1//! pre-commit-lint-json-yaml — parse staged JSON/YAML so a syntax error never
2//! reaches the repo. Both linters soft-fail when absent: warn, don't block.
3//! JSONC files (tsconfig, `.vscode/`, see [`is_jsonc`]) are parsed in-process
4//! with comments and trailing commas allowed.
5
6use super::common::{fail, hl, ok, repo_root, staged_files, warn, which};
7use crate::check::Outcome;
8use std::path::Path;
9use std::process::{Command, Stdio};
10
11/// The extensions each half consumes, and their union.
12///
13/// EXPORTED so `registry.rs` can DECLARE the scope from the same constant the
14/// check FILTERS with. They drifted: the registry declared
15/// `[".json", ".yaml", ".yml"]` while this module asked for `[".yaml"]`, so
16/// `amont list` reported the check as covering `.yml` and a staged, broken
17/// `x.yml` returned `Outcome::Passed` with no output at all. A `const fn` over
18/// a `const` is legal in a const item, so the registry can reference these
19/// directly and the two cannot disagree again.
20pub const JSON: &[&str] = &[".json"];
21pub const YAML: &[&str] = &[".yaml", ".yml"];
22pub const EXTS: &[&str] = &[".json", ".yaml", ".yml"];
23
24/// Helm chart templates carry Go templating (`{{ }}`) and are not valid YAML
25/// until Helm renders them. A staged YAML under a chart's `templates/` — i.e.
26/// with a sibling `Chart.yaml` at the chart root — is skipped, or valid chart
27/// commits would need --no-verify just to get past this hook.
28pub fn is_helm_template(root: &str, file: &str) -> bool {
29    let Some(i) = file.find("/templates/") else {
30        return false;
31    };
32    Path::new(root)
33        .join(&file[..i])
34        .join("Chart.yaml")
35        .is_file()
36}
37
38/// Files whose own tool reads them as JSONC — JSON with `//` and `/* */`
39/// comments and trailing commas: TypeScript's `tsconfig*.json` /
40/// `jsconfig*.json`, everything under a `.vscode/` directory, and
41/// `devcontainer.json`. Parsing them as strict JSON blocked every commit that
42/// touched a commented tsconfig, and pushed repos to move the comments out.
43pub fn is_jsonc(file: &str) -> bool {
44    let path = Path::new(file);
45    let base = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
46    (base.starts_with("tsconfig") || base.starts_with("jsconfig") || base == "devcontainer.json")
47        && base.ends_with(".json")
48        || path.components().any(|c| c.as_os_str() == ".vscode")
49}
50
51/// `text` as strict JSON: comments become spaces (newlines kept), a comma
52/// whose next token is `}` or `]` is dropped, and a leading BOM goes. String
53/// contents are never touched — `"@/*"` in tsconfig `paths` is not a
54/// comment. `None` for an unterminated block comment.
55pub fn strip_jsonc(text: &str) -> Option<String> {
56    let s = text.strip_prefix('\u{feff}').unwrap_or(text).as_bytes();
57    // Pass 1: comments out, strings verbatim.
58    let mut out: Vec<u8> = Vec::with_capacity(s.len());
59    let mut i = 0;
60    while i < s.len() {
61        match s[i] {
62            b'"' => {
63                out.push(b'"');
64                i += 1;
65                while i < s.len() {
66                    let c = s[i];
67                    out.push(c);
68                    i += 1;
69                    if c == b'\\' && i < s.len() {
70                        out.push(s[i]);
71                        i += 1;
72                    } else if c == b'"' {
73                        break;
74                    }
75                }
76            }
77            b'/' if s.get(i + 1) == Some(&b'/') => {
78                while i < s.len() && s[i] != b'\n' {
79                    out.push(b' ');
80                    i += 1;
81                }
82            }
83            b'/' if s.get(i + 1) == Some(&b'*') => {
84                let end = s[i + 2..].windows(2).position(|w| w == b"*/")? + i + 4;
85                for &c in &s[i..end] {
86                    out.push(if c == b'\n' { b'\n' } else { b' ' });
87                }
88                i = end;
89            }
90            c => {
91                out.push(c);
92                i += 1;
93            }
94        }
95    }
96    // Pass 2: trailing commas out, strings verbatim.
97    let mut res: Vec<u8> = Vec::with_capacity(out.len());
98    let mut i = 0;
99    while i < out.len() {
100        match out[i] {
101            b'"' => {
102                res.push(b'"');
103                i += 1;
104                while i < out.len() {
105                    let c = out[i];
106                    res.push(c);
107                    i += 1;
108                    if c == b'\\' && i < out.len() {
109                        res.push(out[i]);
110                        i += 1;
111                    } else if c == b'"' {
112                        break;
113                    }
114                }
115            }
116            b',' => {
117                let next = out[i + 1..].iter().find(|c| !c.is_ascii_whitespace());
118                // Only a comma after a value is trailing: `[,]` stays broken.
119                let prev = res.iter().rev().find(|c| !c.is_ascii_whitespace());
120                if !matches!(next, Some(b'}' | b']')) || matches!(prev, None | Some(b'[' | b'{')) {
121                    res.push(b',');
122                }
123                i += 1;
124            }
125            c => {
126                res.push(c);
127                i += 1;
128            }
129        }
130    }
131    String::from_utf8(res).ok()
132}
133
134/// Whether the JSONC file `f` (under `root`) parses. A read error fails, as
135/// node's would.
136fn parses_jsonc(root: &str, f: &str) -> bool {
137    std::fs::read_to_string(Path::new(root).join(f))
138        .ok()
139        .and_then(|t| strip_jsonc(&t))
140        .and_then(|t| crate::json_read::parse(&t))
141        .is_some()
142}
143
144fn parses(settings: &crate::config::Settings, root: &str, tool: &str, args: &[&str]) -> bool {
145    let mut cmd = Command::new(super::common::program(tool));
146    cmd.args(args)
147        .current_dir(root)
148        .stdin(Stdio::null())
149        .stdout(Stdio::null())
150        .stderr(Stdio::null());
151    super::common::bounded_success(settings, &mut cmd, tool)
152}
153
154pub fn run(settings: &crate::config::Settings, _args: &[std::ffi::OsString]) -> Outcome {
155    let (jsonc, json): (Vec<String>, Vec<String>) =
156        staged_files(JSON).into_iter().partition(|f| is_jsonc(f));
157    let yaml: Vec<String> = staged_files(YAML);
158    if json.is_empty() && jsonc.is_empty() && yaml.is_empty() {
159        return Outcome::Passed;
160    }
161    let root = repo_root();
162    // Independent halves. A missing parser silences one of them, and a
163    // half that never ran must not be reported as a half that passed — so
164    // both a failure anywhere and a gap anywhere outrank the clean case.
165    let mut failed = false;
166    let mut unavailable = false;
167
168    // JSONC is parsed in-process: no node needed, so never a gap.
169    for f in &jsonc {
170        if !parses_jsonc(&root, f) {
171            fail(&format!("Invalid JSONC: {}", hl(f)));
172            failed = true;
173        }
174    }
175
176    if !json.is_empty() {
177        if which("node").is_some() {
178            for f in &json {
179                let script = r#"JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))"#;
180                // `--` before `f`: a staged file named e.g. `-e.json` would
181                // otherwise be read as another `-e` by node's own parser.
182                if !parses(settings, &root, "node", &["-e", script, "--", f]) {
183                    fail(&format!("Invalid JSON: {}", hl(f)));
184                    failed = true;
185                }
186            }
187        } else {
188            warn(&format!(
189                "JSON files detected. To lint them, install {}",
190                hl("node")
191            ));
192            unavailable = true;
193        }
194    }
195
196    if !yaml.is_empty() {
197        if which("yq").is_some() {
198            for f in &yaml {
199                if is_helm_template(&root, f) {
200                    continue;
201                }
202                // `--` before `f`: a staged file starting with `-` would
203                // otherwise be read as a flag by yq's own parser.
204                if !parses(settings, &root, "yq", &["e", "true", "--", f]) {
205                    fail(&format!("Invalid YAML: {}", hl(f)));
206                    failed = true;
207                }
208            }
209        } else {
210            warn(&format!(
211                "YAML files detected. To lint them, install {}",
212                hl("yq")
213            ));
214            unavailable = true;
215        }
216    }
217
218    match (failed, unavailable) {
219        (true, _) => Outcome::Failed,
220        (false, true) => Outcome::Unavailable,
221        (false, false) => {
222            ok(settings, "Json/Yaml Lint passed");
223            Outcome::Passed
224        }
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use crate::json_read::parse;
232
233    fn ok(t: &str) -> bool {
234        strip_jsonc(t).and_then(|s| parse(&s)).is_some()
235    }
236
237    #[test]
238    fn jsonc_names() {
239        for f in [
240            "tsconfig.json",
241            "tsconfig.base.json",
242            "apps/web/tsconfig.app.json",
243            "jsconfig.json",
244            ".vscode/settings.json",
245            "pkg/.vscode/launch.json",
246            ".devcontainer/devcontainer.json",
247        ] {
248            assert!(is_jsonc(f), "{f}");
249        }
250        for f in [
251            "package.json",
252            "my-tsconfig.json",
253            "vscode/settings.json",
254            "tsconfig.json.bak",
255        ] {
256            assert!(!is_jsonc(f), "{f}");
257        }
258    }
259
260    #[test]
261    fn a_commented_tsconfig_with_trailing_commas_parses() {
262        let t = "\u{feff}{\n  // line\n  /* block\n  */ \"compilerOptions\": {\n    \"paths\": { \"@/*\": [\"./src/*\",], },\n    \"x\": \"http://a//b\", // after\n    \"q\": \"a\\\"//not\",\n    \"t\": true, /* c */\n  },\n}\n";
263        assert!(ok(t));
264        // The string contents survive untouched.
265        let s = strip_jsonc(t).unwrap();
266        assert!(
267            s.contains("\"@/*\"") && s.contains("\"http://a//b\"") && s.contains("\"a\\\"//not\"")
268        );
269    }
270
271    #[test]
272    fn broken_jsonc_still_fails() {
273        assert!(!ok("{ \"a\": 1 /* never closed"));
274        assert!(!ok("{ \"a\": }"));
275        assert!(!ok("{ \"a\": 1,, }"));
276        assert!(!ok("{ \"a\": 1 } trailing"));
277        assert!(!ok("[,]"));
278    }
279}