From 5de0ba055cef7f2dc5451b1eaf0857deb77ae009 Mon Sep 17 00:00:00 2001 From: Akshay Date: Sun, 24 Oct 2021 13:24:52 +0530 Subject: add support for json out --- bin/Cargo.toml | 12 ++++++++++++ bin/src/traits.rs | 45 +++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 55 insertions(+), 2 deletions(-) (limited to 'bin') diff --git a/bin/Cargo.toml b/bin/Cargo.toml index af5a288..528f804 100644 --- a/bin/Cargo.toml +++ b/bin/Cargo.toml @@ -14,3 +14,15 @@ thiserror = "1.0.30" similar = "2.1.0" vfs = { path = "../vfs" } lib = { path = "../lib" } + +[dependencies.serde_json] +version = "1.0.68" +optional = true + +[dependencies.serde] +version = "1.0.68" +features = [ "derive" ] +optional = true + +[features] +json = [ "lib/json-out", "serde_json", "serde" ] diff --git a/bin/src/traits.rs b/bin/src/traits.rs index 5cf7208..a0e40d4 100644 --- a/bin/src/traits.rs +++ b/bin/src/traits.rs @@ -32,9 +32,10 @@ where format: OutFormat, ) -> io::Result<()> { match format { + #[cfg(feature = "json")] + OutFormat::Json => json::write_json(self, lint_result, vfs), OutFormat::StdErr => write_stderr(self, lint_result, vfs), OutFormat::Errfmt => write_errfmt(self, lint_result, vfs), - _ => Ok(()), } } } @@ -84,7 +85,11 @@ fn write_stderr( Ok(()) } -fn write_errfmt(writer: &mut T, lint_result: &LintResult, vfs: &ReadOnlyVfs) -> io::Result<()> { +fn write_errfmt( + writer: &mut T, + lint_result: &LintResult, + vfs: &ReadOnlyVfs, +) -> io::Result<()> { let file_id = lint_result.file_id; let src = str::from_utf8(vfs.get(file_id)).unwrap(); let path = vfs.file_path(file_id); @@ -107,6 +112,42 @@ fn write_errfmt(writer: &mut T, lint_result: &LintResult, vfs: &ReadOn Ok(()) } +#[cfg(feature = "json")] +mod json { + use crate::lint::LintResult; + use std::io::{self, Write}; + use vfs::ReadOnlyVfs; + + use lib::Report; + use serde::Serialize; + use serde_json; + + #[derive(Serialize)] + struct JsonReport<'μ> { + file: &'μ std::path::Path, + report: Vec<&'μ Report>, + } + + pub fn write_json( + writer: &mut T, + lint_result: &LintResult, + vfs: &ReadOnlyVfs, + ) -> io::Result<()> { + let file_id = lint_result.file_id; + let path = vfs.file_path(file_id); + writeln!( + writer, + "{}", + serde_json::to_string_pretty(&JsonReport { + file: path, + report: lint_result.reports.iter().collect::>() + }) + .unwrap() + )?; + Ok(()) + } +} + fn line(at: TextRange, src: &str) -> usize { let at = at.start().into(); src[..at].chars().filter(|&c| c == '\n').count() + 1 -- cgit v1.2.3