use std::path::Path;
use mds::{MdsError, Severity};
use serde_json::Value;
use crate::lint::{CapNotice, DirSummary, LintSource};
use crate::output::{
eprint_error, eprint_io_failure, relabel_stdin_error, safe_inline, safe_path, stdout_failure,
write_stdout, StdoutOutcome, WalkResult, STDIN_DISPLAY_LABEL,
};
pub(crate) trait ResultSink {
fn quiet(&self) -> bool;
fn findings(
&mut self,
input: &LintSource<'_>,
findings: &mds::LintResult,
text: Option<&str>,
truncated: bool,
);
fn failed(&mut self, input: &LintSource<'_>, error: MdsError);
fn panicked(&mut self, input: &LintSource<'_>);
fn write_failed(&mut self, input: &LintSource<'_>, error: MdsError) {
self.failed(input, error);
}
fn not_synced(&mut self, _input: &LintSource<'_>, error: MdsError) {
eprint_io_failure(error);
}
fn clean(&mut self, input: &LintSource<'_>, findings: &mds::LintResult);
fn analysis_failed(&mut self, error: &MdsError, stdin_source: Option<&str>);
fn start_document(&mut self);
fn end_document(&mut self, truncated: bool);
fn cap_reached(&mut self, input: &LintSource<'_>, notice: CapNotice) {
if self.quiet() {
return;
}
let cap_advice = match notice {
CapNotice::Plain => "",
CapNotice::RerunFix => " — re-run --fix to continue",
};
match *input {
LintSource::DirEntry { path, .. } => crate::output::ewriteln!(
"{}: diagnostic cap ({}) reached; further findings were suppressed{}",
safe_path(path),
mds::MAX_DIAGNOSTICS,
cap_advice
),
LintSource::Stdin | LintSource::File { .. } => crate::output::ewriteln!(
"diagnostic cap ({}) reached; further findings were suppressed{}",
mds::MAX_DIAGNOSTICS,
cap_advice
),
}
}
fn fix_rejected(&mut self, input: &LintSource<'_>, reason: &str) {
if self.quiet() {
return;
}
match *input {
LintSource::DirEntry { path, .. } => {
crate::output::ewriteln!(
"{}: fix rejected: {}",
safe_path(path),
safe_inline(reason)
);
}
LintSource::Stdin | LintSource::File { .. } => {
crate::output::ewriteln!("fix rejected: {}", safe_inline(reason));
}
}
}
fn would_fix(&mut self, input: &LintSource<'_>) {
if self.quiet() {
return;
}
match *input {
LintSource::Stdin => crate::output::ewriteln!("Would fix: {STDIN_DISPLAY_LABEL}"),
LintSource::File { typed: path, .. } | LintSource::DirEntry { path, .. } => {
crate::output::ewriteln!("Would fix: {}", safe_path(path));
}
}
}
fn fixed(&mut self, input: &LintSource<'_>, partial: Option<(usize, usize)>) {
if self.quiet() {
return;
}
match *input {
LintSource::Stdin => {
if let Some((applied_count, total_count)) = partial {
crate::output::ewriteln!(
"Partially fixed: {STDIN_DISPLAY_LABEL} ({applied_count} of {total_count} fixes applied)"
);
}
}
LintSource::File { typed: path, .. } | LintSource::DirEntry { path, .. } => {
match partial {
None => crate::output::ewriteln!("Fixed: {}", safe_path(path)),
Some((applied_count, total_count)) => crate::output::ewriteln!(
"Partially fixed: {} ({applied_count} of {total_count} fixes applied)",
safe_path(path)
),
}
}
}
}
fn diff(&mut self, diff: &str) -> bool {
emit_stdout(diff)
}
fn fixed_source(&mut self, source: &str) {
emit_stdout(source);
}
fn summary(&mut self, summary: &DirSummary) {
let DirSummary {
clean_count,
warn_file_count,
error_file_count,
limit_file_count,
..
} = *summary;
if !self.quiet() || error_file_count > 0 || limit_file_count > 0 {
crate::output::ewriteln!(
"{clean_count} clean, {warn_file_count} with warnings, \
{error_file_count} with errors, {limit_file_count} resource-limited"
);
}
}
fn nothing_to_lint(&mut self, dir: &Path, walk: &WalkResult) {
crate::output::ewriteln!("{}", safe_inline(nothing_to_lint_message(dir, walk)));
}
fn setup_failed(&mut self, error: miette::Report) {
eprint_error(error);
}
}
fn nothing_to_lint_message(dir: &Path, walk: &WalkResult) -> String {
if walk.excluded_by_default > 0 {
format!(
"{} .mds file(s) found but all are under default-excluded directories \
(hidden dirs, node_modules); nothing was linted",
walk.excluded_by_default
)
} else {
format!(
"no .mds files found in {}; nothing was linted",
safe_path(dir)
)
}
}
pub(crate) struct HumanSink {
quiet: bool,
}
impl HumanSink {
pub(crate) fn new(quiet: bool) -> Self {
Self { quiet }
}
}
impl ResultSink for HumanSink {
fn quiet(&self) -> bool {
self.quiet
}
fn findings(
&mut self,
input: &LintSource<'_>,
findings: &mds::LintResult,
text: Option<&str>,
_truncated: bool,
) {
for diag in &findings.diagnostics {
render_diag_human(diag, self.quiet, input.display_label(), text);
}
}
fn failed(&mut self, _input: &LintSource<'_>, error: MdsError) {
eprint_error(miette::Report::from(error));
}
fn panicked(&mut self, _input: &LintSource<'_>) {}
fn clean(&mut self, input: &LintSource<'_>, findings: &mds::LintResult) {
let LintSource::File { typed, .. } = *input else {
return;
};
if !self.quiet && findings.diagnostics.is_empty() {
crate::output::ewriteln!("Clean: {}", safe_path(typed));
}
}
fn analysis_failed(&mut self, error: &MdsError, stdin_source: Option<&str>) {
let report = match stdin_source {
Some(source) => relabel_stdin_error(error, source),
None => miette::Report::from(error.clone()),
};
eprint_error(report);
}
fn start_document(&mut self) {}
fn end_document(&mut self, _truncated: bool) {}
}
fn render_diag_human(diag: &mds::LintDiagnostic, quiet: bool, filename: &str, text: Option<&str>) {
if quiet && matches!(diag.severity, Severity::Info | Severity::Warn) {
return;
}
let report = miette::Report::from(diag.sanitized_for_render());
let report = match text {
Some(text) => report.with_source_code(mds::named_source_for_render(filename, text)),
None => report,
};
eprint_error(report);
}
pub(crate) struct JsonSink {
quiet: bool,
document: Option<Vec<Value>>,
}
impl JsonSink {
pub(crate) fn new(quiet: bool) -> Self {
Self {
quiet,
document: None,
}
}
#[cfg(test)]
pub(crate) fn document(&self) -> &[Value] {
self.document.as_deref().unwrap_or_default()
}
}
impl ResultSink for JsonSink {
fn quiet(&self) -> bool {
self.quiet
}
fn findings(
&mut self,
_input: &LintSource<'_>,
findings: &mds::LintResult,
_text: Option<&str>,
truncated: bool,
) {
let files = files_of(findings);
match self.document.as_mut() {
Some(document) => document.extend(files),
None => {
emit_stdout(&json_line(&files_document(files, truncated)));
}
}
}
fn failed(&mut self, input: &LintSource<'_>, error: MdsError) {
if let Some(document) = self.document.as_mut() {
document.push(error_entry(input, &error));
return;
}
self.analysis_failed(&error, None);
}
fn panicked(&mut self, input: &LintSource<'_>) {
match self.document.as_mut() {
Some(document) => document.push(serde_json::json!({
"file": entry_key(input),
"error": internal_error(),
})),
None => {
emit_stdout(&json_line(&serde_json::json!({
"version": 1,
"error": internal_error(),
})));
}
}
}
fn clean(&mut self, _input: &LintSource<'_>, _findings: &mds::LintResult) {}
fn analysis_failed(&mut self, error: &MdsError, _stdin_source: Option<&str>) {
emit_stdout(&json_line(&error_envelope(error.serialize())));
}
fn start_document(&mut self) {
self.document = Some(Vec::new());
}
fn end_document(&mut self, truncated: bool) {
if let Some(files) = self.document.take() {
emit_stdout(&json_line(&files_document(files, truncated)));
}
}
fn nothing_to_lint(&mut self, dir: &Path, walk: &WalkResult) {
let error = MdsError::Io {
message: nothing_to_lint_message(dir, walk),
};
self.analysis_failed(&error, None);
}
fn setup_failed(&mut self, error: miette::Report) {
let serialized = match error.downcast::<MdsError>() {
Ok(error) => error.serialize(),
Err(report) => {
let mut serialized = MdsError::Io {
message: report.to_string(),
}
.serialize();
serialized.help = report
.help()
.map(|help| mds::sanitize_control_chars_wire(&help.to_string()).into_owned());
serialized
}
};
emit_stdout(&json_line(&error_envelope(serialized)));
}
}
fn error_envelope(error: mds::SerializedError) -> Value {
serde_json::json!({
"version": 1,
"error": error
})
}
fn files_document(files: Vec<Value>, truncated: bool) -> Value {
serde_json::json!({
"version": 1,
"files": files,
"truncated": truncated,
})
}
fn files_of(findings: &mds::LintResult) -> Vec<Value> {
let mut canonical = findings.to_canonical_json();
match canonical.get_mut("files").map(Value::take) {
Some(Value::Array(files)) => files,
_ => Vec::new(),
}
}
fn error_entry(input: &LintSource<'_>, error: &MdsError) -> Value {
serde_json::json!({
"file": entry_key(input),
"error": error.serialize()
})
}
fn entry_key(input: &LintSource<'_>) -> String {
mds::sanitize_control_chars_wire(input.display_label()).into_owned()
}
fn internal_error() -> Value {
serde_json::json!({
"code": "mds::internal",
"message": "internal compiler error",
"help": null,
"span": null,
})
}
fn json_line(document: &Value) -> String {
format!("{document}\n")
}
fn emit_stdout(text: &str) -> bool {
match write_stdout(text.as_bytes()) {
StdoutOutcome::Written | StdoutOutcome::Closed => false,
StdoutOutcome::Failed(e) => {
eprint_io_failure(stdout_failure(&e));
true
}
StdoutOutcome::FailedAgain => true,
}
}
#[cfg(test)]
mod tests {
use super::{files_document, files_of, json_line};
use mds::{LintDiagnostic, LintResult, SerializedSpan, Severity};
use serde_json::Value;
fn findings_in_two_files() -> LintResult {
LintResult::new(vec![
LintDiagnostic::new("empty-block", Severity::Warn, "an empty block")
.with_help("remove the block")
.with_span(SerializedSpan::new(0, 7))
.with_file("a.mds"),
LintDiagnostic::new("unused-variable", Severity::Error, "an unused variable")
.with_file("b.mds"),
])
}
fn keys(document: &Value) -> Vec<String> {
document
.as_object()
.map(|object| object.keys().cloned().collect())
.unwrap_or_default()
}
#[test]
fn a_files_document_is_core_s_canonical_json() {
for truncated in [false, true] {
let result = if truncated {
findings_in_two_files().truncated()
} else {
findings_in_two_files()
};
let canonical = result.to_canonical_json();
assert_eq!(
canonical["truncated"], truncated,
"precondition: core's document carries this arm's `truncated`"
);
assert_eq!(
canonical["files"].as_array().map(Vec::len),
Some(2),
"precondition: core's document has an entry per file; got {canonical}"
);
let document = files_document(files_of(&result), result.truncated);
assert_eq!(
keys(&document),
keys(&canonical),
"truncated = {truncated}: the document's keys must be core's"
);
assert_eq!(document, canonical, "truncated = {truncated}");
let canonical_line = serde_json::to_string(&canonical)
.expect("a serde_json::Value always serializes")
+ "\n";
assert_eq!(
json_line(&document),
canonical_line,
"truncated = {truncated}: stdout gets core's document byte for byte"
);
}
}
}