From 6b0163217a958eb5f95bc72169ee9d1acb76c664 Mon Sep 17 00:00:00 2001 From: "Gavin M. Roy" Date: Tue, 7 Apr 2026 17:46:26 -0400 Subject: [PATCH 1/2] Add --inplace/-i flag to format files in place Writes formatted output back to the source file instead of stdout. Uses clap conflicts_with to enforce mutual exclusivity with --check. Co-Authored-By: Claude Opus 4.6 (1M context) --- src/main.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 26ef0fa..b0c3673 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,13 +19,17 @@ struct Cli { /// Check if files are already formatted (exit 1 if not) #[arg(long)] check: bool, + + /// Format files in place + #[arg(short, long = "inplace", conflicts_with = "check")] + inplace: bool, } fn format_sql(sql: &str, style: Style) -> Result { libpgfmt::format(sql, style).map_err(|e| e.to_string()) } -fn process(name: &str, sql: &str, cli: &Cli) -> Result { +fn process(name: &str, sql: &str, path: Option<&PathBuf>, cli: &Cli) -> Result { if sql.trim().is_empty() { return Ok(true); } @@ -35,6 +39,9 @@ fn process(name: &str, sql: &str, cli: &Cli) -> Result { eprintln!("Would reformat: {name}"); return Ok(false); } + } else if cli.inplace { + let path = path.ok_or_else(|| "cannot use --inplace with stdin".to_string())?; + fs::write(path, &formatted).map_err(|e| format!("{name}: {e}"))?; } else { println!("{formatted}"); } @@ -43,6 +50,11 @@ fn process(name: &str, sql: &str, cli: &Cli) -> Result { fn run() -> Result { let cli = Cli::parse(); + + if cli.inplace && cli.files.is_empty() { + return Err("--inplace requires at least one file".to_string()); + } + let mut all_ok = true; if cli.files.is_empty() { @@ -53,14 +65,14 @@ fn run() -> Result { io::stdin() .read_to_string(&mut sql) .map_err(|e| e.to_string())?; - if !process("", &sql, &cli)? { + if !process("", &sql, None, &cli)? { all_ok = false; } } else { for path in &cli.files { let sql = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; let name = path.display().to_string(); - if !process(&name, &sql, &cli)? { + if !process(&name, &sql, Some(path), &cli)? { all_ok = false; } } From 304112a3304049362b523537727dca70a021a219 Mon Sep 17 00:00:00 2001 From: "Gavin M. Roy" Date: Tue, 7 Apr 2026 20:57:22 -0400 Subject: [PATCH 2/2] Preserve file permissions on inplace write Read the original file's permissions before writing and restore them after, preventing fs::write from resetting non-default permissions. Co-Authored-By: Claude Opus 4.6 (1M context) --- src/main.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main.rs b/src/main.rs index b0c3673..c21cc8a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -41,7 +41,11 @@ fn process(name: &str, sql: &str, path: Option<&PathBuf>, cli: &Cli) -> Result