Skip to content

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

refactor(config): unify unknown-key detection (#2195)

Maximilian Roosafa923f090cc
diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rs
index c6590012b..0294943ca 100644
--- a/src/commands/config/mod.rs
+++ b/src/commands/config/mod.rs
@@ -27,8 +27,6 @@ pub use update::handle_config_update;
#[cfg(test)]
mod tests {
- use std::collections::HashMap;
-
use insta::assert_snapshot;
use worktrunk::config::{ProjectConfig, UserConfig};
@@ -117,101 +115,61 @@ mod tests {
#[test]
fn test_warn_unknown_keys_empty() {
- let out = warn_unknown_keys::<UserConfig>(&HashMap::new());
+ let out = warn_unknown_keys::<UserConfig>("");
assert!(out.is_empty());
}
#[test]
fn test_warn_unknown_keys() {
// Single unknown key
- let mut unknown = HashMap::new();
- unknown.insert(
- "unknown-key".to_string(),
- toml::Value::String("value".to_string()),
- );
- assert_snapshot!(warn_unknown_keys::<UserConfig>(&unknown), @"▲ Unknown key unknown-key will be ignored");
+ assert_snapshot!(warn_unknown_keys::<UserConfig>("unknown-key = \"value\"\n"), @"▲ Unknown key unknown-key will be ignored");
// Multiple unknown keys (output is sorted deterministically)
- let mut unknown = HashMap::new();
- unknown.insert(
- "key1".to_string(),
- toml::Value::String("value1".to_string()),
- );
- unknown.insert(
- "key2".to_string(),
- toml::Value::String("value2".to_string()),
- );
- assert_snapshot!(warn_unknown_keys::<UserConfig>(&unknown), @"
+ assert_snapshot!(warn_unknown_keys::<UserConfig>("key1 = \"v1\"\nkey2 = \"v2\"\n"), @"
▲ Unknown key key1 will be ignored
▲ Unknown key key2 will be ignored
");
}
+ #[test]
+ fn test_warn_unknown_keys_nested() {
+ // Nested typos surface as dotted paths — a UX win from round-trip analysis.
+ insta::assert_snapshot!(warn_unknown_keys::<UserConfig>("[merge]\nsquas = true\n"));
+ }
+
#[test]
fn test_warn_unknown_keys_suggests_other_config() {
// skip-shell-integration-prompt in project config should suggest user config
- let mut unknown = HashMap::new();
- unknown.insert(
- "skip-shell-integration-prompt".to_string(),
- toml::Value::Boolean(true),
- );
- assert_snapshot!(warn_unknown_keys::<ProjectConfig>(&unknown), @"▲ Key skip-shell-integration-prompt belongs in user config (will be ignored)");
+ assert_snapshot!(
+ warn_unknown_keys::<ProjectConfig>("skip-shell-integration-prompt = true\n"),
+ @"▲ Key skip-shell-integration-prompt belongs in user config (will be ignored)");
// forge in user config should suggest project config
- let mut unknown = HashMap::new();
- let mut inner = toml::map::Map::new();
- inner.insert(
- "platform".to_string(),
- toml::Value::String("github".to_string()),
- );
- unknown.insert("forge".to_string(), toml::Value::Table(inner));
- assert_snapshot!(warn_unknown_keys::<UserConfig>(&unknown), @"▲ Key forge belongs in project config (will be ignored)");
+ assert_snapshot!(warn_unknown_keys::<UserConfig>("[forge]\nplatform = \"github\"\n"), @"▲ Key forge belongs in project config (will be ignored)");
}
#[test]
fn test_warn_unknown_keys_deprecated_in_wrong_config() {
// commit-generation in project config should suggest user config with canonical form
- let mut unknown = HashMap::new();
- let mut inner = toml::map::Map::new();
- inner.insert(
- "command".to_string(),
- toml::Value::String("llm".to_string()),
- );
- unknown.insert("commit-generation".to_string(), toml::Value::Table(inner));
- assert_snapshot!(warn_unknown_keys::<ProjectConfig>(&unknown));
+ assert_snapshot!(warn_unknown_keys::<ProjectConfig>(
+ "[commit-generation]\ncommand = \"llm\"\n"
+ ));
// ci in user config should suggest project config with canonical form
- let mut unknown = HashMap::new();
- let mut inner = toml::map::Map::new();
- inner.insert(
- "platform".to_string(),
- toml::Value::String("github".to_string()),
- );
- unknown.insert("ci".to_string(), toml::Value::Table(inner));
- assert_snapshot!(warn_unknown_keys::<UserConfig>(&unknown));
+ assert_snapshot!(warn_unknown_keys::<UserConfig>(
+ "[ci]\nplatform = \"github\"\n"
+ ));
}
#[test]
fn test_warn_unknown_keys_deprecated_in_right_config_is_skipped() {
// commit-generation in user config should be skipped (deprecation system handles it)
- let mut unknown = HashMap::new();
- let mut inner = toml::map::Map::new();
- inner.insert(
- "command".to_string(),
- toml::Value::String("llm".to_string()),
+ assert!(
+ warn_unknown_keys::<UserConfig>("[commit-generation]\ncommand = \"llm\"\n").is_empty()
);
- unknown.insert("commit-generation".to_string(), toml::Value::Table(inner));
- assert!(warn_unknown_keys::<UserConfig>(&unknown).is_empty());
// ci in project config should be skipped (deprecation system handles it)
- let mut unknown = HashMap::new();
- let mut inner = toml::map::Map::new();
- inner.insert(
- "platform".to_string(),
- toml::Value::String("github".to_string()),
- );
- unknown.insert("ci".to_string(), toml::Value::Table(inner));
- assert!(warn_unknown_keys::<ProjectConfig>(&unknown).is_empty());
+ assert!(warn_unknown_keys::<ProjectConfig>("[ci]\nplatform = \"github\"\n").is_empty());
}
// ==================== render_ci_tool_status tests ====================
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index 79a9afa0b..80b54ca72 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -3,15 +3,14 @@
//! Functions for displaying user config, project config, shell status,
//! diagnostics, and runtime info.
-use std::collections::{HashMap, HashSet};
+use std::collections::HashSet;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use anyhow::Context;
use color_print::cformat;
use worktrunk::config::{
- ProjectConfig, UserConfig, default_system_config_path, find_unknown_project_keys,
- find_unknown_user_keys, system_config_path,
+ ProjectConfig, UserConfig, default_system_config_path, system_config_path,
};
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
@@ -466,9 +465,7 @@ fn render_system_config(out: &mut String) -> anyhow::Result<bool> {
writeln!(out, "{}", error_message("Invalid config"))?;
writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;
} else {
- out.push_str(&warn_unknown_keys::<UserConfig>(&find_unknown_user_keys(
- &contents,
- )));
+ out.push_str(&warn_unknown_keys::<UserConfig>(&contents));
}
// Display TOML with syntax highlighting
@@ -537,12 +534,7 @@ fn render_user_config(out: &mut String, has_system_config: bool) -> anyhow::Resu
writeln!(out, "{}", error_message("Invalid config"))?;
writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;
} else {
- // Only check for unknown keys if config is valid.
- // Filter deprecated section keys to avoid duplicate warnings
- // (deprecation system already warns about these).
- out.push_str(&warn_unknown_keys::<UserConfig>(&find_unknown_user_keys(
- &contents,
- )));
+ out.push_str(&warn_unknown_keys::<UserConfig>(&contents));
}
// Display TOML with syntax highlighting (gutter at column 0).
@@ -572,39 +564,43 @@ fn render_system_config_hint(out: &mut String) -> anyhow::Result<()> {
Ok(())
}
-/// Format warnings for any unknown config keys.
+/// Format warnings for unknown config keys in `raw_contents`.
///
-/// Generic over `C`, the config type where the keys were found. When an unknown
-/// key belongs in `C::Other`, the warning includes a hint about where to move it.
+/// Generic over `C`, the config type. Classification is shared with the
+/// load-time warning path via
+/// [`collect_unknown_warnings`](worktrunk::config::collect_unknown_warnings);
+/// only the message wording differs.
pub(super) fn warn_unknown_keys<C: worktrunk::config::WorktrunkConfig>(
- unknown_keys: &HashMap<String, toml::Value>,
+ raw_contents: &str,
) -> String {
let mut out = String::new();
-
- let mut keys: Vec<_> = unknown_keys.keys().collect();
- keys.sort();
-
- for key in keys {
- let msg = match worktrunk::config::classify_unknown_key::<C>(key) {
- worktrunk::config::UnknownKeyKind::DeprecatedHandled => continue,
- worktrunk::config::UnknownKeyKind::DeprecatedWrongConfig {
- other_description,
- canonical_display,
- } => {
- cformat!("Key <bold>{key}</> belongs in {other_description} as {canonical_display}")
- }
- worktrunk::config::UnknownKeyKind::WrongConfig { other_description } => {
- cformat!("Key <bold>{key}</> belongs in {other_description} (will be ignored)")
- }
- worktrunk::config::UnknownKeyKind::Unknown => {
- cformat!("Unknown key <bold>{key}</> will be ignored")
- }
- };
- let _ = writeln!(out, "{}", warning_message(msg));
+ for warning in worktrunk::config::collect_unknown_warnings::<C>(raw_contents) {
+ let _ = writeln!(out, "{}", warning_message(format_show_warning(&warning)));
}
out
}
+fn format_show_warning(warning: &worktrunk::config::UnknownWarning) -> String {
+ use worktrunk::config::UnknownWarning;
+ match warning {
+ UnknownWarning::TopLevelUnknown { key } => {
+ cformat!("Unknown key <bold>{key}</> will be ignored")
+ }
+ UnknownWarning::TopLevelWrongConfig {
+ key,
+ other_description,
+ } => cformat!("Key <bold>{key}</> belongs in {other_description} (will be ignored)"),
+ UnknownWarning::TopLevelDeprecatedWrongConfig {
+ key,
+ other_description,
+ canonical_display,
+ } => cformat!("Key <bold>{key}</> belongs in {other_description} as {canonical_display}"),
+ UnknownWarning::NestedUnknown { path } => {
+ cformat!("Unknown key <bold>{path}</> will be ignored")
+ }
+ }
+}
+
fn render_project_config(out: &mut String) -> anyhow::Result<()> {
// Try to get current repository root
let repo = match Repository::current() {
@@ -688,10 +684,7 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {
writeln!(out, "{}", error_message("Invalid config"))?;
writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;
} else {
- // Only check for unknown keys if config is valid
- out.push_str(&warn_unknown_keys::<ProjectConfig>(
- &find_unknown_project_keys(&contents),
- ));
+ out.push_str(&warn_unknown_keys::<ProjectConfig>(&contents));
}
// Display TOML with syntax highlighting (gutter at column 0).
diff --git a/src/commands/config/snapshots/wt__commands__config__tests__warn_unknown_keys_nested.snap b/src/commands/config/snapshots/wt__commands__config__tests__warn_unknown_keys_nested.snap
new file mode 100644
index 000000000..7656d368d
--- /dev/null
+++ b/src/commands/config/snapshots/wt__commands__config__tests__warn_unknown_keys_nested.snap
@@ -0,0 +1,5 @@
+---
+source: src/commands/config/mod.rs
+expression: "warn_unknown_keys::<UserConfig>(&tree)"
+---
+▲ Unknown key merge.squas will be ignored
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index 57321b3fc..4454055d8 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -17,7 +17,7 @@
//! spam the same deprecation message from multiple config layers.
use std::borrow::Cow;
-use std::collections::{HashMap, HashSet};
+use std::collections::HashSet;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex, OnceLock};
@@ -1506,21 +1506,21 @@ pub fn classify_unknown_key<C: WorktrunkConfig>(key: &str) -> UnknownKeyKind {
}
}
-/// Warn about unknown fields in config file
+/// Warn about unknown fields in a config file.
///
-/// Generic over `C`, the config type being loaded. Emits a warning for each
-/// unknown field, deduplicated per path per process.
+/// Generic over `C`, the config type being loaded. Classification is shared
+/// with `config show` via [`collect_unknown_warnings`](crate::config::collect_unknown_warnings);
+/// this wrapper adds per-path deduplication and stderr emission.
///
-/// When an unknown key belongs in the other config type (`C::Other`),
-/// the warning includes a hint about where to move it.
-///
-/// The `label` is used in the warning message (e.g., "User config" or "Project config").
-pub fn warn_unknown_fields<C: WorktrunkConfig>(
- path: &Path,
- unknown_keys: &HashMap<String, toml::Value>,
- label: &str,
-) {
- if unknown_keys.is_empty() || warnings_suppressed() {
+/// The `label` is used in the warning message (e.g., "User config" or
+/// "Project config").
+pub fn warn_unknown_fields<C: WorktrunkConfig>(raw_contents: &str, path: &Path, label: &str) {
+ if warnings_suppressed() {
+ return;
+ }
+
+ let warnings = crate::config::collect_unknown_warnings::<C>(raw_contents);
+ if warnings.is_empty() {
return;
}
@@ -1534,32 +1534,39 @@ pub fn warn_unknown_fields<C: WorktrunkConfig>(
guard.insert(canonical_path);
}
- let mut keys: Vec<_> = unknown_keys.keys().collect();
- keys.sort();
-
- for key in keys {
- let msg = match classify_unknown_key::<C>(key) {
- UnknownKeyKind::DeprecatedHandled => continue,
- UnknownKeyKind::DeprecatedWrongConfig {
- other_description,
- canonical_display,
- } => cformat!(
- "{label} has key <bold>{key}</> which belongs in {other_description} as {canonical_display}"
- ),
- UnknownKeyKind::WrongConfig { other_description } => cformat!(
- "{label} has key <bold>{key}</> which belongs in {other_description} (will be ignored)"
- ),
- UnknownKeyKind::Unknown => {
- cformat!("{label} has unknown field <bold>{key}</> (will be ignored)")
- }
- };
- eprintln!("{}", warning_message(msg));
+ for warning in warnings {
+ eprintln!("{}", warning_message(format_load_warning(label, &warning)));
}
// Flush stderr to ensure output appears before any subsequent messages
std::io::stderr().flush().ok();
}
+fn format_load_warning(label: &str, warning: &crate::config::UnknownWarning) -> String {
+ use crate::config::UnknownWarning;
+ match warning {
+ UnknownWarning::TopLevelUnknown { key } => {
+ cformat!("{label} has unknown field <bold>{key}</> (will be ignored)")
+ }
+ UnknownWarning::TopLevelWrongConfig {
+ key,
+ other_description,
+ } => cformat!(
+ "{label} has key <bold>{key}</> which belongs in {other_description} (will be ignored)"
+ ),
+ UnknownWarning::TopLevelDeprecatedWrongConfig {
+ key,
+ other_description,
+ canonical_display,
+ } => cformat!(
+ "{label} has key <bold>{key}</> which belongs in {other_description} as {canonical_display}"
+ ),
+ UnknownWarning::NestedUnknown { path } => {
+ cformat!("{label} has unknown field <bold>{path}</> (will be ignored)")
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -3334,19 +3341,16 @@ ff = true
use crate::config::{ProjectConfig, UserConfig};
// commit-generation in project config → should warn "belongs in user config"
- let mut unknown = HashMap::new();
- unknown.insert(
- "commit-generation".to_string(),
- toml::Value::Table(toml::map::Map::new()),
- );
let path = std::env::temp_dir().join("test-deprecated-wrong-config-project.toml");
- warn_unknown_fields::<ProjectConfig>(&path, &unknown, "Project config");
+ warn_unknown_fields::<ProjectConfig>(
+ "[commit-generation]\ncommand = \"llm\"\n",
+ &path,
+ "Project config",
+ );
// ci in user config → should warn "belongs in project config"
- let mut unknown = HashMap::new();
- unknown.insert("ci".to_string(), toml::Value::Table(toml::map::Map::new()));
let path = std::env::temp_dir().join("test-deprecated-wrong-config-user.toml");
- warn_unknown_fields::<UserConfig>(&path, &unknown, "User config");
+ warn_unknown_fields::<UserConfig>("[ci]\nplatform = \"github\"\n", &path, "User config");
}
// ==================== pre-hook table form tests ====================
diff --git a/src/config/mod.rs b/src/config/mod.rs
index e85821a9d..47d1a7daa 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -21,23 +21,32 @@ mod hooks;
mod project;
#[cfg(test)]
mod test;
+mod unknown_tree;
mod user;
/// Trait for worktrunk config types (user and project config).
///
-/// Both config types use JsonSchema to derive valid keys, allowing validation
-/// to detect misplaced or misspelled keys. The `Other` associated type enables
-/// checking whether a key belongs in the other config.
-pub trait WorktrunkConfig: for<'de> serde::Deserialize<'de> + Sized {
+/// Both config types expose JsonSchema-derived top-level keys. The list drives
+/// `is_valid_key` (for misplaced-key classification) and seeds the round-trip
+/// comparison in `unknown_tree::compute_unknown_tree` so sections that
+/// serialize away when default (e.g., `MergeConfig` under
+/// `skip_serializing_if`) aren't mistaken for schema-unknown paths.
+pub trait WorktrunkConfig:
+ for<'de> serde::Deserialize<'de> + serde::Serialize + Default + Sized
+{
/// The other config type (UserConfig ↔ ProjectConfig).
type Other: WorktrunkConfig;
/// Human-readable description of where this config lives.
fn description() -> &'static str;
+ /// All valid top-level keys for this config type, derived from JsonSchema.
+ fn valid_top_level_keys() -> &'static [String];
+
/// Check if a key would be valid in this config type.
- /// Uses JsonSchema-derived keys for validation.
- fn is_valid_key(key: &str) -> bool;
+ fn is_valid_key(key: &str) -> bool {
+ Self::valid_top_level_keys().iter().any(|k| k == key)
+ }
}
impl WorktrunkConfig for UserConfig {
@@ -47,11 +56,10 @@ impl WorktrunkConfig for UserConfig {
"user config"
}
- fn is_valid_key(key: &str) -> bool {
+ fn valid_top_level_keys() -> &'static [String] {
use std::sync::OnceLock;
static VALID_KEYS: OnceLock<Vec<String>> = OnceLock::new();
- let valid_keys = VALID_KEYS.get_or_init(user::valid_user_config_keys);
- valid_keys.iter().any(|k| k == key)
+ VALID_KEYS.get_or_init(user::valid_user_config_keys)
}
}
@@ -62,11 +70,10 @@ impl WorktrunkConfig for ProjectConfig {
"project config"
}
- fn is_valid_key(key: &str) -> bool {
+ fn valid_top_level_keys() -> &'static [String] {
use std::sync::OnceLock;
static VALID_KEYS: OnceLock<Vec<String>> = OnceLock::new();
- let valid_keys = VALID_KEYS.get_or_init(project::valid_project_config_keys);
- valid_keys.iter().any(|k| k == key)
+ VALID_KEYS.get_or_init(project::valid_project_config_keys)
}
}
@@ -119,17 +126,16 @@ pub use expansion::{
validate_template, validate_template_syntax,
};
pub use hooks::HooksConfig;
-pub use project::{
- ProjectCiConfig, ProjectConfig, ProjectListConfig,
- find_unknown_keys as find_unknown_project_keys, valid_project_config_keys,
+pub use project::{ProjectCiConfig, ProjectConfig, ProjectListConfig, valid_project_config_keys};
+pub use unknown_tree::{
+ UnknownAnalysis, UnknownTree, UnknownWarning, collect_unknown_warnings, compute_unknown_tree,
};
pub(crate) use user::LoadError;
pub use user::{
CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig,
ResolvedConfig, StageMode, StepConfig, SwitchConfig, SwitchPickerConfig, UserConfig,
UserProjectOverrides, config_path, default_config_path, default_system_config_path,
- find_unknown_keys as find_unknown_user_keys, set_config_path, system_config_path,
- valid_user_config_keys,
+ set_config_path, system_config_path, valid_user_config_keys,
};
#[cfg(test)]
@@ -603,53 +609,73 @@ squash-template-file = "~/file.txt"
"#);
}
+ fn project_warn_tree(contents: &str) -> UnknownTree {
+ compute_unknown_tree::<ProjectConfig>(contents)
+ .warn_tree()
+ .cloned()
+ .unwrap()
+ }
+
+ fn user_warn_tree(contents: &str) -> UnknownTree {
+ compute_unknown_tree::<UserConfig>(contents)
+ .warn_tree()
+ .cloned()
+ .unwrap()
+ }
+
#[test]
- fn test_find_unknown_project_keys_with_typo() {
+ fn test_unknown_tree_project_with_typo() {
let toml_str = "[post-merge-command]\ndeploy = \"task deploy\"";
- let unknown = find_unknown_project_keys(toml_str);
- assert!(unknown.contains_key("post-merge-command"));
- assert_eq!(unknown.len(), 1);
+ let tree = project_warn_tree(toml_str);
+ assert!(tree.keys.contains("post-merge-command"));
+ assert_eq!(tree.keys.len(), 1);
}
#[test]
- fn test_find_unknown_project_keys_valid() {
+ fn test_unknown_tree_project_valid() {
let toml_str =
"[post-merge]\ndeploy = \"task deploy\"\n\n[pre-merge]\ntest = \"cargo test\"";
- let unknown = find_unknown_project_keys(toml_str);
- assert!(unknown.is_empty());
+ let tree = project_warn_tree(toml_str);
+ assert!(tree.is_empty());
}
#[test]
- fn test_find_unknown_project_keys_multiple() {
+ fn test_unknown_tree_project_multiple() {
let toml_str = "[post-merge-command]\ndeploy = \"task deploy\"\n\n[after-create]\nsetup = \"npm install\"";
- let unknown = find_unknown_project_keys(toml_str);
- assert_eq!(unknown.len(), 2);
- assert!(unknown.contains_key("post-merge-command"));
- assert!(unknown.contains_key("after-create"));
+ let tree = project_warn_tree(toml_str);
+ assert_eq!(tree.keys.len(), 2);
+ assert!(tree.keys.contains("post-merge-command"));
+ assert!(tree.keys.contains("after-create"));
}
#[test]
- fn test_find_unknown_user_keys_with_typo() {
+ fn test_unknown_tree_user_with_typo() {
let toml_str = "worktree-path = \"../test\"\n\n[commit-gen]\ncommand = \"llm\"";
- let unknown = find_unknown_user_keys(toml_str);
- assert!(unknown.contains_key("commit-gen"));
- assert_eq!(unknown.len(), 1);
+ let tree = user_warn_tree(toml_str);
+ assert!(tree.keys.contains("commit-gen"));
+ assert_eq!(tree.keys.len(), 1);
}
#[test]
- fn test_find_unknown_user_keys_valid() {
+ fn test_unknown_tree_user_valid() {
let toml_str = "worktree-path = \"../test\"\n\n[commit.generation]\ncommand = \"llm\"\n\n[list]\nfull = true";
- let unknown = find_unknown_user_keys(toml_str);
- assert!(unknown.is_empty());
+ let tree = user_warn_tree(toml_str);
+ assert!(tree.is_empty());
}
#[test]
- fn test_find_unknown_keys_invalid_toml() {
+ fn test_unknown_tree_invalid_toml() {
let toml = "this is not valid toml {{{";
- let unknown_project = find_unknown_project_keys(toml);
- let unknown_user = find_unknown_user_keys(toml);
- assert!(unknown_project.is_empty());
- assert!(unknown_user.is_empty());
+ assert!(
+ compute_unknown_tree::<ProjectConfig>(toml)
+ .warn_tree()
+ .is_none()
+ );
+ assert!(
+ compute_unknown_tree::<UserConfig>(toml)
+ .warn_tree()
+ .is_none()
+ );
}
#[test]
@@ -710,11 +736,10 @@ post-create = "npm install"
[pre-merge]
test = "cargo test"
"#;
- let unknown = find_unknown_user_keys(toml_str);
+ let tree = user_warn_tree(toml_str);
assert!(
- unknown.is_empty(),
- "hook fields should not be reported as unknown: {:?}",
- unknown
+ tree.is_empty(),
+ "hook fields should not be reported as unknown: {tree:?}"
);
}
@@ -722,16 +747,15 @@ test = "cargo test"
fn test_user_config_key_in_project_config_is_detected() {
// skip-shell-integration-prompt is a user-config-only key
let toml_str = "skip-shell-integration-prompt = true\n";
- let unknown = find_unknown_project_keys(toml_str);
+ let tree = project_warn_tree(toml_str);
assert!(
- unknown.contains_key("skip-shell-integration-prompt"),
+ tree.keys.contains("skip-shell-integration-prompt"),
"skip-shell-integration-prompt should be unknown in project config"
);
// Verify it's valid in user config
- let unknown_in_user = find_unknown_user_keys(toml_str);
assert!(
- unknown_in_user.is_empty(),
+ user_warn_tree(toml_str).is_empty(),
"skip-shell-integration-prompt should be valid in user config"
);
}
@@ -743,16 +767,15 @@ test = "cargo test"
[ci]
platform = "github"
"#;
- let unknown = find_unknown_user_keys(toml_str);
+ let tree = user_warn_tree(toml_str);
assert!(
- unknown.contains_key("ci"),
+ tree.keys.contains("ci"),
"ci should be unknown in user config"
);
// Verify it's valid in project config
- let unknown_in_project = find_unknown_project_keys(toml_str);
assert!(
- unknown_in_project.is_empty(),
+ project_warn_tree(toml_str).is_empty(),
"ci should be valid in project config"
);
}
diff --git a/src/config/project.rs b/src/config/project.rs
index ccab011e1..a1b95792a 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -222,11 +222,11 @@ impl ProjectConfig {
true, // emit_inline_warnings
);
- // Warn about unknown fields (only in main worktree where it's actionable)
+ // Warn about unknown fields (only in main worktree where it's actionable).
if is_main_worktree {
super::deprecation::warn_unknown_fields::<ProjectConfig>(
+ &contents,
&config_path,
- &find_unknown_keys(&contents),
"Project config",
);
}
@@ -259,24 +259,6 @@ pub fn valid_project_config_keys() -> Vec<String> {
.unwrap_or_default()
}
-/// Find unknown keys in project config TOML content
-///
-/// Returns a map of unrecognized top-level keys (with their values) that will be ignored.
-/// Compares against the known valid keys derived from the JsonSchema.
-/// The values are included to allow checking if keys belong in the other config type.
-pub fn find_unknown_keys(contents: &str) -> std::collections::HashMap<String, toml::Value> {
- let Ok(table) = contents.parse::<toml::Table>() else {
- return std::collections::HashMap::new();
- };
-
- let valid_keys = valid_project_config_keys();
-
- table
- .into_iter()
- .filter(|(key, _)| !valid_keys.contains(key))
- .collect()
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -443,54 +425,6 @@ platform = "github"
assert!(config.hostname.is_none());
}
- // ============================================================================
- // find_unknown_keys Tests
- // ============================================================================
-
- #[test]
- fn test_find_unknown_keys_empty() {
- let contents = "";
- let keys = find_unknown_keys(contents);
- assert!(keys.is_empty());
- }
-
- #[test]
- fn test_find_unknown_keys_all_known() {
- let contents = r#"
-post-create = "npm install"
-pre-merge = "cargo test"
-
-[step.copy-ignored]
-exclude = [".conductor/"]
-"#;
- let keys = find_unknown_keys(contents);
- assert!(keys.is_empty());
- }
-
- #[test]
- fn test_find_unknown_keys_unknown_key() {
- let contents = r#"
-post-create = "npm install"
-unknown-key = "value"
-"#;
- let keys = find_unknown_keys(contents);
- assert_eq!(keys.len(), 1);
- assert!(keys.contains_key("unknown-key"));
- }
-
- #[test]
- fn test_find_unknown_keys_multiple_unknown() {
- let contents = r#"
-foo = "bar"
-baz = "qux"
-post-create = "npm install"
-"#;
- let keys = find_unknown_keys(contents);
- assert_eq!(keys.len(), 2);
- assert!(keys.contains_key("foo"));
- assert!(keys.contains_key("baz"));
- }
-
// ============================================================================
// Serialization Tests
// ============================================================================
diff --git a/src/config/unknown_tree.rs b/src/config/unknown_tree.rs
new file mode 100644
index 000000000..eef4ec1dd
--- /dev/null
+++ b/src/config/unknown_tree.rs
@@ -0,0 +1,353 @@
+//! Nested schema-unknown analysis for worktrunk config files.
+//!
+//! A single round-trip through a [`WorktrunkConfig`] type answers both
+//! load-time questions ("which keys does serde silently drop?") and save-time
+//! questions ("which keys must survive the diff-based merge?"). Reserializing
+//! the parsed config and diffing against the raw TOML identifies every
+//! schema-unknown path at any nesting depth.
+//!
+//! The same tree drives:
+//! - Unknown-key warnings (`warn_unknown_fields`, `config show`) — emits one
+//! message at the shallowest level where a path is unknown.
+//! - Save-path preservation (`UserConfig::save_to`) — prevents the merge from
+//! dropping hand-edited or forward-compat fields.
+
+use std::collections::{BTreeMap, BTreeSet};
+
+use crate::config::WorktrunkConfig;
+
+/// A nested set of schema-unknown paths within a config file.
+///
+/// `keys` holds unknown keys at the current level. Entries in `nested` are for
+/// keys that are themselves *known* but contain unknown children. A key may
+/// appear in both when the entire subtree is unknown — `keys` captures the top
+/// of the unknown subtree, `nested` mirrors it so save-path merges still
+/// preserve individual descendants if a mutation later introduces the table.
+#[derive(Default, Debug, Clone)]
+pub struct UnknownTree {
+ pub keys: BTreeSet<String>,
+ pub nested: BTreeMap<String, UnknownTree>,
+}
+
+impl UnknownTree {
+ pub fn is_empty(&self) -> bool {
+ self.keys.is_empty() && self.nested.is_empty()
+ }
+}
+
+/// Outcome of analyzing a config file for schema-unknown paths.
+///
+/// The `Unreliable` variant covers both syntax errors and type mismatches
+/// (e.g., a hand edit like `commit = "scalar"`). In those cases we can't tell
+/// schema-unknown paths from schema-known-but-wrong-type ones, so:
+/// - Save paths must preserve every on-disk key (the tree marks everything).
+/// - Warning paths must stay silent (the parse/type error is surfaced by the
+/// regular load path with accurate line/column info).
+#[derive(Debug)]
+pub enum UnknownAnalysis {
+ /// `try_into<C>` succeeded; the tree lists schema-unknown paths only.
+ Parsed(UnknownTree),
+ /// Raw TOML was unparsable or failed type-checking against `C`. The tree
+ /// still marks every on-disk key so save-path merges preserve data.
+ Unreliable(UnknownTree),
+}
+
+impl UnknownAnalysis {
+ /// Tree suitable for the save-path merge (preserves unknowns, and
+ /// preserves everything on unreliable input).
+ pub fn preserve_tree(&self) -> &UnknownTree {
+ match self {
+ Self::Parsed(t) | Self::Unreliable(t) => t,
+ }
+ }
+
+ /// Tree suitable for unknown-key warnings (empty on unreliable input).
+ pub fn warn_tree(&self) -> Option<&UnknownTree> {
+ match self {
+ Self::Parsed(t) => Some(t),
+ Self::Unreliable(_) => None,
+ }
+ }
+}
+
+/// Analyze `contents` against config type `C` by round-tripping through serde.
+///
+/// On success, the returned tree captures every path in `contents` that
+/// reserialization drops — i.e., every schema-unknown path. Top-level keys
+/// that serialize away when empty (e.g., `[merge]` with only unknown children
+/// leaves `MergeConfig::default()`, which `skip_serializing_if` omits) are
+/// rescued by seeding the comparison with the JsonSchema key list: a known
+/// section that isn't in the reserialized form is treated as present-but-empty
+/// so only its unknown *children* get flagged, not the section itself.
+pub fn compute_unknown_tree<C>(contents: &str) -> UnknownAnalysis
+where
+ C: WorktrunkConfig,
+{
+ let Ok(raw) = contents.parse::<toml::Table>() else {
+ return UnknownAnalysis::Unreliable(UnknownTree::default());
+ };
+
+ let parsed: Result<C, _> = toml::Value::Table(raw.clone()).try_into();
+ let Ok(config) = parsed else {
+ return UnknownAnalysis::Unreliable(diff_tables(&raw, &toml::Table::new()));
+ };
+
+ let mut reserialized: toml::Table = toml::to_string(&config)
+ .expect("config type is serializable")
+ .parse()
+ .expect("serialized config is valid TOML");
+ seed_schema_skeleton::<C>(&mut reserialized);
+ UnknownAnalysis::Parsed(diff_tables(&raw, &reserialized))
+}
+
+/// Seed `reserialized` with every schema-valid top-level key as an empty
+/// table so `diff_tables` treats valid-but-omitted sections as known.
+fn seed_schema_skeleton<C: WorktrunkConfig>(reserialized: &mut toml::Table) {
+ for key in C::valid_top_level_keys() {
+ reserialized
+ .entry(key.clone())
+ .or_insert_with(|| toml::Value::Table(toml::Table::new()));
+ }
+}
+
+/// Walk `raw` against `known` (the schema-projected view) and record keys
+/// that exist only in `raw`. Recurses into nested tables so deeply-nested
+/// unknown keys are captured at the right level.
+fn diff_tables(raw: &toml::Table, known: &toml::Table) -> UnknownTree {
+ let mut tree = UnknownTree::default();
+ for (key, raw_val) in raw {
+ match (known.get(key), raw_val) {
+ (Some(toml::Value::Table(known_t)), toml::Value::Table(raw_t)) => {
+ let nested = diff_tables(raw_t, known_t);
+ if !nested.is_empty() {
+ tree.nested.insert(key.clone(), nested);
+ }
+ }
+ (Some(_), _) => {}
+ (None, toml::Value::Table(raw_t)) => {
+ // Whole subtree is schema-unknown. Mark the key at this level
+ // and recurse so the preserve set is populated if a later
+ // mutation causes `desired` to introduce this table.
+ tree.keys.insert(key.clone());
+ let nested = diff_tables(raw_t, &toml::Table::new());
+ if !nested.is_empty() {
+ tree.nested.insert(key.clone(), nested);
+ }
+ }
+ (None, _) => {
+ tree.keys.insert(key.clone());
+ }
+ }
+ }
+ tree
+}
+
+/// Structured description of a single unknown-key finding. Callers format
+/// these into warning strings — the `deprecation` and `config show` paths
+/// use different wording, so classification stays here and presentation
+/// stays at the call site.
+#[derive(Debug)]
+pub enum UnknownWarning {
+ /// A top-level key that's not in any schema. Fully unknown.
+ TopLevelUnknown { key: String },
+ /// A top-level key that's valid in the *other* config type (e.g.,
+ /// `forge` appearing in user config).
+ TopLevelWrongConfig {
+ key: String,
+ other_description: &'static str,
+ },
+ /// A top-level key that's deprecated and whose canonical form belongs in
+ /// the other config (e.g., `[commit-generation]` in project config).
+ TopLevelDeprecatedWrongConfig {
+ key: String,
+ other_description: &'static str,
+ canonical_display: &'static str,
+ },
+ /// An unknown path below a schema-valid top-level key, e.g.
+ /// `merge.squas` or `commit.generation.template`.
+ NestedUnknown { path: String },
+}
+
+/// Collect structured warnings for `raw_contents` under config type `C`.
+///
+/// Top-level classification reads the *raw* tree (so deprecated top-level
+/// sections surface informative messages like "belongs in user config as
+/// `[commit.generation]`"). Nested classification reads the *migrated* tree,
+/// so patterns the deprecation system already warns about (e.g.,
+/// `switch.no-cd`, `merge.no-ff`) don't double-warn here.
+///
+/// Returns an empty vec if either analysis is unreliable — the load path
+/// surfaces parse/type errors elsewhere.
+pub fn collect_unknown_warnings<C: WorktrunkConfig>(raw_contents: &str) -> Vec<UnknownWarning> {
+ let raw_tree = match compute_unknown_tree::<C>(raw_contents) {
+ UnknownAnalysis::Parsed(t) => t,
+ UnknownAnalysis::Unreliable(_) => return Vec::new(),
+ };
+ let migrated = crate::config::migrate_content(raw_contents);
+ let migrated_tree = match compute_unknown_tree::<C>(&migrated) {
+ UnknownAnalysis::Parsed(t) => t,
+ UnknownAnalysis::Unreliable(_) => return Vec::new(),
+ };
+
+ let mut out = Vec::new();
+ for key in &raw_tree.keys {
+ use crate::config::UnknownKeyKind;
+ let warning = match crate::config::classify_unknown_key::<C>(key) {
+ UnknownKeyKind::DeprecatedHandled => continue,
+ UnknownKeyKind::DeprecatedWrongConfig {
+ other_description,
+ canonical_display,
+ } => UnknownWarning::TopLevelDeprecatedWrongConfig {
+ key: key.clone(),
+ other_description,
+ canonical_display,
+ },
+ UnknownKeyKind::WrongConfig { other_description } => {
+ UnknownWarning::TopLevelWrongConfig {
+ key: key.clone(),
+ other_description,
+ }
+ }
+ UnknownKeyKind::Unknown => UnknownWarning::TopLevelUnknown { key: key.clone() },
+ };
+ out.push(warning);
+ }
+ for (key, sub) in &migrated_tree.nested {
+ if !C::is_valid_key(key) {
+ continue; // top-level unknowns were classified above against raw
+ }
+ walk_nested(sub, key, &mut out);
+ }
+ out
+}
+
+fn walk_nested(tree: &UnknownTree, prefix: &str, out: &mut Vec<UnknownWarning>) {
+ for key in &tree.keys {
+ out.push(UnknownWarning::NestedUnknown {
+ path: format!("{prefix}.{key}"),
+ });
+ }
+ for (key, sub) in &tree.nested {
+ if tree.keys.contains(key) {
+ continue;
+ }
+ let path = format!("{prefix}.{key}");
+ walk_nested(sub, &path, out);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::config::{ProjectConfig, UserConfig};
+
+ fn parsed<C: WorktrunkConfig>(contents: &str) -> UnknownTree {
+ match compute_unknown_tree::<C>(contents) {
+ UnknownAnalysis::Parsed(t) => t,
+ UnknownAnalysis::Unreliable(_) => panic!("expected Parsed"),
+ }
+ }
+
+ #[test]
+ fn empty_input_has_no_unknowns() {
+ let tree = parsed::<UserConfig>("");
+ assert!(tree.is_empty());
+ }
+
+ #[test]
+ fn known_keys_are_not_flagged() {
+ let tree = parsed::<UserConfig>(
+ r#"
+worktree-path = "../test"
+
+[list]
+full = true
+
+[commit.generation]
+command = "llm"
+"#,
+ );
+ assert!(tree.is_empty(), "tree should be empty, got {tree:?}");
+ }
+
+ #[test]
+ fn unknown_top_level_key() {
+ let tree = parsed::<UserConfig>("unknown-key = \"value\"\n");
+ assert!(tree.keys.contains("unknown-key"));
+ assert!(tree.nested.is_empty());
+ }
+
+ #[test]
+ fn nested_unknown_key_under_known_section() {
+ let tree = parsed::<UserConfig>(
+ r#"
+[merge]
+future-option = true
+"#,
+ );
+ assert!(tree.keys.is_empty());
+ let merge = tree.nested.get("merge").expect("merge subtree");
+ assert!(merge.keys.contains("future-option"));
+ }
+
+ #[test]
+ fn deeply_nested_unknown_key() {
+ let tree = parsed::<UserConfig>(
+ r#"
+[commit.generation]
+command = "llm"
+future-knob = "x"
+"#,
+ );
+ let commit = tree.nested.get("commit").expect("commit subtree");
+ let generation = commit.nested.get("generation").expect("generation subtree");
+ assert!(generation.keys.contains("future-knob"));
+ }
+
+ #[test]
+ fn unknown_whole_subtree_is_marked_at_top_level() {
+ // A wholly-unknown section records the key at its parent level,
+ // which is what warning emitters want — one message for the whole
+ // subtree, not one per descendant.
+ let tree = parsed::<UserConfig>(
+ r#"
+[unknown-section]
+a = 1
+b = 2
+"#,
+ );
+ assert!(tree.keys.contains("unknown-section"));
+ }
+
+ #[test]
+ fn project_config_detects_user_only_key() {
+ let tree = parsed::<ProjectConfig>("skip-shell-integration-prompt = true\n");
+ assert!(tree.keys.contains("skip-shell-integration-prompt"));
+ }
+
+ #[test]
+ fn syntax_error_yields_unreliable() {
+ let analysis = compute_unknown_tree::<UserConfig>("not valid {{{");
+ assert!(matches!(analysis, UnknownAnalysis::Unreliable(_)));
+ assert!(analysis.warn_tree().is_none());
+ }
+
+ #[test]
+ fn type_mismatch_yields_unreliable_but_preserves_all() {
+ // A hand-edit like `commit = "scalar"` can't round-trip through
+ // UserConfig. The warn tree must be empty (parse error is surfaced
+ // elsewhere) but the preserve tree must mark every on-disk key so
+ // save_to doesn't drop data.
+ let analysis = compute_unknown_tree::<UserConfig>(
+ r#"
+commit = "scalar"
+skip-shell-integration-prompt = true
+"#,
+ );
+ assert!(matches!(analysis, UnknownAnalysis::Unreliable(_)));
+ assert!(analysis.warn_tree().is_none());
+ let preserve = analysis.preserve_tree();
+ assert!(preserve.keys.contains("commit"));
+ assert!(preserve.keys.contains("skip-shell-integration-prompt"));
+ }
+}
diff --git a/src/config/user/mod.rs b/src/config/user/mod.rs
index 51eccf685..b4a8072c1 100644
--- a/src/config/user/mod.rs
+++ b/src/config/user/mod.rs
@@ -26,7 +26,7 @@ pub use path::{
system_config_path,
};
pub use resolved::ResolvedConfig;
-pub use schema::{find_unknown_keys, valid_user_config_keys};
+pub use schema::valid_user_config_keys;
pub use sections::{
CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig, StageMode,
StepConfig, SwitchConfig, SwitchPickerConfig, UserProjectOverrides,
@@ -385,8 +385,8 @@ impl UserConfig {
&& let Ok(content) = std::fs::read_to_string(&system_path)
{
super::deprecation::warn_unknown_fields::<UserConfig>(
+ &content,
&system_path,
- &find_unknown_keys(&content),
"System config",
);
let migrated = super::deprecation::migrate_content(&content);
@@ -414,8 +414,8 @@ impl UserConfig {
.unwrap_or_else(|_| super::deprecation::migrate_content(&content));
super::deprecation::warn_unknown_fields::<UserConfig>(
+ &content,
config_path,
- &find_unknown_keys(&content),
"User config",
);
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index 9bbfe7686..5dbddc79e 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -8,86 +8,11 @@
//! handles any new fields without manual wiring — if a struct field is
//! serializable, save_to persists it.
-use crate::config::ConfigError;
+use crate::config::{ConfigError, UnknownTree, compute_unknown_tree};
use super::UserConfig;
use super::sections::CommitGenerationConfig;
-/// Keys to preserve during a diff-based merge, organized by nesting level.
-///
-/// Populated from schema-unknown paths in the existing TOML (keys that serde
-/// would silently drop during deserialization). These survive the save so
-/// hand-edited settings and fields from newer wt versions aren't lost.
-#[derive(Default, Debug)]
-struct PreserveTree {
- /// Keys at this level to keep even when absent from the serialized desired state.
- keys: std::collections::HashSet<String>,
- /// Sub-trees for nested tables, mirroring the TOML structure.
- nested: std::collections::HashMap<String, PreserveTree>,
-}
-
-impl PreserveTree {
- fn is_empty(&self) -> bool {
- self.keys.is_empty() && self.nested.is_empty()
- }
-}
-
-/// Build a [`PreserveTree`] from the on-disk content by round-tripping through
-/// [`UserConfig`]. Any path present in the raw TOML but absent from the
-/// reserialized form is schema-unknown and flagged for preservation.
-///
-/// `existing_content` is already-validated TOML (parsed as
-/// `toml_edit::DocumentMut` earlier in `save_to`), so the parses here are
-/// invariants. `try_into::<UserConfig>` can fail on type mismatches (e.g.,
-/// `commit = "scalar"` from a hand edit) — the `unwrap_or_default()` fallback
-/// marks every key as unknown so the merge preserves the file contents rather
-/// than silently discarding data.
-fn compute_preserve_tree(existing_content: &str) -> PreserveTree {
- let raw: toml::Table = existing_content
- .parse()
- .expect("existing content already validated by toml_edit");
- let config: UserConfig = toml::Value::Table(raw.clone())
- .try_into()
- .unwrap_or_default();
- let reserialized: toml::Table = toml::to_string(&config)
- .expect("UserConfig is serializable")
- .parse()
- .expect("UserConfig serializes to valid TOML");
- diff_tables(&raw, &reserialized)
-}
-
-/// Walk `raw` against `known` (the schema-projected view) and record keys
-/// that exist only in `raw`. Recurses into nested tables so deeply-nested
-/// unknown keys are captured at the right level.
-fn diff_tables(raw: &toml::Table, known: &toml::Table) -> PreserveTree {
- let mut tree = PreserveTree::default();
- for (key, raw_val) in raw {
- match (known.get(key), raw_val) {
- (Some(toml::Value::Table(known_t)), toml::Value::Table(raw_t)) => {
- let nested = diff_tables(raw_t, known_t);
- if !nested.is_empty() {
- tree.nested.insert(key.clone(), nested);
- }
- }
- (Some(_), _) => {}
- (None, toml::Value::Table(raw_t)) => {
- // Whole subtree is schema-unknown. Mark the key at this level
- // and recurse so the preserve set is populated if a later
- // mutation causes `desired` to introduce this table.
- tree.keys.insert(key.clone());
- let nested = diff_tables(raw_t, &toml::Table::new());
- if !nested.is_empty() {
- tree.nested.insert(key.clone(), nested);
- }
- }
- (None, _) => {
- tree.keys.insert(key.clone());
- }
- }
- }
- tree
-}
-
impl UserConfig {
/// Recursively convert inline tables to standard tables for readability.
///
@@ -129,7 +54,7 @@ impl UserConfig {
fn merge_tables(
existing: &mut toml_edit::Table,
desired: &toml_edit::Table,
- preserve: &PreserveTree,
+ preserve: &UnknownTree,
) {
let stale_keys: Vec<_> = existing
.iter()
@@ -140,7 +65,7 @@ impl UserConfig {
existing.remove(key);
}
- let empty_tree = PreserveTree::default();
+ let empty_tree = UnknownTree::default();
for (key, desired_item) in desired.iter() {
match existing.get_mut(key) {
// Both standard tables: recurse
@@ -236,13 +161,16 @@ impl UserConfig {
// Preserve unknown keys at every nesting level (typos, future
// fields, deprecated keys not yet migrated) so they aren't
- // silently deleted on save.
- let preserve = compute_preserve_tree(&existing_content);
+ // silently deleted on save. On type-mismatch we still preserve
+ // every on-disk key — it's safer to round-trip the whole file
+ // than to drop fields we can't interpret.
+ let analysis = compute_unknown_tree::<UserConfig>(&existing_content);
+ let preserve = analysis.preserve_tree();
Self::merge_tables(
existing_doc.as_table_mut(),
desired_doc.as_table(),
- &preserve,
+ preserve,
);
Self::make_commit_table_implicit_if_only_subtables(&mut existing_doc);
diff --git a/src/config/user/schema.rs b/src/config/user/schema.rs
index 5c998830d..096cd0d65 100644
--- a/src/config/user/schema.rs
+++ b/src/config/user/schema.rs
@@ -1,6 +1,8 @@
//! Schema helpers for config validation.
//!
-//! Uses JsonSchema to derive valid keys for unknown key detection.
+//! Uses JsonSchema to derive valid top-level keys, feeding
+//! `WorktrunkConfig::is_valid_key` so unknown-key classification can tell
+//! "belongs in the other config" from "truly unknown."
use schemars::SchemaGenerator;
@@ -22,22 +24,3 @@ pub fn valid_user_config_keys() -> Vec<String> {
.map(|props| props.keys().cloned().collect())
.unwrap_or_default()
}
-
-/// Find unknown keys in user config TOML content.
-///
-/// Returns a map of unrecognized top-level keys (with their values) that will be ignored.
-/// Compares against the known valid keys derived from the JsonSchema rather than using
-/// serde flatten catchall (which doesn't work reliably with nested flattens).
-/// The values are included to allow checking if keys belong in the other config type.
-pub fn find_unknown_keys(contents: &str) -> std::collections::HashMap<String, toml::Value> {
- let Ok(table) = contents.parse::<toml::Table>() else {
- return std::collections::HashMap::new();
- };
-
- let valid_keys = valid_user_config_keys();
-
- table
- .into_iter()
- .filter(|(key, _)| !valid_keys.contains(key))
- .collect()
-}
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index f7254a980..b7cdc3dd2 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -34,34 +34,36 @@ fn test_config_path_falls_through_to_default() {
}
#[test]
-fn test_find_unknown_keys_empty() {
+fn test_compute_unknown_tree_empty() {
// Valid config with no unknown keys
let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"
"#;
- let keys = find_unknown_keys(content);
- assert!(
- keys.is_empty(),
- "Expected no unknown keys, found: {:?}",
- keys
- );
+ let tree = crate::config::compute_unknown_tree::<UserConfig>(content)
+ .warn_tree()
+ .cloned()
+ .unwrap();
+ assert!(tree.is_empty(), "expected no unknowns, got {tree:?}");
}
#[test]
-fn test_find_unknown_keys_with_unknown() {
+fn test_compute_unknown_tree_with_unknown() {
// Config with unknown top-level keys
let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"
unknown-key = "value"
another-unknown = 42
"#;
- let keys = find_unknown_keys(content);
- assert!(keys.contains_key("unknown-key"));
- assert!(keys.contains_key("another-unknown"));
+ let tree = crate::config::compute_unknown_tree::<UserConfig>(content)
+ .warn_tree()
+ .cloned()
+ .unwrap();
+ assert!(tree.keys.contains("unknown-key"));
+ assert!(tree.keys.contains("another-unknown"));
}
#[test]
-fn test_find_unknown_keys_known_sections() {
+fn test_compute_unknown_tree_known_sections() {
// All known sections should not be reported
let content = r#"
worktree-path = "../{{ main_worktree }}.{{ branch }}"
@@ -90,8 +92,11 @@ run = "npm run build"
[post-switch]
rename-tab = "echo 'switched'"
"#;
- let keys = find_unknown_keys(content);
- assert!(keys.is_empty());
+ let tree = crate::config::compute_unknown_tree::<UserConfig>(content)
+ .warn_tree()
+ .cloned()
+ .unwrap();
+ assert!(tree.is_empty());
}
#[test]