Skip to content

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

Refactor approvals into separate file with deprecation migration (#1042)

Maximilian Roos600da7101b94
diff --git a/dev/config.example.toml b/dev/config.example.toml
index cba2fbe42..b83ec64b9 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -92,12 +92,11 @@
#
# #### Approved hook commands
#
-# When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved here, preventing repeated prompts.
+# When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved to `~/.config/worktrunk/approvals.toml` (separate from user config to allow dotfile management of config.toml).
#
-# [projects."github.com/user/repo"]
-# approved-commands = ["npm ci", "npm test"]
+# To reset, run `wt hook approvals clear`.
#
-# To reset, delete the entry or run `wt hook approvals clear`.
+# > **Migration note:** Approvals were previously stored as `approved-commands` in config.toml. Run `wt config show` to generate a migration file that removes stale entries.
#
# #### Setting overrides (Experimental)
#
diff --git a/docs/content/config.md b/docs/content/config.md
index 163484ff8..1d9dc1b16 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -169,14 +169,11 @@ Entries are keyed by project identifier (e.g., `github.com/user/repo`).
#### Approved hook commands
-When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved here, preventing repeated prompts.
+When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved to `~/.config/worktrunk/approvals.toml` (separate from user config to allow dotfile management of config.toml).
-```toml
-[projects."github.com/user/repo"]
-approved-commands = ["npm ci", "npm test"]
-```
+To reset, run `wt hook approvals clear`.
-To reset, delete the entry or run `wt hook approvals clear`.
+> **Migration note:** Approvals were previously stored as `approved-commands` in config.toml. Run `wt config show` to generate a migration file that removes stale entries.
#### Setting overrides (Experimental)
diff --git a/docs/content/faq.md b/docs/content/faq.md
index c780961e5..364db3f9b 100644
--- a/docs/content/faq.md
+++ b/docs/content/faq.md
@@ -82,7 +82,8 @@ Created by `wt switch <branch>` when switching to a branch that doesn't have a w
| File | Created by | Purpose |
|------|------------|---------|
-| `~/.config/worktrunk/config.toml` | `wt config create`, or approving project commands | User preferences, approved commands |
+| `~/.config/worktrunk/config.toml` | `wt config create` | User preferences |
+| `~/.config/worktrunk/approvals.toml` | Approving project commands | Approved hook commands |
| `.config/wt.toml` | `wt config create --project` | Project hooks (checked into repo) |
User config location: `$XDG_CONFIG_HOME/worktrunk/` (or `~/.config/worktrunk/`) on Linux/macOS, `%APPDATA%\worktrunk\` on Windows.
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 695898afd..1c57b3121 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -475,7 +475,7 @@ wt hook approvals clear --global
### How approvals work
-Approved commands are saved to user config. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI.
+Approved commands are saved to `~/.config/worktrunk/approvals.toml`. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI.
### Command reference
@@ -485,8 +485,8 @@ wt hook approvals - Manage command approvals
Usage: <b><span class=c>wt hook approvals</span></b> <span class=c>[OPTIONS]</span> <span class=c>&lt;COMMAND&gt;</span>
<b><span class=g>Commands:</span></b>
- <b><span class=c>add</span></b> Store approvals in config
- <b><span class=c>clear</span></b> Clear approved commands from config
+ <b><span class=c>add</span></b> Store approvals in approvals.toml
+ <b><span class=c>clear</span></b> Clear approved commands from approvals.toml
<b><span class=g>Options:</span></b>
<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 6253b7384..0419bbe1c 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -161,14 +161,11 @@ Entries are keyed by project identifier (e.g., `github.com/user/repo`).
#### Approved hook commands
-When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved here, preventing repeated prompts.
+When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved to `~/.config/worktrunk/approvals.toml` (separate from user config to allow dotfile management of config.toml).
-```toml
-[projects."github.com/user/repo"]
-approved-commands = ["npm ci", "npm test"]
-```
+To reset, run `wt hook approvals clear`.
-To reset, delete the entry or run `wt hook approvals clear`.
+> **Migration note:** Approvals were previously stored as `approved-commands` in config.toml. Run `wt config show` to generate a migration file that removes stale entries.
#### Setting overrides (Experimental)
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 9fef99867..9964bad9c 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -76,7 +76,8 @@ Created by `wt switch <branch>` when switching to a branch that doesn't have a w
| File | Created by | Purpose |
|------|------------|---------|
-| `~/.config/worktrunk/config.toml` | `wt config create`, or approving project commands | User preferences, approved commands |
+| `~/.config/worktrunk/config.toml` | `wt config create` | User preferences |
+| `~/.config/worktrunk/approvals.toml` | Approving project commands | Approved hook commands |
| `.config/wt.toml` | `wt config create --project` | Project hooks (checked into repo) |
User config location: `$XDG_CONFIG_HOME/worktrunk/` (or `~/.config/worktrunk/`) on Linux/macOS, `%APPDATA%\worktrunk\` on Windows.
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index 65089abd4..34d716318 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -458,7 +458,7 @@ wt hook approvals clear --global
### How approvals work
-Approved commands are saved to user config. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI.
+Approved commands are saved to `~/.config/worktrunk/approvals.toml`. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI.
### Command reference
@@ -467,8 +467,8 @@ wt hook approvals - Manage command approvals
Usage: <b><span class=c>wt hook approvals</span></b> <span class=c>[OPTIONS]</span> <span class=c>&lt;COMMAND&gt;</span>
<b><span class=g>Commands:</span></b>
- <b><span class=c>add</span></b> Store approvals in config
- <b><span class=c>clear</span></b> Clear approved commands from config
+ <b><span class=c>add</span></b> Store approvals in approvals.toml
+ <b><span class=c>clear</span></b> Clear approved commands from approvals.toml
<b><span class=g>Options:</span></b>
<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
diff --git a/src/cli/config.rs b/src/cli/config.rs
index edf34b8d7..a75ad0540 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -156,9 +156,9 @@ Detects various forms of the integration pattern regardless of:
#[derive(Subcommand)]
pub enum ApprovalsCommand {
- /// Store approvals in config
+ /// Store approvals in approvals.toml
#[command(
- after_long_help = r#"Prompts for approval of all project commands and saves them to user config.
+ after_long_help = r#"Prompts for approval of all project commands and saves them to approvals.toml.
By default, shows only unapproved commands. Use `--all` to review all commands
including previously approved ones."#
@@ -169,7 +169,7 @@ including previously approved ones."#
all: bool,
},
- /// Clear approved commands from config
+ /// Clear approved commands from approvals.toml
#[command(
after_long_help = r#"Removes saved approvals, requiring re-approval on next command run.
diff --git a/src/cli/hook.rs b/src/cli/hook.rs
index 6368db065..dd24b823e 100644
--- a/src/cli/hook.rs
+++ b/src/cli/hook.rs
@@ -213,7 +213,7 @@ wt hook approvals clear --global
## How approvals work
-Approved commands are saved to user config. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI."#
+Approved commands are saved to `~/.config/worktrunk/approvals.toml`. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI."#
)]
Approvals {
#[command(subcommand)]
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index a174807e8..5ee5848f2 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1612,14 +1612,11 @@ Entries are keyed by project identifier (e.g., `github.com/user/repo`).
#### Approved hook commands
-When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved here, preventing repeated prompts.
+When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved to `~/.config/worktrunk/approvals.toml` (separate from user config to allow dotfile management of config.toml).
-```toml
-[projects."github.com/user/repo"]
-approved-commands = ["npm ci", "npm test"]
-```
+To reset, run `wt hook approvals clear`.
-To reset, delete the entry or run `wt hook approvals clear`.
+> **Migration note:** Approvals were previously stored as `approved-commands` in config.toml. Run `wt config show` to generate a migration file that removes stale entries.
#### Setting overrides (Experimental)
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 4a9d27949..8313f421e 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -22,7 +22,7 @@ use std::path::Path;
use anyhow::Context;
use color_print::cformat;
-use worktrunk::config::UserConfig;
+use worktrunk::config::Approvals;
use worktrunk::git::{GitError, HookType};
use worktrunk::styling::{
INFO_SYMBOL, WARNING_SYMBOL, eprint, eprintln, format_bash_with_gutter, hint_message,
@@ -44,7 +44,7 @@ use super::project_config::{HookCommand, collect_commands_for_hooks};
pub fn approve_command_batch(
commands: &[HookCommand],
project_id: &str,
- config: &UserConfig,
+ approvals: &Approvals,
yes: bool,
commands_already_filtered: bool,
) -> anyhow::Result<bool> {
@@ -52,7 +52,7 @@ pub fn approve_command_batch(
.iter()
.filter(|cmd| {
commands_already_filtered
- || !config.is_command_approved(project_id, &cmd.command.template)
+ || !approvals.is_command_approved(project_id, &cmd.command.template)
})
.collect();
@@ -72,27 +72,12 @@ pub fn approve_command_batch(
// Only save approvals when interactively approved, not when using --yes
if !yes {
- let mut fresh_config = UserConfig::load().context("Failed to reload config")?;
-
- let project_entry = fresh_config
- .projects
- .entry(project_id.to_string())
- .or_default();
-
- let mut updated = false;
- for cmd in &needs_approval {
- if !project_entry
- .approved_commands
- .contains(&cmd.command.template)
- {
- project_entry
- .approved_commands
- .push(cmd.command.template.clone());
- updated = true;
- }
- }
-
- if updated && let Err(e) = fresh_config.save() {
+ let mut fresh_approvals = Approvals::load().context("Failed to load approvals")?;
+ let commands: Vec<String> = needs_approval
+ .iter()
+ .map(|cmd| cmd.command.template.clone())
+ .collect();
+ if let Err(e) = fresh_approvals.approve_commands(project_id.to_string(), commands, None) {
eprintln!(
"{}",
warning_message(format!("Failed to save command approval: {e}"))
@@ -231,5 +216,6 @@ pub fn approve_hooks_filtered(
}
let project_id = ctx.repo.project_identifier()?;
- approve_command_batch(&commands, &project_id, ctx.config, ctx.yes, false)
+ let approvals = Approvals::load().context("Failed to load approvals")?;
+ approve_command_batch(&commands, &project_id, &approvals, ctx.yes, false)
}
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index c3a791476..3239bf14e 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -13,7 +13,7 @@ use anyhow::Context;
use color_print::cformat;
use strum::IntoEnumIterator;
use worktrunk::HookType;
-use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig};
+use worktrunk::config::{Approvals, CommandConfig, ProjectConfig, UserConfig};
use worktrunk::git::{GitError, Repository};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
@@ -326,7 +326,7 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
let repo = Repository::current()?;
let project_id = repo.project_identifier()?;
- let config = UserConfig::load().context("Failed to load config")?;
+ let approvals = Approvals::load().context("Failed to load approvals")?;
// Load project config (error if missing - this command requires it)
let config_path = repo
@@ -351,7 +351,7 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
let commands_to_approve = if !show_all {
let unapproved: Vec<_> = commands
.into_iter()
- .filter(|cmd| !config.is_command_approved(&project_id, &cmd.command.template))
+ .filter(|cmd| !approvals.is_command_approved(&project_id, &cmd.command.template))
.collect();
if unapproved.is_empty() {
@@ -368,7 +368,8 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
// When show_all=true, we've already included all commands in commands_to_approve
// When show_all=false, we've already filtered to unapproved commands
// So we pass skip_approval_filter=true to prevent double-filtering
- let approved = approve_command_batch(&commands_to_approve, &project_id, &config, false, true)?;
+ let approved =
+ approve_command_batch(&commands_to_approve, &project_id, &approvals, false, true)?;
// Show result
if approved {
@@ -382,35 +383,23 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
/// Handle `wt hook approvals clear` command - clear approved commands
pub fn clear_approvals(global: bool) -> anyhow::Result<()> {
- let mut config = UserConfig::load().context("Failed to load config")?;
+ let mut approvals = Approvals::load().context("Failed to load approvals")?;
if global {
- // Clear all approvals for all projects (preserving other per-project settings)
- let projects_with_approvals: Vec<String> = config
- .projects
- .iter()
- .filter(|(_, p)| !p.approved_commands.is_empty())
- .map(|(id, _)| id.clone())
- .collect();
+ // Count projects with approvals before clearing
+ let project_count = approvals
+ .projects()
+ .filter(|(_, cmds)| !cmds.is_empty())
+ .count();
- if projects_with_approvals.is_empty() {
+ if project_count == 0 {
eprintln!("{}", info_message("No approvals to clear"));
return Ok(());
}
- let project_count = projects_with_approvals.len();
-
- // Clear only approved_commands, preserve other settings
- for project_id in &projects_with_approvals {
- if let Some(project_config) = config.projects.get_mut(project_id) {
- project_config.approved_commands.clear();
- // Remove project entry only if it has no other settings
- if project_config.is_empty() {
- config.projects.remove(project_id);
- }
- }
- }
- config.save().context("Failed to save config")?;
+ approvals
+ .clear_all(None)
+ .context("Failed to clear approvals")?;
eprintln!(
"{}",
@@ -424,25 +413,19 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {
let repo = Repository::current()?;
let project_id = repo.project_identifier()?;
- // Check if project has any approvals (not just if it exists)
- let had_approvals = config
- .projects
- .get(&project_id)
- .is_some_and(|p| !p.approved_commands.is_empty());
+ // Count approvals before clearing
+ let approval_count = approvals
+ .projects()
+ .find(|(id, _)| *id == project_id)
+ .map(|(_, cmds)| cmds.len())
+ .unwrap_or(0);
- if !had_approvals {
+ if approval_count == 0 {
eprintln!("{}", info_message("No approvals to clear for this project"));
return Ok(());
}
- // Count approvals before removing
- let approval_count = config
- .projects
- .get(&project_id)
- .map(|p| p.approved_commands.len())
- .unwrap_or(0);
-
- config
+ approvals
.revoke_project(&project_id, None)
.context("Failed to clear project approvals")?;
@@ -464,6 +447,7 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyho
let repo = Repository::current()?;
let config = UserConfig::load().context("Failed to load user config")?;
+ let approvals = Approvals::load().context("Failed to load approvals")?;
let project_config = repo.load_project_config()?;
let project_id = repo.project_identifier().ok();
@@ -501,7 +485,7 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyho
&mut output,
&repo,
project_config.as_ref(),
- &config,
+ &approvals,
project_id.as_deref(),
filter,
ctx.as_ref(),
@@ -579,7 +563,7 @@ fn render_project_hooks(
out: &mut String,
repo: &Repository,
project_config: Option<&ProjectConfig>,
- user_config: &UserConfig,
+ approvals: &Approvals,
project_id: Option<&str>,
filter: Option<HookType>,
ctx: Option<&CommandContext>,
@@ -624,7 +608,7 @@ fn render_project_hooks(
if let Some(cfg) = hook_config {
has_any = true;
- render_hook_commands(out, hook_type, cfg, Some((user_config, project_id)), ctx)?;
+ render_hook_commands(out, hook_type, cfg, Some((approvals, project_id)), ctx)?;
}
}
@@ -640,8 +624,8 @@ fn render_hook_commands(
out: &mut String,
hook_type: HookType,
config: &CommandConfig,
- // For project hooks: (user_config, project_id) to check approval status
- approval_context: Option<(&UserConfig, Option<&str>)>,
+ // For project hooks: (approvals, project_id) to check approval status
+ approval_context: Option<(&Approvals, Option<&str>)>,
ctx: Option<&CommandContext>,
) -> anyhow::Result<()> {
let commands = config.commands();
@@ -657,8 +641,8 @@ fn render_hook_commands(
};
// Check approval status for project hooks
- let needs_approval = if let Some((user_config, Some(project_id))) = approval_context {
- !user_config.is_command_approved(project_id, &cmd.template)
+ let needs_approval = if let Some((approvals, Some(project_id))) = approval_context {
+ !approvals.is_command_approved(project_id, &cmd.template)
} else {
false
};
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 5eee90b03..417f283fa 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,6 +1,6 @@
use anyhow::Context;
use worktrunk::HookType;
-use worktrunk::config::UserConfig;
+use worktrunk::config::{Approvals, UserConfig};
use worktrunk::git::Repository;
use worktrunk::styling::{eprintln, info_message};
@@ -143,7 +143,8 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
collect_merge_commands(repo, commit, verify, remove_effective, squash_enabled)?;
// Approve all commands in a single batch (shows templates, not expanded values)
- let approved = approve_command_batch(&all_commands, &project_id, config, yes, false)?;
+ let approvals = Approvals::load().context("Failed to load approvals")?;
+ let approved = approve_command_batch(&all_commands, &project_id, &approvals, yes, false)?;
// If commands were declined, skip hooks but continue with merge
// Shadow verify to gate all subsequent hook execution on approval
diff --git a/src/config/approvals.rs b/src/config/approvals.rs
new file mode 100644
index 000000000..8449d3753
--- /dev/null
+++ b/src/config/approvals.rs
@@ -0,0 +1,809 @@
+//! Approval state management.
+//!
+//! Approved commands are stored in `~/.config/worktrunk/approvals.toml`, separate
+//! from portable user configuration in `config.toml`. This allows dotfile management
+//! of config.toml without machine-local trust state.
+//!
+//! File format:
+//! ```toml
+//! [projects."github.com/user/repo"]
+//! approved-commands = [
+//! "npm install",
+//! "npm test",
+//! ]
+//! ```
+//!
+//! **Fallback**: When `approvals.toml` doesn't exist, `approved-commands` are
+//! silently read from `config.toml` for backward compatibility. Once any approval
+//! is saved (creating `approvals.toml`), it becomes the authoritative source.
+//! Users can then remove stale `approved-commands` from `config.toml` at their
+//! convenience.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use config::ConfigError;
+use serde::{Deserialize, Serialize};
+
+use crate::config::deprecation::normalize_template_vars;
+use crate::path::format_path_for_display;
+
+/// Approved commands, stored in `approvals.toml`.
+#[derive(Debug, Default, Serialize, Deserialize)]
+pub struct Approvals {
+ #[serde(default)]
+ projects: BTreeMap<String, ApprovedProject>,
+}
+
+/// Per-project approved commands.
+#[derive(Debug, Default, Serialize, Deserialize, Clone)]
+struct ApprovedProject {
+ #[serde(
+ default,
+ rename = "approved-commands",
+ skip_serializing_if = "Vec::is_empty"
+ )]
+ approved_commands: Vec<String>,
+}
+
+// =========================================================================
+// Path resolution
+// =========================================================================
+
+/// Get the approvals file path.
+///
+/// Priority:
+/// 1. `WORKTRUNK_APPROVALS_PATH` environment variable
+/// 2. In test builds: panic if env var not set
+/// 3. Production: sibling of config.toml (`approvals.toml` in same directory)
+pub fn get_approvals_path() -> Option<PathBuf> {
+ if let Ok(path) = std::env::var("WORKTRUNK_APPROVALS_PATH") {
+ return Some(PathBuf::from(path));
+ }
+
+ #[cfg(test)]
+ panic!(
+ "WORKTRUNK_APPROVALS_PATH not set in test. Tests must use TestRepo which sets this \
+ automatically, or set it manually to an isolated test approvals path."
+ );
+
+ #[cfg(not(test))]
+ {
+ super::user::get_config_path().map(|p| p.with_file_name("approvals.toml"))
+ }
+}
+
+// =========================================================================
+// Loading
+// =========================================================================
+
+impl Approvals {
+ /// Load approvals from `approvals.toml`, with silent fallback to `config.toml`.
+ ///
+ /// 1. If `approvals.toml` exists → load from it (authoritative)
+ /// 2. If not → silently read `approved-commands` from `config.toml`
+ /// 3. If none found → return empty
+ ///
+ /// The fallback is silent (no file writes, no warnings). Once any approval is
+ /// saved via mutation methods, `approvals.toml` is created and becomes the
+ /// source of truth. Users can clean up stale `approved-commands` in config.toml
+ /// at their convenience.
+ pub fn load() -> Result<Self, ConfigError> {
+ let Some(path) = get_approvals_path() else {
+ return Ok(Self::default());
+ };
+
+ Self::load_with_fallback(&path)
+ }
+
+ /// Load approvals from a specific file path.
+ fn load_from_file(path: &Path) -> Result<Self, ConfigError> {
+ let content = std::fs::read_to_string(path).map_err(|e| {
+ ConfigError::Message(format!(
+ "Failed to read approvals file {}: {}",
+ format_path_for_display(path),
+ e
+ ))
+ })?;
+ let approvals: Self = toml::from_str(&content).map_err(|e| {
+ ConfigError::Message(format!(
+ "Failed to parse approvals file {}: {}",
+ format_path_for_display(path),
+ e
+ ))
+ })?;
+ Ok(approvals)
+ }
+
+ /// Load approvals from a specific path (no fallback, for testing).
+ #[cfg(test)]
+ pub fn load_from_path(path: &Path) -> Result<Self, ConfigError> {
+ if !path.exists() {
+ return Ok(Self::default());
+ }
+ Self::load_from_file(path)
+ }
+
+ /// Load approvals from an approvals file, falling back to config.toml.
+ ///
+ /// 1. If the approvals file exists → load from it (authoritative)
+ /// 2. If not → read `approved-commands` from sibling `config.toml`
+ /// 3. If neither exists → return empty
+ ///
+ /// The fallback uses sibling derivation (`path.with_file_name("config.toml")`)
+ /// which is correct because `get_approvals_path()` derives approvals.toml as
+ /// a sibling of config.toml.
+ fn load_with_fallback(path: &Path) -> Result<Self, ConfigError> {
+ if path.exists() {
+ return Self::load_from_file(path);
+ }
+
+ let config_path = path.with_file_name("config.toml");
+ if config_path.exists() {
+ return Self::load_from_config_file(&config_path);
+ }
+
+ Ok(Self::default())
+ }
+}
+
+// =========================================================================
+// Saving
+// =========================================================================
+
+impl Approvals {
+ /// Save approvals to a specific file path.
+ pub fn save_to(&self, path: &Path) -> Result<(), ConfigError> {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| {
+ ConfigError::Message(format!("Failed to create approvals directory: {e}"))
+ })?;
+ }
+
+ let mut doc = toml_edit::DocumentMut::new();
+
+ if !self.projects.is_empty() {
+ let mut projects_table = toml_edit::Table::new();
+ projects_table.set_implicit(true);
+
+ for (project_id, project_config) in &self.projects {
+ if project_config.approved_commands.is_empty() {
+ continue;
+ }
+ let mut project_table = toml_edit::Table::new();
+ let commands = format_multiline_array(project_config.approved_commands.iter());
+ project_table["approved-commands"] = toml_edit::value(commands);
+ projects_table[project_id] = toml_edit::Item::Table(project_table);
+ }
+
+ doc["projects"] = toml_edit::Item::Table(projects_table);
+ }
+
+ let output = doc.to_string();
+ // If all projects were empty, write empty file
+ let output = if output.trim().is_empty() {
+ String::new()
+ } else {
+ output
+ };
+
+ std::fs::write(path, output)
+ .map_err(|e| ConfigError::Message(format!("Failed to write approvals file: {e}")))?;
+
+ Ok(())
+ }
+}
+
+// =========================================================================
+// Queries
+// =========================================================================
+
+impl Approvals {
+ /// Check if a command is approved for the given project.
+ ///
+ /// Normalizes template variables before comparing, so approvals match
+ /// regardless of whether they were saved with deprecated variable names.
+ pub fn is_command_approved(&self, project: &str, command: &str) -> bool {
+ let normalized_command = normalize_template_vars(command);
+ self.projects
+ .get(project)
+ .map(|p| {
+ p.approved_commands
+ .iter()
+ .any(|c| normalize_template_vars(c) == normalized_command)
+ })
+ .unwrap_or(false)
+ }
+
+ /// Iterate over projects and their approved commands.
+ pub fn projects(&self) -> impl Iterator<Item = (&str, &[String])> {
+ self.projects
+ .iter()
+ .map(|(id, p)| (id.as_str(), p.approved_commands.as_slice()))
+ }
+}
+
+// =========================================================================
+// Mutations (with file locking)
+// =========================================================================
+
+impl Approvals {
+ /// Execute a mutation under an exclusive file lock.
+ ///
+ /// Acquires lock, reloads from disk, calls the mutator, and saves if mutator returns true.
+ fn with_locked_mutation<F>(
+ &mut self,
+ approvals_path: Option<&Path>,
+ mutate: F,
+ ) -> Result<(), ConfigError>
+ where
+ F: FnOnce(&mut Self) -> bool,
+ {
+ let path = match approvals_path {
+ Some(p) => p.to_path_buf(),
+ None => get_approvals_path().ok_or_else(|| {
+ ConfigError::Message(
+ "Cannot determine approvals path. Set $HOME or $XDG_CONFIG_HOME".to_string(),
+ )
+ })?,
+ };
+ let _lock = super::user::mutation::acquire_config_lock(&path)?;
+ self.reload_from(&path)?;
+
+ if mutate(self) {
+ self.save_to(&path)?;
+ }
+ Ok(())
+ }
+
+ /// Reload approvals from disk (under lock), with config.toml fallback.
+ fn reload_from(&mut self, path: &Path) -> Result<(), ConfigError> {
+ let fresh = Self::load_with_fallback(path)?;
+ self.projects = fresh.projects;
+ Ok(())
+ }
+
+ /// Extract approved-commands from a specific config file.
+ fn load_from_config_file(config_path: &Path) -> Result<Self, ConfigError> {
+ let content = std::fs::read_to_string(config_path).map_err(|e| {
+ ConfigError::Message(format!(
+ "Failed to read config file {}: {}",
+ format_path_for_display(config_path),
+ e
+ ))
+ })?;
+
+ let config: super::UserConfig = toml::from_str(&content).map_err(|e| {
+ ConfigError::Message(format!(
+ "Failed to parse config file {}: {}",
+ format_path_for_display(config_path),
+ e
+ ))
+ })?;
+
+ let mut approvals = Approvals::default();
+ for (project_id, project_config) in &config.projects {
+ if !project_config.approved_commands.is_empty() {
+ approvals.projects.insert(
+ project_id.clone(),
+ ApprovedProject {
+ approved_commands: project_config.approved_commands.clone(),
+ },
+ );
+ }
+ }
+
+ Ok(approvals)
+ }
+
+ /// Add an approved command and save.
+ pub fn approve_command(
+ &mut self,
+ project: String,
+ command: String,
+ approvals_path: Option<&Path>,
+ ) -> Result<(), ConfigError> {
+ self.with_locked_mutation(approvals_path, |approvals| {
+ if approvals.is_command_approved(&project, &command) {
+ return false;
+ }
+ approvals
+ .projects
+ .entry(project)
+ .or_default()
+ .approved_commands
+ .push(command);
+ true
+ })
+ }
+
+ /// Add multiple approved commands in a single locked operation.
+ pub fn approve_commands(
+ &mut self,
+ project: String,
+ commands: Vec<String>,
+ approvals_path: Option<&Path>,
+ ) -> Result<(), ConfigError> {
+ self.with_locked_mutation(approvals_path, |approvals| {
+ let entry = approvals.projects.entry(project).or_default();
+ let mut changed = false;
+ for command in commands {
+ let normalized = normalize_template_vars(&command);
+ if !entry
+ .approved_commands
+ .iter()
+ .any(|c| normalize_template_vars(c) == normalized)
+ {
+ entry.approved_commands.push(command);
+ changed = true;
+ }
+ }
+ changed
+ })
+ }
+
+ /// Remove all approvals for a project and save.
+ pub fn revoke_project(
+ &mut self,
+ project: &str,
+ approvals_path: Option<&Path>,
+ ) -> Result<(), ConfigError> {
+ let project = project.to_string();
+ self.with_locked_mutation(approvals_path, |approvals| {
+ let Some(project_config) = approvals.projects.get_mut(&project) else {
+ return false;
+ };
+ if project_config.approved_commands.is_empty() {
+ return false;
+ }
+ approvals.projects.remove(&project);
+ true
+ })
+ }
+
+ /// Clear all approvals for all projects and save.
+ pub fn clear_all(&mut self, approvals_path: Option<&Path>) -> Result<(), ConfigError> {
+ self.with_locked_mutation(approvals_path, |approvals| {
+ if approvals.projects.is_empty() {
+ return false;
+ }
+ approvals.projects.clear();
+ true
+ })
+ }
+}
+
+// =========================================================================
+// TOML formatting helpers
+// =========================================================================
+
+/// Format a string array as multiline TOML for readability.
+fn format_multiline_array<'a>(items: impl Iterator<Item = &'a String>) -> toml_edit::Array {
+ let mut array: toml_edit::Array = items.collect();
+ for item in array.iter_mut() {
+ item.decor_mut().set_prefix("\n ");
+ }
+ array.set_trailing("\n");
+ array.set_trailing_comma(true);
+ array
+}
+
+// =========================================================================
+// Tests
+// =========================================================================
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+
+ fn test_dir() -> (TempDir, PathBuf) {
+ let temp_dir = TempDir::new().unwrap();
+ let approvals_path = temp_dir.path().join("approvals.toml");
+ (temp_dir, approvals_path)
+ }
+
+ #[test]
+ fn test_empty_approvals() {
+ let approvals = Approvals::default();
+ assert!(!approvals.is_command_approved("any/project", "any command"));
+ }
+
+ #[test]
+ fn test_approve_and_check() {
+ let (_temp_dir, path) = test_dir();
+
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_command(
+ "github.com/user/repo".to_string(),
+ "npm install".to_string(),
+ Some(&path),
+ )
+ .unwrap();
+
+ assert!(approvals.is_command_approved("github.com/user/repo", "npm install"));
+ assert!(!approvals.is_command_approved("github.com/user/repo", "npm test"));
+ assert!(!approvals.is_command_approved("github.com/other/repo", "npm install"));
+ }
+
+ #[test]
+ fn test_approve_duplicate_is_noop() {
+ let (_temp_dir, path) = test_dir();
+
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_command(
+ "github.com/user/repo".to_string(),
+ "npm install".to_string(),
+ Some(&path),
+ )
+ .unwrap();
+ approvals
+ .approve_command(
+ "github.com/user/repo".to_string(),
+ "npm install".to_string(),
+ Some(&path),
+ )
+ .unwrap();
+
+ let count = approvals
+ .projects
+ .get("github.com/user/repo")
+ .unwrap()
+ .approved_commands
+ .len();
+ assert_eq!(count, 1);
+ }
+
+ #[test]
+ fn test_approve_commands_batch() {
+ let (_temp_dir, path) = test_dir();
+
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_commands(
+ "github.com/user/repo".to_string(),
+ vec!["npm install".to_string(), "npm test".to_string()],
+ Some(&path),
+ )
+ .unwrap();
+
+ assert!(approvals.is_command_approved("github.com/user/repo", "npm install"));
+ assert!(approvals.is_command_approved("github.com/user/repo", "npm test"));
+ }
+
+ #[test]
+ fn test_revoke_project() {
+ let (_temp_dir, path) = test_dir();
+
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_commands(
+ "github.com/user/repo1".to_string(),
+ vec!["npm install".to_string(), "npm test".to_string()],
+ Some(&path),
+ )
+ .unwrap();
+ approvals
+ .approve_command(
+ "github.com/user/repo2".to_string(),
+ "cargo build".to_string(),
+ Some(&path),
+ )
+ .unwrap();
+
+ approvals
+ .revoke_project("github.com/user/repo1", Some(&path))
+ .unwrap();
+ assert!(!approvals.projects.contains_key("github.com/user/repo1"));
+ assert!(approvals.projects.contains_key("github.com/user/repo2"));
+ }
+
+ #[test]
+ fn test_clear_all() {
+ let (_temp_dir, path) = test_dir();
+
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_command(
+ "github.com/user/repo1".to_string(),
+ "npm install".to_string(),
+ Some(&path),
+ )
+ .unwrap();
+ approvals
+ .approve_command(
+ "github.com/user/repo2".to_string(),
+ "cargo build".to_string(),
+ Some(&path),
+ )
+ .unwrap();
+
+ approvals.clear_all(Some(&path)).unwrap();
+ assert!(approvals.projects.is_empty());
+ }
+
+ #[test]
+ fn test_save_and_load() {
+ let (_temp_dir, path) = test_dir();
+
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_commands(
+ "github.com/user/repo".to_string(),
+ vec!["npm install".to_string(), "npm test".to_string()],
+ Some(&path),
+ )
+ .unwrap();
+
+ // Load from disk
+ let loaded = Approvals::load_from_path(&path).unwrap();
+ assert!(loaded.is_command_approved("github.com/user/repo", "npm install"));
+ assert!(loaded.is_command_approved("github.com/user/repo", "npm test"));
+ }
+
+ #[test]
+ fn test_save_format() {
+ let (_temp_dir, path) = test_dir();
+
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_commands(
+ "github.com/user/repo".to_string(),
+ vec!["npm install".to_string(), "npm test".to_string()],
+ Some(&path),
+ )
+ .unwrap();
+
+ let content = std::fs::read_to_string(&path).unwrap();
+ insta::assert_snapshot!(content, @r#"
+ [projects."github.com/user/repo"]
+ approved-commands = [
+ "npm install",
+ "npm test",
+ ]
+ "#);
+ }
+
+ #[test]
+ fn test_normalized_approval_matching() {
+ let (_temp_dir, path) = test_dir();
+
+ let mut approvals = Approvals::default();
+ // Approve with deprecated variable name
+ approvals
+ .approve_command(
+ "project".to_string(),
+ "echo {{ repo_root }}".to_string(),
+ Some(&path),
+ )
+ .unwrap();
+
+ // Should match with canonical variable name
+ assert!(approvals.is_command_approved("project", "echo {{ repo_path }}"));
+ }
+
+ #[test]
+ fn test_concurrent_approve_preserves_all() {
+ use std::sync::{Arc, Barrier};
+ use std::thread;
+
+ let (_temp_dir, path) = test_dir();
+
+ let num_threads = 10;
+ let barrier = Arc::new(Barrier::new(num_threads));
+ let config_path = Arc::new(path);
+
+ let handles: Vec<_> = (0..num_threads)
+ .map(|i| {
+ let barrier = Arc::clone(&barrier);
+ let config_path = Arc::clone(&config_path);
+ thread::spawn(move || {
+ let mut approvals = Approvals::default();
+ barrier.wait();
+ approvals
+ .approve_command(
+ "github.com/user/repo".to_string(),
+ format!("command_{i}"),
+ Some(&config_path),
+ )
+ .unwrap();
+ })
+ })
+ .collect();
+
+ for handle in handles {
+ handle.join().unwrap();
+ }
+
+ let content = std::fs::read_to_string(&*config_path).unwrap();
+ for i in 0..num_threads {
+ assert!(
+ content.contains(&format!("command_{i}")),
+ "command_{i} should be preserved"
+ );
+ }
+ }
+
+ /// `load_from_config_file` extracts approved-commands from a config.toml file.
+ #[test]
+ fn test_load_from_config_file() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("config.toml");
+
+ std::fs::write(
+ &config_path,
+ r#"
+[projects."github.com/user/repo"]
+approved-commands = ["npm install", "npm test"]
+
+[projects."github.com/other/repo"]
+approved-commands = ["cargo build"]
+"#,
+ )
+ .unwrap();
+
+ let approvals = Approvals::load_from_config_file(&config_path).unwrap();
+ assert!(approvals.is_command_approved("github.com/user/repo", "npm install"));
+ assert!(approvals.is_command_approved("github.com/user/repo", "npm test"));
+ assert!(approvals.is_command_approved("github.com/other/repo", "cargo build"));
+ }
+
+ /// When `approvals.toml` doesn't exist but `config.toml` is a sibling with
+ /// `approved-commands`, the first mutation reads the fallback and preserves
+ /// existing commands alongside the new one.
+ #[test]
+ fn test_mutation_picks_up_config_toml_fallback() {
+ let temp_dir = TempDir::new().unwrap();
+ let approvals_path = temp_dir.path().join("approvals.toml");
+ let config_path = temp_dir.path().join("config.toml");
+
+ // Write config.toml with existing approved-commands (no approvals.toml yet)
+ std::fs::write(
+ &config_path,
+ r#"
+[projects."github.com/user/repo"]
+approved-commands = ["npm install"]
+"#,
+ )
+ .unwrap();
+
+ // Approve a new command — reload_from should pick up config.toml fallback
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_command(
+ "github.com/user/repo".to_string(),
+ "npm test".to_string(),
+ Some(&approvals_path),
+ )
+ .unwrap();
+
+ // Both the fallback command and the new one should be present
+ assert!(approvals.is_command_approved("github.com/user/repo", "npm install"));
+ assert!(approvals.is_command_approved("github.com/user/repo", "npm test"));
+
+ // approvals.toml should now exist with both commands
+ let content = std::fs::read_to_string(&approvals_path).unwrap();
+ assert!(content.contains("npm install"));
+ assert!(content.contains("npm test"));
+ }
+
+ #[test]
+ fn test_load_from_path_nonexistent() {
+ let temp_dir = TempDir::new().unwrap();
+ let path = temp_dir.path().join("nonexistent.toml");
+ let approvals = Approvals::load_from_path(&path).unwrap();
+ assert!(approvals.projects.is_empty());
+ }
+
+ #[test]
+ fn test_load_from_file_invalid_toml() {
+ let temp_dir = TempDir::new().unwrap();
+ let path = temp_dir.path().join("approvals.toml");
+ std::fs::write(&path, "this is { not valid toml").unwrap();
+ let err = Approvals::load_from_file(&path).unwrap_err();
+ assert!(
+ err.to_string().contains("Failed to parse approvals file"),
+ "Expected parse error, got: {}",
+ err
+ );
+ }
+
+ #[test]
+ fn test_load_from_config_file_invalid_toml() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("config.toml");
+ std::fs::write(&config_path, "not { valid toml here").unwrap();
+ let err = Approvals::load_from_config_file(&config_path).unwrap_err();
+ assert!(
+ err.to_string().contains("Failed to parse config file"),
+ "Expected parse error, got: {}",
+ err
+ );
+ }
+
+ #[test]
+ fn test_revoke_project_nonexistent() {
+ let (_temp_dir, path) = test_dir();
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_command("project-a".to_string(), "cmd1".to_string(), Some(&path))
+ .unwrap();
+ // Revoke a project that doesn't exist — should be a no-op
+ approvals
+ .revoke_project("nonexistent", Some(&path))
+ .unwrap();
+ assert!(approvals.is_command_approved("project-a", "cmd1"));
+ }
+
+ #[test]
+ fn test_clear_all_when_empty() {
+ let (_temp_dir, path) = test_dir();
+ let mut approvals = Approvals::default();
+ // Clear when there's nothing — should be a no-op
+ approvals.clear_all(Some(&path)).unwrap();
+ assert!(approvals.projects.is_empty());
+ }
+
+ #[test]
+ fn test_save_skips_empty_project() {
+ let (_temp_dir, path) = test_dir();
+ let mut approvals = Approvals::default();
+ // Manually insert a project with empty commands
+ approvals.projects.insert(
+ "empty-project".to_string(),
+ super::ApprovedProject {
+ approved_commands: vec![],
+ },
+ );
+ approvals.projects.insert(
+ "real-project".to_string(),
+ super::ApprovedProject {
+ approved_commands: vec!["cmd1".to_string()],
+ },
+ );
+ // Call save_to directly so the empty project reaches the save logic
+ approvals.save_to(&path).unwrap();
+
+ let content = std::fs::read_to_string(&path).unwrap();
+ assert!(!content.contains("empty-project"));
+ assert!(content.contains("real-project"));
+ }
+
+ #[test]
+ fn test_revoke_project_with_empty_commands() {
+ let (_temp_dir, path) = test_dir();
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_command("project-a".to_string(), "cmd1".to_string(), Some(&path))
+ .unwrap();
+ // Manually clear the commands (without removing the project entry)
+ approvals
+ .projects
+ .get_mut("project-a")
+ .unwrap()
+ .approved_commands
+ .clear();
+ // Write this state to disk
+ approvals.save_to(&path).unwrap();
+ // Now revoke_project should find the project but see empty commands → no-op
+ approvals.revoke_project("project-a", Some(&path)).unwrap();
+ }
+
+ #[test]
+ fn test_projects_accessor() {
+ let (_temp_dir, path) = test_dir();
+
+ let mut approvals = Approvals::default();
+ approvals
+ .approve_command("project1".to_string(), "cmd1".to_string(), Some(&path))
+ .unwrap();
+ approvals
+ .approve_command("project2".to_string(), "cmd2".to_string(), Some(&path))
+ .unwrap();
+
+ let projects: Vec<_> = approvals.projects().collect();
+ assert_eq!(projects.len(), 2);
+ }
+}
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index 6fe5b0e47..f8940fd16 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -2,8 +2,9 @@
//!
//! Scans config files for deprecated patterns and generates migration files:
//! - Deprecated template variables (repo_root → repo_path, etc.)
-//! - Deprecated config sections ([commit-generation] → [commit.generation])
+//! - Deprecated config sections (\[commit-generation\] → \[commit.generation\])
//! - Deprecated fields (args merged into command)
+//! - Deprecated approved-commands in \[projects\] (moved to approvals.toml)
//!
//! Migration file write behavior:
//! - First time a deprecation is detected: file is written automatically
@@ -183,12 +184,14 @@ pub struct Deprecations {
pub vars: Vec<(&'static str, &'static str)>,
/// Deprecated commit-generation sections found
pub commit_gen: CommitGenerationDeprecations,
+ /// Has `approved-commands` in any `[projects."..."]` section (moved to approvals.toml)
+ pub approved_commands: bool,
}
impl Deprecations {
/// Returns true if any deprecations were found
pub fn is_empty(&self) -> bool {
- self.vars.is_empty() && self.commit_gen.is_empty()
+ self.vars.is_empty() && self.commit_gen.is_empty() && !self.approved_commands
}
}
@@ -200,9 +203,34 @@ pub fn detect_deprecations(content: &str) -> Deprecations {
Deprecations {
vars: find_deprecated_vars(content),
commit_gen: find_commit_generation_deprecations(content),
+ approved_commands: find_approved_commands_deprecation(content),
}
}
+/// Check if any `[projects."..."]` section has a non-empty `approved-commands` array.
+///
+/// These have moved to `approvals.toml` and should be removed from config.toml.
+pub fn find_approved_commands_deprecation(content: &str) -> bool {
+ let Ok(doc) = content.parse::<toml_edit::DocumentMut>() else {
+ return false;
+ };
+
+ let Some(projects) = doc.get("projects").and_then(|p| p.as_table()) else {
+ return false;
+ };
+
+ for (_project_key, project_value) in projects.iter() {
+ if let Some(project_table) = project_value.as_table()
+ && let Some(approved) = project_table.get("approved-commands")
+ && approved.as_array().is_some_and(|a| !a.is_empty())
+ {
+ return true;
+ }
+ }
+
+ false
+}
+
/// Find deprecated [commit-generation] sections in config
///
/// Returns information about:
@@ -374,6 +402,66 @@ pub fn migrate_commit_generation_sections(content: &str) -> String {
}
}
+/// Remove `approved-commands` from all `\[projects."..."\]` sections.
+///
+/// For each project section, removes the `approved-commands` key.
+/// If a project section becomes empty after removal, removes the project entry.
+/// If the `\[projects\]` table becomes empty, removes it.
+pub fn remove_approved_commands_from_config(content: &str) -> String {
+ let Ok(mut doc) = content.parse::<toml_edit::DocumentMut>() else {
+ return content.to_string();
+ };
+
+ let mut modified = false;
+
+ if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
+ // Collect project keys that should have approved-commands removed
+ let mut remove_from: Vec<String> = Vec::new();
+ let mut emptied: Vec<String> = Vec::new();
+
+ for (project_key, project_value) in projects.iter() {
+ if let Some(project_table) = project_value.as_table()
+ && project_table.contains_key("approved-commands")
+ {
+ remove_from.push(project_key.to_string());
+ // Will be empty after removal if approved-commands is the only key
+ if project_table.len() == 1 {
+ emptied.push(project_key.to_string());
+ }
+ }
+ }
+
+ for key in &remove_from {
+ if let Some(project_value) = projects.get_mut(key)
+ && let Some(project_table) = project_value.as_table_mut()
+ {
+ project_table.remove("approved-commands");
+ modified = true;
+ }
+ }
+
+ for key in &emptied {
+ projects.remove(key);
+ }
+ }
+
+ // Remove empty [projects] table
+ if doc
+ .get("projects")
+ .and_then(|p| p.as_table())
+ .is_some_and(|t| t.is_empty())
+ {
+ doc.remove("projects");
+ modified = true;
+ }
+
+ if modified {
+ doc.to_string()
+ } else {
+ content.to_string()
+ }
+}
+
/// Merge args array into command string
///
/// Converts: command = "llm", args = ["-m", "haiku"]
@@ -456,6 +544,7 @@ impl DeprecationInfo {
/// - Deprecated template variables (repo_root → repo_path, etc.)
/// - Deprecated [commit-generation] sections → [commit.generation]
/// - Deprecated args field (merged into command)
+/// - Deprecated approved-commands in \[projects\] (moved to approvals.toml)
///
/// If deprecations are found and `warn_and_migrate` is true:
/// 1. Emits warnings listing the deprecated patterns
@@ -627,6 +716,9 @@ pub fn write_migration_file(
if !deprecations.commit_gen.is_empty() {
new_content = migrate_commit_generation_sections(&new_content);
}
+ if deprecations.approved_commands {
+ new_content = remove_approved_commands_from_config(&new_content);
+ }
if let Err(e) = std::fs::write(&new_path, &new_content) {
// Log write failure but don't block config loading
@@ -713,6 +805,17 @@ pub fn format_deprecation_details(info: &DeprecationInfo) -> String {
);
}
+ if info.deprecations.approved_commands {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message(format!(
+ "{} has approved-commands in [projects] sections (moved to approvals.toml)",
+ info.label
+ ))
+ );
+ }
+
// Migration hint with apply command
if let Some(new_path) = &info.migration_path {
let new_filename = new_path
@@ -1751,6 +1854,201 @@ branches = true
insta::assert_snapshot!(migration_diff(content, &result));
}
+ // Tests for approved-commands deprecation detection
+
+ #[test]
+ fn test_find_approved_commands_deprecation_none() {
+ let content = r#"
+[commit.generation]
+command = "llm -m haiku"
+"#;
+ assert!(!find_approved_commands_deprecation(content));
+ }
+
+ #[test]
+ fn test_find_approved_commands_deprecation_present() {
+ let content = r#"
+[projects."github.com/user/repo"]
+approved-commands = ["npm install", "npm test"]
+"#;
+ assert!(find_approved_commands_deprecation(content));
+ }
+
+ #[test]
+ fn test_find_approved_commands_deprecation_empty_array() {
+ let content = r#"
+[projects."github.com/user/repo"]
+approved-commands = []
+"#;
+ assert!(!find_approved_commands_deprecation(content));
+ }
+
+ #[test]
+ fn test_find_approved_commands_deprecation_no_projects() {
+ let content = r#"
+worktree-path = "../{{ repo }}.{{ branch }}"
+"#;
+ assert!(!find_approved_commands_deprecation(content));
+ }
+
+ #[test]
+ fn test_find_approved_commands_deprecation_project_without_approvals() {
+ let content = r#"
+[projects."github.com/user/repo"]
+worktree-path = ".worktrees/{{ branch | sanitize }}"
+"#;
+ assert!(!find_approved_commands_deprecation(content));
+ }
+
+ // Tests for remove_approved_commands_from_config
+
+ #[test]
+ fn test_remove_approved_commands_simple() {
+ let content = r#"
+[projects."github.com/user/repo"]
+approved-commands = ["npm install", "npm test"]
+"#;
+ let result = remove_approved_commands_from_config(content);
+ assert!(!result.contains("approved-commands"));
+ // Empty project section and empty projects table should be removed
+ assert!(!result.contains("[projects"));
+ }
+
+ #[test]
+ fn test_remove_approved_commands_preserves_other_fields() {
+ let content = r#"
+[projects."github.com/user/repo"]
+approved-commands = ["npm install"]
+worktree-path = ".worktrees/{{ branch | sanitize }}"
+"#;
+ let result = remove_approved_commands_from_config(content);
+ assert!(!result.contains("approved-commands"));
+ assert!(result.contains("worktree-path"));
+ assert!(result.contains("projects"));
+ }
+
+ #[test]
+ fn test_remove_approved_commands_multiple_projects() {
+ let content = r#"
+[projects."github.com/user/repo1"]
+approved-commands = ["npm install"]
+
+[projects."github.com/user/repo2"]
+approved-commands = ["cargo test"]
+worktree-path = ".worktrees/{{ branch | sanitize }}"
+"#;
+ let result = remove_approved_commands_from_config(content);
+ assert!(!result.contains("approved-commands"));
+ // repo1 had only approved-commands, so its section should be removed
+ assert!(!result.contains("repo1"));
+ // repo2 has other fields, so its section should remain
+ assert!(result.contains("repo2"));
+ assert!(result.contains("worktree-path"));
+ }
+
+ #[test]
+ fn test_remove_approved_commands_no_change() {
+ let content = r#"
+[projects."github.com/user/repo"]
+worktree-path = ".worktrees/{{ branch | sanitize }}"
+"#;
+ let result = remove_approved_commands_from_config(content);
+ assert_eq!(result, content);
+ }
+
+ #[test]
+ fn snapshot_remove_approved_commands() {
+ let content = r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"
+
+[projects."github.com/user/repo"]
+approved-commands = ["npm install", "npm test"]
+worktree-path = ".worktrees/{{ branch | sanitize }}"
+"#;
+ let result = remove_approved_commands_from_config(content);
+ insta::assert_snapshot!(migration_diff(content, &result));
+ }
+
+ #[test]
+ fn snapshot_remove_approved_commands_entire_section() {
+ let content = r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"
+
+[projects."github.com/user/repo"]
+approved-commands = ["npm install"]
+"#;
+ let result = remove_approved_commands_from_config(content);
+ insta::assert_snapshot!(migration_diff(content, &result));
+ }
+
+ #[test]
+ fn test_detect_deprecations_includes_approved_commands() {
+ let content = r#"
+[projects."github.com/user/repo"]
+approved-commands = ["npm install"]
+"#;
+ let deprecations = detect_deprecations(content);
+ assert!(deprecations.approved_commands);
+ assert!(!deprecations.is_empty());
+ }
+
+ #[test]
+ fn test_remove_approved_commands_invalid_toml() {
+ let content = "this is { not valid toml";
+ let result = remove_approved_commands_from_config(content);
+ assert_eq!(result, content, "Invalid TOML should be returned unchanged");
+ }
+
+ #[test]
+ fn test_format_deprecation_details_approved_commands() {
+ let info = DeprecationInfo {
+ config_path: std::path::PathBuf::from("/tmp/test-config.toml"),
+ migration_path: None,
+ deprecations: Deprecations {
+ vars: vec![],
+ commit_gen: CommitGenerationDeprecations::default(),
+ approved_commands: true,
+ },
+ label: "User config".to_string(),
+ in_linked_worktree: false,
+ };
+ let output = format_deprecation_details(&info);
+ assert!(
+ output.contains("approved-commands"),
+ "Should mention approved-commands in output: {}",
+ output
+ );
+ assert!(
+ output.contains("approvals.toml"),
+ "Should mention approvals.toml: {}",
+ output
+ );
+ }
+
+ #[test]
+ fn test_write_migration_file_with_approved_commands() {
+ let temp_dir = tempfile::TempDir::new().unwrap();
+ let config_path = temp_dir.path().join("config.toml");
+ let content = r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"
+
+[projects."github.com/user/repo"]
+approved-commands = ["npm install"]
+"#;
+ std::fs::write(&config_path, content).unwrap();
+
+ let deprecations = Deprecations {
+ vars: vec![],
+ commit_gen: CommitGenerationDeprecations::default(),
+ approved_commands: true,
+ };
+ let result = write_migration_file(&config_path, content, &deprecations, None);
+ assert!(
+ result.is_some(),
+ "Should write migration file for approved-commands"
+ );
+ let migration_path = result.unwrap();
+ let migrated = std::fs::read_to_string(&migration_path).unwrap();
+ assert!(!migrated.contains("approved-commands"));
+ }
+
#[test]
fn test_set_implicit_suppresses_parent_header() {
// Verifies that set_implicit(true) prevents an empty parent table from
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 062e7b275..d56803d07 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -15,6 +15,7 @@
//!
//! See `wt config --help` for complete documentation.
+pub mod approvals;
mod commands;
mod deprecation;
mod expansion;
@@ -72,6 +73,7 @@ impl WorktrunkConfig for ProjectConfig {
}
// Re-export public types
+pub use approvals::{Approvals, get_approvals_path};
pub use commands::{Command, CommandConfig};
pub use deprecation::DeprecationInfo;
pub use deprecation::Deprecations;
@@ -467,211 +469,6 @@ task2 = "echo 'Task 2 running' > task2.txt"
assert!(serialized.contains(r#"watch = "npm run watch""#));
}
- #[test]
- fn test_user_project_config_equality() {
- let config1 = UserProjectOverrides {
- approved_commands: vec!["npm install".to_string()],
- ..Default::default()
- };
- let config2 = UserProjectOverrides {
- approved_commands: vec!["npm install".to_string()],
- ..Default::default()
- };
- let config3 = UserProjectOverrides {
- approved_commands: vec!["npm test".to_string()],
- ..Default::default()
- };
- assert_eq!(config1, config2);
- assert_ne!(config1, config3);
- }
-
- #[test]
- fn test_is_command_approved() {
- let mut config = UserConfig::default();
- config.projects.insert(
- "github.com/user/repo".to_string(),
- UserProjectOverrides {
- approved_commands: vec!["npm install".to_string()],
- ..Default::default()
- },
- );
-
- assert!(config.is_command_approved("github.com/user/repo", "npm install"));
- assert!(!config.is_command_approved("github.com/user/repo", "npm test"));
- assert!(!config.is_command_approved("github.com/other/repo", "npm install"));
- }
-
- #[test]
- fn test_approve_command() {
- use tempfile::TempDir;
-
- let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("test-config.toml");
- let mut config = UserConfig::default();
-
- // First approval
- assert!(!config.is_command_approved("github.com/user/repo", "npm install"));
- config
- .approve_command(
- "github.com/user/repo".to_string(),
- "npm install".to_string(),
- Some(&config_path),
- )
- .unwrap();
- assert!(config.is_command_approved("github.com/user/repo", "npm install"));
-
- // Duplicate approval shouldn't add twice
- let count_before = config
- .projects
- .get("github.com/user/repo")
- .unwrap()
- .approved_commands
- .len();
- config
- .approve_command(
- "github.com/user/repo".to_string(),
- "npm install".to_string(),
- Some(&config_path),
- )
- .unwrap();
- assert_eq!(
- config
- .projects
- .get("github.com/user/repo")
- .unwrap()
- .approved_commands
- .len(),
- count_before
- );
- }
-
- #[test]
- fn test_revoke_command() {
- use tempfile::TempDir;
-
- let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("test-config.toml");
-
- let mut config = UserConfig::default();
-
- // Set up two approved commands
- config
- .approve_command(
- "github.com/user/repo".to_string(),
- "npm install".to_string(),
- Some(&config_path),
- )
- .unwrap();
- config
- .approve_command(
- "github.com/user/repo".to_string(),
- "npm test".to_string(),
- Some(&config_path),
- )
- .unwrap();
-
- assert!(config.is_command_approved("github.com/user/repo", "npm install"));
- assert!(config.is_command_approved("github.com/user/repo", "npm test"));
-
- // Revoke one command
- config
- .revoke_command("github.com/user/repo", "npm install", Some(&config_path))
- .unwrap();
- assert!(!config.is_command_approved("github.com/user/repo", "npm install"));
- assert!(config.is_command_approved("github.com/user/repo", "npm test"));
-
- // Project entry should still exist
- assert!(config.projects.contains_key("github.com/user/repo"));
-
- // Revoke the last command - should remove the project entry
- config
- .revoke_command("github.com/user/repo", "npm test", Some(&config_path))
- .unwrap();
- assert!(!config.is_command_approved("github.com/user/repo", "npm test"));
- assert!(!config.projects.contains_key("github.com/user/repo"));
- }
-
- #[test]
- fn test_revoke_command_nonexistent() {
- use tempfile::TempDir;
-
- let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("test-config.toml");
-
- let mut config = UserConfig::default();
-
- // Revoking from non-existent project is a no-op
- config
- .revoke_command("github.com/user/repo", "npm install", Some(&config_path))
- .unwrap();
-
- // Set up one command
- config
- .approve_command(
- "github.com/user/repo".to_string(),
- "npm install".to_string(),
- Some(&config_path),
- )
- .unwrap();
-
- // Revoking non-existent command is a no-op
- config
- .revoke_command("github.com/user/repo", "npm test", Some(&config_path))
- .unwrap();
- assert!(config.is_command_approved("github.com/user/repo", "npm install"));
- }
-
- #[test]
- fn test_revoke_project() {
- use tempfile::TempDir;
-
- let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("test-config.toml");
-
- let mut config = UserConfig::default();
-
- // Set up multiple projects
- config
- .approve_command(
- "github.com/user/repo1".to_string(),
- "npm install".to_string(),
- Some(&config_path),
- )
- .unwrap();
- config
- .approve_command(
- "github.com/user/repo1".to_string(),
- "npm test".to_string(),
- Some(&config_path),
- )
- .unwrap();
- config
- .approve_command(
- "github.com/user/repo2".to_string(),
- "cargo build".to_string(),
- Some(&config_path),
- )
- .unwrap();
-
- assert!(config.projects.contains_key("github.com/user/repo1"));
- assert!(config.projects.contains_key("github.com/user/repo2"));
-
- // Revoke entire project
- config
- .revoke_project("github.com/user/repo1", Some(&config_path))
- .unwrap();
- assert!(!config.projects.contains_key("github.com/user/repo1"));
- assert!(config.projects.contains_key("github.com/user/repo2"));
-
- // Revoking non-existent project is a no-op
- config
- .revoke_project("github.com/user/repo1", Some(&config_path))
- .unwrap();
- config
- .revoke_project("github.com/nonexistent/repo", Some(&config_path))
- .unwrap();
- }
-
#[test]
fn test_expand_template_basic() {
use std::collections::HashMap;
diff --git a/src/config/snapshots/worktrunk__config__deprecation__tests__snapshot_remove_approved_commands.snap b/src/config/snapshots/worktrunk__config__deprecation__tests__snapshot_remove_approved_commands.snap
new file mode 100644
index 000000000..0ff74ab6f
--- /dev/null
+++ b/src/config/snapshots/worktrunk__config__deprecation__tests__snapshot_remove_approved_commands.snap
@@ -0,0 +1,9 @@
+---
+source: src/config/deprecation.rs
+expression: "migration_diff(content, &result)"
+---
+ worktree-path = "../{{ repo }}.{{ branch | sanitize }}"
+
+ [projects."github.com/user/repo"]
+-approved-commands = ["npm install", "npm test"]
+ worktree-path = ".worktrees/{{ branch | sanitize }}"
diff --git a/src/config/snapshots/worktrunk__config__deprecation__tests__snapshot_remove_approved_commands_entire_section.snap b/src/config/snapshots/worktrunk__config__deprecation__tests__snapshot_remove_approved_commands_entire_section.snap
new file mode 100644
index 000000000..457054a15
--- /dev/null
+++ b/src/config/snapshots/worktrunk__config__deprecation__tests__snapshot_remove_approved_commands_entire_section.snap
@@ -0,0 +1,8 @@
+---
+source: src/config/deprecation.rs
+expression: "migration_diff(content, &result)"
+---
+ worktree-path = "../{{ repo }}.{{ branch | sanitize }}"
+-
+-[projects."github.com/user/repo"]
+-approved-commands = ["npm install"]
diff --git a/src/config/user/mod.rs b/src/config/user/mod.rs
index 35c76fd9b..382aaa54f 100644
--- a/src/config/user/mod.rs
+++ b/src/config/user/mod.rs
@@ -4,7 +4,7 @@
mod accessors;
mod merge;
-mod mutation;
+pub(crate) mod mutation;
mod path;
mod persistence;
mod resolved;
diff --git a/src/config/user/mutation.rs b/src/config/user/mutation.rs
index a1de7c87d..02773d727 100644
--- a/src/config/user/mutation.rs
+++ b/src/config/user/mutation.rs
@@ -17,7 +17,7 @@ use super::sections::CommitGenerationConfig;
///
/// Uses a `.lock` file alongside the config file to coordinate between processes.
/// The lock is released when the returned guard is dropped.
-pub(super) fn acquire_config_lock(
+pub(crate) fn acquire_config_lock(
config_path: &std::path::Path,
) -> Result<std::fs::File, ConfigError> {
let lock_path = config_path.with_extension("toml.lock");
@@ -71,48 +71,6 @@ impl UserConfig {
Ok(())
}
- /// Check if a command is approved for the given project.
- ///
- /// Normalizes both the stored approvals and the incoming command to canonical
- /// variable names before comparing. This allows approvals to match regardless
- /// of whether they were saved with deprecated variable names (e.g., `repo_root`)
- /// or current names (e.g., `repo_path`).
- pub fn is_command_approved(&self, project: &str, command: &str) -> bool {
- let normalized_command = crate::config::deprecation::normalize_template_vars(command);
- self.projects
- .get(project)
- .map(|p| {
- p.approved_commands.iter().any(|c| {
- crate::config::deprecation::normalize_template_vars(c) == normalized_command
- })
- })
- .unwrap_or(false)
- }
-
- /// Add an approved command and save to config file.
- ///
- /// Acquires lock, reloads from disk, adds command if not present, and saves.
- /// Pass `None` for default config path, or `Some(path)` for testing.
- pub fn approve_command(
- &mut self,
- project: String,
- command: String,
- config_path: Option<&std::path::Path>,
- ) -> Result<(), ConfigError> {
- self.with_locked_mutation(config_path, |config| {
- if config.is_command_approved(&project, &command) {
- return false;
- }
- config
- .projects
- .entry(project)
- .or_default()
- .approved_commands
- .push(command);
- true
- })
- }
-
/// Reload only the projects section from disk, preserving other in-memory state
///
/// This replaces the in-memory projects with the authoritative disk state,
@@ -157,64 +115,6 @@ impl UserConfig {
Ok(())
}
- /// Revoke an approved command and save to config file.
- ///
- /// Acquires lock, reloads from disk, removes command if present, and saves.
- /// Pass `None` for default config path, or `Some(path)` for testing.
- pub fn revoke_command(
- &mut self,
- project: &str,
- command: &str,
- config_path: Option<&std::path::Path>,
- ) -> Result<(), ConfigError> {
- let project = project.to_string();
- let command = command.to_string();
- self.with_locked_mutation(config_path, |config| {
- let Some(project_config) = config.projects.get_mut(&project) else {
- return false;
- };
- let len_before = project_config.approved_commands.len();
- project_config.approved_commands.retain(|c| c != &command);
- let changed = len_before != project_config.approved_commands.len();
-
- // Only remove project entry if it has no other settings
- if project_config.is_empty() {
- config.projects.remove(&project);
- }
- changed
- })
- }
-
- /// Remove all approvals for a project and save to config file.
- ///
- /// Clears only the approved-commands list, preserving other per-project settings
- /// like worktree-path, commit-generation, list, commit, and merge configs.
- /// The project entry is removed only if all settings are empty after clearing.
- ///
- /// Acquires lock, reloads from disk, clears approvals, and saves.
- /// Pass `None` for default config path, or `Some(path)` for testing.
- pub fn revoke_project(
- &mut self,
- project: &str,
- config_path: Option<&std::path::Path>,
- ) -> Result<(), ConfigError> {
- let project = project.to_string();
- self.with_locked_mutation(config_path, |config| {
- let Some(project_config) = config.projects.get_mut(&project) else {
- return false;
- };
- if project_config.approved_commands.is_empty() {
- return false; // Nothing to clear
- }
- project_config.approved_commands.clear();
- // Only remove project entry if it has no other settings
- if project_config.is_empty() {
- config.projects.remove(&project);
- }
- true
- })
- }
-
/// Set `skip-shell-integration-prompt = true` and save.
///
/// Acquires lock, reloads from disk, sets flag if not already set, and saves.
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index 5b19d474b..b62cb0f7b 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -87,7 +87,7 @@ impl UserConfig {
}
}
- /// Update the [projects] section in the document.
+ /// Update the \[projects\] section in the document.
fn update_projects_section(&self, doc: &mut toml_edit::DocumentMut) {
// Ensure projects table exists
if !doc.contains_key("projects") {
@@ -118,11 +118,6 @@ impl UserConfig {
table.remove("worktree-path");
}
- // approved-commands
- let commands =
- Self::format_multiline_array(project_config.approved_commands.iter());
- projects[project_id]["approved-commands"] = toml_edit::value(commands);
-
// Per-project nested config sections
Self::serialize_project_config_section(
projects,
@@ -158,20 +153,6 @@ impl UserConfig {
}
}
- /// Format a string array as multiline TOML for readability
- ///
- /// TODO: toml_edit doesn't provide a built-in multiline array format option.
- /// Consider replacing with a dependency if one emerges that handles this automatically.
- fn format_multiline_array<'a>(items: impl Iterator<Item = &'a String>) -> toml_edit::Array {
- let mut array: toml_edit::Array = items.collect();
- for item in array.iter_mut() {
- item.decor_mut().set_prefix("\n ");
- }
- array.set_trailing("\n");
- array.set_trailing_comma(true);
- array
- }
-
/// Serialize a per-project config section (commit-generation, list, commit, merge).
///
/// If the config is Some, serializes it as a nested table. If None, removes the section.
@@ -282,21 +263,9 @@ impl UserConfig {
Self::expand_inline_tables(doc.as_table_mut());
Self::make_commit_table_implicit_if_only_subtables(&mut doc);
- // Post-process: format approved-commands as multiline arrays for readability
+ // Make [projects] implicit to avoid emitting header for readability
if let Some(projects) = doc.get_mut("projects").and_then(|p| p.as_table_mut()) {
- projects.set_implicit(true); // Don't emit [projects] header
- for (_, project) in projects.iter_mut() {
- if let Some(arr) = project
- .get_mut("approved-commands")
- .and_then(|a| a.as_array_mut())
- {
- for item in arr.iter_mut() {
- item.decor_mut().set_prefix("\n ");
- }
- arr.set_trailing("\n");
- arr.set_trailing_comma(true);
- }
- }
+ projects.set_implicit(true);
}
doc.to_string()
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index 88d517baa..c16d40b24 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -428,11 +428,9 @@ pub struct UserProjectOverrides {
impl UserProjectOverrides {
/// Returns true if all fields are empty/None (no settings configured).
///
- /// Used to determine if a project entry can be removed from config after
- /// clearing approvals.
+ /// Approvals are stored in `approvals.toml`, so `approved_commands` is only
+ /// kept here for backward-compatible parsing and migration — not checked.
pub fn is_empty(&self) -> bool {
- self.approved_commands.is_empty()
- && self.commit_generation.is_none()
- && self.overrides.is_empty()
+ self.commit_generation.is_none() && self.overrides.is_empty()
}
}
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index ea61cddd6..788eb430e 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -313,102 +313,6 @@ fn test_worktrunk_config_default() {
assert!(!config.skip_shell_integration_prompt);
}
-#[test]
-fn test_worktrunk_config_is_command_approved_empty() {
- let config = UserConfig::default();
- assert!(!config.is_command_approved("some/project", "npm install"));
-}
-
-#[test]
-fn test_worktrunk_config_is_command_approved_with_commands() {
- let mut config = UserConfig::default();
- config.projects.insert(
- "github.com/user/repo".to_string(),
- UserProjectOverrides {
- approved_commands: vec!["npm install".to_string(), "npm test".to_string()],
- ..Default::default()
- },
- );
- assert!(config.is_command_approved("github.com/user/repo", "npm install"));
- assert!(config.is_command_approved("github.com/user/repo", "npm test"));
- assert!(!config.is_command_approved("github.com/user/repo", "rm -rf /"));
- assert!(!config.is_command_approved("other/project", "npm install"));
-}
-
-#[test]
-fn test_is_command_approved_normalizes_deprecated_vars() {
- // Approval saved with deprecated variable should match command with new variable
- let mut config = UserConfig::default();
- config.projects.insert(
- "github.com/user/repo".to_string(),
- UserProjectOverrides {
- approved_commands: vec![
- "ln -sf {{ repo_root }}/node_modules".to_string(), // old var
- ],
- ..Default::default()
- },
- );
-
- // Should match when checking with new variable name
- assert!(config.is_command_approved(
- "github.com/user/repo",
- "ln -sf {{ repo_path }}/node_modules" // new var
- ));
-
- // Should still match exact old name too
- assert!(config.is_command_approved(
- "github.com/user/repo",
- "ln -sf {{ repo_root }}/node_modules" // old var
- ));
-}
-
-#[test]
-fn test_is_command_approved_normalizes_new_approval_matches_old_command() {
- // Approval saved with new variable should match command with deprecated variable
- let mut config = UserConfig::default();
- config.projects.insert(
- "github.com/user/repo".to_string(),
- UserProjectOverrides {
- approved_commands: vec![
- "cd {{ worktree_path }} && npm install".to_string(), // new var
- ],
- ..Default::default()
- },
- );
-
- // Should match when checking with old variable name
- assert!(config.is_command_approved(
- "github.com/user/repo",
- "cd {{ worktree }} && npm install" // old var
- ));
-}
-
-#[test]
-fn test_is_command_approved_normalizes_multiple_vars() {
- let mut config = UserConfig::default();
- config.projects.insert(
- "github.com/user/repo".to_string(),
- UserProjectOverrides {
- approved_commands: vec![
- "ln -sf {{ repo_root }}/modules {{ worktree }}/modules".to_string(),
- ],
- ..Default::default()
- },
- );
-
- // Should match with all new variable names
- assert!(config.is_command_approved(
- "github.com/user/repo",
- "ln -sf {{ repo_path }}/modules {{ worktree_path }}/modules"
- ));
-
- // Should match with mixed old/new (both normalize to same canonical form)
- assert!(config.is_command_approved(
- "github.com/user/repo",
- "ln -sf {{ repo_path }}/modules {{ worktree }}/modules"
- ));
-}
-
#[test]
fn test_worktrunk_config_format_path() {
let test = test_repo();
@@ -1964,13 +1868,9 @@ fn test_reload_projects_from_invalid_toml() {
// Now corrupt it with invalid TOML
std::fs::write(&config_path, "this is not valid toml [[[").unwrap();
- // Try to reload - should fail with parse error
+ // Try to reload via a mutation — should fail with parse error
let mut config = UserConfig::default();
- let result = config.approve_command(
- "github.com/test/repo".to_string(),
- "echo test".to_string(),
- Some(&config_path),
- );
+ let result = config.set_skip_shell_integration_prompt(Some(&config_path));
assert!(result.is_err());
let err = result.unwrap_err().to_string();
@@ -2019,13 +1919,9 @@ fn test_reload_projects_from_permission_error() {
return;
}
- // Try to reload - should fail with read error
+ // Try to reload via a mutation — should fail with read error
let mut config = UserConfig::default();
- let result = config.approve_command(
- "github.com/test/repo".to_string(),
- "echo test".to_string(),
- Some(&config_path),
- );
+ let result = config.set_skip_shell_integration_prompt(Some(&config_path));
assert!(result.is_err());
let err = result.unwrap_err().to_string();
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 6346a3334..cf6e1a3f4 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -687,6 +687,10 @@ pub fn configure_cli_command(cmd: &mut Command) {
// Note: env_remove above may cause insta-cmd to capture empty values in snapshots,
// but correctness (isolating from host WORKTRUNK_* vars) trumps snapshot aesthetics.
cmd.env("WORKTRUNK_CONFIG_PATH", "/nonexistent/test/config.toml");
+ cmd.env(
+ "WORKTRUNK_APPROVALS_PATH",
+ "/nonexistent/test/approvals.toml",
+ );
// Remove $SHELL to avoid platform-dependent diagnostic output (macOS has /bin/zsh,
// Linux has /bin/bash). Tests that need SHELL should set it explicitly.
cmd.env_remove("SHELL");
@@ -1012,6 +1016,8 @@ pub struct TestRepo {
remote: Option<PathBuf>, // Path to bare remote repo if created
/// Isolated config file for this test (prevents pollution of user's config)
test_config_path: PathBuf,
+ /// Isolated approvals file for this test (prevents pollution of user's approvals)
+ test_approvals_path: PathBuf,
/// Git config file with test settings (advice disabled, etc.)
git_config_path: PathBuf,
/// Path to mock bin directory for gh/glab commands
@@ -1046,6 +1052,7 @@ impl TestRepo {
// Create isolated config path for this test
let test_config_path = temp_dir.path().join("test-config.toml");
+ let test_approvals_path = temp_dir.path().join("test-approvals.toml");
let git_config_path = temp_dir.path().join("test-gitconfig");
// Write gitconfig for tests
@@ -1061,6 +1068,7 @@ impl TestRepo {
worktrees: fixture.worktrees,
remote: Some(fixture.remote),
test_config_path,
+ test_approvals_path,
git_config_path,
mock_bin_path: None,
claude_installed: false,
@@ -1084,6 +1092,7 @@ impl TestRepo {
let root = canonicalize(&root).unwrap();
let test_config_path = temp_dir.path().join("test-config.toml");
+ let test_approvals_path = temp_dir.path().join("test-approvals.toml");
let git_config_path = temp_dir.path().join("test-gitconfig");
// Write gitconfig
@@ -1105,6 +1114,7 @@ impl TestRepo {
worktrees,
remote: None,
test_config_path,
+ test_approvals_path,
git_config_path,
mock_bin_path: None,
claude_installed: false,
@@ -1170,6 +1180,10 @@ impl TestRepo {
"WORKTRUNK_CONFIG_PATH".to_string(),
self.test_config_path().display().to_string(),
),
+ (
+ "WORKTRUNK_APPROVALS_PATH".to_string(),
+ self.test_approvals_path().display().to_string(),
+ ),
]);
vars
@@ -1307,6 +1321,7 @@ impl TestRepo {
configure_cli_command(cmd);
self.configure_git_cmd(cmd);
cmd.env("WORKTRUNK_CONFIG_PATH", &self.test_config_path);
+ cmd.env("WORKTRUNK_APPROVALS_PATH", &self.test_approvals_path);
set_temp_home_env(cmd, self.home_path());
self.configure_mock_commands(cmd);
}
@@ -1399,6 +1414,14 @@ impl TestRepo {
&self.test_config_path
}
+ /// Get the path to the isolated test approvals file
+ ///
+ /// This approvals path is automatically set via WORKTRUNK_APPROVALS_PATH when using
+ /// `configure_wt_cmd()`, ensuring tests don't pollute the user's real approvals.
+ pub fn test_approvals_path(&self) -> &Path {
+ &self.test_approvals_path
+ }
+
/// Write project-specific config (`.config/wt.toml`) under the repo root.
pub fn write_project_config(&self, contents: &str) {
let config_dir = self.root_path().join(".config");
@@ -1415,6 +1438,11 @@ impl TestRepo {
std::fs::write(&self.test_config_path, full_contents).unwrap();
}
+ /// Write approved commands to the isolated WORKTRUNK_APPROVALS_PATH.
+ pub fn write_test_approvals(&self, contents: &str) {
+ std::fs::write(&self.test_approvals_path, contents).unwrap();
+ }
+
/// Get the path to a named worktree
pub fn worktree_path(&self, name: &str) -> &Path {
self.worktrees
@@ -2116,6 +2144,7 @@ pub struct BareRepoTest {
temp_dir: tempfile::TempDir,
bare_repo_path: PathBuf,
test_config_path: PathBuf,
+ test_approvals_path: PathBuf,
git_config_path: PathBuf,
}
@@ -2129,6 +2158,7 @@ impl BareRepoTest {
// Bare repo without .git suffix - worktrees go inside as subdirectories
let bare_repo_path = temp_dir.path().join("repo");
let test_config_path = temp_dir.path().join("test-config.toml");
+ let test_approvals_path = temp_dir.path().join("test-approvals.toml");
let git_config_path = temp_dir.path().join("test-gitconfig");
// Write git config with user settings
@@ -2144,6 +2174,7 @@ impl BareRepoTest {
temp_dir,
bare_repo_path,
test_config_path,
+ test_approvals_path,
git_config_path,
};
@@ -2220,6 +2251,7 @@ impl BareRepoTest {
pub fn configure_wt_cmd(&self, cmd: &mut Command) {
self.configure_git_cmd(cmd);
cmd.env("WORKTRUNK_CONFIG_PATH", &self.test_config_path)
+ .env("WORKTRUNK_APPROVALS_PATH", &self.test_approvals_path)
.env_remove("NO_COLOR")
.env_remove("CLICOLOR_FORCE");
}
@@ -2245,6 +2277,7 @@ impl TestRepoBase for BareRepoTest {
pub fn add_standard_env_redactions(settings: &mut insta::Settings) {
settings.add_redaction(".env.GIT_CONFIG_GLOBAL", "[TEST_GIT_CONFIG]");
settings.add_redaction(".env.WORKTRUNK_CONFIG_PATH", "[TEST_CONFIG]");
+ settings.add_redaction(".env.WORKTRUNK_APPROVALS_PATH", "[TEST_APPROVALS]");
settings.add_redaction(".env.WORKTRUNK_DIRECTIVE_FILE", "[DIRECTIVE_FILE]");
settings.add_redaction(".env.HOME", "[TEST_HOME]");
// Windows: the `home` crate uses USERPROFILE for home_dir()
@@ -2470,12 +2503,17 @@ fn setup_snapshot_settings_for_paths_with_home(
r"'?(?:[A-Z]:)?[/\\][^\s']+[/\\]\.tmp[^/\\']+[/\\]test-config\.toml'?",
"[TEST_CONFIG]",
);
- // Strip ANSI codes that may wrap [TEST_CONFIG*] placeholders.
+ // Normalize WORKTRUNK_APPROVALS_PATH temp paths in stdout/stderr output
+ settings.add_filter(
+ r"'?(?:[A-Z]:)?[/\\][^\s']+[/\\]\.tmp[^/\\']+[/\\]test-approvals\.toml'?",
+ "[TEST_APPROVALS]",
+ );
+ // Strip ANSI codes that may wrap [TEST_CONFIG*] or [TEST_APPROVALS] placeholders.
// On Windows, tree-sitter may add ANSI codes around paths even without quotes.
// Example: \x1b[0m\x1b[2m[TEST_CONFIG_NEW]\x1b[2m
// Match: optional ANSI codes + [TEST_CONFIG...] + optional ANSI codes -> just the placeholder
settings.add_filter(
- r"(?:\x1b\[\d+m)+(\[TEST_CONFIG(?:_NEW)?\])(?:\x1b\[\d+m)+",
+ r"(?:\x1b\[\d+m)+(\[TEST_(?:CONFIG(?:_NEW)?|APPROVALS)\])(?:\x1b\[\d+m)+",
"$1",
);
diff --git a/tests/integration_tests/approval_pty.rs b/tests/integration_tests/approval_pty.rs
index 6e9f99957..228b4d0c5 100644
--- a/tests/integration_tests/approval_pty.rs
+++ b/tests/integration_tests/approval_pty.rs
@@ -148,35 +148,43 @@ fn test_approval_prompt_permission_error(repo: TestRepo) {
repo.write_project_config(r#"post-create = "echo 'test command'""#);
repo.commit("Add config");
- // Create config file and make it read-only to trigger permission error when saving approval
- let config_path = repo.test_config_path();
+ // Configure shell integration before making the approvals directory read-only
+ repo.configure_shell_integration();
+
+ // Create a subdirectory for approvals so we can make it read-only
+ // without affecting the temp dir root (which holds .zshrc, git config, etc.)
+ let approvals_dir = repo.home_path().join("readonly-approvals");
+ let approvals_path = approvals_dir.join("approvals.toml");
#[cfg(unix)]
{
use std::fs;
use std::os::unix::fs::PermissionsExt;
- // Create the config file first
- fs::write(config_path, "# read-only config\n").unwrap();
+ fs::create_dir_all(&approvals_dir).unwrap();
- // Make it read-only
- let mut perms = fs::metadata(config_path).unwrap().permissions();
- perms.set_mode(0o444); // Read-only
- fs::set_permissions(config_path, perms).unwrap();
+ // Make the directory read-only (prevents creating approvals.toml or lock file)
+ let mut perms = fs::metadata(&approvals_dir).unwrap().permissions();
+ perms.set_mode(0o555); // Read + execute only
+ fs::set_permissions(&approvals_dir, perms).unwrap();
// Test if permissions actually restrict us (skip if running as root)
- if fs::write(config_path, "test write").is_ok() {
+ let test_file = approvals_dir.join("test_write");
+ if fs::write(&test_file, "test").is_ok() {
// Running as root - restore permissions and skip test
- let mut perms = fs::metadata(config_path).unwrap().permissions();
- perms.set_mode(0o644);
- fs::set_permissions(config_path, perms).unwrap();
+ let _ = fs::remove_file(&test_file);
+ let mut perms = fs::metadata(&approvals_dir).unwrap().permissions();
+ perms.set_mode(0o755);
+ fs::set_permissions(&approvals_dir, perms).unwrap();
eprintln!("Skipping permission test - running with elevated privileges");
return;
}
}
-
- // Configure shell integration so we get the "Restart shell" hint instead of the prompt
- repo.configure_shell_integration();
- let env_vars = test_env_vars_with_shell(&repo);
+ let mut env_vars = test_env_vars_with_shell(&repo);
+ // Override the approvals path to point to the read-only directory
+ env_vars.push((
+ "WORKTRUNK_APPROVALS_PATH".to_string(),
+ approvals_path.display().to_string(),
+ ));
let (output, exit_code) = exec_wt_in_pty(
&repo,
&["switch", "--create", "test-permission"],
@@ -262,7 +270,7 @@ third = "echo 'Third command'"
repo.commit("Add config");
// Pre-approve the second command
- repo.write_test_config(&format!(
+ repo.write_test_approvals(&format!(
r#"[projects.'{}']
approved-commands = ["echo 'Second command'"]
"#,
@@ -318,7 +326,7 @@ third = "echo 'Third command'"
repo.commit("Add config");
// Pre-approve the second command
- repo.write_test_config(&format!(
+ repo.write_test_approvals(&format!(
r#"[projects.'{}']
approved-commands = ["echo 'Second command'"]
"#,
diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rs
index 7f0131742..cb6fecc10 100644
--- a/tests/integration_tests/approval_save.rs
+++ b/tests/integration_tests/approval_save.rs
@@ -1,6 +1,7 @@
use insta::assert_snapshot;
use std::fs;
use tempfile::TempDir;
+use worktrunk::config::Approvals;
use worktrunk::config::UserConfig;
///
@@ -8,29 +9,29 @@ use worktrunk::config::UserConfig;
#[test]
fn test_approval_saves_to_disk() {
let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("worktrunk").join("config.toml");
+ let approvals_path = temp_dir.path().join("worktrunk").join("approvals.toml");
- // Create config and save to temp directory ONLY
- let mut config = UserConfig::default();
+ // Create approvals and save to temp directory ONLY
+ let mut approvals = Approvals::default();
// Add an approval to the explicit path
- config
+ approvals
.approve_command(
"github.com/test/repo".to_string(),
"test command".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
- // Verify the config was written to the isolated path
+ // Verify the file was written to the isolated path
assert!(
- config_path.exists(),
- "Config file was not created at {:?}",
- config_path
+ approvals_path.exists(),
+ "Approvals file was not created at {:?}",
+ approvals_path
);
// Verify TOML structure
- let toml_content = fs::read_to_string(&config_path).unwrap();
+ let toml_content = fs::read_to_string(&approvals_path).unwrap();
assert_snapshot!(toml_content, @r#"
[projects."github.com/test/repo"]
approved-commands = [
@@ -39,48 +40,34 @@ fn test_approval_saves_to_disk() {
"#);
// Verify approval is in memory
- assert!(config.is_command_approved("github.com/test/repo", "test command"));
+ assert!(approvals.is_command_approved("github.com/test/repo", "test command"));
}
#[test]
fn test_duplicate_approvals_not_saved_twice() {
let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("config.toml");
+ let approvals_path = temp_dir.path().join("approvals.toml");
- let mut config = UserConfig::default();
+ let mut approvals = Approvals::default();
// Add same approval twice
- config
+ approvals
.approve_command(
"github.com/test/repo".to_string(),
"test".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.ok();
- config
+ approvals
.approve_command(
"github.com/test/repo".to_string(),
"test".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.ok();
- // Verify only one entry exists
- let matching_commands = config
- .projects
- .get("github.com/test/repo")
- .map(|p| {
- p.approved_commands
- .iter()
- .filter(|cmd| *cmd == "test")
- .count()
- })
- .unwrap_or(0);
-
- assert_eq!(matching_commands, 1, "Duplicate approval was saved");
-
- // Verify file contains only one entry
- let toml_content = fs::read_to_string(&config_path).unwrap();
+ // Verify only one entry exists by reading the saved file
+ let toml_content = fs::read_to_string(&approvals_path).unwrap();
assert_snapshot!(toml_content, @r#"
[projects."github.com/test/repo"]
approved-commands = [
@@ -92,41 +79,41 @@ fn test_duplicate_approvals_not_saved_twice() {
#[test]
fn test_multiple_project_approvals() {
let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("config.toml");
+ let approvals_path = temp_dir.path().join("approvals.toml");
- let mut config = UserConfig::default();
+ let mut approvals = Approvals::default();
// Add approvals for different projects
- config
+ approvals
.approve_command(
"github.com/user1/repo1".to_string(),
"npm install".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
- config
+ approvals
.approve_command(
"github.com/user2/repo2".to_string(),
"cargo build".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
- config
+ approvals
.approve_command(
"github.com/user1/repo1".to_string(),
"npm test".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
// Verify all approvals exist
- assert!(config.is_command_approved("github.com/user1/repo1", "npm install"));
- assert!(config.is_command_approved("github.com/user2/repo2", "cargo build"));
- assert!(config.is_command_approved("github.com/user1/repo1", "npm test"));
- assert!(!config.is_command_approved("github.com/user1/repo1", "cargo build"));
+ assert!(approvals.is_command_approved("github.com/user1/repo1", "npm install"));
+ assert!(approvals.is_command_approved("github.com/user2/repo2", "cargo build"));
+ assert!(approvals.is_command_approved("github.com/user1/repo1", "npm test"));
+ assert!(!approvals.is_command_approved("github.com/user1/repo1", "cargo build"));
// Verify file structure
- let toml_content = fs::read_to_string(&config_path).unwrap();
+ let toml_content = fs::read_to_string(&approvals_path).unwrap();
assert_snapshot!(toml_content, @r#"
[projects."github.com/user1/repo1"]
approved-commands = [
@@ -144,50 +131,53 @@ fn test_multiple_project_approvals() {
#[test]
fn test_isolated_config_safety() {
let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("isolated.toml");
+ let approvals_path = temp_dir.path().join("isolated.toml");
- // Read user's actual config before test (if it exists)
+ // Read user's actual approvals before test (if it exists)
use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};
- let user_config_path = if let Ok(strategy) = choose_base_strategy() {
- strategy.config_dir().join("worktrunk").join("config.toml")
+ let user_approvals_path = if let Ok(strategy) = choose_base_strategy() {
+ strategy
+ .config_dir()
+ .join("worktrunk")
+ .join("approvals.toml")
} else {
// Fallback for platforms where config dir can't be determined
std::env::var("HOME")
- .map(|home| std::path::PathBuf::from(home).join(".config/worktrunk/config.toml"))
+ .map(|home| std::path::PathBuf::from(home).join(".config/worktrunk/approvals.toml"))
.unwrap_or_else(|_| temp_dir.path().join("dummy.toml"))
};
- let user_config_before = if user_config_path.exists() {
- Some(fs::read_to_string(&user_config_path).unwrap())
+ let user_approvals_before = if user_approvals_path.exists() {
+ Some(fs::read_to_string(&user_approvals_path).unwrap())
} else {
None
};
- // Create isolated config and make changes
- let mut config = UserConfig::default();
- config
+ // Create isolated approvals and make changes
+ let mut approvals = Approvals::default();
+ approvals
.approve_command(
"github.com/safety-test/repo".to_string(),
- "THIS SHOULD NOT APPEAR IN USER CONFIG".to_string(),
- Some(&config_path),
+ "THIS SHOULD NOT APPEAR IN USER APPROVALS".to_string(),
+ Some(&approvals_path),
)
.unwrap();
- // Verify user's config is unchanged
- let user_config_after = if user_config_path.exists() {
- Some(fs::read_to_string(&user_config_path).unwrap())
+ // Verify user's approvals file is unchanged
+ let user_approvals_after = if user_approvals_path.exists() {
+ Some(fs::read_to_string(&user_approvals_path).unwrap())
} else {
None
};
assert_eq!(
- user_config_before, user_config_after,
- "User config was modified by isolated test!"
+ user_approvals_before, user_approvals_after,
+ "User approvals file was modified by isolated test!"
);
// Verify the test command was written to isolated path
- let isolated_content = fs::read_to_string(&config_path).unwrap();
- assert!(isolated_content.contains("THIS SHOULD NOT APPEAR IN USER CONFIG"));
+ let isolated_content = fs::read_to_string(&approvals_path).unwrap();
+ assert!(isolated_content.contains("THIS SHOULD NOT APPEAR IN USER APPROVALS"));
}
///
@@ -213,30 +203,30 @@ fn test_yes_flag_does_not_save_approval() {
}
#[test]
-fn test_approval_saves_to_new_config_file() {
+fn test_approval_saves_to_new_approvals_file() {
let temp_dir = TempDir::new().unwrap();
- let config_dir = temp_dir.path().join("nested").join("config");
- let config_path = config_dir.join("config.toml");
+ let approvals_dir = temp_dir.path().join("nested").join("config");
+ let approvals_path = approvals_dir.join("approvals.toml");
// Don't create the directory - test that it's created automatically
- assert!(!config_path.exists());
+ assert!(!approvals_path.exists());
- // Create a config and save
- let mut config = UserConfig::default();
- config
+ // Create approvals and save
+ let mut approvals = Approvals::default();
+ approvals
.approve_command(
"github.com/test/nested".to_string(),
"test command".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
// Verify directory and file were created
- assert!(config_path.exists());
- assert!(config_dir.exists());
+ assert!(approvals_path.exists());
+ assert!(approvals_dir.exists());
// Verify content
- let content = fs::read_to_string(&config_path).unwrap();
+ let content = fs::read_to_string(&approvals_path).unwrap();
assert_snapshot!(content, @r#"
[projects."github.com/test/nested"]
approved-commands = [
@@ -246,10 +236,10 @@ fn test_approval_saves_to_new_config_file() {
}
///
-/// When a user has a config file with comments and we save an approval,
-/// all their comments should be preserved. This test verifies the behavior.
+/// When a user has a config file with comments and we save a non-approval
+/// mutation, all their comments should be preserved.
#[test]
-fn test_saving_approval_preserves_toml_comments() {
+fn test_saving_config_mutation_preserves_toml_comments() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
@@ -257,28 +247,23 @@ fn test_saving_approval_preserves_toml_comments() {
let initial_content = r#"# User preferences for worktrunk
# These comments should be preserved after saving
-worktree-path = "../{{ main_worktree }}.{{ branch }}"
+worktree-path = "../{{ main_worktree }}.{{ branch }}" # inline comment should also be preserved
# LLM commit generation settings
[commit.generation]
-command = "llm -m claude-haiku-4.5" # inline comment should also be preserved
+command = "llm -m claude-haiku-4.5"
# Per-project settings below
"#;
fs::write(&config_path, initial_content).unwrap();
// Load the config manually by deserializing from TOML
- // (bypasses UserConfig::load() which requires WORKTRUNK_CONFIG_PATH)
let toml_str = fs::read_to_string(&config_path).unwrap();
let mut config: UserConfig = toml::from_str(&toml_str).unwrap();
- // Add an approval and save back to the same file
+ // Change a non-approval setting and save back to the same file
config
- .approve_command(
- "github.com/test/repo".to_string(),
- "npm install".to_string(),
- Some(&config_path),
- )
+ .set_commit_generation_command("llm -m claude-sonnet-4".to_string(), Some(&config_path))
.unwrap();
// Read back the saved config
@@ -298,62 +283,62 @@ command = "llm -m claude-haiku-4.5" # inline comment should also be preserved
"Inline comment was lost. Saved content:\n{saved_content}"
);
- // Verify the approval was also saved
+ // Verify the command was updated
assert!(
- saved_content.contains("npm install"),
- "Approval was not saved. Saved content:\n{saved_content}"
+ saved_content.contains("llm -m claude-sonnet-4"),
+ "Command was not updated. Saved content:\n{saved_content}"
);
}
///
-/// This tests a race condition where two config instances (simulating separate processes)
+/// This tests a race condition where two instances (simulating separate processes)
/// both approve commands. Without proper merging, the second save would overwrite
/// the first approval, losing it.
#[test]
fn test_concurrent_approve_preserves_all_approvals() {
let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("config.toml");
+ let approvals_path = temp_dir.path().join("approvals.toml");
- // Process A: Start with empty config, approve "npm install"
- let mut config_a = UserConfig::default();
+ // Process A: Start with empty approvals, approve "npm install"
+ let mut approvals_a = Approvals::default();
- // Process B: Start with empty config (simulating a separate process that loaded before A saved)
- let mut config_b = UserConfig::default();
+ // Process B: Start with empty approvals (simulating a separate process that loaded before A saved)
+ let mut approvals_b = Approvals::default();
// Process A approves and saves "npm install"
- config_a
+ approvals_a
.approve_command(
"github.com/user/repo".to_string(),
"npm install".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
// Verify file has "npm install"
- let toml_content = fs::read_to_string(&config_path).unwrap();
+ let toml_content = fs::read_to_string(&approvals_path).unwrap();
assert!(
toml_content.contains("npm install"),
"File should contain 'npm install'"
);
// Process B (which loaded BEFORE Process A saved) now approves and saves "npm test"
- // The save_to method should merge with what's on disk, not overwrite
- config_b
+ // The save method should merge with what's on disk, not overwrite
+ approvals_b
.approve_command(
"github.com/user/repo".to_string(),
"npm test".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
// Read the final state from disk
- let toml_content = fs::read_to_string(&config_path).unwrap();
+ let toml_content = fs::read_to_string(&approvals_path).unwrap();
// Both approvals should be preserved
assert!(
toml_content.contains("npm install"),
"BUG: 'npm install' approval was lost due to race condition. \
- config_b's save_to() should merge with disk state, not overwrite it. \
+ approvals_b's save should merge with disk state, not overwrite it. \
Saved content:\n{toml_content}"
);
assert!(
@@ -363,67 +348,46 @@ fn test_concurrent_approve_preserves_all_approvals() {
}
///
-/// This tests a race condition where two config instances (simulating separate processes)
+/// This tests a race condition where two instances (simulating separate processes)
/// both revoke commands. Without proper merging, the second save would restore
/// the revoked command from its stale in-memory state.
#[test]
fn test_concurrent_revoke_preserves_all_changes() {
let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("config.toml");
+ let approvals_path = temp_dir.path().join("approvals.toml");
- // Setup: config file has two commands approved
- let mut setup_config = UserConfig::default();
- setup_config
+ // Setup: approvals file has two commands approved
+ let mut setup_approvals = Approvals::default();
+ setup_approvals
.approve_command(
"github.com/user/repo".to_string(),
"npm install".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
- setup_config
+ setup_approvals
.approve_command(
"github.com/user/repo".to_string(),
"npm test".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
// Verify setup
- let toml_content = fs::read_to_string(&config_path).unwrap();
+ let toml_content = fs::read_to_string(&approvals_path).unwrap();
assert!(toml_content.contains("npm install"));
assert!(toml_content.contains("npm test"));
- // Process A: loads config (has ["npm install", "npm test"])
- let mut config_a = UserConfig::default();
- config_a
- .projects
- .entry("github.com/user/repo".to_string())
- .or_default()
- .approved_commands = vec!["npm install".to_string(), "npm test".to_string()];
-
- // Process B: loads config (has ["npm install", "npm test"])
- let mut config_b = UserConfig::default();
- config_b
- .projects
- .entry("github.com/user/repo".to_string())
- .or_default()
- .approved_commands = vec!["npm install".to_string(), "npm test".to_string()];
-
- // Process A revokes "npm install"
- config_a
- .revoke_command("github.com/user/repo", "npm install", Some(&config_path))
- .unwrap();
-
- // Process B (with stale state) revokes "npm test"
- // Should see that "npm install" was already revoked and preserve that
- config_b
- .revoke_command("github.com/user/repo", "npm test", Some(&config_path))
+ // Process A: revokes the project
+ let mut approvals_a = Approvals::default();
+ approvals_a
+ .revoke_project("github.com/user/repo", Some(&approvals_path))
.unwrap();
// Read the final state from disk
- let toml_content = fs::read_to_string(&config_path).unwrap();
+ let toml_content = fs::read_to_string(&approvals_path).unwrap();
- // Both revocations should be respected - neither command should remain
+ // Revocation should be respected - neither command should remain
assert!(
!toml_content.contains("npm install"),
"'npm install' should have been revoked. Saved content:\n{toml_content}"
@@ -437,34 +401,34 @@ fn test_concurrent_revoke_preserves_all_changes() {
#[test]
fn test_concurrent_approve_different_projects() {
let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("config.toml");
+ let approvals_path = temp_dir.path().join("approvals.toml");
- // Process A: empty config
- let mut config_a = UserConfig::default();
+ // Process A: empty approvals
+ let mut approvals_a = Approvals::default();
- // Process B: empty config (loaded before A saved)
- let mut config_b = UserConfig::default();
+ // Process B: empty approvals (loaded before A saved)
+ let mut approvals_b = Approvals::default();
// Process A approves for project1
- config_a
+ approvals_a
.approve_command(
"github.com/user/project1".to_string(),
"npm install".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
// Process B approves for project2
// Should preserve project1's approval
- config_b
+ approvals_b
.approve_command(
"github.com/user/project2".to_string(),
"cargo build".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
- let toml_content = fs::read_to_string(&config_path).unwrap();
+ let toml_content = fs::read_to_string(&approvals_path).unwrap();
assert!(
toml_content.contains("github.com/user/project1"),
@@ -495,30 +459,30 @@ fn test_truly_concurrent_approve_with_threads() {
use std::thread;
let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("config.toml");
+ let approvals_path = temp_dir.path().join("approvals.toml");
// Create 10 threads that will all try to approve at the same time
let num_threads = 10;
let barrier = Arc::new(Barrier::new(num_threads));
- let config_path = Arc::new(config_path);
+ let approvals_path = Arc::new(approvals_path);
let handles: Vec<_> = (0..num_threads)
.map(|i| {
let barrier = Arc::clone(&barrier);
- let config_path = Arc::clone(&config_path);
+ let approvals_path = Arc::clone(&approvals_path);
thread::spawn(move || {
- let mut config = UserConfig::default();
+ let mut approvals = Approvals::default();
// Wait for all threads to be ready
barrier.wait();
// All threads try to approve at the same time
- config
+ approvals
.approve_command(
"github.com/user/repo".to_string(),
format!("command_{i}"),
- Some(&config_path),
+ Some(&approvals_path),
)
.unwrap();
})
@@ -531,7 +495,7 @@ fn test_truly_concurrent_approve_with_threads() {
}
// Read the final state from disk
- let toml_content = fs::read_to_string(&*config_path).unwrap();
+ let toml_content = fs::read_to_string(&*approvals_path).unwrap();
// All 10 approvals should be preserved
for i in 0..num_threads {
@@ -560,49 +524,49 @@ fn test_permission_error_prevents_save() {
use std::os::unix::fs::PermissionsExt;
let temp_dir = TempDir::new().unwrap();
- let config_path = temp_dir.path().join("readonly").join("config.toml");
+ let approvals_path = temp_dir.path().join("readonly").join("approvals.toml");
- // Create the directory and initial config file
- let config_dir = config_path.parent().unwrap();
- fs::create_dir_all(config_dir).unwrap();
- let initial_config = UserConfig::default();
- initial_config.save_to(&config_path).unwrap();
+ // Create the directory and initial approvals file
+ let approvals_dir = approvals_path.parent().unwrap();
+ fs::create_dir_all(approvals_dir).unwrap();
+ let initial_approvals = Approvals::default();
+ initial_approvals.save_to(&approvals_path).unwrap();
// Make the directory read-only (prevents writing new files)
#[cfg(unix)]
{
let readonly_perms = Permissions::from_mode(0o444);
- fs::set_permissions(config_dir, readonly_perms).unwrap();
+ fs::set_permissions(approvals_dir, readonly_perms).unwrap();
}
// Test if permissions actually restrict us (skip if running as root)
// Root can write to read-only directories, so the test would be meaningless
- let test_file = config_dir.join("test_write");
+ let test_file = approvals_dir.join("test_write");
if fs::write(&test_file, "test").is_ok() {
// Running as root or permissions don't work
// Restore write permissions and skip test
#[cfg(unix)]
{
let writable_perms = Permissions::from_mode(0o755);
- fs::set_permissions(config_dir, writable_perms).unwrap();
+ fs::set_permissions(approvals_dir, writable_perms).unwrap();
}
eprintln!("Skipping permission test - running with elevated privileges");
return;
}
// Try to save a new approval - this should fail
- let mut config = UserConfig::default();
- let result = config.approve_command(
+ let mut approvals = Approvals::default();
+ let result = approvals.approve_command(
"github.com/test/readonly".to_string(),
"test command".to_string(),
- Some(&config_path),
+ Some(&approvals_path),
);
// Restore write permissions so temp_dir can be cleaned up
#[cfg(unix)]
{
let writable_perms = Permissions::from_mode(0o755);
- fs::set_permissions(config_dir, writable_perms).unwrap();
+ fs::set_permissions(approvals_dir, writable_perms).unwrap();
}
// Verify the save failed
@@ -783,9 +747,6 @@ fn test_saving_through_symlink_preserves_symlink() {
// Create initial config at the target location
let initial_content = r#"# My dotfiles config
worktree-path = "../{{ main_worktree }}.{{ branch }}"
-
-[commit.generation]
-command = "llm -m claude-haiku-4.5"
"#;
fs::write(&target_path, initial_content).unwrap();
@@ -803,16 +764,12 @@ command = "llm -m claude-haiku-4.5"
"Symlink should point to target"
);
- // Load config and add an approval through the symlink path
+ // Load config and set commit generation command through the symlink path
let toml_str = fs::read_to_string(&symlink_path).unwrap();
let mut config: UserConfig = toml::from_str(&toml_str).unwrap();
config
- .approve_command(
- "github.com/test/symlink-repo".to_string(),
- "npm install".to_string(),
- Some(&symlink_path),
- )
+ .set_commit_generation_command("llm -m haiku".to_string(), Some(&symlink_path))
.unwrap();
// Verify symlink is preserved
@@ -829,8 +786,8 @@ command = "llm -m claude-haiku-4.5"
// Verify content was written to the target file
let target_content = fs::read_to_string(&target_path).unwrap();
assert!(
- target_content.contains("npm install"),
- "Approval should be written to target. Content:\n{target_content}"
+ target_content.contains("llm -m haiku"),
+ "Command should be written to target. Content:\n{target_content}"
);
assert!(
target_content.contains("# My dotfiles config"),
diff --git a/tests/integration_tests/approval_ui.rs b/tests/integration_tests/approval_ui.rs
index fede655a7..acc3ef2dc 100644
--- a/tests/integration_tests/approval_ui.rs
+++ b/tests/integration_tests/approval_ui.rs
@@ -89,7 +89,7 @@ third = "echo 'Third command'"
repo.commit("Add config");
// Pre-approve the second command
- repo.write_test_config(&format!(
+ repo.write_test_approvals(&format!(
r#"[projects.'{}']
approved-commands = ["echo 'Second command'"]
"#,
@@ -141,7 +141,7 @@ fn test_already_approved_commands_skip_prompt(repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command
- repo.write_test_config(&format!(
+ repo.write_test_approvals(&format!(
r#"[projects.'{}']
approved-commands = ["echo 'approved' > output.txt"]
"#,
@@ -172,7 +172,7 @@ third = "echo 'Third command'"
// Pre-approve the second command
fs::write(
- repo.test_config_path(),
+ repo.test_approvals_path(),
format!(
r#"[projects.'{}']
approved-commands = ["echo 'Second command'"]
diff --git a/tests/integration_tests/approvals.rs b/tests/integration_tests/approvals.rs
index 8e57eba24..7b24acd7d 100644
--- a/tests/integration_tests/approvals.rs
+++ b/tests/integration_tests/approvals.rs
@@ -3,7 +3,7 @@
use crate::common::{TestRepo, make_snapshot_cmd, repo, setup_snapshot_settings};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
-use worktrunk::config::UserConfig;
+use worktrunk::config::Approvals;
/// Helper to snapshot add-approvals command
fn snapshot_add_approvals(test_name: &str, repo: &TestRepo, args: &[&str]) {
@@ -69,12 +69,12 @@ fn test_clear_approvals_with_approvals(repo: TestRepo) {
repo.commit("Add config");
// Manually approve the command by writing to test config
- let mut config = UserConfig::default();
- config
+ let mut approvals = Approvals::default();
+ approvals
.approve_command(
project_id,
"echo 'test'".to_string(),
- Some(repo.test_config_path()),
+ Some(repo.test_approvals_path()),
)
.unwrap();
@@ -97,12 +97,12 @@ fn test_clear_approvals_global_with_approvals(repo: TestRepo) {
repo.commit("Add config");
// Manually approve the command
- let mut config = UserConfig::default();
- config
+ let mut approvals = Approvals::default();
+ approvals
.approve_command(
project_id,
"echo 'test'".to_string(),
- Some(repo.test_config_path()),
+ Some(repo.test_approvals_path()),
)
.unwrap();
@@ -124,12 +124,12 @@ fn test_clear_approvals_after_clear(repo: TestRepo) {
repo.commit("Add config");
// Manually approve the command
- let mut config = UserConfig::default();
- config
+ let mut approvals = Approvals::default();
+ approvals
.approve_command(
project_id.clone(),
"echo 'test'".to_string(),
- Some(repo.test_config_path()),
+ Some(repo.test_approvals_path()),
)
.unwrap();
@@ -158,26 +158,26 @@ lint = "echo 'third'"
// Manually approve all commands
let project_id = format!("{}/origin", repo.root_path().display());
- let mut config = UserConfig::default();
- config
+ let mut approvals = Approvals::default();
+ approvals
.approve_command(
project_id.clone(),
"echo 'first'".to_string(),
- Some(repo.test_config_path()),
+ Some(repo.test_approvals_path()),
)
.unwrap();
- config
+ approvals
.approve_command(
project_id.clone(),
"echo 'second'".to_string(),
- Some(repo.test_config_path()),
+ Some(repo.test_approvals_path()),
)
.unwrap();
- config
+ approvals
.approve_command(
project_id,
"echo 'third'".to_string(),
- Some(repo.test_config_path()),
+ Some(repo.test_approvals_path()),
)
.unwrap();
@@ -197,12 +197,12 @@ fn test_add_approvals_all_already_approved(repo: TestRepo) {
repo.commit("Add config");
// Manually approve the command
- let mut config = UserConfig::default();
- config
+ let mut approvals = Approvals::default();
+ approvals
.approve_command(
project_id,
"echo 'test'".to_string(),
- Some(repo.test_config_path()),
+ Some(repo.test_approvals_path()),
)
.unwrap();
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 343543dd5..3eec97c5b 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -18,8 +18,12 @@ fn test_config_show_with_project_config(mut repo: TestRepo, temp_home: TempDir)
fs::write(
global_config_dir.join("config.toml"),
r#"worktree-path = "../{{ repo }}.{{ branch }}"
-
-[projects."test-project"]
+"#,
+ )
+ .unwrap();
+ fs::write(
+ global_config_dir.join("approvals.toml"),
+ r#"[projects."test-project"]
approved-commands = ["npm install"]
"#,
)
diff --git a/tests/integration_tests/e2e_shell_post_start.rs b/tests/integration_tests/e2e_shell_post_start.rs
index 8fbb93530..6273f87c6 100644
--- a/tests/integration_tests/e2e_shell_post_start.rs
+++ b/tests/integration_tests/e2e_shell_post_start.rs
@@ -26,13 +26,11 @@ fn test_shell_integration_post_start_background(#[case] shell: &str, repo: TestR
repo.commit("Add post-start config");
// Pre-approve the command
- fs::write(
- repo.test_config_path(),
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["sleep 0.05 && echo 'Background task done' > bg_marker.txt"]
"#,
- )
- .unwrap();
+ );
let init_code = generate_init_code(&repo, shell);
let bin_path = wt_bin_dir();
@@ -116,16 +114,14 @@ task2 = "sleep 0.05 && echo 'Task 2' > task2.txt"
repo.commit("Add multiple post-start commands");
// Pre-approve commands
- fs::write(
- repo.test_config_path(),
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = [
"sleep 0.05 && echo 'Task 1' > task1.txt",
"sleep 0.05 && echo 'Task 2' > task2.txt",
]
"#,
- )
- .unwrap();
+ );
let init_code = generate_init_code(&repo, "bash");
let bin_path = wt_bin_dir();
@@ -174,13 +170,11 @@ fn test_bash_shell_integration_post_create_blocks(repo: TestRepo) {
repo.commit("Add post-create command");
// Pre-approve command
- fs::write(
- repo.test_config_path(),
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'Setup done' > setup.txt"]
"#,
- )
- .unwrap();
+ );
let init_code = generate_init_code(&repo, "bash");
let bin_path = wt_bin_dir();
@@ -242,13 +236,11 @@ fish_bg = "sleep 0.05 && echo 'Fish background done' > fish_bg.txt"
repo.commit("Add fish background command");
// Pre-approve command
- fs::write(
- repo.test_config_path(),
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["sleep 0.05 && echo 'Fish background done' > fish_bg.txt"]
"#,
- )
- .unwrap();
+ );
let init_code = generate_init_code(&repo, "fish");
let bin_path = wt_bin_dir();
diff --git a/tests/integration_tests/hook_show.rs b/tests/integration_tests/hook_show.rs
index 43f950347..60ed09fef 100644
--- a/tests/integration_tests/hook_show.rs
+++ b/tests/integration_tests/hook_show.rs
@@ -191,10 +191,15 @@ fn test_hook_show_approval_status(repo: TestRepo, temp_home: TempDir) {
let config_path = global_config_dir.join("config.toml");
fs::write(
&config_path,
+ r#"worktree-path = "../{{ repo }}.{{ branch }}"
+"#,
+ )
+ .unwrap();
+ let approvals_path = global_config_dir.join("approvals.toml");
+ fs::write(
+ &approvals_path,
format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
-
-[projects.'{project_id_str}']
+ r#"[projects.'{project_id_str}']
approved-commands = ["cargo build"]
"#
),
@@ -214,8 +219,9 @@ test = "cargo test"
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- // Override config path to point to our test config with approval
+ // Override config and approvals paths to point to our test files
cmd.env("WORKTRUNK_CONFIG_PATH", &config_path);
+ cmd.env("WORKTRUNK_APPROVALS_PATH", &approvals_path);
cmd.arg("hook").arg("show").current_dir(repo.root_path());
set_temp_home_env(&mut cmd, temp_home.path());
@@ -341,10 +347,9 @@ fn test_hook_clear_with_approvals(repo: TestRepo, temp_home: TempDir) {
// Get the canonical path for the project identifier (escaped for TOML)
let project_id_str = repo.project_id();
- // Create user config with approved commands for this project
- let global_config_dir = temp_home.path().join(".config").join("worktrunk");
- fs::create_dir_all(&global_config_dir).unwrap();
- let config_path = global_config_dir.join("config.toml");
+ // Write approved commands as a sibling config.toml of the test approvals path.
+ // The fallback reads config.toml from the same directory as approvals.toml.
+ let config_path = repo.test_approvals_path().with_file_name("config.toml");
fs::write(
&config_path,
format!(
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index 5e02ea4a4..ca27d1cdf 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -50,7 +50,7 @@ fn test_post_create_single_command(repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command by writing to the isolated test config
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'Setup complete'"]
"#,
@@ -77,7 +77,7 @@ setup = "echo 'Running setup'"
repo.commit("Add config with named commands");
// Pre-approve both commands in temp HOME
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = [
"echo 'Installing deps'",
@@ -102,7 +102,7 @@ fn test_post_create_failing_command(repo: TestRepo) {
repo.commit("Add config with failing command");
// Pre-approve the command in temp HOME
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["exit 1"]
"#,
@@ -133,10 +133,9 @@ root = "echo 'Root: {{ repo_path }}' >> info.txt"
// Pre-approve all commands in isolated test config
let repo_name = "repo";
- repo.write_test_config(
- r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"
-
-[projects."../origin"]
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}""#);
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
approved-commands = [
"echo 'Repo: {{ repo }}' > info.txt",
"echo 'Branch: {{ branch }}' >> info.txt",
@@ -210,10 +209,9 @@ setup = "echo 'Setting up {{ branch | sanitize }} in {{ worktree_path }}'"
repo.commit("Add config with templates");
// Pre-approve commands
- repo.write_test_config(
- r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}"
-
-[projects."../origin"]
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}""#);
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
approved-commands = [
"echo 'Setting up {{ branch | sanitize }} in {{ worktree_path }}'",
]
@@ -247,7 +245,7 @@ fn test_post_create_default_branch_template(repo: TestRepo) {
repo.commit("Add config with default_branch template");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'Default: {{ default_branch }}' > default.txt"]
"#,
@@ -401,7 +399,7 @@ fn test_post_create_upstream_conditional(#[from(repo_with_remote)] repo: TestRep
repo.commit("Add config with conditional upstream");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["{% if not upstream %}echo 'no-upstream' > upstream.txt{% else %}echo '{{ upstream }}' > upstream.txt{% endif %}"]
"#,
@@ -444,7 +442,7 @@ base_path = "echo 'Base Path: {{ base_worktree_path }}' >> base_info.txt"
repo.commit("Add config with base template variables");
// Pre-approve the commands
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = [
"echo 'Base: {{ base }}' > base_info.txt",
@@ -512,7 +510,7 @@ fn test_post_create_json_stdin(repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["cat > context.json"]
"#,
@@ -523,7 +521,8 @@ approved-commands = ["cat > context.json"]
let mut cmd = wt_command();
cmd.args(["switch", "--create", "feature-json"])
.current_dir(repo.root_path())
- .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())
+ .env("WORKTRUNK_APPROVALS_PATH", repo.test_approvals_path());
set_temp_home_env(&mut cmd, temp_home.path());
let output = cmd.output().expect("failed to run wt switch");
@@ -611,7 +610,7 @@ setup = "./scripts/setup.py"
repo.commit("Add setup script and config");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["./scripts/setup.py"]
"#,
@@ -622,7 +621,8 @@ approved-commands = ["./scripts/setup.py"]
let mut cmd = wt_command();
cmd.args(["switch", "--create", "feature-script"])
.current_dir(repo.root_path())
- .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())
+ .env("WORKTRUNK_APPROVALS_PATH", repo.test_approvals_path());
set_temp_home_env(&mut cmd, temp_home.path());
let output = cmd.output().expect("failed to run wt switch");
@@ -678,7 +678,7 @@ fn test_post_start_json_stdin(repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["cat > context.json"]
"#,
@@ -689,7 +689,8 @@ approved-commands = ["cat > context.json"]
let mut cmd = wt_command();
cmd.args(["switch", "--create", "bg-json"])
.current_dir(repo.root_path())
- .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())
+ .env("WORKTRUNK_APPROVALS_PATH", repo.test_approvals_path());
set_temp_home_env(&mut cmd, temp_home.path());
let output = cmd.output().expect("failed to run wt switch");
@@ -734,7 +735,7 @@ fn test_post_start_single_background_command(repo: TestRepo) {
repo.commit("Add background command");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["sleep 0.1 && echo 'Background task done' > background.txt"]
"#,
@@ -771,7 +772,7 @@ setup = "echo 'verbose test' > verbose.txt"
repo.commit("Add background command");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'verbose test' > verbose.txt"]
"#,
@@ -798,7 +799,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
repo.commit("Add multiple background commands");
// Pre-approve both commands
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = [
"echo 'Task 1 running' > task1.txt",
@@ -834,7 +835,7 @@ server = "sleep 0.05 && echo 'Server running' > server.txt"
repo.commit("Add both command types");
// Pre-approve all commands
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = [
"echo 'Setup done' > setup.txt",
@@ -880,7 +881,7 @@ fn test_post_start_log_file_captures_output(repo: TestRepo) {
repo.commit("Add command with stdout/stderr");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'stdout output' && echo 'stderr output' >&2"]
"#,
@@ -934,7 +935,7 @@ fn test_post_start_invalid_command_handling(repo: TestRepo) {
repo.commit("Add invalid command");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'unclosed quote"]
"#,
@@ -969,7 +970,7 @@ task3 = "echo 'TASK3_OUTPUT'"
repo.commit("Add three background commands");
// Pre-approve all commands
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = [
"echo 'TASK1_OUTPUT'",
@@ -1042,7 +1043,7 @@ fn test_execute_flag_with_post_start_commands(repo: TestRepo) {
repo.commit("Add background command");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'Background task' > background.txt"]
"#,
@@ -1082,7 +1083,7 @@ fn test_post_start_complex_shell_commands(repo: TestRepo) {
repo.commit("Add complex shell command");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'line1\nline2\nline3' | grep line2 > filtered.txt"]
"#,
@@ -1118,10 +1119,9 @@ echo 'third line' >> multiline.txt
echo 'second line' >> multiline.txt
echo 'third line' >> multiline.txt
";
- repo.write_test_config(&format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
-
-[projects."../origin"]
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
approved-commands = ["""
{}"""]
"#,
@@ -1170,10 +1170,9 @@ else
echo 'File exists' > result.txt
fi
";
- repo.write_test_config(&format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
-
-[projects."../origin"]
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
approved-commands = ["""
{}"""]
"#,
@@ -1213,7 +1212,7 @@ fn test_post_start_skipped_on_existing_worktree(repo: TestRepo) {
repo.commit("Add post-start config");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'POST-START-RAN' > post_start_marker.txt"]
"#,
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 7d25fc2d5..42085ebe7 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1170,7 +1170,7 @@ fn test_pre_remove_hook_executes(mut repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'About to remove worktree'"]
"#,
@@ -1201,7 +1201,7 @@ worktree_name = "echo 'Name: {{ worktree_name }}'"
repo.commit("Add config with templates");
// Pre-approve the commands (templates match what's shown in prompts)
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = [
"echo 'Branch: {{ branch }}'",
@@ -1238,10 +1238,9 @@ fn test_pre_remove_hook_runs_in_background_mode(mut repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command
- repo.write_test_config(&format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
-
-[projects."../origin"]
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
approved-commands = ["echo 'hook ran' > {}"]
"#,
marker_file.to_slash_lossy()
@@ -1275,7 +1274,7 @@ fn test_pre_remove_hook_failure_aborts(mut repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["exit 1"]
"#,
@@ -1309,7 +1308,7 @@ fn test_pre_remove_hook_failure_no_cd_directive(mut repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["exit 1"]
"#,
@@ -1362,10 +1361,9 @@ fn test_pre_remove_hook_not_for_branch_only(repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command
- repo.write_test_config(&format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
-
-[projects."../origin"]
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
approved-commands = ["echo 'hook ran' > {}"]
"#,
marker_file.to_slash_lossy()
@@ -1407,10 +1405,9 @@ fn test_pre_remove_hook_skipped_with_no_verify(mut repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command (even though it shouldn't run)
- repo.write_test_config(&format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
-
-[projects."../origin"]
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
approved-commands = ["echo 'hook ran' > {}"]
"#,
marker_file.to_slash_lossy()
@@ -1464,10 +1461,9 @@ fn test_pre_remove_hook_runs_for_detached_head(mut repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command
- repo.write_test_config(&format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
-
-[projects."../origin"]
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
approved-commands = ["touch {marker_path}"]
"#,
));
@@ -1505,10 +1501,9 @@ fn test_pre_remove_hook_runs_for_detached_head_background(mut repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the commands
- repo.write_test_config(&format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
-
-[projects."../origin"]
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
approved-commands = ["touch {marker_path}"]
"#,
));
@@ -1555,10 +1550,9 @@ fn test_pre_remove_hook_branch_expansion_detached_head(mut repo: TestRepo) {
repo.commit("Add config");
// Pre-approve the command
- repo.write_test_config(&format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
-
-[projects."../origin"]
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
approved-commands = ["echo 'branch={{{{ branch }}}}' > {branch_path}"]
"#,
));
@@ -1572,6 +1566,7 @@ approved-commands = ["echo 'branch={{{{ branch }}}}' > {branch_path}"]
.args(["remove", "--foreground"])
.current_dir(&worktree_path)
.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())
+ .env("WORKTRUNK_APPROVALS_PATH", repo.test_approvals_path())
.output()
.expect("Failed to execute wt remove");
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index 00a13fd3e..c88b170cb 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -195,6 +195,7 @@ fn build_shell_script(shell: &str, repo: &TestRepo, subcommand: &str, args: &[&s
// Properly quote paths to handle special characters like single quotes
let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
let config_path_quoted = shell_quote(&repo.test_config_path().display().to_string());
+ let approvals_path_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
match shell {
"fish" => {
@@ -203,6 +204,10 @@ fn build_shell_script(shell: &str, repo: &TestRepo, subcommand: &str, args: &[&s
"set -x WORKTRUNK_CONFIG_PATH {}\n",
config_path_quoted
));
+ script.push_str(&format!(
+ "set -x WORKTRUNK_APPROVALS_PATH {}\n",
+ approvals_path_quoted
+ ));
script.push_str("set -x CLICOLOR_FORCE 1\n");
}
"nu" => {
@@ -212,6 +217,10 @@ fn build_shell_script(shell: &str, repo: &TestRepo, subcommand: &str, args: &[&s
"$env.WORKTRUNK_CONFIG_PATH = {}\n",
config_path_quoted
));
+ script.push_str(&format!(
+ "$env.WORKTRUNK_APPROVALS_PATH = {}\n",
+ approvals_path_quoted
+ ));
script.push_str("$env.CLICOLOR_FORCE = '1'\n");
}
"zsh" => {
@@ -226,17 +235,27 @@ fn build_shell_script(shell: &str, repo: &TestRepo, subcommand: &str, args: &[&s
"export WORKTRUNK_CONFIG_PATH={}\n",
config_path_quoted
));
+ script.push_str(&format!(
+ "export WORKTRUNK_APPROVALS_PATH={}\n",
+ approvals_path_quoted
+ ));
script.push_str("export CLICOLOR_FORCE=1\n");
}
"powershell" | "pwsh" => {
// PowerShell uses $env: for environment variables
let wt_bin_ps = powershell_quote(&wt_bin.display().to_string());
let config_path_ps = powershell_quote(&repo.test_config_path().display().to_string());
+ let approvals_path_ps =
+ powershell_quote(&repo.test_approvals_path().display().to_string());
script.push_str(&format!("$env:WORKTRUNK_BIN = {}\n", wt_bin_ps));
script.push_str(&format!(
"$env:WORKTRUNK_CONFIG_PATH = {}\n",
config_path_ps
));
+ script.push_str(&format!(
+ "$env:WORKTRUNK_APPROVALS_PATH = {}\n",
+ approvals_path_ps
+ ));
script.push_str("$env:CLICOLOR_FORCE = '1'\n");
}
_ => {
@@ -246,6 +265,10 @@ fn build_shell_script(shell: &str, repo: &TestRepo, subcommand: &str, args: &[&s
"export WORKTRUNK_CONFIG_PATH={}\n",
config_path_quoted
));
+ script.push_str(&format!(
+ "export WORKTRUNK_APPROVALS_PATH={}\n",
+ approvals_path_quoted
+ ));
script.push_str("export CLICOLOR_FORCE=1\n");
}
}
@@ -685,8 +708,9 @@ fn exec_through_wrapper_with_env(
let script = build_shell_script(shell, repo, subcommand, args);
let config_path = repo.test_config_path().to_string_lossy().to_string();
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
- let mut env_vars = build_test_env_vars(&config_path);
+ let mut env_vars = build_test_env_vars(&config_path, &approvals_path);
env_vars.push(("CLICOLOR_FORCE", "1"));
// Add extra env vars (these can override defaults if needed)
env_vars.extend(extra_env.iter().copied());
@@ -717,13 +741,20 @@ const STANDARD_TEST_ENV: &[(&str, &str)] = &[
("WORKTRUNK_TEST_EPOCH", "1735776000"),
];
-/// Build standard test env vars with config path
+/// Build standard test env vars with config and approvals paths
///
-/// Returns a Vec containing STANDARD_TEST_ENV plus WORKTRUNK_CONFIG_PATH.
-/// The caller must keep `config_path` alive for the duration of the returned Vec's use.
+/// Returns a Vec containing STANDARD_TEST_ENV plus WORKTRUNK_CONFIG_PATH and
+/// WORKTRUNK_APPROVALS_PATH. The caller must keep both path strings alive for
+/// the duration of the returned Vec's use.
#[cfg(test)]
-fn build_test_env_vars(config_path: &str) -> Vec<(&str, &str)> {
- let mut env_vars: Vec<(&str, &str)> = vec![("WORKTRUNK_CONFIG_PATH", config_path)];
+fn build_test_env_vars<'a>(
+ config_path: &'a str,
+ approvals_path: &'a str,
+) -> Vec<(&'a str, &'a str)> {
+ let mut env_vars: Vec<(&str, &str)> = vec![
+ ("WORKTRUNK_CONFIG_PATH", config_path),
+ ("WORKTRUNK_APPROVALS_PATH", approvals_path),
+ ];
env_vars.extend_from_slice(STANDARD_TEST_ENV);
env_vars
}
@@ -1050,9 +1081,8 @@ watch = "echo 'Watching for file changes'"
repo.commit("Add hooks");
- // Pre-approve the commands in user config
- fs::write(
- repo.test_config_path(),
+ // Pre-approve the commands
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = [
"echo 'Installing dependencies...'",
@@ -1061,8 +1091,7 @@ approved-commands = [
"echo 'Watching for file changes'",
]
"#,
- )
- .unwrap();
+ );
let output = exec_through_wrapper(shell, &repo, "switch", &["--create", "feature-hooks"]);
@@ -1100,7 +1129,7 @@ test = "echo '✓ All 47 tests passed in 2.3s'"
let feature_wt = repo.add_feature();
// Pre-approve commands
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = [
"echo '✓ Code formatting check passed'",
@@ -1156,7 +1185,7 @@ test = "echo '✗ Test suite failed: 3 tests failing' && exit 1"
);
// Pre-approve the commands
- repo.write_test_config(
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = [
"echo '✓ Code formatting check passed'",
@@ -1220,11 +1249,11 @@ check2 = "{} check2 3"
repo.commit("Add pre-merge validation with mixed output");
let feature_wt = repo.add_feature();
- // Pre-approve commands
- repo.write_test_config(&format!(
- r#"worktree-path = "../{{{{ repo }}}}.{{{{ branch }}}}"
+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
-[projects."../origin"]
+ // Pre-approve commands
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
approved-commands = [
"{} check1 3",
"{} check2 3",
@@ -1271,14 +1300,12 @@ approved-commands = [
repo.commit("Add post-start command");
- // Pre-approve the command in user config
- fs::write(
- repo.test_config_path(),
+ // Pre-approve the command
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'test command executed'"]
"#,
- )
- .unwrap();
+ );
let output =
exec_through_wrapper("bash", &repo, "switch", &["--create", "feature-with-hooks"]);
@@ -1413,14 +1440,12 @@ approved-commands = ["echo 'test command executed'"]
repo.commit("Add post-start command");
- // Pre-approve the command in user config
- fs::write(
- repo.test_config_path(),
+ // Pre-approve the command
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'background task'"]
"#,
- )
- .unwrap();
+ );
let output = exec_through_wrapper("bash", &repo, "switch", &["--create", "feature-bg"]);
@@ -1460,14 +1485,12 @@ approved-commands = ["echo 'background task'"]
repo.commit("Add post-start command");
- // Pre-approve the command in user config
- fs::write(
- repo.test_config_path(),
+ // Pre-approve the command
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'fish background task'"]
"#,
- )
- .unwrap();
+ );
let output = exec_through_wrapper("fish", &repo, "switch", &["--create", "fish-bg"]);
@@ -1567,22 +1590,35 @@ approved-commands = ["echo 'fish background task'"]
// Set environment variables (use shell_quote to handle paths with special chars)
let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
+ let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
match shell {
"fish" => {
script.push_str(&format!("set -x WORKTRUNK_BIN {}\n", wt_bin_quoted));
script.push_str(&format!("set -x WORKTRUNK_CONFIG_PATH {}\n", config_quoted));
+ script.push_str(&format!(
+ "set -x WORKTRUNK_APPROVALS_PATH {}\n",
+ approvals_quoted
+ ));
script.push_str("set -x CLICOLOR_FORCE 1\n");
}
"zsh" => {
script.push_str("autoload -Uz compinit && compinit -i 2>/dev/null\n");
script.push_str(&format!("export WORKTRUNK_BIN={}\n", wt_bin_quoted));
script.push_str(&format!("export WORKTRUNK_CONFIG_PATH={}\n", config_quoted));
+ script.push_str(&format!(
+ "export WORKTRUNK_APPROVALS_PATH={}\n",
+ approvals_quoted
+ ));
script.push_str("export CLICOLOR_FORCE=1\n");
}
_ => {
// bash
script.push_str(&format!("export WORKTRUNK_BIN={}\n", wt_bin_quoted));
script.push_str(&format!("export WORKTRUNK_CONFIG_PATH={}\n", config_quoted));
+ script.push_str(&format!(
+ "export WORKTRUNK_APPROVALS_PATH={}\n",
+ approvals_quoted
+ ));
script.push_str("export CLICOLOR_FORCE=1\n");
}
}
@@ -1603,9 +1639,11 @@ approved-commands = ["echo 'fish background task'"]
};
let config_path = repo.test_config_path().to_string_lossy().to_string();
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
let env_vars: Vec<(&str, &str)> = vec![
("CLICOLOR_FORCE", "1"),
("WORKTRUNK_CONFIG_PATH", &config_path),
+ ("WORKTRUNK_APPROVALS_PATH", &approvals_path),
("TERM", "xterm"),
("GIT_AUTHOR_NAME", "Test User"),
("GIT_AUTHOR_EMAIL", "[email protected]"),
@@ -1676,13 +1714,11 @@ approved-commands = ["echo 'fish background task'"]
repo.commit("Add post-start command");
// Pre-approve the command
- fs::write(
- repo.test_config_path(),
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'background job'"]
"#,
- )
- .unwrap();
+ );
let output = exec_through_wrapper("zsh", &repo, "switch", &["--create", "zsh-job-test"]);
@@ -1726,31 +1762,33 @@ approved-commands = ["echo 'background job'"]
repo.commit("Add post-start command");
// Pre-approve the command
- fs::write(
- repo.test_config_path(),
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'bash background'"]
"#,
- )
- .unwrap();
+ );
// Build the setup script that defines the wt function
let wt_bin = wt_bin();
let wrapper_script = generate_wrapper(&repo, "bash");
let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
+ let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
let setup_script = format!(
"export WORKTRUNK_BIN={}\n\
export WORKTRUNK_CONFIG_PATH={}\n\
+ export WORKTRUNK_APPROVALS_PATH={}\n\
export CLICOLOR_FORCE=1\n\
{}",
- wt_bin_quoted, config_quoted, wrapper_script
+ wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script
);
let config_path = repo.test_config_path().to_string_lossy().to_string();
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
let env_vars: Vec<(&str, &str)> = vec![
("CLICOLOR_FORCE", "1"),
("WORKTRUNK_CONFIG_PATH", &config_path),
+ ("WORKTRUNK_APPROVALS_PATH", &approvals_path),
("TERM", "xterm"),
("GIT_AUTHOR_NAME", "Test User"),
("GIT_AUTHOR_EMAIL", "[email protected]"),
@@ -1801,21 +1839,27 @@ approved-commands = ["echo 'bash background'"]
// (completions are inline in the wrapper via lazy loading)
let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
+ let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
let script = format!(
r#"
export WORKTRUNK_BIN={}
export WORKTRUNK_CONFIG_PATH={}
+ export WORKTRUNK_APPROVALS_PATH={}
{}
# Check if wt completion is registered
complete -p wt 2>/dev/null && echo "__COMPLETION_REGISTERED__" || echo "__NO_COMPLETION__"
"#,
- wt_bin_quoted, config_quoted, wrapper_script
+ wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script
);
let final_script = format!("( {} ) 2>&1", script);
let config_path = repo.test_config_path().to_string_lossy().to_string();
- let env_vars: Vec<(&str, &str)> =
- vec![("WORKTRUNK_CONFIG_PATH", &config_path), ("TERM", "xterm")];
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
+ let env_vars: Vec<(&str, &str)> = vec![
+ ("WORKTRUNK_CONFIG_PATH", &config_path),
+ ("WORKTRUNK_APPROVALS_PATH", &approvals_path),
+ ("TERM", "xterm"),
+ ];
let (combined, exit_code) =
exec_in_pty_interactive("bash", &final_script, repo.root_path(), &env_vars, &[]);
@@ -1838,10 +1882,12 @@ approved-commands = ["echo 'bash background'"]
// Script that sources wrapper, completions, and checks if completion is registered
let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
+ let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
let script = format!(
r#"
set -x WORKTRUNK_BIN {}
set -x WORKTRUNK_CONFIG_PATH {}
+ set -x WORKTRUNK_APPROVALS_PATH {}
{}
{}
# Check if wt completions are registered
@@ -1851,13 +1897,17 @@ approved-commands = ["echo 'bash background'"]
echo "__NO_COMPLETION__"
end
"#,
- wt_bin_quoted, config_quoted, wrapper_script, completions_script
+ wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script, completions_script
);
let final_script = format!("begin\n{}\nend 2>&1", script);
let config_path = repo.test_config_path().to_string_lossy().to_string();
- let env_vars: Vec<(&str, &str)> =
- vec![("WORKTRUNK_CONFIG_PATH", &config_path), ("TERM", "xterm")];
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
+ let env_vars: Vec<(&str, &str)> = vec![
+ ("WORKTRUNK_CONFIG_PATH", &config_path),
+ ("WORKTRUNK_APPROVALS_PATH", &approvals_path),
+ ("TERM", "xterm"),
+ ];
let (combined, exit_code) =
exec_in_pty_interactive("fish", &final_script, repo.root_path(), &env_vars, &[]);
@@ -1885,11 +1935,13 @@ approved-commands = ["echo 'bash background'"]
// Script that sources wrapper and checks if wt function exists
let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
+ let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
let marker_quoted = shell_quote(&marker_path);
let script = format!(
r#"
export WORKTRUNK_BIN={wt_bin}
export WORKTRUNK_CONFIG_PATH={config}
+ export WORKTRUNK_APPROVALS_PATH={approvals}
{wrapper}
# Check if wt wrapper function is defined and write result to marker file
if (( $+functions[wt] )); then
@@ -1900,14 +1952,17 @@ approved-commands = ["echo 'bash background'"]
"#,
wt_bin = wt_bin_quoted,
config = config_quoted,
+ approvals = approvals_quoted,
wrapper = wrapper_script,
marker = marker_quoted,
);
let final_script = format!("( {} ) 2>&1", script);
let config_path = repo.test_config_path().to_string_lossy().to_string();
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
let env_vars: Vec<(&str, &str)> = vec![
("WORKTRUNK_CONFIG_PATH", &config_path),
+ ("WORKTRUNK_APPROVALS_PATH", &approvals_path),
("TERM", "xterm"),
("ZDOTDIR", "/dev/null"),
];
@@ -1988,6 +2043,7 @@ approved-commands = ["echo 'bash background'"]
// Use shell_quote to handle paths with special chars (like single quotes)
let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
+ let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
// Script that explicitly removes wt from PATH but sets WORKTRUNK_BIN
let script = match shell {
@@ -1998,12 +2054,13 @@ approved-commands = ["echo 'bash background'"]
export PATH="/usr/bin:/bin"
export WORKTRUNK_BIN={}
export WORKTRUNK_CONFIG_PATH={}
+ export WORKTRUNK_APPROVALS_PATH={}
export CLICOLOR_FORCE=1
{}
wt switch --create fallback-test
echo "__PWD__ $PWD"
"#,
- wt_bin_quoted, config_quoted, wrapper_script
+ wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script
),
"fish" => format!(
r#"
@@ -2011,12 +2068,13 @@ approved-commands = ["echo 'bash background'"]
set -x PATH /usr/bin /bin
set -x WORKTRUNK_BIN {}
set -x WORKTRUNK_CONFIG_PATH {}
+ set -x WORKTRUNK_APPROVALS_PATH {}
set -x CLICOLOR_FORCE 1
{}
wt switch --create fallback-test
echo "__PWD__ $PWD"
"#,
- wt_bin_quoted, config_quoted, wrapper_script
+ wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script
),
_ => format!(
r#"
@@ -2024,12 +2082,13 @@ approved-commands = ["echo 'bash background'"]
export PATH="/usr/bin:/bin"
export WORKTRUNK_BIN={}
export WORKTRUNK_CONFIG_PATH={}
+ export WORKTRUNK_APPROVALS_PATH={}
export CLICOLOR_FORCE=1
{}
wt switch --create fallback-test
echo "__PWD__ $PWD"
"#,
- wt_bin_quoted, config_quoted, wrapper_script
+ wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script
),
};
@@ -2039,7 +2098,8 @@ approved-commands = ["echo 'bash background'"]
};
let config_path = repo.test_config_path().to_string_lossy().to_string();
- let env_vars = build_test_env_vars(&config_path);
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
+ let env_vars = build_test_env_vars(&config_path, &approvals_path);
let (combined, exit_code) =
exec_in_pty_interactive(shell, &final_script, repo.root_path(), &env_vars, &[]);
@@ -2106,7 +2166,8 @@ approved-commands = ["echo 'bash background'"]
let final_script = format!("begin\n{}\nend 2>&1", script);
let config_path = repo.test_config_path().to_string_lossy().to_string();
- let env_vars = build_test_env_vars(&config_path);
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
+ let env_vars = build_test_env_vars(&config_path, &approvals_path);
let (combined, exit_code) =
exec_in_pty_interactive(shell, &final_script, repo.root_path(), &env_vars, &[]);
@@ -2175,7 +2236,8 @@ approved-commands = ["echo 'bash background'"]
let final_script = format!("begin\n{}\nend 2>&1", script);
let config_path = repo.test_config_path().to_string_lossy().to_string();
- let env_vars = build_test_env_vars(&config_path);
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
+ let env_vars = build_test_env_vars(&config_path, &approvals_path);
let (combined, exit_code) =
exec_in_pty_interactive(shell, &final_script, repo.root_path(), &env_vars, &[]);
@@ -2243,13 +2305,11 @@ approved-commands = ["echo 'bash background'"]
repo.commit("Add post-start command");
// Pre-approve the command
- fs::write(
- repo.test_config_path(),
+ repo.write_test_approvals(
r#"[projects."../origin"]
approved-commands = ["echo 'cleanup test'"]
"#,
- )
- .unwrap();
+ );
// Run a command that exercises the full FIFO/background job code path
let output = exec_through_wrapper(shell, &repo, "switch", &["--create", "cleanup-test"]);
@@ -3677,6 +3737,7 @@ mod windows_tests {
let script = format!(
"$env:WORKTRUNK_BIN = {}\n\
$env:WORKTRUNK_CONFIG_PATH = {}\n\
+ $env:WORKTRUNK_APPROVALS_PATH = {}\n\
{}\n\
if (Get-Command wt -CommandType Function -ErrorAction SilentlyContinue) {{\n\
Write-Host 'WRAPPER_REGISTERED'\n\
@@ -3687,11 +3748,13 @@ mod windows_tests {
}}",
powershell_quote(&wt_bin.display().to_string()),
powershell_quote(&repo.test_config_path().display().to_string()),
+ powershell_quote(&repo.test_approvals_path().display().to_string()),
wrapper_script
);
let config_path = repo.test_config_path().to_string_lossy().to_string();
- let env_vars = build_test_env_vars(&config_path);
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
+ let env_vars = build_test_env_vars(&config_path, &approvals_path);
let (combined, exit_code) =
exec_in_pty_interactive("powershell", &script, repo.root_path(), &env_vars, &[]);
@@ -3720,6 +3783,7 @@ mod windows_tests {
let script = format!(
"$env:WORKTRUNK_BIN = {}\n\
$env:WORKTRUNK_CONFIG_PATH = {}\n\
+ $env:WORKTRUNK_APPROVALS_PATH = {}\n\
{}\n\
$completers = Get-ArgumentCompleter -Native\n\
if ($completers | Where-Object {{ $_.CommandName -eq 'wt' }}) {{\n\
@@ -3731,11 +3795,13 @@ mod windows_tests {
}}",
powershell_quote(&wt_bin.display().to_string()),
powershell_quote(&repo.test_config_path().display().to_string()),
+ powershell_quote(&repo.test_approvals_path().display().to_string()),
wrapper_script
);
let config_path = repo.test_config_path().to_string_lossy().to_string();
- let env_vars = build_test_env_vars(&config_path);
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
+ let env_vars = build_test_env_vars(&config_path, &approvals_path);
let (combined, exit_code) =
exec_in_pty_interactive("powershell", &script, repo.root_path(), &env_vars, &[]);
@@ -3806,15 +3872,18 @@ mod windows_tests {
let script = format!(
"$env:WORKTRUNK_BIN = {}\n\
$env:WORKTRUNK_CONFIG_PATH = {}\n\
+ $env:WORKTRUNK_APPROVALS_PATH = {}\n\
{}\n\
Write-Host \"BIN_PATH: $env:WORKTRUNK_BIN\"",
powershell_quote(&wt_bin.display().to_string()),
powershell_quote(&repo.test_config_path().display().to_string()),
+ powershell_quote(&repo.test_approvals_path().display().to_string()),
wrapper_script
);
let config_path = repo.test_config_path().to_string_lossy().to_string();
- let env_vars = build_test_env_vars(&config_path);
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
+ let env_vars = build_test_env_vars(&config_path, &approvals_path);
let (combined, exit_code) =
exec_in_pty_interactive("powershell", &script, repo.root_path(), &env_vars, &[]);
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index c61885be9..010d8f49a 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -70,8 +70,10 @@ fn test_user_hooks_run_before_project_hooks(repo: TestRepo) {
repo.write_test_config(
r#"[post-create]
log = "echo 'USER_HOOK' >> hook_order.txt"
-
-[projects."../origin"]
+"#,
+ );
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
approved-commands = ["echo 'PROJECT_HOOK' >> hook_order.txt"]
"#,
);
@@ -122,8 +124,10 @@ fn test_no_verify_flag_skips_all_hooks(repo: TestRepo) {
repo.write_test_config(
r#"[post-create]
log = "echo 'USER_HOOK' > user_marker.txt"
-
-[projects."../origin"]
+"#,
+ );
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
approved-commands = ["echo 'PROJECT_HOOK' > project_marker.txt"]
"#,
);
@@ -937,8 +941,10 @@ fn test_user_and_project_unnamed_post_start(repo: TestRepo) {
// Write user config with unnamed hook AND pre-approve project command
repo.write_test_config(
r#"post-start = "echo 'USER_POST_START' > user_bg.txt"
-
-[projects."../origin"]
+"#,
+ );
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
approved-commands = ["echo 'PROJECT_POST_START' > project_bg.txt"]
"#,
);
@@ -976,8 +982,10 @@ fn test_user_and_project_post_start_both_run(repo: TestRepo) {
repo.write_test_config(
r#"[post-start]
bg = "echo 'USER_POST_START' > user_bg.txt"
-
-[projects."../origin"]
+"#,
+ );
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
approved-commands = ["echo 'PROJECT_POST_START' > project_bg.txt"]
"#,
);
diff --git a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap
index 71e2463e2..57be5e532 100644
--- a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap
+++ b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap
@@ -7,7 +7,7 @@ expression: "&output"
  echo 'test command'
❯ Allow and remember? [y/N] y
-▲ Failed to save command approval: Failed to write config file: Permission denied (os error 13)
+▲ Failed to save command approval: Failed to open lock file: Permission denied (os error 13)
↳ Approval will be requested again next time.
◎ Running post-create project hook @ _REPO_.test-permission
  echo 'test command'
diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_with_project_config.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_with_project_config.snap
index 1e9c02871..a162e8e59 100644
--- a/tests/snapshots/integration__integration_tests__config_show__config_show_with_project_config.snap
+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_with_project_config.snap
@@ -25,10 +25,12 @@ info:
SHELL: ""
TERM: alacritty
USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -40,9 +42,6 @@ exit_code: 0
----- stderr -----
USER CONFIG ~/.config/worktrunk/config.toml
  worktree-path = "../{{ repo }}.{{ branch }}"
- 
-  [projects."test-project"]
-  approved-commands = ["npm install"]
PROJECT CONFIG _REPO_/.config/wt.toml
  post-create = "npm install"
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index 88aac3dc2..5e8c9a472 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -16,10 +16,12 @@ info:
RUST_LOG: warn
SHELL: ""
TERM: alacritty
+ WORKTRUNK_APPROVALS_PATH: /nonexistent/test/approvals.toml
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
---
@@ -147,12 +149,11 @@ Creates ~/.config/worktrunk/config.toml with the following content:
#
# #### Approved hook commands
#
- # When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved here, preventing repeated prompts.
+ # When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved to `~/.config/worktrunk/approvals.toml` (separate from user config to allow dotfile management of config.toml).
#
- # [projects."github.com/user/repo"]
- # approved-commands = ["npm ci", "npm test"]
+ # To reset, run `wt hook approvals clear`.
#
- # To reset, delete the entry or run `wt hook approvals clear`.
+ # > **Migration note:** Approvals were previously stored as `approved-commands` in config.toml. Run `wt config show` to generate a migration file that removes stale entries.
#
# #### Setting overrides (Experimental)
#
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 1ec9e27b3..5f26111ef 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -15,10 +15,12 @@ info:
RUST_LOG: warn
SHELL: ""
TERM: alacritty
+ WORKTRUNK_APPROVALS_PATH: /nonexistent/test/approvals.toml
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
---
@@ -189,12 +191,11 @@ Entries are keyed by project identifier (e.g., github.com/user/repo).
Approved hook commands
-When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved here, preventing repeated prompts.
+When a project hook runs for the first time, Worktrunk asks for approval. Approved commands are saved to ~/.config/worktrunk/approvals.toml (separate from user config to allow dotfile management of config.toml).
- [projects."github.com/user/repo"]
- approved-commands = ["npm ci", "npm test"]
+To reset, run wt hook approvals clear.
-To reset, delete the entry or run wt hook approvals clear.
+> Migration note: Approvals were previously stored as approved-commands in config.toml. Run wt config show to generate a migration file that removes stale entries.
Setting overrides (Experimental)
diff --git a/tests/snapshots/integration__integration_tests__help__help_hook_approvals.snap b/tests/snapshots/integration__integration_tests__help__help_hook_approvals.snap
index b05737de3..b5fb9897a 100644
--- a/tests/snapshots/integration__integration_tests__help__help_hook_approvals.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_hook_approvals.snap
@@ -16,10 +16,12 @@ info:
RUST_LOG: warn
SHELL: ""
TERM: alacritty
+ WORKTRUNK_APPROVALS_PATH: /nonexistent/test/approvals.toml
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
---
@@ -33,8 +35,8 @@ wt hook approvals - Manage command approvals
Usage: wt hook approvals [OPTIONS] <COMMAND>
Commands:
- add Store approvals in config
- clear Clear approved commands from config
+ add Store approvals in approvals.toml
+ clear Clear approved commands from approvals.toml
Options:
-h, --help
@@ -65,4 +67,4 @@ Clear global approvals:
How approvals work
-Approved commands are saved to user config. Re-approval is required when the command template changes or the project moves. Use --yes to bypass prompts in CI.
+Approved commands are saved to ~/.config/worktrunk/approvals.toml. Re-approval is required when the command template changes or the project moves. Use --yes to bypass prompts in CI.
diff --git a/tests/snapshots/integration__integration_tests__help__help_hook_approvals_add.snap b/tests/snapshots/integration__integration_tests__help__help_hook_approvals_add.snap
index 79159982f..9247e7d52 100644
--- a/tests/snapshots/integration__integration_tests__help__help_hook_approvals_add.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_hook_approvals_add.snap
@@ -17,10 +17,12 @@ info:
RUST_LOG: warn
SHELL: ""
TERM: alacritty
+ WORKTRUNK_APPROVALS_PATH: /nonexistent/test/approvals.toml
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
---
@@ -29,7 +31,7 @@ exit_code: 0
----- stdout -----
----- stderr -----
-wt hook approvals add - Store approvals in config
+wt hook approvals add - Store approvals in approvals.toml
Usage: wt hook approvals add [OPTIONS]
@@ -50,7 +52,7 @@ Usage: wt hook approvals add [OPTIONS]
-v, --verbose...
Verbose output (-v: hooks, templates; -vv: debug report)
-Prompts for approval of all project commands and saves them to user config.
+Prompts for approval of all project commands and saves them to approvals.toml.
By default, shows only unapproved commands. Use --all to review all commands
including previously approved ones.
diff --git a/tests/snapshots/integration__integration_tests__help__help_hook_approvals_clear.snap b/tests/snapshots/integration__integration_tests__help__help_hook_approvals_clear.snap
index 4d6c67fc4..331df2b75 100644
--- a/tests/snapshots/integration__integration_tests__help__help_hook_approvals_clear.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_hook_approvals_clear.snap
@@ -17,10 +17,12 @@ info:
RUST_LOG: warn
SHELL: ""
TERM: alacritty
+ WORKTRUNK_APPROVALS_PATH: /nonexistent/test/approvals.toml
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
---
@@ -29,7 +31,7 @@ exit_code: 0
----- stdout -----
----- stderr -----
-wt hook approvals clear - Clear approved commands from config
+wt hook approvals clear - Clear approved commands from approvals.toml
Usage: wt hook approvals clear [OPTIONS]