474 lines
15 KiB
Rust
474 lines
15 KiB
Rust
//! Detector command-line adapter.
|
|
|
|
#[path = "john-slop/output.rs"]
|
|
mod output;
|
|
|
|
use std::{
|
|
path::{Path, PathBuf},
|
|
process::ExitCode,
|
|
};
|
|
|
|
use clap::{Parser, Subcommand, ValueEnum};
|
|
use globset::{Glob, GlobSet, GlobSetBuilder};
|
|
use john_slop::{
|
|
AnalysisContext, Config, ConfigLoader, ConfigName, ConfigOverrides, Detector, InputOverrides,
|
|
SourceId, read_inputs, read_stdin,
|
|
};
|
|
use miette::{IntoDiagnostic, Result, WrapErr};
|
|
|
|
use output::{OutputFormat, render_analysis, render_input_error};
|
|
|
|
/// Inspect files, directories, or ZIP-based documents for low-care signals.
|
|
#[derive(Debug, Parser)]
|
|
#[command(
|
|
name = "john-slop",
|
|
version,
|
|
about,
|
|
subcommand_negates_reqs = true,
|
|
subcommand_precedence_over_arg = true,
|
|
args_conflicts_with_subcommands = true
|
|
)]
|
|
struct Cli {
|
|
/// Load a named user configuration from the platform config directory.
|
|
#[arg(long, global = true, value_name = "NAME")]
|
|
config_name: Option<ConfigName>,
|
|
|
|
/// Load an explicit TOML configuration after user configuration.
|
|
#[arg(long, global = true, value_name = "FILE")]
|
|
config: Option<PathBuf>,
|
|
|
|
/// Override the maximum accepted bytes for one input document.
|
|
#[arg(long, global = true, value_name = "BYTES")]
|
|
max_document_bytes: Option<u64>,
|
|
|
|
/// Override the maximum accepted bytes for an outer archive.
|
|
#[arg(long, global = true, value_name = "BYTES")]
|
|
max_archive_bytes: Option<u64>,
|
|
|
|
/// Override the maximum total expanded bytes for an archive.
|
|
#[arg(long, global = true, value_name = "BYTES")]
|
|
max_expanded_bytes: Option<u64>,
|
|
|
|
/// Override the maximum members accepted in one archive.
|
|
#[arg(long, global = true, value_name = "COUNT")]
|
|
max_archive_entries: Option<usize>,
|
|
|
|
/// Override the maximum expanded-to-compressed archive ratio.
|
|
#[arg(long, global = true, value_name = "RATIO")]
|
|
max_compression_ratio: Option<u64>,
|
|
|
|
/// Override the maximum recursive directory depth.
|
|
#[arg(long, global = true, value_name = "DEPTH")]
|
|
max_walk_depth: Option<usize>,
|
|
|
|
/// Read one document from standard input in addition to any paths.
|
|
#[arg(long)]
|
|
stdin: bool,
|
|
|
|
/// Virtual filename used only for standard-input language and path scoping.
|
|
#[arg(long, value_name = "PATH", requires = "stdin")]
|
|
stdin_filename: Option<PathBuf>,
|
|
|
|
/// Skip source paths matching a glob; may be supplied more than once.
|
|
#[arg(long, value_name = "GLOB", action = clap::ArgAction::Append)]
|
|
ignore: Vec<String>,
|
|
|
|
/// Select plain human, graphical Miette, concise, or versioned JSON output.
|
|
#[arg(
|
|
long,
|
|
value_enum,
|
|
default_value_t,
|
|
value_name = "human|miette|concise|json",
|
|
hide_possible_values = true
|
|
)]
|
|
output: OutputFormat,
|
|
|
|
/// Return exit code 1 when a document reaches this evidence-confidence score.
|
|
#[arg(
|
|
long,
|
|
default_value_t = 100,
|
|
value_parser = parse_confidence,
|
|
conflicts_with = "fail_level"
|
|
)]
|
|
fail_confidence: u8,
|
|
|
|
/// Return exit code 1 at the configured low, medium, or high threshold.
|
|
#[arg(long, value_enum, conflicts_with = "fail_confidence")]
|
|
fail_level: Option<FailLevel>,
|
|
|
|
/// Files, directories, or supported ZIP-based containers to inspect.
|
|
#[arg(required_unless_present = "stdin", value_name = "PATH")]
|
|
paths: Vec<PathBuf>,
|
|
|
|
/// Inspect resolved configuration instead of analyzing documents.
|
|
#[command(subcommand)]
|
|
command: Option<Command>,
|
|
}
|
|
|
|
/// Top-level utility commands.
|
|
#[derive(Debug, Subcommand)]
|
|
enum Command {
|
|
/// Inspect configuration sources and resolved values.
|
|
Config {
|
|
/// Configuration inspection operation.
|
|
#[command(subcommand)]
|
|
command: ConfigCommand,
|
|
},
|
|
}
|
|
|
|
/// Configuration inspection operations.
|
|
#[derive(Debug, Subcommand)]
|
|
enum ConfigCommand {
|
|
/// Print the fully resolved, validated configuration as deterministic TOML.
|
|
Show,
|
|
/// Print every selected configuration path in precedence order.
|
|
Paths,
|
|
}
|
|
|
|
/// Configured confidence band that should make analysis fail.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
|
enum FailLevel {
|
|
Low,
|
|
Medium,
|
|
High,
|
|
}
|
|
|
|
fn main() -> ExitCode {
|
|
let cli = Cli::parse();
|
|
match run(&cli) {
|
|
Ok(outcome) if outcome.input_errors => ExitCode::from(2),
|
|
Ok(outcome) if outcome.threshold_reached => ExitCode::from(1),
|
|
Ok(_) => ExitCode::SUCCESS,
|
|
Err(error) => {
|
|
eprintln!("{error:?}");
|
|
ExitCode::from(2)
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
|
struct RunOutcome {
|
|
threshold_reached: bool,
|
|
input_errors: bool,
|
|
}
|
|
|
|
/// Execute one parsed detector invocation and retain threshold/error state.
|
|
fn run(cli: &Cli) -> Result<RunOutcome> {
|
|
let loader = ConfigLoader::discover(cli.config_name.as_ref(), cli.config.clone())?
|
|
.with_overrides(ConfigOverrides {
|
|
input: InputOverrides {
|
|
max_document_bytes: cli.max_document_bytes,
|
|
max_archive_bytes: cli.max_archive_bytes,
|
|
max_expanded_bytes: cli.max_expanded_bytes,
|
|
max_archive_entries: cli.max_archive_entries,
|
|
max_compression_ratio: cli.max_compression_ratio,
|
|
max_walk_depth: cli.max_walk_depth,
|
|
},
|
|
..ConfigOverrides::default()
|
|
});
|
|
|
|
if let Some(Command::Config { command }) = &cli.command {
|
|
match command {
|
|
ConfigCommand::Show => {
|
|
let config = loader.load()?;
|
|
print!("{}", toml::to_string_pretty(&config).into_diagnostic()?);
|
|
}
|
|
ConfigCommand::Paths => print_config_paths(&loader),
|
|
}
|
|
return Ok(RunOutcome::default());
|
|
}
|
|
|
|
let config = loader.load()?;
|
|
let detector = Detector::new(&config).into_diagnostic()?;
|
|
let ignore = compile_ignore_globs(&cli.ignore)?;
|
|
let failure_threshold = fail_threshold(cli, &config);
|
|
let mut outcome = RunOutcome::default();
|
|
|
|
if cli.stdin {
|
|
match read_stdin(std::io::stdin().lock(), &config.input) {
|
|
Ok(document) => {
|
|
let context = cli
|
|
.stdin_filename
|
|
.as_ref()
|
|
.map_or_else(AnalysisContext::prose, |path| {
|
|
AnalysisContext::for_path(path.clone())
|
|
});
|
|
if !is_ignored(&ignore, cli.stdin_filename.as_deref()) {
|
|
let analysis = detector.analyze_with(&document.content, &context);
|
|
print!(
|
|
"{}",
|
|
render_analysis(cli.output, &document.source, &document.content, &analysis)
|
|
.into_diagnostic()?
|
|
);
|
|
outcome.threshold_reached |= analysis.confidence.score() >= failure_threshold;
|
|
}
|
|
}
|
|
Err(error) => {
|
|
emit_input_error(cli.output, "<stdin>", &error.to_string())?;
|
|
outcome.input_errors = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
for path in &cli.paths {
|
|
let documents = match read_inputs(&config, path) {
|
|
Ok(documents) => documents,
|
|
Err(error) => {
|
|
emit_input_error(cli.output, &path.display().to_string(), &error.to_string())?;
|
|
outcome.input_errors = true;
|
|
continue;
|
|
}
|
|
};
|
|
for document in documents {
|
|
let document = match document {
|
|
Ok(document) => document,
|
|
Err(error) => {
|
|
let source = error
|
|
.source_id()
|
|
.map_or_else(|| path.display().to_string(), ToString::to_string);
|
|
emit_input_error(cli.output, &source, &error.to_string())?;
|
|
outcome.input_errors = true;
|
|
continue;
|
|
}
|
|
};
|
|
if is_ignored(&ignore, source_path(&document.source)) {
|
|
continue;
|
|
}
|
|
let context = john_slop::AnalysisContext::for_source(&document.source);
|
|
let analysis = detector.analyze_with(&document.content, &context);
|
|
print!(
|
|
"{}",
|
|
render_analysis(cli.output, &document.source, &document.content, &analysis)
|
|
.into_diagnostic()?
|
|
);
|
|
outcome.threshold_reached |= analysis.confidence.score() >= failure_threshold;
|
|
}
|
|
}
|
|
|
|
Ok(outcome)
|
|
}
|
|
|
|
fn emit_input_error(format: OutputFormat, source: &str, message: &str) -> Result<()> {
|
|
let rendered = render_input_error(format, source, message).into_diagnostic()?;
|
|
if format == OutputFormat::Json {
|
|
print!("{rendered}");
|
|
} else {
|
|
eprint!("{rendered}");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
const fn fail_threshold(cli: &Cli, config: &Config) -> u8 {
|
|
match cli.fail_level {
|
|
Some(FailLevel::Low) => config.thresholds.low,
|
|
Some(FailLevel::Medium) => config.thresholds.medium,
|
|
Some(FailLevel::High) => config.thresholds.high,
|
|
None => cli.fail_confidence,
|
|
}
|
|
}
|
|
|
|
fn compile_ignore_globs(patterns: &[String]) -> Result<GlobSet> {
|
|
let mut builder = GlobSetBuilder::new();
|
|
for pattern in patterns {
|
|
builder.add(
|
|
Glob::new(pattern)
|
|
.into_diagnostic()
|
|
.wrap_err_with(|| format!("invalid --ignore glob `{pattern}`"))?,
|
|
);
|
|
}
|
|
builder
|
|
.build()
|
|
.into_diagnostic()
|
|
.wrap_err("failed to compile --ignore globs")
|
|
}
|
|
|
|
fn source_path(source: &SourceId) -> Option<&Path> {
|
|
match source {
|
|
SourceId::Stdin => None,
|
|
SourceId::File(path) => Some(path),
|
|
SourceId::ArchiveMember { member, .. } => Some(member),
|
|
}
|
|
}
|
|
|
|
fn is_ignored(ignore: &GlobSet, path: Option<&Path>) -> bool {
|
|
path.is_some_and(|path| ignore.is_match(path))
|
|
}
|
|
|
|
/// Print selected layers without reading or validating their contents.
|
|
fn print_config_paths(loader: &ConfigLoader) {
|
|
let paths = loader.paths();
|
|
println!("embedded_config = \"<embedded:assets/config.toml>\"");
|
|
println!("embedded_heuristics = \"<embedded:assets/heuristics.toml>\"");
|
|
println!("user_base = {:?}", paths.base.display().to_string());
|
|
println!(
|
|
"user_named = {:?}",
|
|
paths.named.as_ref().map_or_else(
|
|
|| "<not selected>".to_owned(),
|
|
|path| path.display().to_string()
|
|
)
|
|
);
|
|
println!(
|
|
"explicit = {:?}",
|
|
paths.explicit.as_ref().map_or_else(
|
|
|| "<not selected>".to_owned(),
|
|
|path| path.display().to_string()
|
|
)
|
|
);
|
|
println!("command_line_overrides = \"<current invocation>\"");
|
|
}
|
|
|
|
/// Parse and validate an inclusive confidence threshold.
|
|
fn parse_confidence(value: &str) -> Result<u8, String> {
|
|
let score = value
|
|
.parse::<u8>()
|
|
.map_err(|_| "confidence must be an integer from 0 through 100".to_owned())?;
|
|
if score > 100 {
|
|
return Err("confidence must be an integer from 0 through 100".to_owned());
|
|
}
|
|
Ok(score)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn parses_multiple_paths_and_threshold() {
|
|
let cli =
|
|
Cli::try_parse_from(["john-slop", "--fail-confidence", "42", "one.txt", "two.txt"])
|
|
.expect("valid CLI");
|
|
|
|
assert_eq!(cli.fail_confidence, 42);
|
|
assert_eq!(cli.fail_level, None);
|
|
assert_eq!(cli.config_name, None);
|
|
assert!(cli.command.is_none());
|
|
assert_eq!(
|
|
cli.paths,
|
|
[PathBuf::from("one.txt"), PathBuf::from("two.txt")]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_invalid_threshold() {
|
|
let error = Cli::try_parse_from(["john-slop", "--fail-confidence", "101", "file.txt"])
|
|
.expect_err("threshold above 100 should fail");
|
|
|
|
assert_eq!(error.exit_code(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn requires_at_least_one_path() {
|
|
let error = Cli::try_parse_from(["john-slop"]).expect_err("path should be required");
|
|
|
|
assert_eq!(error.exit_code(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn parses_configuration_subcommands_without_detector_paths() {
|
|
let cli = Cli::try_parse_from(["john-slop", "config", "show"]).unwrap();
|
|
|
|
assert!(cli.paths.is_empty());
|
|
assert!(matches!(
|
|
cli.command,
|
|
Some(Command::Config {
|
|
command: ConfigCommand::Show
|
|
})
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn parses_stdin_filename_ignore_and_resource_limits() {
|
|
let cli = Cli::try_parse_from([
|
|
"john-slop",
|
|
"--stdin",
|
|
"--stdin-filename",
|
|
"src/input.rs",
|
|
"--ignore",
|
|
"generated/**",
|
|
"--max-archive-bytes",
|
|
"1024",
|
|
"--max-expanded-bytes",
|
|
"2048",
|
|
"--max-archive-entries",
|
|
"20",
|
|
"--max-compression-ratio",
|
|
"10",
|
|
"--max-walk-depth",
|
|
"4",
|
|
])
|
|
.unwrap();
|
|
|
|
assert!(cli.stdin);
|
|
assert_eq!(cli.stdin_filename, Some(PathBuf::from("src/input.rs")));
|
|
assert_eq!(cli.ignore, ["generated/**"]);
|
|
assert_eq!(cli.max_archive_bytes, Some(1024));
|
|
assert_eq!(cli.max_expanded_bytes, Some(2048));
|
|
assert_eq!(cli.max_archive_entries, Some(20));
|
|
assert_eq!(cli.max_compression_ratio, Some(10));
|
|
assert_eq!(cli.max_walk_depth, Some(4));
|
|
assert!(cli.paths.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn fail_level_uses_resolved_configured_threshold() {
|
|
let cli =
|
|
Cli::try_parse_from(["john-slop", "--fail-level", "medium", "article.md"]).unwrap();
|
|
let mut config = Config::embedded();
|
|
config.thresholds.medium = 47;
|
|
|
|
assert_eq!(fail_threshold(&cli, &config), 47);
|
|
}
|
|
|
|
#[test]
|
|
fn fail_level_and_explicit_score_are_mutually_exclusive() {
|
|
let error = Cli::try_parse_from([
|
|
"john-slop",
|
|
"--fail-level",
|
|
"low",
|
|
"--fail-confidence",
|
|
"20",
|
|
"article.md",
|
|
])
|
|
.unwrap_err();
|
|
|
|
assert_eq!(error.exit_code(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn threshold_source_paths_and_ignore_globs_cover_every_variant() {
|
|
let config = Config::embedded();
|
|
for (level, expected) in [
|
|
("low", config.thresholds.low),
|
|
("medium", config.thresholds.medium),
|
|
("high", config.thresholds.high),
|
|
] {
|
|
let cli =
|
|
Cli::try_parse_from(["john-slop", "--fail-level", level, "article.md"]).unwrap();
|
|
assert_eq!(fail_threshold(&cli, &config), expected);
|
|
}
|
|
let cli =
|
|
Cli::try_parse_from(["john-slop", "--fail-confidence", "17", "article.md"]).unwrap();
|
|
assert_eq!(fail_threshold(&cli, &config), 17);
|
|
|
|
assert_eq!(source_path(&SourceId::Stdin), None);
|
|
assert_eq!(
|
|
source_path(&SourceId::File("article.md".into())),
|
|
Some(Path::new("article.md"))
|
|
);
|
|
assert_eq!(
|
|
source_path(&SourceId::ArchiveMember {
|
|
archive: "bundle.zip".into(),
|
|
member: "docs/article.md".into(),
|
|
}),
|
|
Some(Path::new("docs/article.md"))
|
|
);
|
|
|
|
let globs = compile_ignore_globs(&["generated/**".into(), "*.min.js".into()]).unwrap();
|
|
assert!(is_ignored(&globs, Some(Path::new("generated/out.rs"))));
|
|
assert!(is_ignored(&globs, Some(Path::new("bundle.min.js"))));
|
|
assert!(!is_ignored(&globs, Some(Path::new("src/lib.rs"))));
|
|
assert!(!is_ignored(&globs, None));
|
|
assert!(compile_ignore_globs(&["[".into()]).is_err());
|
|
}
|
|
}
|