Skip to content

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

Retain valid environment overrides when another setting is invalid (#4348)

Maximilian Roos27d12e0afa6d
diff --git a/docs/src/content/docs/config.md b/docs/src/content/docs/config.md
index 3f08e24a7..7d35423a0 100644
--- a/docs/src/content/docs/config.md
+++ b/docs/src/content/docs/config.md
@@ -638,6 +638,7 @@ On first run without shell integration, Worktrunk offers to install it. On first
## Environment variables
All user config options can be overridden with environment variables using the `WORKTRUNK_` prefix.
+Invalid environment overrides are ignored with a warning; other valid overrides still apply.
### Naming convention
diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.md
index 0fdb3623d..8416aca7d 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/config.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md
@@ -630,6 +630,7 @@ On first run without shell integration, Worktrunk offers to install it. On first
## Environment variables
All user config options can be overridden with environment variables using the `WORKTRUNK_` prefix.
+Invalid environment overrides are ignored with a warning; other valid overrides still apply.
### Naming convention
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 0fdb3623d..8416aca7d 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -630,6 +630,7 @@ On first run without shell integration, Worktrunk offers to install it. On first
## Environment variables
All user config options can be overridden with environment variables using the `WORKTRUNK_` prefix.
+Invalid environment overrides are ignored with a warning; other valid overrides still apply.
### Naming convention
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 17c64c18d..193f522e6 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -2599,6 +2599,7 @@ On first run without shell integration, Worktrunk offers to install it. On first
## Environment variables
All user config options can be overridden with environment variables using the `WORKTRUNK_` prefix.
+Invalid environment overrides are ignored with a warning; other valid overrides still apply.
### Naming convention
diff --git a/src/config/user/mod.rs b/src/config/user/mod.rs
index 7f0b10828..e567d421d 100644
--- a/src/config/user/mod.rs
+++ b/src/config/user/mod.rs
@@ -123,6 +123,7 @@ impl std::error::Error for LoadError {
// ---- Env-var overlay ----
/// A single parsed WORKTRUNK_* env var with both typed and string representations.
+#[derive(Clone)]
struct EnvVar {
/// Original env var name (e.g., `WORKTRUNK__LIST__TIMEOUT_MS`)
name: String,
@@ -136,6 +137,17 @@ struct EnvVar {
raw_value: String,
}
+/// Environment overrides that form one independently validatable setting.
+///
+/// Most settings are one leaf. Entries under an atomic section (currently a
+/// custom list column) stay together so a required field and its companion
+/// fields are validated as the setting the user actually configured.
+#[derive(Default)]
+struct EnvOverrideUnit {
+ vars: Vec<EnvVar>,
+ overlay: toml::Table,
+}
+
/// Read `WORKTRUNK_*` env vars and parse each into an [`EnvVar`].
///
/// Env-var convention (matches the config crate's prior behavior):
@@ -189,36 +201,6 @@ fn parse_worktrunk_env_vars() -> Vec<EnvVar> {
.collect()
}
-/// For each env var, probe whether its typed or string representation
-/// deserializes correctly against the file config, then build a single
-/// overlay table with the correct representation per var.
-///
-/// Each var is tested independently against the file table (not against other
-/// env vars). This lets serde itself decide the correct type — no schema
-/// walking or guessing needed. O(N) deserializations where N is the number
-/// of env vars (tiny in practice).
-fn resolve_env_overlay(file_table: &toml::Table, vars: &[EnvVar]) -> toml::Table {
- let mut overlay = toml::Table::new();
- for var in vars {
- // Typed probe: merge just this var's typed value into the file table
- let mut probe = file_table.clone();
- set_nested_value(&mut probe, &var.segments, var.typed_value.clone());
- if toml::Value::Table(probe).try_into::<UserConfig>().is_ok() {
- set_nested_value(&mut overlay, &var.segments, var.typed_value.clone());
- } else {
- // Typed form doesn't fit the target field — use raw string.
- // If this is also wrong (e.g., "not-a-bool" for a bool field),
- // the final deserialize will catch it and surface LoadError::Env.
- set_nested_value(
- &mut overlay,
- &var.segments,
- toml::Value::String(var.raw_value.clone()),
- );
- }
- }
- overlay
-}
-
/// Canonicalize a built env-var overlay through the same deprecation migration
/// as config files and `--config-set`, so a deprecated env var such as
/// `WORKTRUNK__MERGE__NO_FF` (which resolves to the deprecated key
@@ -236,12 +218,9 @@ fn resolve_env_overlay(file_table: &toml::Table, vars: &[EnvVar]) -> toml::Table
/// `migrate_content` always returns valid TOML — mirroring the same
/// post-migration reparse `expect` in [`load_config_file`].
///
-/// Canonicalization can surface a type mismatch the deprecated name hid: an
-/// unknown key like `commit-generation.command = 42` deserializes (unknown
-/// fields are ignored) but the migrated `commit.generation.command = 42` does
-/// not, so it joins the whole-env-layer `LoadError::Env` drop at the call site
-/// instead of being silently ignored — the same outcome a type-mismatched value
-/// in a *canonical* env var already produces.
+/// Canonicalization happens before choosing typed or string representations,
+/// so deprecated names are checked against the same field types as canonical
+/// names.
fn migrate_env_overlay(overlay: toml::Table) -> toml::Table {
let serialized = toml::to_string(&overlay).expect("env overlay serializes to TOML");
super::deprecation::migrate_content(&serialized)
@@ -249,6 +228,116 @@ fn migrate_env_overlay(overlay: toml::Table) -> toml::Table {
.expect("migrate_content returns valid TOML")
}
+/// Return the path of a single-variable overlay after deprecation migration.
+/// Migration moves, renames, or removes a scalar; it never expands it into
+/// several settings. Removing an obsolete setting can leave an empty overlay.
+fn env_overlay_path(mut table: &toml::Table) -> Option<Vec<String>> {
+ let mut path = Vec::new();
+ loop {
+ let (key, value) = table.iter().next()?;
+ path.push(key.clone());
+ match value {
+ toml::Value::Table(nested) if !nested.is_empty() => table = nested,
+ _ => return Some(path),
+ }
+ }
+}
+
+/// Group the fields that make up one setting, keeping atomic section entries
+/// together. This reuses the same atomic-section contract as project precedence.
+fn env_override_key(path: &[String]) -> Vec<String> {
+ for section_len in 0..path.len() {
+ let section: Vec<_> = path[..section_len].iter().map(String::as_str).collect();
+ let project_section =
+ section.len() == 4 && section[0] == "projects" && is_atomic_section(&section[2..]);
+ if is_atomic_section(&section) || project_section {
+ return path[..section_len + 1].to_vec();
+ }
+ }
+ path.to_vec()
+}
+
+/// Build and migrate an overlay from a chosen representation for every var.
+fn env_overlay_from_values(vars: &[EnvVar], values: &[toml::Value]) -> toml::Table {
+ let mut overlay = toml::Table::new();
+ for (var, value) in vars.iter().zip(values) {
+ set_nested_value(&mut overlay, &var.segments, value.clone());
+ }
+ migrate_env_overlay(overlay)
+}
+
+/// Choose typed or string values for one setting as a group. Probing the
+/// whole setting keeps required compound fields together: a custom column's
+/// width can be typed as an integer when its required template arrives in the
+/// same environment layer.
+fn resolve_env_override_unit(file_table: &toml::Table, vars: &[EnvVar]) -> toml::Table {
+ let mut values: Vec<_> = vars.iter().map(|var| var.typed_value.clone()).collect();
+
+ loop {
+ let mut changed = false;
+ for (index, var) in vars.iter().enumerate() {
+ let overlay = env_overlay_from_values(vars, &values);
+ let mut candidate = file_table.clone();
+ merge_layer(&mut candidate, overlay);
+ if toml::Value::Table(candidate)
+ .try_into::<UserConfig>()
+ .is_ok()
+ {
+ continue;
+ }
+
+ let typed_value = std::mem::replace(
+ &mut values[index],
+ toml::Value::String(var.raw_value.clone()),
+ );
+ let overlay = env_overlay_from_values(vars, &values);
+ let mut candidate = file_table.clone();
+ merge_layer(&mut candidate, overlay);
+ if toml::Value::Table(candidate)
+ .try_into::<UserConfig>()
+ .is_ok()
+ {
+ changed = true;
+ } else {
+ values[index] = typed_value;
+ }
+ }
+
+ if !changed {
+ return env_overlay_from_values(vars, &values);
+ }
+ }
+}
+
+/// Resolve, migrate, and group each environment variable against the same
+/// lower-layer config. Sorting makes aliases that migrate to one setting
+/// deterministic, independent of the caller's input order.
+fn env_override_units(file_table: &toml::Table, vars: &[EnvVar]) -> Vec<EnvOverrideUnit> {
+ let mut ordered_vars: Vec<_> = vars.iter().collect();
+ ordered_vars.sort_by(|left, right| left.name.cmp(&right.name));
+
+ let mut grouped_vars = std::collections::BTreeMap::<Vec<String>, Vec<EnvVar>>::new();
+ for var in ordered_vars {
+ let overlay = env_overlay_from_values(
+ std::slice::from_ref(var),
+ std::slice::from_ref(&var.typed_value),
+ );
+ let Some(path) = env_overlay_path(&overlay) else {
+ continue;
+ };
+ let key = env_override_key(&path);
+ grouped_vars.entry(key).or_default().push(var.clone());
+ }
+
+ grouped_vars
+ .into_values()
+ .map(|vars| EnvOverrideUnit {
+ overlay: resolve_env_override_unit(file_table, &vars),
+ vars,
+ })
+ .collect()
+}
+
/// Try to coerce a string into a typed TOML value (bool → i64 → f64 → string).
fn try_parse_value(s: &str) -> toml::Value {
if s.eq_ignore_ascii_case("true") {
@@ -366,6 +455,15 @@ fn deserialize_and_validate(table: &toml::Table) -> Result<(), String> {
}
}
+fn deserialize_validation_issues(
+ table: &toml::Table,
+) -> Result<Vec<persistence::UserConfigValidationIssue>, String> {
+ let config = toml::Value::Table(table.clone())
+ .try_into::<UserConfig>()
+ .map_err(|err| err.to_string())?;
+ Ok(config.validation_issues())
+}
+
/// Remove from `entry` every leaf `overlay` sets. `section` tracks the path
/// walked so far for the predicates beside it.
fn drop_overridden_keys<'a>(
@@ -687,29 +785,9 @@ impl UserConfig {
// 3. Env-var overrides (override config files)
let env_vars = parse_worktrunk_env_vars();
- if !env_vars.is_empty() {
- // Resolve each env var's type independently: probe typed form against
- // the file table, fall back to string if typed doesn't fit the target
- // field. This handles mixed cases (e.g., WORKTRUNK__LIST__TIMEOUT_MS=100
- // needs Integer for u64, WORKTRUNK_WORKTREE_PATH=42 needs String).
- let file_table = merged_table.clone();
- let env_overlay = migrate_env_overlay(resolve_env_overlay(&file_table, &env_vars));
- merge_layer(&mut merged_table, env_overlay);
-
- // A bad env layer must not discard valid file layers. Attribute the
- // failure to env only when the file-only table itself is valid.
- if let Err(err) = deserialize_and_validate(&merged_table)
- && deserialize_and_validate(&file_table).is_ok()
- {
- warnings.push(LoadError::Env {
- err,
- vars: env_vars
- .iter()
- .map(|v| (v.name.clone(), v.raw_value.clone()))
- .collect(),
- });
- merged_table = file_table;
- }
+ if let Err(err) = Self::apply_env_vars(&env_vars, &mut merged_table, &mut warnings) {
+ warnings.push(LoadError::Validation(err));
+ return (Self::default(), warnings);
}
// 4. CLI `--config-set` overrides (override env vars and config files)
@@ -718,6 +796,71 @@ impl UserConfig {
Self::finalize(merged_table, warnings)
}
+ /// Apply the environment override layer above the file layers.
+ fn apply_env_vars(
+ env_vars: &[EnvVar],
+ merged_table: &mut toml::Table,
+ warnings: &mut Vec<LoadError>,
+ ) -> Result<(), String> {
+ if env_vars.is_empty() {
+ return Ok(());
+ }
+
+ let file_table = merged_table.clone();
+
+ // File layers deserialize before merging. A malformed merged table
+ // is a loader error, rather than an error attributed to an env var.
+ let lower_validation_issues = deserialize_validation_issues(&file_table)?;
+
+ // Validate each setting against the same lower layer. Sequentially
+ // accepting values here would make compound settings such as custom
+ // columns depend on which field happened to be visited first.
+ let mut accepted_overlay = toml::Table::new();
+ for unit in env_override_units(&file_table, env_vars) {
+ let mut candidate = file_table.clone();
+ merge_layer(&mut candidate, unit.overlay.clone());
+ match deserialize_validation_issues(&candidate) {
+ Ok(issues) => {
+ // An unrelated unit may leave an existing file error for
+ // another override to repair. A unit setting that invalid
+ // value itself must be rejected, even if its issue matches
+ // the lower layer: retaining it could undo a valid repair.
+ if let Some(issue) = issues.iter().find(|issue| {
+ !lower_validation_issues.contains(issue) || issue.is_set_in(&unit.overlay)
+ }) {
+ warnings.push(LoadError::Env {
+ err: issue.to_string(),
+ vars: unit
+ .vars
+ .into_iter()
+ .map(|var| (var.name, var.raw_value))
+ .collect(),
+ });
+ } else {
+ deep_merge_table(&mut accepted_overlay, unit.overlay);
+ }
+ }
+ Err(err) => warnings.push(LoadError::Env {
+ err,
+ vars: unit
+ .vars
+ .into_iter()
+ .map(|var| (var.name, var.raw_value))
+ .collect(),
+ }),
+ }
+ }
+
+ if accepted_overlay.is_empty() {
+ return Ok(());
+ }
+
+ let mut candidate = file_table.clone();
+ merge_layer(&mut candidate, accepted_overlay);
+ *merged_table = candidate;
+ Ok(())
+ }
+
/// Apply CLI `--config-set <toml>` overrides as the highest-priority layer.
///
/// Each override is an independent TOML fragment merged in order, so a
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index 4c4159b50..f3859707d 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -206,14 +206,56 @@ fn load(doc: &DocumentMut) -> Result<UserConfig, toml::de::Error> {
// Validation
// =========================================================================
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
+pub(super) enum UserConfigValidationIssue {
+ EmptyWorktreePath,
+ EmptyProjectWorktreePath(String),
+}
+
+impl UserConfigValidationIssue {
+ fn path(&self) -> Vec<&str> {
+ match self {
+ Self::EmptyWorktreePath => vec!["worktree-path"],
+ Self::EmptyProjectWorktreePath(project) => {
+ vec!["projects", project, "worktree-path"]
+ }
+ }
+ }
+
+ /// Whether an overlay explicitly sets the value this issue describes.
+ pub(super) fn is_set_in(&self, table: &toml::Table) -> bool {
+ let path = self.path();
+ path[1..]
+ .iter()
+ .fold(table.get(path[0]), |value, key| {
+ value.and_then(|value| value.get(*key))
+ })
+ .is_some()
+ }
+}
+
+impl std::fmt::Display for UserConfigValidationIssue {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{} cannot be empty", self.path().join("."))
+ }
+}
+
impl UserConfig {
/// Validate configuration values.
pub fn validate(&self) -> Result<(), ConfigError> {
+ if let Some(issue) = self.validation_issues().into_iter().next() {
+ return Err(ConfigError::Message(issue.to_string()));
+ }
+ Ok(())
+ }
+
+ pub(super) fn validation_issues(&self) -> Vec<UserConfigValidationIssue> {
+ let mut issues = Vec::new();
// Validate worktree path (only if explicitly set - default is always valid)
if let Some(ref path) = self.worktree_path
&& path.trim().is_empty()
{
- return Err(ConfigError::Message("worktree-path cannot be empty".into()));
+ issues.push(UserConfigValidationIssue::EmptyWorktreePath);
}
// Validate per-project configs
@@ -222,12 +264,12 @@ impl UserConfig {
if let Some(ref path) = project_config.worktree_path
&& path.trim().is_empty()
{
- return Err(ConfigError::Message(format!(
- "projects.{project}.worktree-path cannot be empty"
- )));
+ issues.push(UserConfigValidationIssue::EmptyProjectWorktreePath(
+ project.clone(),
+ ));
}
}
- Ok(())
+ issues
}
}
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 2eace0958..cee54139c 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -2424,9 +2424,7 @@ fn test_cli_layer_outranks_project_worktree_path() {
#[test]
fn test_env_layer_outranks_project_worktree_path() {
- // The env half of the same fix, driven through the overlay
- // `load_with_warnings` builds rather than the process environment.
- use super::{EnvVar, migrate_env_overlay, resolve_env_overlay, try_parse_value};
+ use super::{EnvVar, try_parse_value};
let var = EnvVar {
name: "WORKTRUNK_WORKTREE_PATH".to_string(),
segments: vec!["worktree-path".to_string()],
@@ -2434,9 +2432,10 @@ fn test_env_layer_outranks_project_worktree_path() {
raw_value: "/from-env".to_string(),
};
let mut table = base_with_project("worktree-path = \"/from-project\"\n");
- let overlay = migrate_env_overlay(resolve_env_overlay(&table, &[var]));
- merge_layer(&mut table, overlay);
+ let mut warnings = Vec::new();
+ UserConfig::apply_env_vars(&[var], &mut table, &mut warnings).unwrap();
+ assert!(warnings.is_empty());
assert_eq!(
loaded(table).worktree_path_for_project(PROJECT),
"/from-env"
@@ -2445,18 +2444,9 @@ fn test_env_layer_outranks_project_worktree_path() {
#[test]
fn test_layer_keeps_an_already_invalid_candidate_untouched() {
- // The pass discards a candidate that does not deserialize and validate.
- // Step 3's env probe only deserializes, so an empty `worktree-path` from
- // the environment reaches here already invalid — and the removals are
- // dropped rather than handed to `finalize`, which would answer the same
- // failure by wiping the config to defaults.
- use super::{EnvVar, migrate_env_overlay, resolve_env_overlay, try_parse_value};
- let empty_path = |value: &str| EnvVar {
- name: "WORKTRUNK_WORKTREE_PATH".to_string(),
- segments: vec!["worktree-path".to_string()],
- typed_value: try_parse_value(value),
- raw_value: value.to_string(),
- };
+ // A layer with an empty global `worktree-path` fails validation. Its
+ // project-precedence removals are dropped as a unit, while the layer still
+ // reaches the caller for validation and attribution.
let plain_merge = |overlay: &toml::Table| {
let mut plain = base_with_project("worktree-path = \"/from-project\"\n");
deep_merge_table(&mut plain, overlay.clone());
@@ -2464,7 +2454,7 @@ fn test_layer_keeps_an_already_invalid_candidate_untouched() {
};
let mut table = base_with_project("worktree-path = \"/from-project\"\n");
- let overlay = migrate_env_overlay(resolve_env_overlay(&table, &[empty_path("")]));
+ let overlay: toml::Table = "worktree-path = \"\"\n".parse().unwrap();
let plain = plain_merge(&overlay);
merge_layer(&mut table, overlay);
assert_eq!(
@@ -2476,7 +2466,7 @@ fn test_layer_keeps_an_already_invalid_candidate_untouched() {
// key, so the assertion above is the discard and not a pass that found
// nothing to do.
let mut table = base_with_project("worktree-path = \"/from-project\"\n");
- let overlay = migrate_env_overlay(resolve_env_overlay(&table, &[empty_path("/from-env")]));
+ let overlay: toml::Table = "worktree-path = \"/from-env\"\n".parse().unwrap();
let plain = plain_merge(&overlay);
merge_layer(&mut table, overlay);
assert_ne!(table, plain);
@@ -2673,7 +2663,7 @@ fn test_dropped_layer_leaves_projects_intact() {
#[test]
fn test_env_overlay_migrates_deprecated_key() {
- use super::{EnvVar, migrate_env_overlay, resolve_env_overlay, try_parse_value};
+ use super::{EnvVar, try_parse_value};
// `WORKTRUNK__MERGE__NO_FF=true` resolves to the deprecated key
// `merge.no-ff`. The env overlay runs through the same deprecation migration
// as config files and `--config-set`, so it takes effect as `merge.ff =
@@ -2684,8 +2674,11 @@ fn test_env_overlay_migrates_deprecated_key() {
typed_value: try_parse_value("true"),
raw_value: "true".to_string(),
};
- let overlay = migrate_env_overlay(resolve_env_overlay(&toml::Table::new(), &[var]));
- let config: UserConfig = toml::Value::Table(overlay).try_into().unwrap();
+ let mut table = toml::Table::new();
+ let mut warnings = Vec::new();
+ UserConfig::apply_env_vars(&[var], &mut table, &mut warnings).unwrap();
+ assert!(warnings.is_empty());
+ let config = loaded(table);
assert_eq!(config.merge.ff, Some(false));
}
@@ -3277,3 +3270,137 @@ hostname = "github.company.example"
);
assert_eq!(config.forge_hostname(None), None);
}
+
+/// Invalid scalar overrides must not erase unrelated environment values.
+#[test]
+fn test_env_failure_keeps_other_overrides() {
+ let env_var = |name: &str, path: &[&str], value: &str| super::EnvVar {
+ name: name.into(),
+ segments: path.iter().map(|s| s.to_string()).collect(),
+ typed_value: super::try_parse_value(value),
+ raw_value: value.into(),
+ };
+ let vars = [
+ // Deliberately pass the custom-column width before its required
+ // template. Both fields form one valid setting after migration.
+ env_var(
+ "WORKTRUNK__LIST__CUSTOM_COLUMNS__TICKET__WIDTH",
+ &["list", "custom-columns", "ticket", "width"],
+ "20",
+ ),
+ env_var(
+ "WORKTRUNK__LIST__CUSTOM_COLUMNS__TICKET__TEMPLATE",
+ &["list", "custom-columns", "ticket", "template"],
+ "{{ branch }}",
+ ),
+ env_var("WORKTRUNK__LIST__COLUMNS", &["list", "columns"], "oops"),
+ env_var("WORKTRUNK__LIST__FULL", &["list", "full"], "true"),
+ env_var("WORKTRUNK_WORKTREE_PATH", &["worktree-path"], "/tmp/zzz"),
+ // The old select section drops unsupported fields completely. An
+ // empty migrated overlay must not become a spurious validation unit.
+ env_var(
+ "WORKTRUNK__SELECT__OBSOLETE",
+ &["select", "obsolete"],
+ "old",
+ ),
+ ];
+ let mut table = "[list]\nbranches=true\ncolumns=[\"path\"]\n"
+ .parse()
+ .unwrap();
+ let mut warnings = Vec::new();
+ UserConfig::apply_env_vars(&vars, &mut table, &mut warnings).unwrap();
+ assert!(!table.contains_key("select"));
+ let config = loaded(table);
+ assert_eq!(config.list.full, Some(true));
+ assert_eq!(config.worktree_path.as_deref(), Some("/tmp/zzz"));
+ assert_eq!(config.list.branches, Some(true));
+ assert_eq!(config.list.columns, ["path"]);
+ assert_eq!(
+ config.list.custom_columns["ticket"].template,
+ "{{ branch }}"
+ );
+ assert_eq!(config.list.custom_columns["ticket"].width, Some(20));
+ assert_eq!(warnings.len(), 1);
+ let LoadError::Env { vars, .. } = &warnings[0] else {
+ panic!("expected env warning")
+ };
+ assert_eq!(vars, &[("WORKTRUNK__LIST__COLUMNS".into(), "oops".into())]);
+}
+
+#[test]
+fn test_env_override_can_repair_invalid_lower_layer() {
+ let var = super::EnvVar {
+ name: "WORKTRUNK_WORKTREE_PATH".into(),
+ segments: vec!["worktree-path".into()],
+ typed_value: super::try_parse_value("/tmp/worktrees/{{ branch }}"),
+ raw_value: "/tmp/worktrees/{{ branch }}".into(),
+ };
+ let mut table = "worktree-path = \"\"\n".parse().unwrap();
+ let mut warnings = Vec::new();
+
+ UserConfig::apply_env_vars(&[var], &mut table, &mut warnings).unwrap();
+
+ let config = loaded(table);
+ assert_eq!(
+ config.worktree_path.as_deref(),
+ Some("/tmp/worktrees/{{ branch }}")
+ );
+ assert!(config.validate().is_ok());
+ assert!(warnings.is_empty());
+}
+
+#[test]
+fn test_invalid_project_env_override_keeps_global_repair() {
+ let global = super::EnvVar {
+ name: "WORKTRUNK_WORKTREE_PATH".into(),
+ segments: vec!["worktree-path".into()],
+ typed_value: toml::Value::String("/valid".into()),
+ raw_value: "/valid".into(),
+ };
+ let project = super::EnvVar {
+ name: "WORKTRUNK__PROJECTS__GITHUB.COM/OWNER/REPO__WORKTREE_PATH".into(),
+ segments: vec![
+ "projects".into(),
+ "github.com/owner/repo".into(),
+ "worktree-path".into(),
+ ],
+ typed_value: toml::Value::String(String::new()),
+ raw_value: String::new(),
+ };
+ let mut table =
+ "[list]\nbranches = true\n[projects.\"github.com/owner/repo\"]\nworktree-path = \"\"\n"
+ .parse()
+ .unwrap();
+ let mut warnings = Vec::new();
+
+ UserConfig::apply_env_vars(&[global, project], &mut table, &mut warnings).unwrap();
+
+ let config = loaded(table);
+ assert_eq!(config.worktree_path.as_deref(), Some("/valid"));
+ assert_eq!(config.list.branches, Some(true));
+ assert!(config.validate().is_ok());
+ assert!(matches!(warnings.as_slice(), [LoadError::Env { vars, .. }]
+ if vars == &[("WORKTRUNK__PROJECTS__GITHUB.COM/OWNER/REPO__WORKTREE_PATH".into(), String::new())]));
+}
+
+/// A broken internal lower-layer contract must surface a schema error without
+/// blaming an unrelated environment setting or replacing the lower table.
+#[test]
+fn test_env_layer_reports_malformed_lower_table() {
+ let var = super::EnvVar {
+ name: "WORKTRUNK__LIST__FULL".into(),
+ segments: vec!["list".into(), "full".into()],
+ typed_value: toml::Value::Boolean(true),
+ raw_value: "true".into(),
+ };
+ let mut table: toml::Table = "[list]\nbranches = \"invalid\"\n".parse().unwrap();
+ let original = table.clone();
+ let mut warnings = Vec::new();
+
+ let err = UserConfig::apply_env_vars(&[var], &mut table, &mut warnings).unwrap_err();
+
+ assert!(err.contains("branches"), "{err}");
+ assert!(err.contains("boolean"), "{err}");
+ assert_eq!(table, original);
+ assert!(warnings.is_empty());
+}
diff --git a/tests/integration_tests/list_config.rs b/tests/integration_tests/list_config.rs
index 5c3a73249..9b7b61506 100644
--- a/tests/integration_tests/list_config.rs
+++ b/tests/integration_tests/list_config.rs
@@ -414,26 +414,26 @@ fn test_list_config_env_override_bad_value_warns_on_stderr(repo: TestRepo) {
});
}
-/// A *deprecated* env var is canonicalized before it is applied, so a
-/// type-mismatched value the deprecated name hid now surfaces.
-/// `WORKTRUNK__COMMIT_GENERATION__COMMAND=42` migrates to
-/// `commit.generation.command = 42`, which fails to deserialize (the field is a
-/// String), so the whole env layer is dropped with a `LoadError::Env` warning
-/// naming the var — the same contract as a bad value in a canonical env var.
-/// File config survives. (Pre-migration the unknown key was silently ignored.)
+/// A deprecated env var is canonicalized before its type is validated, so a
+/// numeric-looking value for a String field stays a string after migration.
#[rstest]
-fn test_list_config_env_deprecated_type_mismatch_drops_layer(repo: TestRepo) {
+fn test_list_config_env_deprecated_numeric_string_field(repo: TestRepo) {
fs::write(repo.test_config_path(), "[list]\nbranches = true\n").unwrap();
- let settings = setup_snapshot_settings(&repo);
- settings.bind(|| {
- let mut cmd = wt_command();
- repo.configure_wt_cmd(&mut cmd);
- cmd.env("WORKTRUNK__COMMIT_GENERATION__COMMAND", "42");
- cmd.arg("list").current_dir(repo.root_path());
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.env("WORKTRUNK__COMMIT_GENERATION__COMMAND", "42");
+ cmd.args(["config", "show", "--format=json"])
+ .current_dir(repo.root_path());
- assert_cmd_snapshot!(cmd);
- });
+ let output = cmd.output().unwrap();
+ assert!(output.status.success());
+ let config: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(
+ config["user"]["config"]["commit"]["generation"]["command"],
+ "42"
+ );
+ assert!(output.stderr.is_empty());
}
/// Numeric-looking env var values for String fields must not break config
@@ -531,6 +531,197 @@ fn test_list_config_env_override_validation_failure(repo: TestRepo) {
});
}
+#[rstest]
+fn test_list_config_bad_env_override_keeps_valid_overrides(repo: TestRepo) {
+ fs::write(
+ repo.test_config_path(),
+ "[list]\nbranches = true\ncolumns = [\"path\"]\n",
+ )
+ .unwrap();
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.env("WORKTRUNK__LIST__COLUMNS", "oops")
+ .env("WORKTRUNK__LIST__FULL", "true")
+ .env("WORKTRUNK_WORKTREE_PATH", "/tmp/zzz")
+ .args(["config", "show", "--format=json"])
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let config = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
+ let config = &config["user"]["config"];
+ assert_eq!(config["list"]["branches"], true);
+ assert_eq!(config["list"]["full"], true);
+ assert_eq!(config["list"]["columns"], serde_json::json!(["path"]));
+ assert_eq!(config["worktree-path"], "/tmp/zzz");
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("WORKTRUNK__LIST__COLUMNS"), "{stderr}");
+ assert!(!stderr.contains("WORKTRUNK__LIST__FULL"), "{stderr}");
+ assert!(!stderr.contains("WORKTRUNK_WORKTREE_PATH"), "{stderr}");
+}
+
+#[rstest]
+fn test_list_config_bad_env_override_keeps_repair_overrides(repo: TestRepo) {
+ fs::write(repo.test_config_path(), "worktree-path = \"\"\n").unwrap();
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.env("WORKTRUNK__LIST__COLUMNS", "oops")
+ .env("WORKTRUNK__LIST__FULL", "true")
+ .env("WORKTRUNK_WORKTREE_PATH", "/tmp/zzz")
+ .arg("list")
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("WORKTRUNK__LIST__COLUMNS"), "{stderr}");
+ assert!(!stderr.contains("WORKTRUNK__LIST__FULL"), "{stderr}");
+ assert!(!stderr.contains("WORKTRUNK_WORKTREE_PATH"), "{stderr}");
+}
+
+/// Independently valid file layers remain available while env settings discard
+/// invalid or retired overrides.
+#[rstest]
+fn test_env_validation_preserves_merged_file_layers(repo: TestRepo) {
+ let system_config = repo.root_path().join("system-config.toml");
+ fs::write(
+ &system_config,
+ "worktree-path = \"/from-system\"\n[list]\nbranches = true\ncolumns = [\"path\"]\n[merge]\nrebase = false\n",
+ )
+ .unwrap();
+ fs::write(
+ repo.test_config_path(),
+ "worktree-path = \"/from-user\"\n[merge]\nsquash = false\n",
+ )
+ .unwrap();
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.env("WORKTRUNK_SYSTEM_CONFIG_PATH", &system_config)
+ .env("WORKTRUNK__SELECT__OBSOLETE", "old")
+ .env("WORKTRUNK__LIST__COLUMNS", "oops")
+ .env("WORKTRUNK__LIST__FULL", "true")
+ .env("WORKTRUNK_WORKTREE_PATH", "/tmp/zzz")
+ .args(["config", "show", "--format=json"])
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ assert!(output.status.success(), "{output:?}");
+ let config = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
+ let config = &config["user"]["config"];
+ assert_eq!(config["list"]["branches"], true);
+ assert_eq!(config["list"]["columns"], serde_json::json!(["path"]));
+ assert_eq!(config["list"]["full"], true);
+ assert_eq!(config["merge"]["rebase"], false);
+ assert_eq!(config["merge"]["squash"], false);
+ assert_eq!(config["worktree-path"], "/tmp/zzz");
+ assert!(config.get("select").is_none());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("WORKTRUNK__LIST__COLUMNS"), "{stderr}");
+ assert!(!stderr.contains("WORKTRUNK__SELECT__OBSOLETE"), "{stderr}");
+ assert!(!stderr.contains("WORKTRUNK__LIST__FULL"), "{stderr}");
+ assert!(!stderr.contains("WORKTRUNK_WORKTREE_PATH"), "{stderr}");
+}
+
+/// A bad project override must not undo a valid global override's repair,
+/// even when that project error was already present in the file layer.
+#[rstest]
+#[case::repair_only(false)]
+#[case::repair_with_invalid_override(true)]
+fn test_env_project_error_does_not_undo_global_repair(
+ repo: TestRepo,
+ #[case] invalid_project_override: bool,
+) {
+ repo.run_git(&["branch", "feature"]);
+ fs::write(
+ repo.test_config_path(),
+ "[list]\nbranches = true\n[projects.\"github.com/owner/repo\"]\nworktree-path = \"\"\n",
+ )
+ .unwrap();
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.env("WORKTRUNK_WORKTREE_PATH", "/tmp/zzz");
+ if invalid_project_override {
+ cmd.env(
+ "WORKTRUNK__PROJECTS__GITHUB.COM/OWNER/REPO__WORKTREE_PATH",
+ "",
+ );
+ }
+ cmd.args(["list", "--format=json"])
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ assert!(output.status.success(), "{output:?}");
+ let list = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
+ assert!(
+ list["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|item| item["branch"] == "feature"),
+ "the file layer's branch-listing setting must survive: {list}"
+ );
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ if invalid_project_override {
+ assert!(
+ stderr.contains("Ignoring env var overrides: WORKTRUNK__PROJECTS__GITHUB.COM/OWNER/REPO__WORKTREE_PATH="),
+ "{stderr}"
+ );
+ assert!(!stderr.contains("Config validation warning"), "{stderr}");
+ assert!(!stderr.contains("WORKTRUNK_WORKTREE_PATH"), "{stderr}");
+ } else {
+ assert!(stderr.is_empty(), "{stderr}");
+ }
+}
+
+#[rstest]
+fn test_project_custom_column_env_fields_are_atomic(repo: TestRepo) {
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://github.com/owner/repo.git",
+ ]);
+ fs::write(repo.test_config_path(), "").unwrap();
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.env(
+ "WORKTRUNK__PROJECTS__GITHUB.COM/OWNER/REPO__LIST__CUSTOM_COLUMNS__TICKET__WIDTH",
+ "20",
+ )
+ .env(
+ "WORKTRUNK__PROJECTS__GITHUB.COM/OWNER/REPO__LIST__CUSTOM_COLUMNS__TICKET__TEMPLATE",
+ "{{ branch }}",
+ )
+ .args(["config", "show", "--format=json"])
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let config = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
+ let column = &config["user"]["config"]["projects"]["github.com/owner/repo"]["list"]["custom-columns"]
+ ["ticket"];
+ assert_eq!(column["template"], "{{ branch }}");
+ assert_eq!(column["width"], 20);
+ assert!(output.stderr.is_empty());
+}
+
/// A `--config-set` override is the highest-priority layer: it wins over the
/// config file. A file that disables branch listing is overridden back on,
/// surfacing the branch without a worktree.
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 08c4c1c02..467407635 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -617,6 +617,7 @@ On first run without shell integration, Worktrunk offers to install it. On first
Environment variables
All user config options can be overridden with environment variables using the WORKTRUNK_ prefix.
+Invalid environment overrides are ignored with a warning; other valid overrides still apply.
Naming convention
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_env_deprecated_type_mismatch_drops_layer.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_env_deprecated_type_mismatch_drops_layer.snap
deleted file mode 100644
index daa8306d9..000000000
--- a/tests/snapshots/integration__integration_tests__list_config__list_config_env_deprecated_type_mismatch_drops_layer.snap
+++ /dev/null
@@ -1,71 +0,0 @@
----
-source: tests/integration_tests/list_config.rs
-info:
- program: wt
- args:
- - list
- env:
- APPDATA: "[TEST_CONFIG_HOME]"
- CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
- CLICOLOR_FORCE: "1"
- COLUMNS: "500"
- GIT_ALLOW_PROTOCOL: file
- GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
- GIT_AUTHOR_EMAIL: [email protected]
- GIT_AUTHOR_NAME: Test User
- GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_COMMITTER_EMAIL: [email protected]
- GIT_COMMITTER_NAME: Test User
- GIT_CONFIG_COUNT: "2"
- GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
- GIT_CONFIG_KEY_0: user.useConfigOnly
- GIT_CONFIG_KEY_1: rerere.enabled
- GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
- GIT_CONFIG_VALUE_0: "true"
- GIT_CONFIG_VALUE_1: "false"
- GIT_TERMINAL_PROMPT: "0"
- HOME: "[TEST_HOME]"
- LANG: C
- LC_ALL: C
- LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
- OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
- PATH: "[PATH]"
- TERM: alacritty
- USERPROFILE: "[TEST_HOME]"
- WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
- WORKTRUNK_TEST_BASH_INSTALLED: "0"
- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
- WORKTRUNK_TEST_CODEX_INSTALLED: "0"
- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
- WORKTRUNK_TEST_EPOCH: "1735776000"
- WORKTRUNK_TEST_FISH_INSTALLED: "0"
- WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
- WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
- WORKTRUNK_TEST_NUSHELL_ENV: "0"
- WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
- WORKTRUNK_TEST_PARENT_SHELL: ""
- WORKTRUNK_TEST_POWERSHELL_ENV: "0"
- WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
- WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
- WORKTRUNK_TEST_ZSH_INSTALLED: "0"
- WORKTRUNK__COMMIT_GENERATION__COMMAND: "42"
- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
----
-success: true
-exit_code: 0
------ stdout -----
- Branch Status HEAD± main↕ main…± Remote⇅ Path Commit Age Message
-@ main ^| | . 05a4a45 16h Initial commit
-+ feature-a ↑ ↑1 +1 ../repo.feature-a 1b87d47 16h Add feature-a file
-+ feature-b ↑ ↑1 +1 ../repo.feature-b f62940f 16h Add feature-b file
-+ feature-c ↑ ↑1 +1 ../repo.feature-c 345c7c9 16h Add feature-c file
-
------ stderr -----
-▲ Ignoring env var overrides: WORKTRUNK__COMMIT_GENERATION__COMMAND=42
-  invalid type: integer `42`, expected a string
-  in `commit.generation.command`
-
-○ Showing 4 worktrees, 3 ahead