greengate_runtime/hooks/
lint_json_yaml.rs1use 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
11pub const JSON: &[&str] = &[".json"];
21pub const YAML: &[&str] = &[".yaml", ".yml"];
22pub const EXTS: &[&str] = &[".json", ".yaml", ".yml"];
23
24pub 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
38pub 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
51pub fn strip_jsonc(text: &str) -> Option<String> {
56 let s = text.strip_prefix('\u{feff}').unwrap_or(text).as_bytes();
57 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 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 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
134fn 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 let mut failed = false;
166 let mut unavailable = false;
167
168 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 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 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 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}