diff --git a/Cargo.lock b/Cargo.lock index e7a0174..f93d2eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -594,6 +594,7 @@ dependencies = [ "regex", "serde", "serde_json", + "similar", "tempfile", "thiserror", "toml 1.1.6+spec-1.1.0", diff --git a/Cargo.toml b/Cargo.toml index 7a492f3..f1851a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,8 @@ miette = { version = "7.6.0", default-features = false, features = ["derive"] } regex = "1.13.1" serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" +similar = "2.7.0" +tempfile = "3.27.0" thiserror = "2.0.21" toml = "1.1.6" walkdir = "2.5.0" @@ -39,4 +41,3 @@ zip = "8.6.0" [dev-dependencies] insta = { version = "1.48.0", default-features = false } -tempfile = "3.27.0" diff --git a/src/bin/john-slop-fmt.rs b/src/bin/john-slop-fmt.rs index c97b751..4f57040 100644 --- a/src/bin/john-slop-fmt.rs +++ b/src/bin/john-slop-fmt.rs @@ -1,10 +1,22 @@ -//! Formatter command-line adapter scaffold. +//! Safe ASCII replacement formatter command-line adapter. #[path = "editor_help.rs"] mod editor_help; -use clap::Parser; -use miette::{Result, miette}; +use std::{ + fs, + io::{self, Write}, + path::{Path, PathBuf}, + process::ExitCode, +}; + +use clap::{ArgGroup, Parser}; +use john_slop::{ + Config, ConfigLoader, ConfigName, SourceId, apply_replacements, plan_replacements, read_inputs, + read_stdin, +}; +use miette::{Diagnostic, IntoDiagnostic, Result, WrapErr}; +use similar::TextDiff; /// Replace configured Unicode punctuation with safe ASCII equivalents. #[derive(Debug, Parser)] @@ -12,13 +24,329 @@ use miette::{Result, miette}; name = "john-slop-fmt", version, about, - after_help = editor_help::EDITOR_SETUP + after_help = editor_help::EDITOR_SETUP, + group(ArgGroup::new("mode").args(["check", "diff", "write"]).multiple(false)) )] -struct Cli {} +struct Cli { + /// Load a named user configuration from the platform config directory. + #[arg(long, value_name = "NAME")] + config_name: Option, -fn main() -> Result<()> { - let _cli = Cli::parse(); - Err(miette!( - "john-slop-fmt is not implemented yet; replacement planning is available through the library" - )) + /// Load an explicit TOML configuration after user configuration. + #[arg(long, value_name = "FILE")] + config: Option, + + /// Exit 1 if any input would change; do not emit formatted text. + #[arg(long)] + check: bool, + + /// Print a unified diff and exit 1 if the input would change. + #[arg(long)] + diff: bool, + + /// Atomically replace files in place; never accepted for standard input. + #[arg(long)] + write: bool, + + /// Permit directory traversal with --check or --write. + #[arg(long, requires = "path")] + recursive: bool, + + /// UTF-8 file or directory; omit to format standard input to standard output. + #[arg(value_name = "PATH")] + path: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mode { + Format, + Check, + Diff, + Write, +} + +#[derive(Debug)] +struct FormattedDocument { + path: Option, + label: String, + original: String, + formatted: String, +} + +impl FormattedDocument { + fn changed(&self) -> bool { + self.original != self.formatted + } +} + +#[derive(Debug, thiserror::Error, Diagnostic)] +enum FormatterError { + #[error("--write requires a filesystem path")] + #[diagnostic(help("omit --write to format standard input to standard output"))] + WriteRequiresPath, + + #[error("directory `{path}` requires --recursive")] + #[diagnostic(help("use --check --recursive or --write --recursive"))] + DirectoryRequiresRecursive { path: PathBuf }, + + #[error("--recursive requires --check or --write")] + #[diagnostic(help("recursive stdout and diff output are intentionally unsupported"))] + InvalidRecursiveMode, + + #[error("formatting ZIP-based container `{path}` is unsupported")] + #[diagnostic(help( + "extract the document and format individual UTF-8 files; archive rewriting is deferred" + ))] + UnsupportedArchive { path: PathBuf }, + + #[error("cannot write non-file source `{source_id}`")] + UnsupportedWriteSource { source_id: SourceId }, + + #[error("failed to {action} `{path}`")] + Io { + action: &'static str, + path: PathBuf, + #[source] + source: io::Error, + }, +} + +fn main() -> ExitCode { + let cli = Cli::parse(); + match run(&cli) { + Ok(true) if cli.check || cli.diff => ExitCode::from(1), + Ok(_) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("{error:?}"); + ExitCode::from(2) + } + } +} + +fn run(cli: &Cli) -> Result { + let mode = mode(cli); + validate_invocation(cli, mode)?; + let config = ConfigLoader::discover(cli.config_name.as_ref(), cli.config.clone())?.load()?; + let documents = load_documents(cli.path.as_deref(), cli.recursive, &config)?; + let formatted = format_documents(documents, &config)?; + let changed = formatted.iter().any(FormattedDocument::changed); + + match mode { + Mode::Format => write_formatted_stdout(&formatted)?, + Mode::Check => {} + Mode::Diff => write_diffs(&formatted)?, + Mode::Write => write_files(&formatted)?, + } + Ok(changed) +} + +const fn mode(cli: &Cli) -> Mode { + if cli.check { + Mode::Check + } else if cli.diff { + Mode::Diff + } else if cli.write { + Mode::Write + } else { + Mode::Format + } +} + +fn validate_invocation(cli: &Cli, mode: Mode) -> Result<()> { + if mode == Mode::Write && cli.path.is_none() { + return Err(FormatterError::WriteRequiresPath.into()); + } + if cli.recursive && !matches!(mode, Mode::Check | Mode::Write) { + return Err(FormatterError::InvalidRecursiveMode.into()); + } + Ok(()) +} + +type LoadedDocument = (Option, String, String); + +fn load_documents( + path: Option<&Path>, + recursive: bool, + config: &Config, +) -> Result> { + let Some(path) = path else { + let document = read_stdin(io::stdin().lock(), &config.input).into_diagnostic()?; + return Ok(vec![(None, document.source.to_string(), document.content)]); + }; + + if has_archive_extension(path) { + return Err(FormatterError::UnsupportedArchive { + path: path.to_owned(), + } + .into()); + } + if path.is_dir() && !recursive { + return Err(FormatterError::DirectoryRequiresRecursive { + path: path.to_owned(), + } + .into()); + } + + let mut loaded = Vec::new(); + for document in read_inputs(config, path).into_diagnostic()? { + let document = document.into_diagnostic()?; + match document.source { + SourceId::File(path) => { + let label = path.display().to_string(); + loaded.push((Some(path), label, document.content)); + } + source_id @ SourceId::ArchiveMember { .. } => { + return Err(FormatterError::UnsupportedWriteSource { source_id }.into()); + } + SourceId::Stdin => { + loaded.push((None, "".to_owned(), document.content)); + } + } + } + Ok(loaded) +} + +fn format_documents( + documents: Vec, + config: &Config, +) -> Result> { + documents + .into_iter() + .map(|(path, label, original)| { + let edits = plan_replacements(config, &original); + let formatted = apply_replacements(&original, &edits) + .map_err(miette::Report::new)? + .into_owned(); + Ok(FormattedDocument { + path, + label, + original, + formatted, + }) + }) + .collect() +} + +fn write_formatted_stdout(documents: &[FormattedDocument]) -> Result<()> { + let mut stdout = io::stdout().lock(); + for document in documents { + stdout + .write_all(document.formatted.as_bytes()) + .into_diagnostic() + .wrap_err("failed to write formatted output")?; + } + Ok(()) +} + +fn write_diffs(documents: &[FormattedDocument]) -> Result<()> { + let mut stdout = io::stdout().lock(); + for document in documents.iter().filter(|document| document.changed()) { + let formatted_label = format!("{}.formatted", document.label); + let diff = TextDiff::from_lines(&document.original, &document.formatted) + .unified_diff() + .header(&document.label, &formatted_label) + .to_string(); + stdout + .write_all(diff.as_bytes()) + .into_diagnostic() + .wrap_err("failed to write formatter diff")?; + } + Ok(()) +} + +fn write_files(documents: &[FormattedDocument]) -> Result<()> { + for document in documents.iter().filter(|document| document.changed()) { + let path = document + .path + .as_deref() + .ok_or(FormatterError::WriteRequiresPath)?; + atomic_write(path, document.formatted.as_bytes())?; + } + Ok(()) +} + +fn atomic_write(path: &Path, contents: &[u8]) -> Result<()> { + let metadata = fs::metadata(path).map_err(|source| FormatterError::Io { + action: "read metadata for", + path: path.to_owned(), + source, + })?; + let parent = path.parent().unwrap_or_else(|| Path::new(".")); + let mut temporary = + tempfile::NamedTempFile::new_in(parent).map_err(|source| FormatterError::Io { + action: "create temporary file beside", + path: path.to_owned(), + source, + })?; + temporary + .as_file() + .set_permissions(metadata.permissions()) + .map_err(|source| FormatterError::Io { + action: "copy permissions for", + path: path.to_owned(), + source, + })?; + temporary + .write_all(contents) + .and_then(|()| temporary.as_file().sync_all()) + .map_err(|source| FormatterError::Io { + action: "write temporary replacement for", + path: path.to_owned(), + source, + })?; + temporary + .persist(path) + .map_err(|error| FormatterError::Io { + action: "atomically replace", + path: path.to_owned(), + source: error.error, + })?; + Ok(()) +} + +fn has_archive_extension(path: &Path) -> bool { + path.extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| { + matches!( + extension.to_ascii_lowercase().as_str(), + "zip" | "docx" | "xlsx" | "pptx" + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_each_exclusive_mode_and_configuration() { + let check = Cli::try_parse_from(["john-slop-fmt", "--check", "input.txt"]).unwrap(); + assert_eq!(mode(&check), Mode::Check); + + let diff = Cli::try_parse_from(["john-slop-fmt", "--diff", "input.txt"]).unwrap(); + assert_eq!(mode(&diff), Mode::Diff); + + let write = Cli::try_parse_from([ + "john-slop-fmt", + "--write", + "--recursive", + "--config-name", + "strict", + "docs", + ]) + .unwrap(); + assert_eq!(mode(&write), Mode::Write); + assert!(write.recursive); + assert_eq!(write.config_name.unwrap().as_str(), "strict"); + + assert!(Cli::try_parse_from(["john-slop-fmt", "--check", "--write", "input.txt"]).is_err()); + } + + #[test] + fn identifies_supported_archive_extensions_case_insensitively() { + assert!(has_archive_extension(Path::new("report.DOCX"))); + assert!(has_archive_extension(Path::new("bundle.zip"))); + assert!(!has_archive_extension(Path::new("article.txt"))); + } }