From ae448ad60c1eac83b4d1b8ce300360dd7c096747 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 30 Sep 2026 00:48:49 +0200 Subject: [PATCH] feat: generate a local default configuration --- README.md | 7 +++ crates/john-slop-core/assets/config.toml | 6 +++ crates/john-slop-core/src/config.rs | 5 ++ crates/john-slop-core/src/lib.rs | 1 + docs/configuration.md | 14 +++++ examples/config/README.md | 7 +++ src/bin/john-slop.rs | 54 ++++++++++++++++++- tasks.md | 2 +- tests/cli.rs | 69 ++++++++++++++++++++++++ 9 files changed, 163 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b9b8651..a1c96a6 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,13 @@ Scan a document or source directory: john-slop path/to/document path/to/source-directory ``` +Generate a commented `config.toml` in the current directory, then edit category +or individual-rule switches as needed: + +```sh +john-slop config init +``` + Diagnostics are colored Miette reports by default. Make the command fail when a document reaches a chosen low-care evidence score with `--fail-score 0..100`: diff --git a/crates/john-slop-core/assets/config.toml b/crates/john-slop-core/assets/config.toml index 357feae..47249fc 100644 --- a/crates/john-slop-core/assets/config.toml +++ b/crates/john-slop-core/assets/config.toml @@ -12,6 +12,12 @@ style = true prompt-leakage = true source-code = true +# Disable or re-enable one diagnostic by its stable ID. Uncomment and change +# the ID as needed; `john-slop config show` lists the complete resolved rules. +# [[rules]] +# id = "templated-conclusion" +# enabled = false + [input] max_document_bytes = 8388608 max_archive_bytes = 67108864 diff --git a/crates/john-slop-core/src/config.rs b/crates/john-slop-core/src/config.rs index ba680ab..8e0146f 100644 --- a/crates/john-slop-core/src/config.rs +++ b/crates/john-slop-core/src/config.rs @@ -17,6 +17,11 @@ const EMBEDDED_CONFIG: &str = include_str!("../assets/config.toml"); const EMBEDDED_HEURISTICS: &str = include_str!("../assets/heuristics.toml"); const EMBEDDED_UNICODE: &str = include_str!("../assets/unicode.toml"); +/// Return the commented base configuration suitable for a user or project layer. +pub const fn default_config_template() -> &'static str { + EMBEDDED_CONFIG +} + /// A validated named configuration without path syntax or a file extension. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ConfigName(String); diff --git a/crates/john-slop-core/src/lib.rs b/crates/john-slop-core/src/lib.rs index 7aeed42..d6bdbfb 100644 --- a/crates/john-slop-core/src/lib.rs +++ b/crates/john-slop-core/src/lib.rs @@ -19,6 +19,7 @@ pub use config::{ ConfigOverrides, ConfigPaths, ConfigValidationError, ConfusablePolicy, ContentKind, DiagnosticCategories, DiagnosticPolicy, EvidenceThresholds, HeuristicRule, InputLimits, InputOverrides, MatcherType, ReplacementRule, RuleScope, ThresholdOverrides, UnicodePolicy, + default_config_template, }; pub use detector::{AnalysisContext, Detector, DetectorBuildError, Rule}; pub use diagnostic::FindingDiagnostic; diff --git a/docs/configuration.md b/docs/configuration.md index 6222aa9..fa4e8fc 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -27,6 +27,20 @@ Named configurations accept only ASCII letters, digits, `_`, and `-`. Do not include a directory, dot component, or `.toml` extension. Missing user and named files are optional; a selected explicit file must exist. +## Generate a project configuration + +Create the embedded, commented base configuration as `./config.toml`: + +```sh +john-slop config init +``` + +The command refuses to overwrite an existing file. Use +`john-slop config init --force` only when replacing that file is intentional. +`config generate` is an alias for `config init`. Load a project-local file with +`john-slop --config config.toml path/to/input` or inspect it with the command +shown below. + ## Schema The current `schema_version` is `1`. The complete defaults live in diff --git a/examples/config/README.md b/examples/config/README.md index 1a97e69..a3c0d82 100644 --- a/examples/config/README.md +++ b/examples/config/README.md @@ -13,3 +13,10 @@ john-slop config show --config-name editorial ``` Project-local policy can use either file with `--config path/to/file.toml`. +The CLI can also create the embedded commented base in the current directory: + +```sh +john-slop config init +``` + +It preserves an existing `config.toml` unless `--force` is explicit. diff --git a/src/bin/john-slop.rs b/src/bin/john-slop.rs index 634cd81..0fdb6b0 100644 --- a/src/bin/john-slop.rs +++ b/src/bin/john-slop.rs @@ -4,6 +4,8 @@ mod output; use std::{ + fs::OpenOptions, + io::Write, path::{Path, PathBuf}, process::ExitCode, }; @@ -12,7 +14,7 @@ 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, + SourceId, default_config_template, read_inputs, read_stdin, }; use miette::{IntoDiagnostic, Result, WrapErr}; @@ -120,6 +122,13 @@ enum Command { /// Configuration inspection operations. #[derive(Debug, Subcommand)] enum ConfigCommand { + /// Generate a commented config.toml in the current directory. + #[command(visible_alias = "generate")] + Init { + /// Replace an existing config.toml instead of refusing to overwrite it. + #[arg(long)] + force: bool, + }, /// Print the fully resolved, validated configuration as deterministic TOML. Show, /// Print every selected configuration path in precedence order. @@ -170,6 +179,7 @@ fn run(cli: &Cli) -> Result { if let Some(Command::Config { command }) = &cli.command { match command { + ConfigCommand::Init { force } => write_default_config(*force)?, ConfigCommand::Show => { let config = loader.load()?; print!("{}", toml::to_string_pretty(&config).into_diagnostic()?); @@ -250,6 +260,29 @@ fn run(cli: &Cli) -> Result { Ok(outcome) } +fn write_default_config(force: bool) -> Result<()> { + let path = Path::new("config.toml"); + let mut options = OpenOptions::new(); + options.write(true).create(true); + if force { + options.truncate(true); + } else { + options.create_new(true); + } + let mut file = options.open(path).into_diagnostic().wrap_err_with(|| { + if path.exists() && !force { + "refusing to overwrite ./config.toml; rerun with `config init --force`".to_owned() + } else { + "failed to create ./config.toml".to_owned() + } + })?; + file.write_all(default_config_template().as_bytes()) + .into_diagnostic() + .wrap_err("failed to write ./config.toml")?; + println!("wrote ./config.toml"); + Ok(()) +} + 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 { @@ -378,6 +411,25 @@ mod tests { )); } + #[test] + fn parses_config_init_and_force_without_detector_paths() { + let init = Cli::try_parse_from(["john-slop", "config", "init"]).unwrap(); + assert!(matches!( + init.command, + Some(Command::Config { + command: ConfigCommand::Init { force: false } + }) + )); + + let forced = Cli::try_parse_from(["john-slop", "config", "generate", "--force"]).unwrap(); + assert!(matches!( + forced.command, + Some(Command::Config { + command: ConfigCommand::Init { force: true } + }) + )); + } + #[test] fn parses_stdin_filename_ignore_and_resource_limits() { let cli = Cli::try_parse_from([ diff --git a/tasks.md b/tasks.md index 7504e63..a96503f 100644 --- a/tasks.md +++ b/tasks.md @@ -585,7 +585,7 @@ is 93.05% (1,487/1,598 lines), and release metadata agrees on `0.1.22`. retaining `[[rules]] enabled = true|false` for individual diagnostics. A rule runs only when both its category and individual switches are enabled; test user, named, and explicit-layer precedence plus unknown configuration keys. -- [ ] Add `john-slop config init` to write the embedded, commented default +- [x] Add `john-slop config init` to write the embedded, commented default configuration to `./config.toml`. Refuse to replace an existing file by default, support an explicit `--force`, and test the generated file by loading it through the public configuration path. diff --git a/tests/cli.rs b/tests/cli.rs index d806325..08c8494 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -47,6 +47,20 @@ fn help_is_successful_and_names_the_command() { insta::assert_snapshot!(String::from_utf8(output.stdout).expect("UTF-8 stdout")); } +#[test] +fn config_help_lists_generation_and_inspection_commands() { + let output = detector() + .args(["config", "--help"]) + .output() + .expect("run config help"); + let stdout = String::from_utf8(output.stdout).expect("UTF-8 stdout"); + + assert!(output.status.success()); + assert!(stdout.contains("init")); + assert!(stdout.contains("show")); + assert!(stdout.contains("paths")); +} + #[test] fn invalid_evidence_score_is_a_usage_error() { let output = detector() @@ -124,6 +138,61 @@ fn config_show_emits_resolved_toml_with_explicit_overrides() { assert_eq!(resolved["replacements"].as_array().unwrap().len(), 1_829); } +#[test] +fn config_init_writes_valid_defaults_and_requires_force_to_overwrite() { + let directory = tempdir().expect("temp dir"); + let config = directory.path().join("config.toml"); + let config_home = directory.path().join("config-home"); + + let created = detector() + .current_dir(directory.path()) + .env("XDG_CONFIG_HOME", &config_home) + .args(["config", "init"]) + .output() + .expect("generate default config"); + assert!(created.status.success()); + assert_eq!(created.stdout, b"wrote ./config.toml\n"); + let generated = fs::read_to_string(&config).expect("read generated config"); + let parsed = toml::from_str::(&generated).expect("valid generated TOML"); + assert_eq!(parsed["schema_version"].as_integer(), Some(1)); + assert_eq!( + parsed["diagnostics"]["categories"]["prompt-leakage"].as_bool(), + Some(true) + ); + + let loaded = detector() + .current_dir(directory.path()) + .env("XDG_CONFIG_HOME", &config_home) + .args(["config", "show", "--config", "config.toml"]) + .output() + .expect("load generated config"); + assert!( + loaded.status.success(), + "{}", + String::from_utf8_lossy(&loaded.stderr) + ); + + let refused = detector() + .current_dir(directory.path()) + .env("XDG_CONFIG_HOME", &config_home) + .args(["config", "init"]) + .output() + .expect("refuse overwrite"); + assert_eq!(refused.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&refused.stderr).contains("refusing to overwrite")); + assert_eq!(fs::read_to_string(&config).unwrap(), generated); + + fs::write(&config, "not valid TOML").unwrap(); + let forced = detector() + .current_dir(directory.path()) + .env("XDG_CONFIG_HOME", &config_home) + .args(["config", "generate", "--force"]) + .output() + .expect("force overwrite"); + assert!(forced.status.success()); + assert_eq!(fs::read_to_string(&config).unwrap(), generated); +} + #[test] fn category_and_individual_configuration_disable_cli_diagnostics() { let directory = tempdir().expect("temp dir");