feat: generate a local default configuration

This commit is contained in:
Dandaedre 2026-09-30 00:48:49 +02:00
parent cd15bb8503
commit ae448ad60c
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
9 changed files with 163 additions and 2 deletions

View File

@ -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`:

View File

@ -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

View File

@ -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);

View File

@ -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;

View File

@ -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

View File

@ -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.

View File

@ -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<RunOutcome> {
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<RunOutcome> {
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([

View File

@ -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.

View File

@ -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::<toml::Value>(&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");