1use std::ffi::{OsStr, OsString};
4use std::io::{self, BufWriter, IsTerminal, Read, Write};
5use std::path::{Path, PathBuf};
6use std::process::ExitCode;
7
8use std::sync::atomic::{AtomicUsize, Ordering};
9use std::sync::{Arc, Mutex};
10
11use jsonvet::{Dialect, Problem, Report, Severity};
12
13mod args;
14mod editorconfig;
15mod format;
16mod frame;
17mod glob;
18mod json;
19mod messages;
20mod output;
21mod rules;
22mod sarif;
23mod schema;
24mod settings;
25mod write;
26
27use args::{Command, STDIN};
28use output::{Format, Look, Printer};
29use schema::Schema;
30use schema::select::{Job, Schemas, check_own_schema, jobs, with_schema};
31use settings::{Resolver, Settings};
32use write::write_atomically;
33
34const STACK: usize = 64 << 20;
39
40const CHUNK_BYTES: usize = 64 << 20;
42
43const SCHEMA_BYTES: usize = 20;
47
48const SPLIT_BYTES: usize = 1 << 20;
51
52pub fn run() -> ExitCode {
54 std::panic::set_hook(Box::new(|info| {
57 eprintln!(
58 "jsonvet: internal error: {info}\n\nThis is a bug in jsonvet. Please report it at \
59 https://github.com/simonvanlierde/jsonvet/issues with the command you ran and, if \
60 you can share it, the file that caused it."
61 );
62 std::process::exit(101);
63 }));
64 on_big_stack(run_here)
65}
66
67fn on_big_stack<T: Send + 'static>(f: fn() -> T) -> T {
70 let thread = std::thread::Builder::new().name("jsonvet".into());
71 match thread.stack_size(STACK).spawn(f) {
72 Ok(thread) => thread
73 .join()
74 .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
75 Err(_) => f(),
76 }
77}
78
79fn run_here() -> ExitCode {
80 #[cfg(debug_assertions)]
83 assert!(
84 std::env::var_os("JSONVET_TEST_PANIC").is_none(),
85 "test panic"
86 );
87 let annotate = std::env::var_os("GITHUB_ACTIONS").is_some_and(|v| v == "true");
88 let stdout = io::stdout().lock();
89 let set = |name| std::env::var_os(name).is_some_and(|v| !v.is_empty());
90 let color = if set("NO_COLOR") {
93 Some(false)
94 } else if set("FORCE_COLOR") {
95 Some(std::env::var_os("FORCE_COLOR").is_none_or(|v| v != "0" && v != "false"))
96 } else {
97 None
98 };
99 let terminal = Terminal {
100 tty: stdout.is_terminal(),
101 color,
102 };
103 match run_with(
104 std::env::args_os().skip(1),
105 annotate,
106 terminal,
107 BufWriter::new(stdout),
108 ) {
109 Ok(code) => ExitCode::from(code),
110 Err(message) => {
111 eprintln!("jsonvet: {message}");
112 ExitCode::from(2)
113 }
114 }
115}
116
117fn print_summary(
120 printer: &mut Printer<impl Write>,
121 line: Option<&str>,
122 text: bool,
123 found: bool,
124) -> io::Result<()> {
125 if let Some(line) = line {
126 if text {
127 printer.text_line(line)?;
128 }
129 if found {
130 printer.summary_annotation(line)?;
131 }
132 }
133 printer.finish()
134}
135
136#[doc(hidden)]
139#[derive(Clone, Copy, Debug, Default)]
140pub struct Terminal {
141 pub tty: bool,
144 pub color: Option<bool>,
147}
148
149#[doc(hidden)]
154pub fn run_with(
155 args: impl IntoIterator<Item = OsString>,
156 annotate: bool,
157 terminal: Terminal,
158 out: impl Write,
159) -> Result<u8, String> {
160 let args = match args::parse(args)
162 .map_err(|e| messages::fill("error.usage", &[("error", &output::printable(&e))]))?
163 {
164 Command::Help => return print(out, messages::text("help")),
165 Command::Version => return print(out, concat!("jsonvet ", env!("CARGO_PKG_VERSION"))),
166 Command::ListRules => return print(out, &rules::list()),
167 Command::Explain(text) => return print(out, &text),
168 Command::Check(args) => *args,
169 };
170 messages::english_only(args.format != Format::Text);
171 let resolver = Arc::new(Mutex::new(Resolver::new(&args.config, args.settings)?));
172 let settings_for = |path: &Path| lock(&resolver).for_file(path);
173 let threads = std::thread::available_parallelism().map_or(1, std::num::NonZero::get);
174 let files = expand(args.files, &resolver, threads)?;
175 if let Some(check_only) = args.fmt {
176 return format::run(&files, check_only, args.stdin_filename, &resolver, out);
177 }
178 let schemas = Schemas::default();
179 let load = |path: &Path, quiet| {
180 schemas.get(path, quiet, |admit| {
181 Schema::load(path, &*settings_for(path)?, quiet, admit)
182 })
183 };
184 let root = |path: &Path| lock(&resolver).root(path);
185
186 let stdin_name = args.stdin_filename.unwrap_or_else(|| STDIN.into());
188 let shown = |file: &OsStr| -> OsString {
189 if file == STDIN {
190 stdin_name.clone()
191 } else {
192 file.to_owned()
193 }
194 };
195 let files = jobs(files, &shown, &settings_for, args.schema.as_deref(), &load)?;
198 let look = look(args.format, args.color, terminal);
199 let stdin_fix = args.fix && files.iter().any(|(_, file)| file == STDIN);
201 let mut out = out;
202 let sink = Diagnostics::new(stdin_fix, &mut out);
203 let mut printer = Printer::new(sink, args.format, annotate, look);
204 let mut fixed = FixRun::default();
205 let mut counts = Counts::default();
206 let mut rest = &files[..];
216 let shares = schema_shares(&files, threads);
217 let mut ahead = Vec::new();
218 let written = loop {
219 if rest.is_empty() {
220 let line = (!files.is_empty()).then(|| counts.summary(files.len()));
221 let found = counts.errors + counts.warnings > 0;
222 break print_summary(&mut printer, line.as_deref(), terminal.tty, found);
223 }
224 let shares = shares.get(files.len() - rest.len()..);
225 let with_schema = |job: &Job, text: &str| with_schema(job, &shown(&job.1), text);
226 let mut texts = take_chunk(&mut ahead, rest, shares, threads, &with_schema);
227 let chunk;
228 (chunk, rest) = rest.split_at(texts.len());
229 let known = if args.fix {
230 fix_chunk(
231 chunk,
232 &mut texts,
233 &shown,
234 args.unsafe_fixes,
235 threads,
236 &mut fixed,
237 )
238 } else {
239 vec![None; texts.len()]
240 };
241 let jobs: Vec<_> = chunk.iter().zip(&texts).zip(&known).collect();
242 let parts = (threads / jobs.len()).max(1);
243 let checked = parallel(
244 &jobs,
245 threads,
246 || false,
247 |((((settings, schema), file), (text, with)), known)| {
248 let name = shown(file);
249 let name = name.to_string_lossy();
250 text.as_deref().map(|text| match schema {
251 Some(schema) => check(&name, text, settings, Some(schema), parts, None),
252 None if *with => {
253 check_own_schema(&name, text, settings, &schemas, &root, &load, parts)
254 }
255 None => check(&name, text, settings, None, parts, known.as_deref()),
256 })
257 },
258 );
259 schemas.over().map_err(|e| output::printable(&e))?;
260 let outcome = print_checked(chunk, checked, &shown, &mut printer, &mut counts);
261 if outcome.is_err() {
262 break outcome;
263 }
264 };
265 let written = written.and_then(|()| fixed.finish(&mut out));
266 conclude(written, &schemas, &counts, args.max_warnings)
267}
268
269type Checked<'t> = (Report<'t>, Vec<(usize, String, bool)>);
271
272fn print_checked(
275 chunk: &[Job],
276 checked: Vec<Result<Checked<'_>, &String>>,
277 shown: &impl Fn(&OsStr) -> OsString,
278 printer: &mut Printer<impl Write>,
279 counts: &mut Counts,
280) -> io::Result<()> {
281 chunk
282 .iter()
283 .zip(checked)
284 .try_for_each(|((_, file), checked)| match checked {
285 Ok((report, schema_errors)) => {
286 print_file(&shown(file), &report, &schema_errors, printer, counts)
287 }
288 Err(message) => {
289 counts.errors += 1;
290 counts.files += 1;
291 printer.unreadable(&shown(file), message)
292 }
293 })
294}
295
296fn conclude(
299 written: io::Result<()>,
300 schemas: &Schemas,
301 counts: &Counts,
302 max_warnings: Option<usize>,
303) -> Result<u8, String> {
304 match written {
306 Err(e) if e.kind() != io::ErrorKind::BrokenPipe => {
307 return Err(messages::fill("error.write", &[("error", &e)]));
308 }
309 _ => {}
310 }
311 schemas.note_missing();
312 let too_many_warnings = max_warnings.is_some_and(|max| counts.warnings > max);
313 Ok(u8::from(counts.errors > 0 || too_many_warnings))
314}
315
316fn read_chunk<S: Sync>(
320 files: &[(S, OsString)],
321 threads: usize,
322 with_schema: &(impl Fn(&(S, OsString), &str) -> bool + Sync),
323) -> Vec<(Result<String, String>, bool)> {
324 let bytes = AtomicUsize::new(0);
325 let full = || bytes.load(Ordering::Relaxed) >= CHUNK_BYTES;
326 parallel(files, threads, full, |file| {
327 let text = if file.1 == STDIN {
328 read_stdin()
329 } else {
330 read(Path::new(&file.1))
331 };
332 let with = text.as_ref().is_ok_and(|text| with_schema(file, text));
333 bytes.fetch_add(weight(&text, with), Ordering::Relaxed);
334 (text, with)
335 })
336}
337
338fn take_chunk(
343 ahead: &mut Vec<(Result<String, String>, bool)>,
344 rest: &[Job],
345 shares: Option<&[usize]>,
346 threads: usize,
347 with_schema: &(impl Fn(&Job, &str) -> bool + Sync),
348) -> Vec<(Result<String, String>, bool)> {
349 if ahead.is_empty() {
350 let offered = match shares {
351 Some(shares) if !shares.is_empty() => &rest[..chunk_len(shares)],
352 _ => rest,
353 };
354 *ahead = read_chunk(offered, threads, with_schema);
355 }
356 let weights: Vec<usize> = ahead
357 .iter()
358 .map(|(text, with)| weight(text, *with))
359 .collect();
360 ahead.drain(..chunk_len(&weights)).collect()
361}
362
363fn weight(text: &Result<String, String>, with_schema: bool) -> usize {
366 let size = text.as_ref().map_or(0, String::len);
367 if with_schema {
368 size.saturating_mul(SCHEMA_BYTES).min(CHUNK_BYTES)
369 } else {
370 size
371 }
372}
373
374fn schema_share(file: &OsStr) -> usize {
379 if file == STDIN {
380 return CHUNK_BYTES;
381 }
382 let size = std::fs::metadata(file).map_or(0, |meta| meta.len());
383 usize::try_from(size)
384 .unwrap_or(usize::MAX)
385 .saturating_mul(SCHEMA_BYTES)
386 .min(CHUNK_BYTES)
387}
388
389fn schema_shares(files: &[Job], threads: usize) -> Vec<usize> {
391 if files.iter().all(|((_, schema), _)| schema.is_none()) {
392 return Vec::new();
393 }
394 parallel(
395 files,
396 threads,
397 || false,
398 |((_, schema), file)| schema.as_ref().map_or(0, |_| schema_share(file)),
399 )
400}
401
402fn chunk_len(shares: &[usize]) -> usize {
405 let mut total = 0;
406 shares
407 .iter()
408 .position(|share| {
409 total += share;
410 total >= CHUNK_BYTES
411 })
412 .map_or(shares.len(), |last| last + 1)
413}
414
415fn expand(
420 args: Vec<OsString>,
421 resolver: &Arc<Mutex<Resolver>>,
422 threads: usize,
423) -> Result<Vec<OsString>, String> {
424 let mut files = Vec::with_capacity(args.len());
425 let dirs = parallel(
427 &args,
428 threads,
429 || false,
430 |arg| arg != STDIN && Path::new(arg).is_dir(),
431 );
432 let mut roots = Vec::new();
434 let mut distinct = true;
435 for (arg, dir) in args.into_iter().zip(dirs) {
436 if !dir {
437 distinct = false;
438 files.push(arg);
439 continue;
440 }
441 let start = files.len();
442 let above = std::fs::canonicalize(&arg).ok();
445 match &above {
446 Some(root) => roots.push(root.clone()),
447 None => distinct = false,
448 }
449 if let Some(problem) = std::iter::once(Path::new(&arg))
450 .chain(above.iter().flat_map(|dir| dir.ancestors()))
451 .find_map(unsafe_ignore_file)
452 {
453 return Err(problem);
454 }
455 let skipped = Arc::new(Mutex::new(None));
456 let skip = Arc::clone(&skipped);
457 let resolver = Arc::clone(resolver);
459 let walk = ignore::WalkBuilder::new(&arg)
462 .filter_entry(move |entry| {
463 if entry.file_type().is_some_and(|t| t.is_dir())
465 && let Some(problem) = unsafe_ignore_file(entry.path())
466 {
467 skip.lock()
469 .unwrap_or_else(std::sync::PoisonError::into_inner)
470 .get_or_insert(problem);
471 return false;
472 }
473 let settings = lock(&resolver).for_file(entry.path());
474 !settings.is_ok_and(|settings| settings.excluded(entry.path()))
475 })
476 .build();
477 for entry in walk {
478 let entry = entry
479 .map_err(|e| output::printable(&messages::fill("error.walk", &[("error", &e)])))?;
480 if entry.file_type().is_some_and(|t| t.is_file())
481 && Dialect::for_path(entry.path()).is_some()
482 {
483 files.push(entry.into_path().into_os_string());
484 }
485 }
486 if let Some(problem) = skipped
487 .lock()
488 .unwrap_or_else(std::sync::PoisonError::into_inner)
489 .take()
490 {
491 return Err(problem);
492 }
493 files[start..].sort_unstable();
494 }
495 let overlap = |i: usize, root: &PathBuf| {
497 roots[..i]
498 .iter()
499 .any(|r| r.starts_with(root) || root.starts_with(r))
500 };
501 if distinct && !roots.iter().enumerate().any(|(i, root)| overlap(i, root)) {
502 return Ok(files);
503 }
504 Ok(unique(files, threads))
505}
506
507#[derive(PartialEq, Eq, Hash)]
509enum Identity {
510 #[cfg(unix)]
511 Inode(u64, u64),
512 Path(PathBuf),
513}
514
515fn identity(file: &OsStr) -> Identity {
516 #[cfg(unix)]
517 if let Ok(meta) = std::fs::metadata(file) {
518 use std::os::unix::fs::MetadataExt;
519 return Identity::Inode(meta.dev(), meta.ino());
520 }
521 Identity::Path(std::fs::canonicalize(file).unwrap_or_else(|_| file.into()))
523}
524
525fn unique(files: Vec<OsString>, threads: usize) -> Vec<OsString> {
528 let ids = parallel(&files, threads, || false, |file| identity(file));
529 let mut seen = std::collections::HashSet::with_capacity(files.len());
530 files
531 .into_iter()
532 .zip(ids)
533 .filter_map(|(file, id)| seen.insert(id).then_some(file))
534 .collect()
535}
536
537fn lock(resolver: &Mutex<Resolver>) -> std::sync::MutexGuard<'_, Resolver> {
539 resolver
540 .lock()
541 .unwrap_or_else(std::sync::PoisonError::into_inner)
542}
543
544enum Diagnostics<'w, W: Write> {
547 Out(&'w mut W),
548 Stderr(io::Stderr),
549}
550
551impl<'w, W: Write> Diagnostics<'w, W> {
552 fn new(to_stderr: bool, out: &'w mut W) -> Self {
553 if to_stderr {
554 Diagnostics::Stderr(io::stderr())
555 } else {
556 Diagnostics::Out(out)
557 }
558 }
559}
560
561impl<W: Write> Write for Diagnostics<'_, W> {
562 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
563 match self {
564 Diagnostics::Out(out) => out.write(buf),
565 Diagnostics::Stderr(err) => err.write(buf),
566 }
567 }
568
569 fn flush(&mut self) -> io::Result<()> {
570 match self {
571 Diagnostics::Out(out) => out.flush(),
572 Diagnostics::Stderr(err) => err.flush(),
573 }
574 }
575}
576
577#[derive(Default)]
579struct FixRun {
580 problems: usize,
581 files: usize,
582 stdin: Option<String>,
584}
585
586impl FixRun {
587 fn finish(&self, out: &mut impl Write) -> io::Result<()> {
589 if let Some(summary) = self.summary() {
590 eprintln!("{summary}");
591 }
592 match &self.stdin {
593 Some(text) => out.write_all(text.as_bytes()).and_then(|()| out.flush()),
594 None => Ok(()),
595 }
596 }
597
598 fn summary(&self) -> Option<String> {
600 (self.problems > 0).then(|| {
601 messages::fill(
602 "summary.fixed",
603 &[
604 (
605 "problems",
606 &messages::count("summary.problems", self.problems),
607 ),
608 ("files", &messages::count("summary.files", self.files)),
609 ],
610 )
611 })
612 }
613}
614
615fn fix_chunk(
618 chunk: &[Job],
619 texts: &mut [(Result<String, String>, bool)],
620 shown: &(impl Fn(&OsStr) -> OsString + Sync),
621 unsafe_fixes: bool,
622 threads: usize,
623 run: &mut FixRun,
624) -> Vec<Option<Vec<Problem>>> {
625 let jobs: Vec<_> = chunk.iter().zip(texts.iter()).collect();
626 let done = parallel(
627 &jobs,
628 threads,
629 || false,
630 |(((settings, _), file), (text, _))| {
631 let text = text.as_ref().ok()?;
632 let name = shown(file);
633 let config = settings.config_for(&name.to_string_lossy());
634 let fixed = match jsonvet::try_fix(text, &config, unsafe_fixes) {
635 Ok(fixed) => fixed,
636 Err(problems) => return Some(Err(problems)),
637 };
638 let saved = if file == STDIN {
639 Ok(())
640 } else {
641 write_atomically(Path::new(file), &fixed.text)
642 };
643 Some(Ok((fixed, saved)))
644 },
645 );
646 drop(jobs);
647 let mut known = Vec::with_capacity(done.len());
648 for (((_, file), entry), done) in chunk.iter().zip(texts.iter_mut()).zip(done) {
649 known.push(match &done {
651 Some(Err(problems)) => problems.clone(),
652 _ => None,
653 });
654 let done = done.and_then(Result::ok);
655 match done {
656 Some((fixed, Ok(()))) => {
657 run.problems += fixed.fixes.len();
658 run.files += 1;
659 entry.0 = Ok(fixed.text);
660 }
661 Some((_, Err(error))) => {
662 entry.0 = Err(error);
663 }
664 None => {}
665 }
666 if file == STDIN
667 && let Ok(text) = &entry.0
668 {
669 run.stdin = Some(text.clone());
670 }
671 }
672 known
673}
674
675#[derive(Default)]
676struct Counts {
677 errors: usize,
678 warnings: usize,
679 files: usize,
681}
682
683impl Counts {
684 fn summary(&self, checked: usize) -> String {
686 let files = messages::count("summary.files", checked);
687 if self.errors + self.warnings == 0 {
688 return messages::fill("summary.none", &[("files", &files)]);
689 }
690 let errors = || messages::count("summary.errors", self.errors);
691 let warnings = || messages::count("summary.warnings", self.warnings);
692 let problems = match (self.errors, self.warnings) {
693 (_, 0) => errors(),
694 (0, _) => warnings(),
695 _ => messages::fill(
696 "summary.both",
697 &[("errors", &errors()), ("warnings", &warnings())],
698 ),
699 };
700 messages::fill(
701 "summary.some",
702 &[
703 ("problems", &problems),
704 ("failed", &self.files),
705 ("files", &files),
706 ],
707 )
708 }
709}
710
711fn parallel<T: Sync, U: Send>(
715 items: &[T],
716 threads: usize,
717 stop: impl Fn() -> bool + Sync,
718 f: impl Fn(&T) -> U + Sync,
719) -> Vec<U> {
720 let next = AtomicUsize::new(0);
721 let work = || {
724 let mut done = Vec::new();
725 loop {
726 if stop() && next.load(Ordering::Relaxed) > 0 {
727 break done;
728 }
729 let i = next.fetch_add(1, Ordering::Relaxed);
730 let Some(item) = items.get(i) else { break done };
731 done.push((i, f(item)));
732 }
733 };
734 let mut done = std::thread::scope(|scope| {
735 let helpers: Vec<_> = (1..threads.min(items.len()))
737 .filter_map(|_| {
738 std::thread::Builder::new()
739 .stack_size(STACK)
740 .spawn_scoped(scope, work)
741 .ok()
742 })
743 .collect();
744 let mut done = work();
745 for helper in helpers {
746 done.extend(
747 helper
748 .join()
749 .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
750 );
751 }
752 done
753 });
754 done.sort_unstable_by_key(|&(i, _)| i);
755 done.into_iter().map(|(_, result)| result).collect()
756}
757
758fn split(text: &str, dialect: Dialect, parts: usize) -> Vec<std::ops::Range<usize>> {
761 let split = dialect == Dialect::JsonLines && parts > 1 && text.len() >= SPLIT_BYTES;
762 jsonvet::line_parts(text, if split { parts } else { 1 })
763}
764
765fn check<'t>(
768 name: &str,
769 text: &'t str,
770 settings: &Settings,
771 schema: Option<&Schema>,
772 parts: usize,
773 known: Option<&[Problem]>,
774) -> (Report<'t>, Vec<(usize, String, bool)>) {
775 let config = settings.config_for(name);
776 let ranges = split(text, config.dialect(), parts);
777 if ranges.len() > 1 {
778 let (lines, errors): (Vec<_>, Vec<_>) = parallel(
781 &ranges,
782 parts,
783 || false,
784 |lines| match schema {
785 Some(schema) => schema.check_lines(text, lines.clone(), &config),
786 None => (
787 jsonvet::parse_lines(text, lines.clone(), &config, None),
788 Vec::new(),
789 ),
790 },
791 )
792 .into_iter()
793 .unzip();
794 let (report, syntax_error) = jsonvet::join_lines(text, lines);
795 let errors = if syntax_error {
797 Vec::new()
798 } else {
799 errors.into_iter().flatten().collect()
800 };
801 return (report, errors);
802 }
803 match schema {
804 Some(schema) => schema.check(text, &config),
806 None => match known {
808 Some(problems) => (
809 jsonvet::report(text, problems.to_vec(), &config),
810 Vec::new(),
811 ),
812 None => (jsonvet::check(text, &config), Vec::new()),
813 },
814 }
815}
816
817fn look(format: Format, color: Option<bool>, terminal: Terminal) -> Look {
820 let text = format == Format::Text;
821 Look {
822 frames: text && terminal.tty,
823 color: text && color.or(terminal.color).unwrap_or(terminal.tty),
824 }
825}
826
827fn print_file(
831 file: &OsStr,
832 report: &Report<'_>,
833 schema_errors: &[(usize, String, bool)],
834 printer: &mut Printer<impl Write>,
835 counts: &mut Counts,
836) -> io::Result<()> {
837 let before = counts.errors + counts.warnings;
838 for problem in report.problems() {
839 match problem.severity() {
840 Severity::Error => counts.errors += 1,
841 Severity::Warning => counts.warnings += 1,
842 _ => {}
843 }
844 printer.problem(file, report, problem)?;
845 }
846 for (offset, message, summary) in schema_errors {
847 counts.errors += usize::from(!summary);
848 printer.schema_error(file, report, *offset, message, *summary)?;
849 }
850 counts.files += usize::from(counts.errors + counts.warnings > before);
851 Ok(())
852}
853
854fn read(path: &Path) -> Result<String, String> {
858 let read = std::fs::metadata(path).and_then(|meta| {
859 if meta.is_file() {
860 std::fs::read(path).map(Some)
861 } else {
862 Ok(None)
863 }
864 });
865 match read {
866 Ok(Some(bytes)) => decode(bytes),
867 Ok(None) => Err(messages::text("read.not-regular").to_owned()),
868 Err(e) if e.kind() == io::ErrorKind::NotFound => {
869 Err(messages::text("read.missing").to_owned())
870 }
871 Err(e) => Err(messages::fill("read.error", &[("error", &e)])),
872 }
873}
874
875fn read_stdin() -> Result<String, String> {
877 let mut bytes = Vec::new();
878 match io::stdin().lock().read_to_end(&mut bytes) {
879 Ok(_) => decode(bytes),
880 Err(e) => Err(messages::fill("read.error", &[("error", &e)])),
881 }
882}
883
884fn decode(bytes: Vec<u8>) -> Result<String, String> {
888 let opens_string = |b: u8| b == b'"' || b == b'\'';
892 let encoding = match *bytes.as_slice() {
894 [0xFF, 0xFE, 0, 0, ..] => Some("UTF-32 (LE)"),
895 [0, 0, 0xFE, 0xFF, ..] => Some("UTF-32 (BE)"),
896 [0xFF, 0xFE, ..] => Some("UTF-16 (LE)"),
897 [0xFE, 0xFF, ..] => Some("UTF-16 (BE)"),
898 [0, 0, 0, a, ..] if a != 0 => Some("UTF-32 (BE)"),
899 [0, a, 0, b, ..] if a != 0 && b != 0 => Some("UTF-16 (BE)"),
900 [a, 0, 0, 0, ..] if a != 0 && !opens_string(a) => Some("UTF-32 (LE)"),
901 [a, 0, b, 0, ..] if a != 0 && b != 0 && !opens_string(a) => Some("UTF-16 (LE)"),
902 _ => None,
903 };
904 if let Some(encoding) = encoding {
905 return Err(messages::fill("read.encoding", &[("encoding", &encoding)]));
906 }
907 String::from_utf8(bytes).map_err(|e| {
908 let byte = e.utf8_error().valid_up_to();
909 messages::fill("read.not-utf8", &[("byte", &byte)])
910 })
911}
912
913pub(crate) const MAX_CONFIG_BYTES: u64 = 16 << 20;
915
916pub(crate) const MAX_SCHEMA_BYTES: u64 = 64 << 20;
919
920pub(crate) fn read_small(path: &Path, max: u64) -> io::Result<String> {
924 if !std::fs::metadata(path)?.is_file() {
925 return Err(io::Error::other(messages::text("read.not-regular")));
926 }
927 let mut text = String::new();
928 std::fs::File::open(path)?
930 .take(max + 1)
931 .read_to_string(&mut text)?;
932 if text.len() as u64 > max {
933 let mb = max >> 20;
934 return Err(io::Error::other(messages::fill(
935 "read.too-large",
936 &[("mb", &mb)],
937 )));
938 }
939 Ok(text)
940}
941
942fn unsafe_ignore_file(dir: &Path) -> Option<String> {
947 [".gitignore", ".ignore"].into_iter().find_map(|name| {
948 let path = dir.join(name);
949 let meta = std::fs::metadata(&path).ok()?;
950 let problem = if !meta.is_file() {
951 messages::text("read.not-regular").to_owned()
952 } else if meta.len() > MAX_CONFIG_BYTES {
953 messages::fill("read.too-large", &[("mb", &(MAX_CONFIG_BYTES >> 20))])
954 } else {
955 return None;
956 };
957 let error = format!("{}: {problem}", path.display());
958 Some(output::printable(&messages::fill(
959 "error.walk",
960 &[("error", &error)],
961 )))
962 })
963}
964
965fn print(mut out: impl Write, text: &str) -> Result<u8, String> {
966 match writeln!(out, "{text}").and_then(|()| out.flush()) {
967 Err(e) if e.kind() != io::ErrorKind::BrokenPipe => {
968 Err(messages::fill("error.write", &[("error", &e)]))
969 }
970 _ => Ok(0),
971 }
972}
973
974#[cfg(test)]
975mod tests {
976 use std::fmt::Write as _;
977 use std::sync::atomic::{AtomicUsize, Ordering};
978
979 use jsonvet::Dialect;
980
981 use super::{
982 CHUNK_BYTES, MAX_CONFIG_BYTES, SCHEMA_BYTES, SPLIT_BYTES, STDIN, Schema, Settings, check,
983 chunk_len, parallel, read_small, schema_share, schema_shares, split, take_chunk,
984 unsafe_ignore_file,
985 };
986 use crate::schema::select::Job;
987 use std::sync::Arc;
988
989 fn any_schema(test: &str) -> (std::path::PathBuf, Schema) {
992 let dir = std::env::temp_dir().join(format!("jsonvet-{test}-{}", std::process::id()));
993 std::fs::create_dir_all(dir.join("x")).expect("a temporary directory");
994 std::fs::write(dir.join("s.json"), "{}").expect("written");
995 let schema = Schema::load(&dir.join("s.json"), &Settings::default(), false, |_| Ok(()));
996 (dir, schema.expect("a schema"))
997 }
998
999 #[test]
1000 fn only_files_with_a_schema_take_a_share() {
1001 let (dir, schema) = any_schema("shares");
1002 let _ = std::fs::remove_dir_all(&dir);
1003 let schema = Arc::new(schema);
1004 let settings = Arc::new(Settings::default());
1005 let job =
1006 |schema: Option<&Arc<Schema>>| ((Arc::clone(&settings), schema.cloned()), STDIN.into());
1007 assert_eq!(
1008 schema_shares(&[job(None), job(None)], 2),
1009 Vec::<usize>::new()
1010 );
1011 assert_eq!(
1012 schema_shares(&[job(None), job(Some(&schema)), job(None)], 2),
1013 [0, CHUNK_BYTES, 0]
1014 );
1015 }
1016
1017 #[test]
1018 fn small_files_are_read_up_to_their_limit_and_no_further() {
1019 let dir = std::env::temp_dir().join(format!("jsonvet-small-{}", std::process::id()));
1020 std::fs::create_dir_all(&dir).expect("a temporary directory");
1021 let path = dir.join("f");
1022 std::fs::write(&path, "0123456789").expect("written");
1023 assert_eq!(read_small(&path, 10).expect("ten bytes"), "0123456789");
1024 assert!(read_small(&path, 9).is_err());
1025 let sized = |len: u64| {
1027 std::fs::File::create(dir.join(".gitignore"))
1028 .and_then(|file| file.set_len(len))
1029 .expect("a large file");
1030 };
1031 sized(MAX_CONFIG_BYTES);
1032 assert_eq!(unsafe_ignore_file(&dir), None);
1033 sized(MAX_CONFIG_BYTES + 1);
1034 assert!(unsafe_ignore_file(&dir).is_some_and(|e| e.ends_with("larger than 16 MB")));
1035 let _ = std::fs::remove_dir_all(&dir);
1036 }
1037
1038 #[test]
1039 fn only_json_lines_of_the_split_size_is_split_one_part_per_thread() {
1040 let line = "[1]\n".repeat(SPLIT_BYTES / 4);
1041 assert_eq!(split(&line, Dialect::JsonLines, 8).len(), 8);
1042 assert_eq!(split(&line, Dialect::JsonLines, 1).len(), 1);
1043 assert_eq!(split(&line, Dialect::Json, 8).len(), 1);
1044 assert_eq!(split(&line[4..], Dialect::JsonLines, 8).len(), 1);
1045 }
1046
1047 #[test]
1048 fn a_large_json_lines_file_checked_in_parts_reports_what_one_pass_does() {
1049 let pad = "x".repeat(500);
1053 let wide: Vec<String> = (0..150).map(|k| format!("\"k{k}\": \"s\"")).collect();
1054 let wide = format!("{{{}}}", wide.join(", "));
1055 let mut text = String::from("\u{FEFF}");
1056 for i in 0..4_000 {
1057 let _ = match i % 7 {
1058 _ if i % 1_000 == 999 => writeln!(text, "{wide}"),
1059 _ if i % 1_000 == 500 => writeln!(text, "{{\"a\": 1e400}}"),
1060 _ if i % 1_000 == 501 => writeln!(text, r#"{{"\ud800": 1, "\ud801": 2}}"#),
1061 0 => writeln!(text, "{{\"a\": {i}, \"a\": 1}}"),
1062 1 => write!(text, "{{\"a\": \"{i}\", \"p\": \"{pad}\"}}\r\n"),
1063 _ => writeln!(text, "{{\"a\": {i}, \"p\": \"{pad}\"}}"),
1064 };
1065 }
1066 assert!(text.len() > SPLIT_BYTES);
1067 let deep = format!("{}{}\n", "[".repeat(600), "]".repeat(600));
1068 let texts = [
1069 text.clone(),
1070 format!("{text}{{\"a\": 1\n{text}"),
1071 format!("{text}{deep}{text}"),
1072 ];
1073 let dir = std::env::temp_dir().join(format!("jsonvet-split-{}", std::process::id()));
1074 std::fs::create_dir_all(&dir).expect("a temporary directory");
1075 let path = dir.join("schema.json");
1076 let schema = concat!(
1077 r#"{"properties": {"a": {"type": "integer"}}, "#,
1078 r#""patternProperties": {"^k": {"type": "integer"}}}"#,
1079 );
1080 std::fs::write(&path, schema).expect("written");
1081 let settings = Settings::default();
1082 let schema = Schema::load(&path, &settings, false, |_| Ok(())).expect("a schema");
1083 let _ = std::fs::remove_dir_all(&dir);
1084 for text in &texts {
1085 for schema in [None, Some(&schema)] {
1086 let (whole, whole_errors) = check("x.jsonl", text, &settings, schema, 1, None);
1087 let (split, split_errors) = check("x.jsonl", text, &settings, schema, 8, None);
1088 assert_ne!(whole.problems(), &[]);
1089 assert_eq!(split.problems(), whole.problems());
1090 assert_eq!(split_errors, whole_errors);
1091 }
1092 }
1093 let (_, errors) = check("x.jsonl", &texts[0], &settings, Some(&schema), 8, None);
1094 assert_eq!(errors.len(), 570 + 4 * 101 + 8);
1096 let unchecked = errors.iter().filter(|(_, m, _)| m.contains("not checked"));
1097 assert_eq!(unchecked.count(), 8);
1098 }
1099
1100 #[test]
1101 fn parallel_keeps_the_order_and_stops_after_a_prefix() {
1102 let items: Vec<usize> = (0..1000).collect();
1103 for threads in [1, 3, 16] {
1104 let squares = parallel(&items, threads, || false, |i| i * i);
1105 assert_eq!(squares, items.iter().map(|i| i * i).collect::<Vec<_>>());
1106 let stopped = parallel(&items, threads, || true, |&i| i);
1109 assert!((1..=threads).contains(&stopped.len()), "{stopped:?}");
1110 assert_eq!(stopped, (0..stopped.len()).collect::<Vec<_>>());
1111 let done = AtomicUsize::new(0);
1112 let some = parallel(
1113 &items,
1114 threads,
1115 || done.load(Ordering::Relaxed) >= 100,
1116 |&i| {
1117 done.fetch_add(1, Ordering::Relaxed);
1118 i
1119 },
1120 );
1121 assert!((100..100 + threads).contains(&some.len()), "{}", some.len());
1123 assert_eq!(some, (0..some.len()).collect::<Vec<_>>());
1124 }
1125 assert_eq!(
1126 parallel(&[] as &[u8], 4, || false, |&b| b),
1127 Vec::<u8>::new()
1128 );
1129 }
1130
1131 #[test]
1132 fn a_chunk_ends_with_the_file_that_fills_it() {
1133 assert_eq!(chunk_len(&[]), 0);
1134 assert_eq!(chunk_len(&[1, 2, 3]), 3);
1135 assert_eq!(chunk_len(&[CHUNK_BYTES, 1]), 1);
1136 assert_eq!(chunk_len(&[CHUNK_BYTES - 1, 1, 1]), 2);
1137 assert_eq!(chunk_len(&[CHUNK_BYTES - 2, 1, 1]), 3);
1138 assert_eq!(chunk_len(&[0, CHUNK_BYTES - 1, 0, 2, 5]), 4);
1139 }
1140
1141 #[test]
1142 fn take_chunk_respects_shares() {
1143 let dir = std::env::temp_dir().join(format!("jsonvet-chunk-{}", std::process::id()));
1144 std::fs::create_dir_all(&dir).expect("dir");
1145 let f1 = dir.join("1.json");
1146 let f2 = dir.join("2.json");
1147 std::fs::write(&f1, "{}").expect("write");
1148 std::fs::write(&f2, "{}").expect("write");
1149 let settings = Arc::new(Settings::default());
1150 let job1: Job = ((settings.clone(), None), f1.into_os_string());
1151 let job2: Job = ((settings.clone(), None), f2.into_os_string());
1152 let rest = [job1, job2];
1153 let mut ahead = Vec::new();
1154 let shares = [CHUNK_BYTES, CHUNK_BYTES];
1155 let taken = take_chunk(&mut ahead, &rest, Some(&shares), 1, &|_, _| false);
1156 assert_eq!(taken.len(), 1);
1157 assert_eq!(ahead, []);
1158 let _ = std::fs::remove_dir_all(&dir);
1159 }
1160
1161 #[test]
1162 fn a_file_counts_its_size_twenty_times_with_a_schema() {
1163 let dir = std::env::temp_dir().join(format!("jsonvet-share-{}", std::process::id()));
1164 std::fs::create_dir_all(&dir).expect("a temp dir");
1165 let path = dir.join("a.json");
1166 std::fs::write(&path, " ".repeat(1000)).expect("write");
1167 let path = path.as_os_str();
1168 assert_eq!(schema_share(path), 1000 * SCHEMA_BYTES);
1169 std::fs::write(path, " ".repeat(CHUNK_BYTES / SCHEMA_BYTES + 1)).expect("write");
1170 assert_eq!(schema_share(path), CHUNK_BYTES, "capped");
1171 assert_eq!(schema_share(dir.join("gone.json").as_os_str()), 0);
1172 assert_eq!(schema_share(std::ffi::OsStr::new("-")), CHUNK_BYTES);
1173 let _ = std::fs::remove_dir_all(&dir);
1174 }
1175
1176 #[test]
1177 fn frames_show_on_a_terminal_and_color_follows_the_option_then_the_environment() {
1178 use super::{Format, Look, Terminal, look};
1179 let terminal = |tty, color| Terminal { tty, color };
1180 let frames = |color| Look {
1183 frames: true,
1184 color,
1185 };
1186 let lines = Look {
1187 frames: false,
1188 color: false,
1189 };
1190 let cases = [
1191 (Format::Text, None, terminal(true, None), frames(true)),
1192 (
1193 Format::Text,
1194 None,
1195 terminal(true, Some(false)),
1196 frames(false),
1197 ),
1198 (
1199 Format::Text,
1200 Some(false),
1201 terminal(true, Some(true)),
1202 frames(false),
1203 ),
1204 (Format::Sarif, Some(true), terminal(true, None), lines),
1205 (Format::Json, Some(true), terminal(true, None), lines),
1206 ];
1207 for (format, color, terminal, want) in cases {
1208 assert_eq!(
1209 look(format, color, terminal),
1210 want,
1211 "{format:?} {color:?} {terminal:?}"
1212 );
1213 }
1214 }
1215
1216 #[test]
1217 fn the_summary_counts_problems_and_files() {
1218 let dir = std::env::temp_dir().join(format!("jsonvet-summary-{}", std::process::id()));
1219 std::fs::create_dir_all(&dir).expect("a temp dir");
1220 let dup = dir.join("dup.json");
1221 let ok = dir.join("ok.json");
1222 std::fs::write(&dup, "{\"a\": 1, \"a\": 2}").expect("write");
1223 std::fs::write(&ok, "{}").expect("write");
1224 let run = |summary: bool, files: &[&std::path::Path]| {
1225 let mut out = Vec::new();
1226 let args = ["--no-config".into()]
1227 .into_iter()
1228 .chain(files.iter().map(|f| f.as_os_str().to_owned()));
1229 let terminal = super::Terminal {
1230 tty: summary,
1231 color: Some(false),
1232 };
1233 let code = super::run_with(args, false, terminal, &mut out).expect("a check");
1234 (code, String::from_utf8(out).expect("UTF-8"))
1235 };
1236 let (code, out) = run(true, &[&dup, &ok]);
1237 assert_eq!(code, 1);
1238 assert!(out.ends_with("\n1 error in 1 of 2 files\n"), "{out}");
1239 let gone = dir.join("gone.json");
1241 let dup2 = dir.join("dup2.json");
1243 std::fs::write(&dup2, "{\"a\": 1, \"a\": 2}").expect("write");
1244 let (_, out) = run(true, &[&dup, &gone, &dup2, &ok]);
1245 assert!(out.ends_with("\n3 errors in 3 of 4 files\n"), "{out}");
1246 assert_eq!(run(true, &[&ok]).1, "no problems in 1 file\n");
1247 assert!(!run(false, &[&dup]).1.contains(" in 1 of 1 file"));
1249 assert_eq!(run(true, &[]).1, "");
1250 for format in ["sarif", "json"] {
1252 let args = ["--no-config", "--format", format]
1253 .map(std::ffi::OsString::from)
1254 .into_iter()
1255 .chain([dup.clone().into_os_string()]);
1256 let mut out = Vec::new();
1257 let terminal = super::Terminal {
1258 tty: true,
1259 color: None,
1260 };
1261 super::run_with(args, false, terminal, &mut out).expect("a check");
1262 let out = String::from_utf8(out).expect("UTF-8");
1263 assert!(
1264 serde_json::from_str::<serde_json::Value>(&out).is_ok(),
1265 "{out}"
1266 );
1267 }
1268 let _ = std::fs::remove_dir_all(&dir);
1269 }
1270
1271 #[test]
1273 fn a_translation_reaches_text_output_only() {
1274 let dir = std::env::temp_dir().join(format!("jsonvet-locale-{}", std::process::id()));
1275 std::fs::create_dir_all(&dir).expect("a temp dir");
1276 let dup = dir.join("dup.json");
1277 std::fs::write(&dup, "{\"a\": 1, \"a\": 2}").expect("write");
1278 crate::messages::use_translation(
1279 "\"duplicate-key\" = \"XX {path}\"\n\"related.first-at\" = \"XX {line}:{column}\"\n",
1280 );
1281 let run = |format: &str| {
1282 let args = ["--no-config", "--format", format]
1283 .map(std::ffi::OsString::from)
1284 .into_iter()
1285 .chain([dup.clone().into_os_string()]);
1286 let mut out = Vec::new();
1287 super::run_with(args, false, super::Terminal::default(), &mut out).expect("a check");
1288 String::from_utf8(out).expect("UTF-8")
1289 };
1290 let text = run("text");
1291 assert!(text.contains("XX $.a (XX 1:2)"), "{text}");
1292 for format in ["json", "sarif"] {
1293 let out = run(format);
1294 assert!(out.contains("duplicate key $.a (first at 1:2)"), "{out}");
1295 assert!(!out.contains("XX"), "{out}");
1296 }
1297 let _ = std::fs::remove_dir_all(&dir);
1298 }
1299
1300 #[test]
1303 fn json_lines_and_schema_errors_get_code_frames_on_a_terminal() {
1304 let dir = std::env::temp_dir().join(format!("jsonvet-frames-{}", std::process::id()));
1305 std::fs::create_dir_all(&dir).expect("a temp dir");
1306 let lines = dir.join("l.jsonl");
1307 let schema = dir.join("s.json");
1308 let data = dir.join("d.json");
1309 std::fs::write(&lines, "{\"a\": 1}\n{\"a\": True}\n").expect("write");
1310 std::fs::write(&schema, r#"{"properties": {"a": {"type": "string"}}}"#).expect("write");
1311 std::fs::write(&data, "{\n \"a\": 1\n}\n").expect("write");
1312 let run = |args: &[&std::ffi::OsStr]| {
1313 let args = ["--no-config".into()]
1314 .into_iter()
1315 .chain(args.iter().map(|a| (*a).to_owned()));
1316 let terminal = super::Terminal {
1317 tty: true,
1318 color: Some(false),
1319 };
1320 let mut out = Vec::new();
1321 let code = super::run_with(args, false, terminal, &mut out).expect("a check");
1322 let out = String::from_utf8(out).expect("UTF-8");
1323 (
1324 code,
1325 out.replace(
1326 &format!("{}{}", dir.display(), std::path::MAIN_SEPARATOR),
1327 "",
1328 ),
1329 )
1330 };
1331 assert_eq!(
1332 run(&[lines.as_os_str()]),
1333 (
1334 1,
1335 "error[syntax]: expected a value, found `True`; did you mean `true`?\n \
1336 --> l.jsonl:2:7\n |\n2 | {\"a\": True}\n | ^^^^\n |\n = help: https://github.com/simonvanlierde/jsonvet/blob/main/docs/usage.md#syntax\n\n\
1337 1 error in 1 of 1 file\n"
1338 .to_owned()
1339 )
1340 );
1341 assert_eq!(
1342 run(&["--schema".as_ref(), schema.as_os_str(), data.as_os_str()]),
1343 (
1344 1,
1345 "error[schema]: 1 is not of type \"string\" (at $.a)\n \
1346 --> d.json:2:8\n |\n2 | \"a\": 1\n | ^\n |\n = help: https://github.com/simonvanlierde/jsonvet/blob/main/docs/usage.md#schema\n\n\
1347 1 error in 1 of 1 file\n"
1348 .to_owned()
1349 )
1350 );
1351 let _ = std::fs::remove_dir_all(&dir);
1352 }
1353
1354 #[test]
1355 fn the_summary_names_errors_and_warnings_together() {
1356 let counts = |errors, warnings| super::Counts {
1357 errors,
1358 warnings,
1359 files: 1,
1360 };
1361 assert_eq!(
1362 counts(1, 1).summary(2),
1363 "1 error and 1 warning in 1 of 2 files"
1364 );
1365 assert_eq!(counts(0, 2).summary(1), "2 warnings in 1 of 1 file");
1366 }
1367
1368 #[test]
1369 fn a_line_separator_ends_a_frame_line_only_in_a_json5_file() {
1370 let dir = std::env::temp_dir().join(format!("jsonvet-u2028-{}", std::process::id()));
1371 std::fs::create_dir_all(&dir).expect("a temp dir");
1372 let frame = |name: &str| {
1373 let file = dir.join(name);
1374 std::fs::write(&file, "{\"a\": \"x\u{2028}y\", \"a\": 2}\n").expect("write");
1375 let mut out = Vec::new();
1376 let args = ["--no-config".into(), file.into_os_string()];
1377 let terminal = super::Terminal {
1378 tty: true,
1379 color: Some(false),
1380 };
1381 super::run_with(args, false, terminal, &mut out).expect("a check");
1382 String::from_utf8(out).expect("UTF-8")
1383 };
1384 let five = frame("a.json5");
1385 assert!(five.contains("\n2 | y\", \"a\": 2}\n"), "{five}");
1387 assert!(five.contains("\n1 | {\"a\": \"x\n"), "{five}");
1388 let other = frame("a.jsonc");
1389 assert!(
1391 other
1392 .lines()
1393 .any(|l| l.starts_with("1 | {\"a\": \"x\u{FFFD}y\", \"a\": 2}")),
1394 "{other}"
1395 );
1396 let _ = std::fs::remove_dir_all(&dir);
1397 }
1398
1399 #[test]
1400 fn a_panic_on_the_big_stack_carries_on_in_the_caller() {
1401 static RUNS: AtomicUsize = AtomicUsize::new(0);
1402 let panic = std::panic::catch_unwind(|| {
1403 super::on_big_stack(|| -> u8 {
1404 RUNS.fetch_add(1, Ordering::Relaxed);
1405 panic!("on the big stack")
1406 })
1407 })
1408 .expect_err("the panic carries on");
1409 assert_eq!(panic.downcast_ref::<&str>(), Some(&"on the big stack"));
1410 assert_eq!(RUNS.load(Ordering::Relaxed), 1);
1411 }
1412}