use std::path::PathBuf;
use anyhow::{bail, Result};
use clap::Args;
use super::selection::{selected_paths, FileSelectionArgs};
use crate::diagnostic::{Diagnostic, Severity};
use crate::lint;
use crate::output::{has_errors, has_warnings, print_diagnostics};
use crate::util::resolve_config_root;
#[derive(Debug, Args)]
pub(crate) struct LintArgs {
#[command(flatten)]
files: FileSelectionArgs,
#[arg(long, conflicts_with_all = ["json", "github", "root", "changed", "staged", "base", "paths", "include_tests", "content_summary", "use_rsjs_strategy_cache", "deny_warnings", "deny", "min_severity"])]
stdio: bool,
#[arg(long)]
root: Option<PathBuf>,
#[arg(long)]
deny_warnings: bool,
#[arg(long, value_name = "LEVEL_OR_CODE")]
deny: Vec<String>,
#[arg(long)]
json: bool,
#[arg(long, value_name = "LEVEL")]
min_severity: Option<String>,
#[arg(long)]
github: bool,
#[arg(long)]
include_tests: bool,
#[arg(long)]
content_summary: bool,
#[arg(long)]
use_rsjs_strategy_cache: bool,
#[arg(long, requires = "use_rsjs_strategy_cache")]
require_fresh_strategy_cache: bool,
}
pub(crate) fn run(args: LintArgs) -> Result<()> {
if args.stdio {
return serve_snapshots();
}
let paths = selected_paths(&args.files)?;
let rsjs_strategy_cache = if args.use_rsjs_strategy_cache {
Some(lint::RsjsStrategyCacheOptions {
root: resolve_config_root(args.root.clone())?,
require_fresh: args.require_fresh_strategy_cache,
})
} else {
None
};
let diagnostics = if args.files.uses_git_selection() && paths.is_empty() {
Vec::new()
} else {
lint::lint_paths(
&paths,
lint::LintOptions {
include_tests: args.include_tests,
rsjs_strategy_cache,
content: lint::content::ContentOptions {
root: args.root.clone(),
report_status: args.content_summary,
..Default::default()
},
},
)?
};
let min_severity = resolve_min_severity(&args)?;
let shown: Vec<_> = diagnostics
.iter()
.filter(|diag| {
diag.severity.rank() >= min_severity.rank()
|| args.deny.iter().any(|code| code == diag.code)
})
.cloned()
.collect();
print_diagnostics(&shown, args.json, args.github)?;
let hidden = diagnostics.len() - shown.len();
if hidden > 0 && !args.json && !args.github {
eprintln!(
"({hidden} lower-severity diagnostics hidden; pass `--min-severity info` to show them)"
);
}
if has_errors(&diagnostics) || has_denied_lint(&args, &diagnostics) {
bail!("Proa lint failed");
}
Ok(())
}
fn serve_snapshots() -> Result<()> {
use std::io::{BufRead, Write};
#[derive(serde::Deserialize)]
struct Request {
id: serde_json::Value,
overlays: Vec<lint::live::SourceOverlay>,
}
let stdin = std::io::stdin();
let mut stdout = std::io::stdout().lock();
for line in stdin.lock().lines() {
let line = line?;
let input: serde_json::Value = match serde_json::from_str(&line) {
Ok(input) => input,
Err(error) => {
serde_json::to_writer(
&mut stdout,
&serde_json::json!({"id": null, "error": error.to_string()}),
)?;
writeln!(stdout)?;
stdout.flush()?;
continue;
}
};
let id = input.get("id").cloned().unwrap_or_default();
let result = serde_json::from_value::<Request>(input)
.map_err(anyhow::Error::from)
.and_then(|request| {
let diagnostics = lint::live::lint_snapshot(&request.overlays)?;
Ok(serde_json::json!({"id": request.id, "diagnostics": diagnostics}))
});
let response = result
.unwrap_or_else(|error| serde_json::json!({"id": id, "error": error.to_string()}));
serde_json::to_writer(&mut stdout, &response)?;
writeln!(stdout)?;
stdout.flush()?;
}
Ok(())
}
fn resolve_min_severity(args: &LintArgs) -> Result<Severity> {
match args.min_severity.as_deref() {
Some("error" | "errors") => Ok(Severity::Error),
Some("warning" | "warnings") => Ok(Severity::Warning),
Some("info" | "all") => Ok(Severity::Info),
Some(other) => {
bail!("unknown --min-severity level `{other}` (use error, warning, or info)")
}
None if args.json || args.github => Ok(Severity::Info),
None => Ok(Severity::Warning),
}
}
fn deny_warnings(args: &LintArgs) -> bool {
args.deny_warnings
|| args
.deny
.iter()
.any(|level| matches!(level.as_str(), "warning" | "warnings"))
}
fn has_denied_lint(args: &LintArgs, diagnostics: &[Diagnostic]) -> bool {
if deny_warnings(args) && has_warnings(diagnostics) {
return true;
}
diagnostics.iter().any(|diag| {
args.deny
.iter()
.any(|denied| denied != "warning" && denied != "warnings" && denied == diag.code)
})
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use clap::Parser;
use super::*;
use crate::cli::Cli;
use crate::commands::Command;
#[test]
fn lint_accepts_an_explicit_strategy_cache_root() {
let cli = Cli::try_parse_from([
"proa",
"lint",
"src/page.rs",
"--root",
"/tmp/demo",
"--use-rsjs-strategy-cache",
])
.unwrap();
let Command::Lint(args) = cli.command else {
panic!("expected lint command");
};
assert_eq!(args.files.paths, [PathBuf::from("src/page.rs")]);
assert_eq!(args.root, Some(PathBuf::from("/tmp/demo")));
assert!(args.use_rsjs_strategy_cache);
}
#[test]
fn lint_deny_accepts_specific_diagnostic_codes() {
let args = LintArgs {
stdio: false,
files: FileSelectionArgs {
paths: Vec::new(),
changed: false,
staged: false,
base: None,
},
root: None,
deny_warnings: false,
deny: vec!["rsjs/client-crossing".to_string()],
json: false,
min_severity: None,
github: false,
include_tests: false,
content_summary: false,
use_rsjs_strategy_cache: false,
require_fresh_strategy_cache: false,
};
let diagnostics = vec![
Diagnostic::new(
Path::new("src/page.rs"),
4,
9,
Severity::Info,
"render/advisory",
"advisory",
),
Diagnostic::new(
Path::new("src/page.rs"),
5,
13,
Severity::Info,
"rsjs/client-crossing",
"public crossing",
),
];
assert!(has_denied_lint(&args, &diagnostics));
let mut unrelated = args;
unrelated.deny = vec!["rsjs/unused-client-module".to_string()];
assert!(!has_denied_lint(&unrelated, &diagnostics));
}
#[test]
fn lint_deny_warnings_keeps_existing_severity_behavior() {
let args = LintArgs {
stdio: false,
files: FileSelectionArgs {
paths: Vec::new(),
changed: false,
staged: false,
base: None,
},
root: None,
deny_warnings: false,
deny: vec!["warnings".to_string()],
json: false,
min_severity: None,
github: false,
include_tests: false,
content_summary: false,
use_rsjs_strategy_cache: false,
require_fresh_strategy_cache: false,
};
let diagnostics = vec![Diagnostic::new(
Path::new("src/page.rs"),
4,
9,
Severity::Warning,
"render/advisory",
"warning",
)];
assert!(has_denied_lint(&args, &diagnostics));
}
}