Skip to content

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

Report unreadable config files and share layer loading (#4564)

Maximilian Roosbc828a714322
diff --git a/src/config/user/mod.rs b/src/config/user/mod.rs
index ee5c7c39b..7566fa29c 100644
--- a/src/config/user/mod.rs
+++ b/src/config/user/mod.rs
@@ -701,32 +701,60 @@ impl UserConfig {
let mut warnings = Vec::new();
let mut merged_table = toml::Table::new();
- // 1. System config (lowest priority)
- if let Some(system_path) = path::system_config_path()
- && let Ok(content) = std::fs::read_to_string(&system_path)
- {
+ // File layers merge in priority order: user settings override system settings.
+ for (config_path, kind) in [
+ (path::system_config_path(), ConfigFileKind::System),
+ (config_path(), ConfigFileKind::User),
+ ] {
+ let Some(config_path) = config_path else {
+ continue;
+ };
+ let content = match std::fs::read_to_string(&config_path) {
+ Ok(content) => content,
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
+ if kind == ConfigFileKind::User
+ && path::is_config_path_explicit()
+ && WARNED_MISSING_CONFIG_PATHS
+ .lock()
+ .unwrap()
+ .insert(config_path.clone())
+ {
+ crate::styling::eprintln!(
+ "{}",
+ crate::styling::warning_message(color_print::cformat!(
+ "Config file not found: <bold>{}</>",
+ crate::path::format_path_for_display(&config_path)
+ ))
+ );
+ }
+ continue;
+ }
+ Err(err) => {
+ warnings.push(LoadError::Validation(format!(
+ "Failed to read {} @ {}: {err}",
+ kind.label().to_lowercase(),
+ crate::path::format_path_for_display(&config_path)
+ )));
+ continue;
+ }
+ };
match super::deprecation::check_and_migrate(
- &system_path,
+ &config_path,
&content,
true,
- ConfigFileKind::System,
+ kind,
None,
true,
) {
Ok(result) => {
super::deprecation::warn_unknown_fields::<UserConfig>(
&content,
- &system_path,
- ConfigFileKind::System,
+ &config_path,
+ kind,
);
-
- match load_config_file(
- &system_path,
- &result.migrated_content,
- ConfigFileKind::System,
- ) {
+ match load_config_file(&config_path, &result.migrated_content, kind) {
Ok(table) => merge_layer(&mut merged_table, table),
- Err(e) => warnings.push(e),
+ Err(err) => warnings.push(err),
}
}
Err(err) => {
@@ -735,57 +763,6 @@ impl UserConfig {
}
}
- // 2. User config (overrides system)
- let config_path = config_path();
- if let Some(config_path) = config_path.as_ref()
- && config_path.exists()
- {
- if let Ok(content) = std::fs::read_to_string(config_path) {
- match super::deprecation::check_and_migrate(
- config_path,
- &content,
- true,
- ConfigFileKind::User,
- None,
- true,
- ) {
- Ok(result) => {
- super::deprecation::warn_unknown_fields::<UserConfig>(
- &content,
- config_path,
- ConfigFileKind::User,
- );
-
- match load_config_file(
- config_path,
- &result.migrated_content,
- ConfigFileKind::User,
- ) {
- Ok(table) => merge_layer(&mut merged_table, table),
- Err(e) => warnings.push(e),
- }
- }
- Err(err) => {
- warnings.push(LoadError::Validation(err.to_string()));
- }
- }
- }
- } else if let Some(config_path) = config_path.as_ref()
- && path::is_config_path_explicit()
- && WARNED_MISSING_CONFIG_PATHS
- .lock()
- .unwrap()
- .insert(config_path.clone())
- {
- crate::styling::eprintln!(
- "{}",
- crate::styling::warning_message(color_print::cformat!(
- "Config file not found: <bold>{}</>",
- crate::path::format_path_for_display(config_path)
- ))
- );
- }
-
// 3. Env-var overrides (override config files)
let env_vars = parse_worktrunk_env_vars();
if let Err(err) = Self::apply_env_vars(&env_vars, &mut merged_table, &mut warnings) {
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index abadfc139..62e6bae79 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -7987,3 +7987,42 @@ fn test_config_show_non_utf8_environment(repo: TestRepo) {
.unwrap();
assert!(output.status.success(), "{output:?}");
}
+
+/// An unreadable config must stop a mutation before it uses default settings.
+#[rstest]
+#[case("WORKTRUNK_CONFIG_PATH", false)]
+#[case("WORKTRUNK_SYSTEM_CONFIG_PATH", false)]
+#[case("WORKTRUNK_CONFIG_PATH", true)]
+#[case("WORKTRUNK_SYSTEM_CONFIG_PATH", true)]
+fn test_unreadable_config_stops_switch(
+ repo: TestRepo,
+ #[case] variable: &str,
+ #[case] invalid_utf8: bool,
+) {
+ let scratch = crate::common::test_tempdir();
+ let config = scratch.path().join("unreadable.toml");
+ if invalid_utf8 {
+ fs::write(&config, [0xff]).unwrap();
+ } else {
+ fs::create_dir(&config).unwrap();
+ }
+ let output = repo
+ .wt_command()
+ .env(variable, &config)
+ .args(["switch", "--create", "unreadable-config", "--yes"])
+ .output()
+ .unwrap();
+ assert_eq!(output.status.code(), Some(1), "{output:?}");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("Failed to read"), "{stderr}");
+ assert!(stderr.contains("unreadable.toml"), "{stderr}");
+ let branch = repo
+ .git_command()
+ .args(["show-ref", "--verify", "refs/heads/unreadable-config"])
+ .run()
+ .unwrap();
+ assert!(
+ !branch.status.success(),
+ "branch was created despite unreadable config"
+ );
+}
diff --git a/tests/integration_tests/shell_integration_prompt.rs b/tests/integration_tests/shell_integration_prompt.rs
index 7a6a53a62..104653cde 100644
--- a/tests/integration_tests/shell_integration_prompt.rs
+++ b/tests/integration_tests/shell_integration_prompt.rs
@@ -865,7 +865,9 @@ mod pty_tests {
#[cfg(all(unix, feature = "shell-integration-tests"))]
mod commit_generation_prompt_tests {
use super::*;
- use crate::common::pty::{build_pty_command, exec_cmd_in_pty, exec_cmd_in_pty_prompted};
+ use crate::common::pty::{
+ build_pty_command, exec_cmd_in_pty, exec_cmd_in_pty_prompted, exec_cmd_in_pty_prompted_with,
+ };
use crate::common::wt_bin;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
@@ -1141,9 +1143,9 @@ mod commit_generation_prompt_tests {
/// Test: LLM tool available, user accepts, but the config save fails
///
- /// Points WORKTRUNK_CONFIG_PATH at a path whose parent is a regular file,
- /// so the write fails with ENOTDIR — exercising the save-failure hint,
- /// which names the resolved config path via `config_path_for_display`.
+ /// Makes the config path unwritable after the prompt appears, so loading
+ /// succeeds but saving fails with ENOTDIR. This exercises the save-failure
+ /// hint, which names the resolved path via `config_path_for_display`.
#[rstest]
fn test_user_accepts_but_save_fails_shows_manual_hint(repo: TestRepo) {
let temp_home = TempDir::new().unwrap();
@@ -1154,10 +1156,10 @@ mod commit_generation_prompt_tests {
fs::write(&test_file, "test content\n").unwrap();
repo.run_git(&["add", "test.txt"]);
- // A regular file standing in for the config's parent directory makes
- // every write under it fail with ENOTDIR — root-proof, unlike chmod.
+ // Create the blocking file only after config loading has completed.
+ // This isolates a save failure from an earlier read failure and stays
+ // root-proof, unlike chmod.
let blocker = temp_home.path().join("blocker");
- fs::write(&blocker, "x").unwrap();
let unwritable_config = blocker.join("config.toml");
let mut env_vars = repo.test_env_vars();
@@ -1176,7 +1178,9 @@ mod commit_generation_prompt_tests {
&env_vars,
Some(temp_home.path()),
);
- let (output, exit_code) = exec_cmd_in_pty_prompted(cmd, &["y\n"], "[y/N");
+ let (output, exit_code) = exec_cmd_in_pty_prompted_with(cmd, &["y\n"], "[y/N", |_| {
+ fs::write(&blocker, "x").unwrap();
+ });
// The commit still completes with a fallback message; only the config
// save fails, so the manual-add hint fires.