Skip to content

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

refactor(config): flatten section fields from Option<T> to T (#2104)

Maximilian Roos4bacab23afee
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 3508ffc31..54931f147 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -536,7 +536,7 @@ template-file = "~/file.txt"
// The deserialization should succeed, but validation in load() would fail
// Since we can't easily test load() without env vars, we verify the fields deserialize
if let Ok(config) = config_result {
- let generation = config.commit.as_ref().and_then(|c| c.generation.as_ref());
+ let generation = config.commit.generation.as_ref();
// Verify validation logic: both fields should not be Some
let has_both = generation
.map(|g| g.template.is_some() && g.template_file.is_some())
@@ -566,7 +566,7 @@ squash-template-file = "~/file.txt"
// The deserialization should succeed, but validation in load() would fail
// Since we can't easily test load() without env vars, we verify the fields deserialize
if let Ok(config) = config_result {
- let generation = config.commit.as_ref().and_then(|c| c.generation.as_ref());
+ let generation = config.commit.generation.as_ref();
// Verify validation logic: both fields should not be Some
let has_both = generation
.map(|g| g.squash_template.is_some() && g.squash_template_file.is_some())
diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rs
index 95e105edb..04b832dbc 100644
--- a/src/config/user/accessors.rs
+++ b/src/config/user/accessors.rs
@@ -10,7 +10,7 @@ use crate::config::commands::CommandConfig;
use crate::config::expansion::expand_template;
use super::UserConfig;
-use super::merge::{Merge, merge_optional};
+use super::merge::Merge;
use super::sections::{
CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig, StepConfig,
SwitchConfig, SwitchPickerConfig,
@@ -32,13 +32,13 @@ impl UserConfig {
fn merged_project_config<T: Merge + Clone>(
&self,
project: Option<&str>,
- global: Option<&T>,
- project_config: impl FnOnce(&super::sections::UserProjectOverrides) -> Option<&T>,
- ) -> Option<T> {
- merge_optional(
- global,
- self.project_overrides(project).and_then(project_config),
- )
+ global: &T,
+ project_config: impl FnOnce(&super::sections::UserProjectOverrides) -> &T,
+ ) -> T {
+ match self.project_overrides(project).map(project_config) {
+ Some(proj) => global.merge_with(proj),
+ None => global.clone(),
+ }
}
/// Returns the worktree path template, falling back to the default if not set.
@@ -79,67 +79,56 @@ impl UserConfig {
/// `[commit-generation]` sections are normalized into `[commit.generation]`
/// during config loading.
pub fn commit_generation(&self, project: Option<&str>) -> CommitGenerationConfig {
- self.merged_project_config(
- project,
- self.commit
- .as_ref()
- .and_then(|commit| commit.generation.as_ref()),
- |config| {
- config
- .commit
- .as_ref()
- .and_then(|commit| commit.generation.as_ref())
- },
- )
- .unwrap_or_default()
+ let global = self.commit.generation.clone().unwrap_or_default();
+ match self
+ .project_overrides(project)
+ .and_then(|config| config.commit.generation.as_ref())
+ {
+ Some(proj) => global.merge_with(proj),
+ None => global,
+ }
}
/// Returns the list config for a specific project.
///
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
- pub fn list(&self, project: Option<&str>) -> Option<ListConfig> {
- self.merged_project_config(project, self.list.as_ref(), |config| config.list.as_ref())
+ pub fn list(&self, project: Option<&str>) -> ListConfig {
+ self.merged_project_config(project, &self.list, |config| &config.list)
}
/// Returns the commit config for a specific project.
///
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
- pub fn commit(&self, project: Option<&str>) -> Option<CommitConfig> {
- self.merged_project_config(project, self.commit.as_ref(), |config| {
- config.commit.as_ref()
- })
+ pub fn commit(&self, project: Option<&str>) -> CommitConfig {
+ self.merged_project_config(project, &self.commit, |config| &config.commit)
}
/// Returns the merge config for a specific project.
///
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
- pub fn merge(&self, project: Option<&str>) -> Option<MergeConfig> {
- self.merged_project_config(project, self.merge.as_ref(), |config| config.merge.as_ref())
+ pub fn merge(&self, project: Option<&str>) -> MergeConfig {
+ self.merged_project_config(project, &self.merge, |config| &config.merge)
}
/// Returns the switch config for a specific project.
///
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
- pub fn switch(&self, project: Option<&str>) -> Option<SwitchConfig> {
- self.merged_project_config(project, self.switch.as_ref(), |config| {
- config.switch.as_ref()
- })
+ pub fn switch(&self, project: Option<&str>) -> SwitchConfig {
+ self.merged_project_config(project, &self.switch, |config| &config.switch)
}
/// Returns the `wt step` config for a specific project.
- pub fn step(&self, project: Option<&str>) -> Option<StepConfig> {
- self.merged_project_config(project, self.step.as_ref(), |config| config.step.as_ref())
+ pub fn step(&self, project: Option<&str>) -> StepConfig {
+ self.merged_project_config(project, &self.step, |config| &config.step)
}
/// Returns the `wt step copy-ignored` config for a specific project.
pub fn copy_ignored(&self, project: Option<&str>) -> CopyIgnoredConfig {
- self.step(project)
- .and_then(|step| step.copy_ignored)
- .unwrap_or_default()
+ self.step(project).copy_ignored.unwrap_or_default()
}
/// Returns the switch picker config for a specific project.
@@ -148,23 +137,14 @@ impl UserConfig {
/// settings take precedence for fields that are set. Deprecated `[select]`
/// sections are normalized into `[switch.picker]` during config loading.
pub fn switch_picker(&self, project: Option<&str>) -> SwitchPickerConfig {
- let global = self
- .switch
- .as_ref()
- .and_then(|switch| switch.picker.as_ref())
- .cloned()
- .unwrap_or_default();
-
- self.project_overrides(project)
- .and_then(|config| {
- config
- .switch
- .as_ref()
- .and_then(|switch| switch.picker.as_ref())
- .cloned()
- })
- .map(|project_config| global.merge_with(&project_config))
- .unwrap_or(global)
+ let global = self.switch.picker.clone().unwrap_or_default();
+ match self
+ .project_overrides(project)
+ .and_then(|config| config.switch.picker.as_ref())
+ {
+ Some(proj) => global.merge_with(proj),
+ None => global,
+ }
}
/// Returns effective hooks for a specific project.
diff --git a/src/config/user/merge.rs b/src/config/user/merge.rs
index 0334276d7..dbe2448c3 100644
--- a/src/config/user/merge.rs
+++ b/src/config/user/merge.rs
@@ -26,3 +26,11 @@ pub fn merge_optional<T: Merge + Clone>(global: Option<&T>, project: Option<&T>)
(None, None) => None,
}
}
+
+/// Returns true if the given value equals `T::default()`.
+///
+/// Used as `skip_serializing_if` so section types like `ListConfig` /
+/// `MergeConfig` are omitted from serialized TOML when no fields are set.
+pub(crate) fn is_default<T: Default + PartialEq>(value: &T) -> bool {
+ *value == T::default()
+}
diff --git a/src/config/user/mod.rs b/src/config/user/mod.rs
index 5fc647203..1fab872cb 100644
--- a/src/config/user/mod.rs
+++ b/src/config/user/mod.rs
@@ -269,24 +269,24 @@ pub struct UserConfig {
pub worktree_path: Option<String>,
/// Configuration for the `wt list` command
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub list: Option<sections::ListConfig>,
+ #[serde(default, skip_serializing_if = "merge::is_default")]
+ pub list: sections::ListConfig,
/// Configuration for the `wt step commit` command (also used by merge)
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub commit: Option<sections::CommitConfig>,
+ #[serde(default, skip_serializing_if = "merge::is_default")]
+ pub commit: sections::CommitConfig,
/// Configuration for the `wt merge` command
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub merge: Option<sections::MergeConfig>,
+ #[serde(default, skip_serializing_if = "merge::is_default")]
+ pub merge: sections::MergeConfig,
/// Configuration for the `wt switch` command
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub switch: Option<sections::SwitchConfig>,
+ #[serde(default, skip_serializing_if = "merge::is_default")]
+ pub switch: sections::SwitchConfig,
/// Configuration for `wt step` subcommands
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub step: Option<sections::StepConfig>,
+ #[serde(default, skip_serializing_if = "merge::is_default")]
+ pub step: sections::StepConfig,
/// Command aliases for `wt step <name>`
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
diff --git a/src/config/user/mutation.rs b/src/config/user/mutation.rs
index a75eaeb62..fa48b0041 100644
--- a/src/config/user/mutation.rs
+++ b/src/config/user/mutation.rs
@@ -11,7 +11,7 @@ use crate::path::format_path_for_display;
use super::UserConfig;
use super::path;
-use super::sections::{CommitConfig, CommitGenerationConfig};
+use super::sections::CommitGenerationConfig;
const NO_CONFIG_DIR_MSG: &str = "Cannot determine config directory. Set $HOME or $XDG_CONFIG_HOME";
@@ -167,13 +167,11 @@ impl UserConfig {
config_path: Option<&std::path::Path>,
) -> Result<(), ConfigError> {
self.with_locked_mutation(config_path, |config| {
- // Ensure commit config exists
- let commit_config = config.commit.get_or_insert_with(CommitConfig::default);
- let gen_config = commit_config
+ let gen_config = config
+ .commit
.generation
.get_or_insert_with(CommitGenerationConfig::default);
- // Set the command
gen_config.command = Some(command.clone());
true
})
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index 6ccee38ee..b5b638795 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -33,11 +33,15 @@ impl UserConfig {
}
}
- fn sync_serialized_section(
+ fn sync_serialized_section<T: Serialize + Default + PartialEq>(
table: &mut toml_edit::Table,
section_name: &str,
- config: Option<&impl Serialize>,
+ config: &T,
) {
+ if *config == T::default() {
+ table.remove(section_name);
+ return;
+ }
match Self::serialize_section_item(config) {
Some(item) => {
table[section_name] = item;
@@ -48,9 +52,8 @@ impl UserConfig {
}
}
- fn serialize_section_item(config: Option<&impl Serialize>) -> Option<toml_edit::Item> {
- let cfg = config?;
- let toml_value = toml::to_string(cfg).ok()?;
+ fn serialize_section_item(config: &impl Serialize) -> Option<toml_edit::Item> {
+ let toml_value = toml::to_string(config).ok()?;
let parsed = toml_value.parse::<toml_edit::DocumentMut>().ok()?;
let mut table = toml_edit::Table::new();
for (k, v) in parsed.iter() {
@@ -61,9 +64,7 @@ impl UserConfig {
/// Update the [commit.generation] section in the document.
fn update_commit_generation_section(&self, doc: &mut toml_edit::DocumentMut) {
- if let Some(ref commit_cfg) = self.commit
- && let Some(ref gen_cfg) = commit_cfg.generation
- {
+ if let Some(ref gen_cfg) = self.commit.generation {
// Ensure [commit] table exists
if !doc.contains_key("commit") {
doc["commit"] = toml_edit::Item::Table(toml_edit::Table::new());
@@ -125,22 +126,10 @@ impl UserConfig {
project_config.worktree_path.as_ref(),
);
- Self::sync_serialized_section(project_table, "list", project_config.list.as_ref());
- Self::sync_serialized_section(
- project_table,
- "commit",
- project_config.commit.as_ref(),
- );
- Self::sync_serialized_section(
- project_table,
- "merge",
- project_config.merge.as_ref(),
- );
- Self::sync_serialized_section(
- project_table,
- "switch",
- project_config.switch.as_ref(),
- );
+ Self::sync_serialized_section(project_table, "list", &project_config.list);
+ Self::sync_serialized_section(project_table, "commit", &project_config.commit);
+ Self::sync_serialized_section(project_table, "merge", &project_config.merge);
+ Self::sync_serialized_section(project_table, "switch", &project_config.switch);
}
}
}
@@ -265,16 +254,12 @@ impl UserConfig {
)));
}
- if let Some(ref commit) = project_config.commit
- && let Some(ref cg) = commit.generation
- {
+ if let Some(ref cg) = project_config.commit.generation {
Self::validate_commit_generation(cg, &format!("projects.{project}"))?;
}
}
- if let Some(ref commit) = self.commit
- && let Some(ref cg) = commit.generation
- {
+ if let Some(ref cg) = self.commit.generation {
if cg.template.is_some() && cg.template_file.is_some() {
return Err(ConfigError(
"commit.generation.template and commit.generation.template-file are mutually exclusive".into(),
diff --git a/src/config/user/resolved.rs b/src/config/user/resolved.rs
index dd139eb44..2abf8687e 100644
--- a/src/config/user/resolved.rs
+++ b/src/config/user/resolved.rs
@@ -44,13 +44,13 @@ impl ResolvedConfig {
/// Resolve all configuration for a project.
pub fn for_project(config: &UserConfig, project: Option<&str>) -> Self {
Self {
- list: config.list(project).unwrap_or_default(),
- merge: config.merge(project).unwrap_or_default(),
- commit: config.commit(project).unwrap_or_default(),
+ list: config.list(project),
+ merge: config.merge(project),
+ commit: config.commit(project),
commit_generation: config.commit_generation(project),
switch_picker: config.switch_picker(project),
- switch: config.switch(project).unwrap_or_default(),
- step: config.step(project).unwrap_or_default(),
+ switch: config.switch(project),
+ step: config.step(project),
}
}
}
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index 1419b6c25..0e0d7fad0 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -8,7 +8,7 @@ use std::collections::BTreeMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
-use super::merge::{Merge, merge_optional};
+use super::merge::{Merge, is_default, merge_optional};
use crate::config::HooksConfig;
use crate::config::commands::CommandConfig;
@@ -502,20 +502,20 @@ pub struct UserProjectOverrides {
)]
pub worktree_path: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub list: Option<ListConfig>,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub list: ListConfig,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub commit: Option<CommitConfig>,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub commit: CommitConfig,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub merge: Option<MergeConfig>,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub merge: MergeConfig,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub switch: Option<SwitchConfig>,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub switch: SwitchConfig,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub step: Option<StepConfig>,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub step: StepConfig,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub aliases: BTreeMap<String, CommandConfig>,
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 617ff47d5..65704f02d 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -303,9 +303,9 @@ fn test_worktrunk_config_default() {
"{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}"
);
assert!(config.projects.is_empty());
- assert!(config.list.is_none());
- assert!(config.commit.is_none());
- assert!(config.merge.is_none());
+ assert_eq!(config.list, ListConfig::default());
+ assert_eq!(config.commit, CommitConfig::default());
+ assert_eq!(config.merge, MergeConfig::default());
assert!(!config.skip_shell_integration_prompt);
}
@@ -796,13 +796,13 @@ fn test_commit_generation_merge_squash_template_mutual_exclusivity() {
#[test]
fn test_effective_commit_generation_no_project() {
let config = UserConfig {
- commit: Some(CommitConfig {
+ commit: CommitConfig {
stage: None,
generation: Some(CommitGenerationConfig {
command: Some("global-llm".to_string()),
..Default::default()
}),
- }),
+ },
..Default::default()
};
@@ -813,26 +813,26 @@ fn test_effective_commit_generation_no_project() {
#[test]
fn test_effective_commit_generation_with_project_override() {
let mut config = UserConfig {
- commit: Some(CommitConfig {
+ commit: CommitConfig {
stage: None,
generation: Some(CommitGenerationConfig {
command: Some("global-llm".to_string()),
..Default::default()
}),
- }),
+ },
..Default::default()
};
config.projects.insert(
"github.com/user/repo".to_string(),
UserProjectOverrides {
- commit: Some(CommitConfig {
+ commit: CommitConfig {
stage: None,
generation: Some(CommitGenerationConfig {
command: Some("project-llm".to_string()),
..Default::default()
}),
- }),
+ },
..Default::default()
},
);
@@ -852,33 +852,33 @@ fn test_effective_commit_generation_with_project_override() {
#[test]
fn test_effective_merge_with_partial_override() {
let mut config = UserConfig {
- merge: Some(MergeConfig {
+ merge: MergeConfig {
squash: Some(true),
commit: Some(true),
rebase: Some(true),
remove: Some(true),
verify: Some(true),
ff: Some(true),
- }),
+ },
..Default::default()
};
config.projects.insert(
"github.com/user/repo".to_string(),
UserProjectOverrides {
- merge: Some(MergeConfig {
+ merge: MergeConfig {
squash: Some(false), // Only override squash
commit: None,
rebase: None,
remove: None,
verify: None,
ff: None,
- }),
+ },
..Default::default()
},
);
- let effective = config.merge(Some("github.com/user/repo")).unwrap();
+ let effective = config.merge(Some("github.com/user/repo"));
assert_eq!(effective.squash, Some(false)); // From project
assert_eq!(effective.commit, Some(true)); // From global
assert_eq!(effective.rebase, Some(true)); // From global
@@ -888,39 +888,42 @@ fn test_effective_merge_with_partial_override() {
fn test_effective_list_project_only() {
// No global list config, only project config
let mut config = UserConfig::default();
- assert!(config.list.is_none());
+ assert_eq!(config.list, ListConfig::default());
config.projects.insert(
"github.com/user/repo".to_string(),
UserProjectOverrides {
- list: Some(ListConfig {
+ list: ListConfig {
full: Some(true),
..Default::default()
- }),
+ },
..Default::default()
},
);
- let effective = config.list(Some("github.com/user/repo")).unwrap();
+ let effective = config.list(Some("github.com/user/repo"));
assert_eq!(effective.full, Some(true));
assert!(effective.branches.is_none());
- // No global, no matching project = None
- assert!(config.list(Some("github.com/other/repo")).is_none());
+ // No global, no matching project falls back to default
+ assert_eq!(
+ config.list(Some("github.com/other/repo")),
+ ListConfig::default()
+ );
}
#[test]
fn test_effective_commit_global_only() {
// Only global config, no project config
let config = UserConfig {
- commit: Some(CommitConfig {
+ commit: CommitConfig {
stage: Some(StageMode::Tracked),
generation: None,
- }),
+ },
..Default::default()
};
- let effective = config.commit(Some("github.com/any/project")).unwrap();
+ let effective = config.commit(Some("github.com/any/project"));
assert_eq!(effective.stage, Some(StageMode::Tracked));
}
@@ -995,14 +998,14 @@ fn test_merge_config_accessor_methods_with_values() {
#[test]
fn test_deprecated_no_ff_migrated_to_ff() {
let config = UserConfig::load_from_str("[merge]\nno-ff = true\n").unwrap();
- assert!(!config.merge.unwrap().ff());
+ assert!(!config.merge.ff());
}
#[test]
fn test_deprecated_no_ff_does_not_override_explicit_ff() {
// If both `ff` and `no-ff` are set, `ff` wins (no-ff is ignored)
let config = UserConfig::load_from_str("[merge]\nff = true\nno-ff = true\n").unwrap();
- assert!(config.merge.unwrap().ff());
+ assert!(config.merge.ff());
}
#[test]
@@ -1074,7 +1077,7 @@ pager = "delta --paging=never"
timeout-ms = 300
"#;
let config: UserConfig = toml::from_str(content).unwrap();
- let picker = config.switch.as_ref().unwrap().picker.as_ref().unwrap();
+ let picker = config.switch.picker.as_ref().unwrap();
assert_eq!(picker.pager.as_deref(), Some("delta --paging=never"));
assert_eq!(picker.timeout_ms, Some(300));
}
@@ -1195,7 +1198,7 @@ fn test_switch_config_cd_from_toml() {
cd = false
"#;
let config = UserConfig::load_from_str(toml).unwrap();
- let switch = config.switch(None).unwrap();
+ let switch = config.switch(None);
assert!(!switch.cd());
}
@@ -1213,13 +1216,13 @@ cd = false
#[test]
fn test_deprecated_no_cd_migrated_to_cd() {
let config = UserConfig::load_from_str("[switch]\nno-cd = true\n").unwrap();
- assert!(!config.switch.unwrap().cd());
+ assert!(!config.switch.cd());
}
#[test]
fn test_deprecated_no_cd_does_not_override_explicit_cd() {
let config = UserConfig::load_from_str("[switch]\ncd = true\nno-cd = true\n").unwrap();
- assert!(config.switch.unwrap().cd());
+ assert!(config.switch.cd());
}
#[test]
@@ -1238,8 +1241,8 @@ pager = "bat"
assert_eq!(
config
.switch
+ .picker
.as_ref()
- .and_then(|switch| switch.picker.as_ref())
.and_then(|picker| picker.pager.as_deref()),
Some("bat")
);
@@ -1275,26 +1278,26 @@ fn test_switch_picker_project_override() {
use crate::config::user::{SwitchConfig, SwitchPickerConfig};
let mut config = UserConfig {
- switch: Some(SwitchConfig {
+ switch: SwitchConfig {
picker: Some(SwitchPickerConfig {
pager: Some("delta".to_string()),
timeout_ms: Some(200),
}),
..Default::default()
- }),
+ },
..Default::default()
};
config.projects.insert(
"github.com/user/repo".to_string(),
UserProjectOverrides {
- switch: Some(SwitchConfig {
+ switch: SwitchConfig {
picker: Some(SwitchPickerConfig {
pager: Some("bat".to_string()),
timeout_ms: None, // Fall back to global
}),
..Default::default()
- }),
+ },
..Default::default()
},
);
@@ -1329,8 +1332,8 @@ pager = "bat"
.get("github.com/user/repo")
.unwrap()
.switch
+ .picker
.as_ref()
- .and_then(|s| s.picker.as_ref())
.and_then(|p| p.pager.as_deref())
== Some("bat")
);
@@ -1342,25 +1345,25 @@ fn test_resolved_config_for_project() {
use crate::config::user::SwitchPickerConfig;
let config = UserConfig {
- list: Some(ListConfig {
+ list: ListConfig {
full: Some(true),
..Default::default()
- }),
- merge: Some(MergeConfig {
+ },
+ merge: MergeConfig {
squash: Some(false),
..Default::default()
- }),
- commit: Some(CommitConfig {
+ },
+ commit: CommitConfig {
stage: Some(StageMode::None),
..Default::default()
- }),
- switch: Some(SwitchConfig {
+ },
+ switch: SwitchConfig {
picker: Some(SwitchPickerConfig {
pager: Some("less".to_string()),
timeout_ms: Some(300),
}),
..Default::default()
- }),
+ },
..Default::default()
};
@@ -1386,21 +1389,21 @@ fn test_user_project_config_with_nested_configs_serde() {
let config = UserProjectOverrides {
approved_commands: vec!["npm install".to_string()],
worktree_path: Some(".worktrees/{{ branch }}".to_string()),
- list: Some(ListConfig {
+ list: ListConfig {
full: Some(true),
..Default::default()
- }),
- commit: Some(CommitConfig {
+ },
+ commit: CommitConfig {
stage: Some(StageMode::Tracked),
generation: Some(CommitGenerationConfig {
command: Some("llm -m gpt-4".to_string()),
..Default::default()
}),
- }),
- merge: Some(MergeConfig {
+ },
+ merge: MergeConfig {
squash: Some(false),
..Default::default()
- }),
+ },
..Default::default()
};
@@ -1412,22 +1415,12 @@ fn test_user_project_config_with_nested_configs_serde() {
Some(".worktrees/{{ branch }}".to_string())
);
assert_eq!(
- parsed
- .commit
- .as_ref()
- .unwrap()
- .generation
- .as_ref()
- .unwrap()
- .command,
+ parsed.commit.generation.as_ref().unwrap().command,
Some("llm -m gpt-4".to_string())
);
- assert_eq!(parsed.list.as_ref().unwrap().full, Some(true));
- assert_eq!(
- parsed.commit.as_ref().unwrap().stage,
- Some(StageMode::Tracked)
- );
- assert_eq!(parsed.merge.as_ref().unwrap().squash, Some(false));
+ assert_eq!(parsed.list.full, Some(true));
+ assert_eq!(parsed.commit.stage, Some(StageMode::Tracked));
+ assert_eq!(parsed.merge.squash, Some(false));
}
#[test]
@@ -1461,14 +1454,7 @@ squash = false
Some("../{{ repo }}.{{ branch | sanitize }}".to_string())
);
assert_eq!(
- config
- .commit
- .as_ref()
- .unwrap()
- .generation
- .as_ref()
- .unwrap()
- .command,
+ config.commit.generation.as_ref().unwrap().command,
Some("llm -m claude-haiku-4.5".to_string())
);
@@ -1479,18 +1465,11 @@ squash = false
Some(".worktrees/{{ branch | sanitize }}".to_string())
);
assert_eq!(
- project
- .commit
- .as_ref()
- .unwrap()
- .generation
- .as_ref()
- .unwrap()
- .command,
+ project.commit.generation.as_ref().unwrap().command,
Some("claude -p --model opus".to_string())
);
- assert_eq!(project.list.as_ref().unwrap().full, Some(true));
- assert_eq!(project.merge.as_ref().unwrap().squash, Some(false));
+ assert_eq!(project.list.full, Some(true));
+ assert_eq!(project.merge.squash, Some(false));
// Effective config for project
let effective_cg = config.commit_generation(Some("github.com/user/repo"));
@@ -1499,7 +1478,7 @@ squash = false
Some("claude -p --model opus".to_string())
);
- let effective_merge = config.merge(Some("github.com/user/repo")).unwrap();
+ let effective_merge = config.merge(Some("github.com/user/repo"));
assert_eq!(effective_merge.squash, Some(false));
}
@@ -1556,8 +1535,8 @@ command = "claude -p --model opus"
assert_eq!(
config
.commit
+ .generation
.as_ref()
- .and_then(|commit| commit.generation.as_ref())
.and_then(|generation| generation.command.as_deref()),
Some("llm -m claude-haiku-4.5")
);
@@ -1566,8 +1545,8 @@ command = "claude -p --model opus"
assert_eq!(
project
.commit
+ .generation
.as_ref()
- .and_then(|commit| commit.generation.as_ref())
.and_then(|generation| generation.command.as_deref()),
Some("claude -p --model opus")
);
@@ -1593,8 +1572,8 @@ args = ["-m", "claude-haiku-4.5"]
assert_eq!(
config
.commit
+ .generation
.as_ref()
- .and_then(|c| c.generation.as_ref())
.and_then(|g| g.command.as_deref()),
Some("llm -m claude-haiku-4.5")
);
@@ -1692,13 +1671,13 @@ fn test_save_to_new_file_with_commit_generation() {
let config_path = dir.path().join("config.toml");
let config = UserConfig {
- commit: Some(CommitConfig {
+ commit: CommitConfig {
stage: None,
generation: Some(CommitGenerationConfig {
command: Some("llm -m haiku".to_string()),
..Default::default()
}),
- }),
+ },
..Default::default()
};
@@ -1727,13 +1706,13 @@ fn test_save_to_new_file_commit_with_stage_and_generation() {
let config_path = dir.path().join("config.toml");
let config = UserConfig {
- commit: Some(CommitConfig {
+ commit: CommitConfig {
stage: Some(StageMode::Tracked),
generation: Some(CommitGenerationConfig {
command: Some("llm -m haiku".to_string()),
..Default::default()
}),
- }),
+ },
..Default::default()
};
@@ -1794,6 +1773,83 @@ fn test_save_to_new_file_with_worktree_path() {
);
}
+#[test]
+fn test_save_to_preserves_project_section_configs() {
+ // Exercises sync_serialized_section through the surgical-update save path
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+
+ // Create initial file with a project
+ let initial = r#"
+[projects."github.com/user/repo"]
+worktree-path = ".wt/{{ branch | sanitize }}"
+"#;
+ std::fs::write(&config_path, initial).unwrap();
+
+ // Build config with project section overrides
+ let mut config = UserConfig::default();
+ config.projects.insert(
+ "github.com/user/repo".to_string(),
+ UserProjectOverrides {
+ worktree_path: Some(".wt/{{ branch | sanitize }}".to_string()),
+ merge: MergeConfig {
+ squash: Some(false),
+ ..Default::default()
+ },
+ list: ListConfig {
+ full: Some(true),
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ );
+
+ config.save_to(&config_path).unwrap();
+
+ let saved = std::fs::read_to_string(&config_path).unwrap();
+ assert!(
+ saved.contains("squash = false"),
+ "Should serialize merge config: {saved}"
+ );
+ assert!(
+ saved.contains("full = true"),
+ "Should serialize list config: {saved}"
+ );
+
+ // Default sections should not appear
+ assert!(
+ !saved.contains("[projects.\"github.com/user/repo\".commit]"),
+ "Default commit section should not appear: {saved}"
+ );
+ assert!(
+ !saved.contains("[projects.\"github.com/user/repo\".switch]"),
+ "Default switch section should not appear: {saved}"
+ );
+}
+
+#[test]
+fn test_save_to_removes_default_project_section() {
+ // Exercises the is_default → remove branch in sync_serialized_section
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+ std::fs::write(
+ &config_path,
+ "[projects.\"github.com/u/r\".list]\nfull = true\n",
+ )
+ .unwrap();
+
+ let mut config =
+ UserConfig::load_from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
+ config.projects.get_mut("github.com/u/r").unwrap().list = ListConfig::default();
+ config.save_to(&config_path).unwrap();
+
+ let saved = std::fs::read_to_string(&config_path).unwrap();
+ assert!(
+ !saved.contains("[projects.\"github.com/u/r\".list]"),
+ "Default section should be removed: {saved}"
+ );
+}
+
// =========================================================================
// Per-project hooks tests (append semantics)
// =========================================================================
@@ -2120,21 +2176,19 @@ squash = true
let user_config = UserConfig::load_from_str(user_toml).unwrap();
// Verify system config values
- assert_eq!(system_config.merge.as_ref().unwrap().squash, Some(false));
- assert_eq!(system_config.merge.as_ref().unwrap().rebase, Some(false));
- assert_eq!(system_config.list.as_ref().unwrap().full, Some(true));
+ assert_eq!(system_config.merge.squash, Some(false));
+ assert_eq!(system_config.merge.rebase, Some(false));
+ assert_eq!(system_config.list.full, Some(true));
// Verify user config values
- assert_eq!(user_config.merge.as_ref().unwrap().squash, Some(true));
+ assert_eq!(user_config.merge.squash, Some(true));
// Simulate the merge that happens via the config crate's builder:
// When both system and user configs define [merge], the config crate
// performs a deep merge where user values override system values.
// This is tested end-to-end via integration tests; here we verify
// the Merge trait works correctly for the layering.
- let system_merge = system_config.merge.as_ref().unwrap();
- let user_merge = user_config.merge.as_ref().unwrap();
- let merged = system_merge.merge_with(user_merge);
+ let merged = system_config.merge.merge_with(&user_config.merge);
assert_eq!(merged.squash, Some(true)); // User overrides
assert_eq!(merged.rebase, Some(false)); // System default preserved
@@ -2415,22 +2469,22 @@ fn test_save_to_existing_file_writes_project_sections() {
"github.com/user/repo".to_string(),
UserProjectOverrides {
worktree_path: Some("../{{ branch | sanitize }}".to_string()),
- list: Some(ListConfig {
+ list: ListConfig {
full: Some(true),
..Default::default()
- }),
- commit: Some(CommitConfig {
+ },
+ commit: CommitConfig {
stage: Some(StageMode::Tracked),
generation: None,
- }),
- merge: Some(MergeConfig {
+ },
+ merge: MergeConfig {
squash: Some(false),
..Default::default()
- }),
- switch: Some(SwitchConfig {
+ },
+ switch: SwitchConfig {
cd: Some(false),
picker: None,
- }),
+ },
..Default::default()
},
);
@@ -2475,13 +2529,10 @@ fn test_save_to_existing_file_writes_project_sections() {
reloaded.worktree_path.as_deref(),
Some("../{{ branch | sanitize }}")
);
- assert_eq!(reloaded.list.as_ref().unwrap().full, Some(true));
- assert_eq!(
- reloaded.commit.as_ref().unwrap().stage,
- Some(StageMode::Tracked)
- );
- assert_eq!(reloaded.merge.as_ref().unwrap().squash, Some(false));
- assert_eq!(reloaded.switch.as_ref().unwrap().cd, Some(false));
+ assert_eq!(reloaded.list.full, Some(true));
+ assert_eq!(reloaded.commit.stage, Some(StageMode::Tracked));
+ assert_eq!(reloaded.merge.squash, Some(false));
+ assert_eq!(reloaded.switch.cd, Some(false));
}
#[test]
@@ -2513,7 +2564,7 @@ worktree-path = "drop-path"
"keep".to_string(),
UserProjectOverrides {
worktree_path: Some("keep-path".to_string()),
- list: None, // was Some on disk, now None — should be removed
+ list: ListConfig::default(), // was non-default on disk, now default — should be removed
..Default::default()
},
);
@@ -2553,14 +2604,14 @@ template = "stays: {{ diff }}"
.unwrap();
let config = UserConfig {
- commit: Some(CommitConfig {
+ commit: CommitConfig {
stage: None,
generation: Some(CommitGenerationConfig {
command: Some("new-llm".to_string()),
template: Some("stays: {{ diff }}".to_string()),
..Default::default()
}),
- }),
+ },
..Default::default()
};
@@ -2601,13 +2652,13 @@ stage = "all"
.unwrap();
let config = UserConfig {
- commit: Some(CommitConfig {
+ commit: CommitConfig {
stage: Some(StageMode::All),
generation: Some(CommitGenerationConfig {
command: Some("llm".to_string()),
..Default::default()
}),
- }),
+ },
..Default::default()
};
@@ -2689,13 +2740,13 @@ fn test_save_to_existing_file_where_commit_is_scalar() {
std::fs::write(&config_path, "commit = \"hand-edited-mistake\"\n").unwrap();
let config = UserConfig {
- commit: Some(CommitConfig {
+ commit: CommitConfig {
stage: None,
generation: Some(CommitGenerationConfig {
command: Some("llm".to_string()),
..Default::default()
}),
- }),
+ },
..Default::default()
};
@@ -2724,13 +2775,13 @@ fn test_save_to_existing_file_where_commit_generation_is_scalar() {
.unwrap();
let config = UserConfig {
- commit: Some(CommitConfig {
+ commit: CommitConfig {
stage: Some(StageMode::Tracked),
generation: Some(CommitGenerationConfig {
command: Some("llm".to_string()),
..Default::default()
}),
- }),
+ },
..Default::default()
};
@@ -2885,15 +2936,15 @@ fn test_save_to_new_file_expands_nested_project_inline_tables() {
config.projects.insert(
"repo".to_string(),
UserProjectOverrides {
- list: Some(ListConfig {
+ list: ListConfig {
full: Some(true),
branches: Some(true),
..Default::default()
- }),
- switch: Some(SwitchConfig {
+ },
+ switch: SwitchConfig {
cd: Some(false),
picker: None,
- }),
+ },
..Default::default()
},
);
@@ -2922,14 +2973,7 @@ fn test_save_to_new_file_expands_nested_project_inline_tables() {
// And it should round-trip cleanly
let reparsed = UserConfig::load_from_str(&saved).unwrap();
assert_eq!(
- reparsed
- .projects
- .get("repo")
- .unwrap()
- .list
- .as_ref()
- .unwrap()
- .branches,
+ reparsed.projects.get("repo").unwrap().list.branches,
Some(true)
);
}
diff --git a/tests/integration_tests/select_config.rs b/tests/integration_tests/select_config.rs
index 4fae22986..047d357e1 100644
--- a/tests/integration_tests/select_config.rs
+++ b/tests/integration_tests/select_config.rs
@@ -22,5 +22,5 @@ fn test_select_config_optional() {
full = true
"#;
let config: UserConfig = toml::from_str(content).unwrap();
- assert!(config.switch.is_none());
+ assert_eq!(config.switch, worktrunk::config::SwitchConfig::default());
}