Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(config): route every user-file write through one atomic writer (#3591)

Maximilian Roos7562f7f29845
diff --git a/CLAUDE.md b/CLAUDE.md
index 4697583bf..2af8f3a2f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -58,6 +58,7 @@ Never risk data loss without explicit user consent. A failed command that preser
- **No implicit destructive side effects** — never silently delete/overwrite as a side effect of an unrelated operation; make cleanup a separate explicit action the user chooses.
- **Favor the failing variant on races** — `git reset --keep` (fails if tracked files were modified) over `--hard`; `git checkout --merge` over `--force`. If no safer variant exists, document the risk inline.
- **Time-of-check vs time-of-use** — be conservative when there's a gap between the safety check and the operation. `wt merge` verifies clean before rebasing, but files could appear before cleanup — don't force-remove during cleanup.
+- **Replace files, never truncate them** — `fs::write` truncates before it writes, so a crash mid-write leaves the file empty. Every write to a file worktrunk can't put back (rc files, shell wrappers, `config.toml`, `approvals.toml`, another tool's `settings.json`) goes through `utils::write_atomically`, which renames a sibling temp file over the target; the spec on that function covers symlinks, mode, and what a rename costs. Regenerable content (the cache, the `-vv` diagnostic report) keeps the plain write.
Full inventory: FAQ [What files does Worktrunk create?](docs/content/faq.md#what-files-does-worktrunk-create) and [What can Worktrunk delete?](docs/content/faq.md#what-can-worktrunk-delete). Review new code that changes this surface against those sections.
diff --git a/src/commands/config/create.rs b/src/commands/config/create.rs
index 69ce50398..436fe0ba9 100644
--- a/src/commands/config/create.rs
+++ b/src/commands/config/create.rs
@@ -126,7 +126,8 @@ fn create_config_file(
// Write the example config with all values commented out
let commented_config = comment_out_config(content);
- std::fs::write(&path, commented_config).context("Failed to write config file")?;
+ worktrunk::utils::write_atomically(&path, &commented_config)
+ .context("Failed to write config file")?;
// Success message
eprintln!(
diff --git a/src/commands/config/opencode.rs b/src/commands/config/opencode.rs
index 1fd3ab34d..9cf47b5e4 100644
--- a/src/commands/config/opencode.rs
+++ b/src/commands/config/opencode.rs
@@ -104,7 +104,7 @@ pub fn handle_opencode_install(yes: bool) -> Result<()> {
.with_context(|| format!("Failed to create directory {}", parent.display()))?;
// Write the plugin file
- std::fs::write(&target, PLUGIN_SOURCE)
+ worktrunk::utils::write_atomically(&target, PLUGIN_SOURCE)
.with_context(|| format!("Failed to write plugin to {target_display}"))?;
eprintln!(
diff --git a/src/commands/config/plugins.rs b/src/commands/config/plugins.rs
index 1d4d97e02..16758edf7 100644
--- a/src/commands/config/plugins.rs
+++ b/src/commands/config/plugins.rs
@@ -141,7 +141,8 @@ pub fn handle_claude_install_statusline(yes: bool) -> anyhow::Result<()> {
);
let json = serde_json::to_string_pretty(&settings).context("Failed to serialize settings")?;
- std::fs::write(&settings_path, json + "\n").context("Failed to write settings.json")?;
+ worktrunk::utils::write_atomically(&settings_path, &(json + "\n"))
+ .context("Failed to write settings.json")?;
eprintln!("{}", success_message("Statusline configured"));
diff --git a/src/commands/config/update.rs b/src/commands/config/update.rs
index db5d8332a..046e15f3e 100644
--- a/src/commands/config/update.rs
+++ b/src/commands/config/update.rs
@@ -111,7 +111,7 @@ pub fn handle_config_update(yes: bool, print: bool) -> anyhow::Result<()> {
);
}
- std::fs::write(&candidate.config_path, &candidate.migrated)
+ worktrunk::utils::write_atomically(&candidate.config_path, &candidate.migrated)
.with_context(|| format!("Failed to update {}", candidate.info.label()))?;
eprintln!(
"{}",
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index 93bf92241..366215fab 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -10,6 +10,7 @@ use worktrunk::styling::{
INFO_SYMBOL, SUCCESS_SYMBOL, eprint, eprintln, format_bash_with_gutter, format_toml,
format_with_gutter, hint_message, println, prompt_message, warning_message,
};
+use worktrunk::utils::write_atomically;
use crate::output::prompt::{PromptResponse, prompt_yes_no_preview};
use crate::output::shell_integration::shell_extension_label;
@@ -659,7 +660,7 @@ fn configure_shell_file(
}
// Write the config content
- fs::write(path, format!("{}\n", config_line)).map_err(|e| {
+ write_atomically(path, &format!("{}\n", config_line)).map_err(|e| {
format!(
"Failed to write to {}: {}",
format_path_for_display(path),
@@ -765,7 +766,7 @@ fn configure_wrapper_file(
}
// Write the complete wrapper file
- fs::write(path, format!("{}\n", content))
+ write_atomically(path, &format!("{}\n", content))
.map_err(|e| format!("Failed to write {}: {e}", format_path_for_display(path)))?;
Ok(Some(ConfigureResult {
@@ -1024,7 +1025,7 @@ pub fn process_shell_completions(
}
// Write the completion file
- fs::write(&completion_path, &fish_completion).map_err(|e| {
+ write_atomically(&completion_path, &fish_completion).map_err(|e| {
format!(
"Failed to write {}: {e}",
format_path_for_display(&completion_path)
@@ -1282,70 +1283,6 @@ fn scan_managed_files(
Ok(out)
}
-/// Replace a file's contents by renaming a sibling temp file over it.
-///
-/// `fs::write` truncates in place, so a crash, a full disk, or a lost power
-/// cable between the truncate and the write leaves the user's rc file empty or
-/// half-written — every line they ever added to it gone. Uninstall is the one
-/// place worktrunk rewrites a file whose other contents belong to the user, so
-/// it takes the rename path: the file is either entirely the old version or
-/// entirely the new one.
-///
-/// Three details a bare `NamedTempFile::new()` + `persist()` gets wrong:
-///
-/// - **Symlinks.** Dotfile managers (Mackup, chezmoi, stow) symlink `~/.zshrc`
-/// into a repo or a synced folder. `fs::write` follows the link and updates
-/// the real file; a rename would replace the link itself with a regular file
-/// and silently detach the user's setup. The target is resolved first, so the
-/// rename lands on the real file and the link survives.
-/// - **Same directory.** A temp file elsewhere (`/tmp`) means `persist` crosses
-/// a filesystem boundary, where it degrades to a copy — no longer atomic, and
-/// an outright failure on some setups. The temp file is created beside the
-/// resolved target.
-/// - **Mode.** A fresh temp file is `0600`; an rc file is typically `0644`. The
-/// target's mode is copied onto the temp file before the rename, so the
-/// permissions survive the replacement. Windows has no equivalent to carry.
-///
-/// Ownership is not preserved — the replacement belongs to the running user, so
-/// a root-run uninstall against another user's rc file would change its owner.
-/// Restoring it needs a `chown`, which no current dependency exposes.
-///
-/// Creating the temp file needs write access to the target's directory, which a
-/// truncating write did not, so uninstall now fails where a read-only directory
-/// holds a writable rc file. Failing is the trade Data Safety asks for: the rc
-/// file is left as it was, and the user can rerun once the directory is
-/// writable.
-fn replace_file_atomically(path: &Path, content: &str) -> Result<(), String> {
- let write_err =
- |e: io::Error| format!("Failed to write {}: {e}", format_path_for_display(path));
-
- let target = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
- let dir = target.parent().unwrap_or_else(|| Path::new("."));
-
- let mut temp = tempfile::Builder::new()
- .prefix(".wt-shell-config.")
- .suffix(".tmp")
- .tempfile_in(dir)
- .map_err(write_err)?;
- temp.write_all(content.as_bytes()).map_err(write_err)?;
- temp.flush().map_err(write_err)?;
-
- // Before the sync, so the mode lands on disk with the contents.
- #[cfg(unix)]
- if let Ok(metadata) = fs::metadata(&target) {
- use std::os::unix::fs::PermissionsExt;
- let mode = metadata.permissions().mode();
- temp.as_file()
- .set_permissions(fs::Permissions::from_mode(mode))
- .map_err(write_err)?;
- }
-
- temp.as_file().sync_all().map_err(write_err)?;
- temp.persist(&target).map_err(|e| write_err(e.error))?;
-
- Ok(())
-}
-
fn uninstall_from_file(
shell: Shell,
path: &Path,
@@ -1404,7 +1341,8 @@ fn uninstall_from_file(
new_content
};
- replace_file_atomically(path, &new_content)?;
+ write_atomically(path, &new_content)
+ .map_err(|e| format!("Failed to write {}: {e}", format_path_for_display(path)))?;
Ok(Some(UninstallResult {
shell,
diff --git a/src/config/approvals.rs b/src/config/approvals.rs
index 81eabf41f..c44679998 100644
--- a/src/config/approvals.rs
+++ b/src/config/approvals.rs
@@ -20,7 +20,6 @@
//! convenience.
use std::collections::BTreeMap;
-use std::io::Write;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
@@ -29,6 +28,7 @@ use super::ConfigError;
use crate::config::deprecation::normalize_template_vars;
use crate::path::format_path_for_display;
+use crate::utils::write_atomically;
/// Approved commands, stored in `approvals.toml`.
#[derive(Debug, Default, Serialize, Deserialize)]
@@ -202,7 +202,8 @@ impl Approvals {
output
};
- write_approvals_file(path, &output)?;
+ write_atomically(path, &output)
+ .map_err(|e| ConfigError(format!("Failed to write approvals file: {e}")))?;
Ok(())
}
@@ -214,28 +215,6 @@ fn save_parent(path: &Path) -> &Path {
.unwrap_or_else(|| Path::new("."))
}
-fn write_approvals_file(path: &Path, output: &str) -> Result<(), ConfigError> {
- let parent = save_parent(path);
- let mut temp = tempfile::Builder::new()
- .prefix(".approvals.")
- .suffix(".tmp")
- .tempfile_in(parent)
- .map_err(|e| ConfigError(format!("Failed to create temporary approvals file: {e}")))?;
-
- temp.write_all(output.as_bytes())
- .map_err(|e| ConfigError(format!("Failed to write temporary approvals file: {e}")))?;
- temp.flush()
- .map_err(|e| ConfigError(format!("Failed to flush temporary approvals file: {e}")))?;
- temp.as_file()
- .sync_all()
- .map_err(|e| ConfigError(format!("Failed to sync temporary approvals file: {e}")))?;
-
- temp.persist(path)
- .map_err(|e| ConfigError(format!("Failed to replace approvals file: {}", e.error)))?;
-
- Ok(())
-}
-
// =========================================================================
// Queries
// =========================================================================
@@ -691,9 +670,8 @@ mod tests {
);
let err = replacement.save_to(&path).unwrap_err();
assert!(
- err.to_string()
- .contains("Failed to create temporary approvals file"),
- "Expected temporary file creation error, got: {}",
+ err.to_string().contains("Failed to write approvals file"),
+ "Expected a write error, got: {}",
err
);
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index 5dbddc79e..fea0b7896 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -189,7 +189,7 @@ impl UserConfig {
doc.to_string()
};
- std::fs::write(config_path, toml_string)
+ crate::utils::write_atomically(config_path, &toml_string)
.map_err(|e| ConfigError(format!("Failed to write config file: {}", e)))?;
Ok(())
diff --git a/src/utils.rs b/src/utils.rs
index f8e88154a..7b654c393 100644
--- a/src/utils.rs
+++ b/src/utils.rs
@@ -1,6 +1,8 @@
//! General utilities.
use std::borrow::Cow;
+use std::io::{self, Write};
+use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
/// Replace C0/C1 control characters — other than tab and newline — with a
@@ -93,10 +95,115 @@ pub fn epoch_now() -> u64 {
})
}
+/// Replace `path`'s contents in one step: write a sibling temp file, sync it,
+/// then rename it over the target.
+///
+/// `fs::write` truncates in place, so a crash, a full disk, or a lost power
+/// cable between the truncate and the write leaves the file empty or
+/// half-written. Every file that reaches this function is one a torn write
+/// breaks — rc files and shell wrappers the user's shell sources at startup,
+/// `config.toml`, `approvals.toml`, another tool's `settings.json` — so it ends
+/// up either entirely the old version or entirely the new one. Regenerable
+/// content keeps the plain write ([`crate::cache::write_json`], the `-vv`
+/// diagnostic report): a torn write there costs a recompute, not the user's
+/// data.
+///
+/// Three details a bare `NamedTempFile::new()` + `persist()` gets wrong:
+///
+/// - **Symlinks.** Dotfile managers (Mackup, chezmoi, stow) symlink `~/.zshrc`
+/// or `~/.config/worktrunk` into a repo or a synced folder. `fs::write`
+/// follows the link and updates the real file; a rename would replace the
+/// link itself with a regular file and silently detach the user's setup. The
+/// target is resolved first, so the rename lands on the real file and the
+/// link survives. A dangling link has nothing to resolve to, so it is
+/// replaced by a regular file rather than followed to the missing path it
+/// names.
+/// - **Same directory.** A temp file elsewhere (`/tmp`) means `persist` crosses
+/// a filesystem boundary, where it degrades to a copy — no longer atomic, and
+/// an outright failure on some setups. The temp file is created beside the
+/// resolved target.
+/// - **Mode.** A fresh temp file is `0600`. An existing target's mode is copied
+/// onto the temp file before the rename, so permissions survive the
+/// replacement. A file that doesn't exist yet keeps the `0600`, narrower than
+/// the `0644` a truncating write leaves under a default umask; every file
+/// written here is read by its own owner. Windows has no equivalent to carry.
+///
+/// The target becomes a new inode, so ownership resets to the running user (a
+/// root-run rewrite of someone else's file hands it to root) and any hardlink
+/// to it keeps the old contents. The `atomic-write-file` crate carries owner
+/// and mode across, but replaces a symlink instead of writing through it,
+/// leaving the canonicalize step here either way; `atomicwrites` does neither.
+///
+/// The temp file needs a writable parent directory, which a truncating write
+/// did not, so a read-only directory holding a writable file now fails with the
+/// file left as it was — the trade Data Safety asks for.
+pub fn write_atomically(path: &Path, content: &str) -> io::Result<()> {
+ let target = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
+ // A bare filename's parent is `Some("")`, which no directory call accepts.
+ let dir = target
+ .parent()
+ .filter(|parent| !parent.as_os_str().is_empty())
+ .unwrap_or_else(|| Path::new("."));
+
+ let mut temp = tempfile::Builder::new()
+ .prefix(".wt-tmp.")
+ .suffix(".tmp")
+ .tempfile_in(dir)?;
+ temp.write_all(content.as_bytes())?;
+ temp.flush()?;
+
+ // Before the sync, so the mode lands on disk with the contents.
+ #[cfg(unix)]
+ if let Ok(metadata) = std::fs::metadata(&target) {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = metadata.permissions().mode();
+ temp.as_file()
+ .set_permissions(std::fs::Permissions::from_mode(mode))?;
+ }
+
+ temp.as_file().sync_all()?;
+ temp.persist(&target).map_err(|e| e.error)?;
+
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn test_write_atomically_creates_then_replaces() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("config.toml");
+
+ write_atomically(&path, "first\n").unwrap();
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "first\n");
+
+ write_atomically(&path, "second\n").unwrap();
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "second\n");
+
+ // The rename leaves no temp file behind.
+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
+ }
+
+ /// A file with no target to copy a mode from keeps the temp file's `0600`,
+ /// narrower than the `0644` a truncating write leaves under a default
+ /// umask.
+ #[cfg(unix)]
+ #[test]
+ fn test_write_atomically_creates_owner_only() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("new.toml");
+ write_atomically(&path, "x\n").unwrap();
+
+ assert_eq!(
+ std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ }
+
#[test]
fn test_epoch_now_returns_reasonable_timestamp() {
let now = epoch_now();