Skip to content

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

fix: preserve multiline state variable values (#4272)

DDLd36078e3e855
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 91746b427..6e0b92afb 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -1796,29 +1796,27 @@ pub fn handle_vars_clear(
/// Clear all branch markers. Used by `state clear marker --all` and
/// `state clear --all`.
///
-/// `get_config_regexp` returns an empty string when no keys match (git exit 1)
-/// and `Err` for real config errors — both the listing step and each
-/// `unset_config` call propagate errors so user-initiated clears never lie
-/// about success.
+/// `config_regexp_entries` returns an empty list when Git reports no matches.
+/// It returns `Err` for real config errors. Both the listing step and each
+/// `unset_config` call propagate errors so user-initiated clears never report
+/// false success.
fn clear_all_markers(repo: &Repository) -> anyhow::Result<usize> {
clear_matching_config(repo, r"^worktrunk\.state\..+\.marker$")
}
fn clear_matching_config(repo: &Repository, pattern: &str) -> anyhow::Result<usize> {
- let output = repo.get_config_regexp(pattern)?;
+ let entries = repo.config_regexp_entries(pattern)?;
let mut cleared = 0;
- for line in output.lines() {
- if let Some(config_key) = line.split_whitespace().next() {
- repo.unset_config(config_key)?;
- cleared += 1;
- }
+ for (config_key, _) in entries {
+ repo.unset_config(&config_key)?;
+ cleared += 1;
}
Ok(cleared)
}
/// Clear all vars entries across all branches (used by handle_state_clear_all).
///
-/// Enumerates keys via `get_config_regexp` (not `all_vars_entries`) so a
+/// Enumerates keys via `config_regexp_entries` (not `all_vars_entries`) so a
/// config read failure surfaces as an error — the display-path helper
/// absorbs errors as empty, which would silently report "cleared 0" here.
fn clear_all_vars(repo: &Repository) -> anyhow::Result<usize> {
@@ -1836,23 +1834,19 @@ pub(super) struct MarkerEntry {
/// Get all branch markers from git config with timestamps
pub(super) fn all_markers(repo: &Repository) -> Vec<MarkerEntry> {
- let output = repo
- .get_config_regexp(r"^worktrunk\.state\..+\.marker$")
+ let entries = repo
+ .config_regexp_entries(r"^worktrunk\.state\..+\.marker$")
.unwrap_or_default();
let mut markers = Vec::new();
- for line in output.lines() {
- // Format: "worktrunk.state.<branch>.marker json_value"
- let Some((key, value)) = line.split_once(' ') else {
- continue;
- };
+ for (key, value) in entries {
let Some(branch) = key
.strip_prefix("worktrunk.state.")
.and_then(|s| s.strip_suffix(".marker"))
else {
continue;
};
- let Ok(parsed) = serde_json::from_str::<serde_json::Value>(value) else {
+ let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&value) else {
continue; // Skip invalid JSON
};
let Some(marker) = parsed.get("marker").and_then(|v| v.as_str()) else {
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index f1ed39e3a..519015f83 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -131,20 +131,22 @@ impl Repository {
Ok(existed)
}
- /// Run `git config --get-regexp <pattern>` and return stdout.
+ /// Read matching config entries without using newlines as record boundaries.
///
- /// Distinguishes exit 1 (no matching keys — expected, returns empty
- /// string) from real config errors (corrupt config, permission denied —
- /// surfaced as `Err`). Use this instead of `run_command` + `.unwrap_or_default()`,
- /// which conflates the two.
- pub fn get_config_regexp(&self, pattern: &str) -> anyhow::Result<String> {
- let args = ["config", "--get-regexp", pattern];
+ /// `git config --null --get-regexp` emits `key\nvalue\0` records, so values
+ /// containing newlines remain intact. Valueless keys are emitted as
+ /// `key\0` and represented with an empty value. When a key has multiple
+ /// values, the last value wins, matching the other config readers.
+ pub fn config_regexp_entries(&self, pattern: &str) -> anyhow::Result<Vec<(String, String)>> {
+ let args = ["config", "--null", "--get-regexp", pattern];
let output = self.run_command_output(&args)?;
if output.status.success() {
- Ok(String::from_utf8_lossy(&output.stdout).into_owned())
+ Ok(super::parse_config_list_z(&output.stdout)
+ .into_iter()
+ .filter_map(|(key, values)| values.into_iter().last().map(|value| (key, value)))
+ .collect())
} else if output.status.code() == Some(1) {
- // Exit 1 = no keys matched the pattern
- Ok(String::new())
+ Ok(Vec::new())
} else {
Err(CommandError::from_failed_output("git", &args, &output).into())
}
@@ -186,15 +188,13 @@ impl Repository {
pub fn vars_entries(&self, branch: &str) -> std::collections::BTreeMap<String, String> {
let escaped = regex::escape(branch);
let pattern = format!(r"^worktrunk\.state\.{escaped}\.vars\.");
- let output = self.get_config_regexp(&pattern).unwrap_or_default();
-
let prefix = format!("worktrunk.state.{branch}.vars.");
- output
- .lines()
- .filter_map(|line| {
- let (config_key, value) = line.split_once(' ')?;
+ self.config_regexp_entries(&pattern)
+ .unwrap_or_default()
+ .into_iter()
+ .filter_map(|(config_key, value)| {
let key = config_key.strip_prefix(&prefix)?;
- Some((key.to_string(), value.to_string()))
+ Some((key.to_string(), value))
})
.collect()
}
@@ -207,25 +207,21 @@ impl Repository {
pub fn all_vars_entries(
&self,
) -> std::collections::HashMap<String, std::collections::BTreeMap<String, String>> {
- let output = self
- .get_config_regexp(r"^worktrunk\.state\..+\.vars\.")
+ let entries = self
+ .config_regexp_entries(r"^worktrunk\.state\..+\.vars\.")
.unwrap_or_default();
let mut result: std::collections::HashMap<
String,
std::collections::BTreeMap<String, String>,
> = std::collections::HashMap::new();
- for line in output.lines() {
- let Some((config_key, value)) = line.split_once(' ') else {
- continue;
- };
- let Some((branch, key)) = parse_vars_config_key(config_key) else {
- continue;
- };
+ for (config_key, value) in entries {
+ let (branch, key) =
+ parse_vars_config_key(&config_key).expect("config key matched vars pattern");
result
.entry(branch.to_string())
.or_default()
- .insert(key.to_string(), value.to_string());
+ .insert(key.to_string(), value);
}
result
}
@@ -1065,29 +1061,29 @@ mod tests {
use crate::testing::TestRepo;
#[test]
- fn test_get_config_regexp_no_match_returns_empty() {
+ fn test_config_regexp_entries_no_match_returns_empty() {
// Exit 1 from git config --get-regexp means "no keys matched" — must
- // surface as Ok("") rather than an error so callers don't conflate
+ // surface as an empty list rather than an error so callers don't conflate
// no-matches with real config failures.
let test = TestRepo::with_initial_commit();
let repo = Repository::at(test.root_path()).unwrap();
- let output = repo
- .get_config_regexp(r"^worktrunk\.state\..+\.marker$")
+ let entries = repo
+ .config_regexp_entries(r"^worktrunk\.state\..+\.marker$")
.unwrap();
- assert_eq!(output, "");
+ assert!(entries.is_empty());
}
#[test]
- fn test_get_config_regexp_failure_is_command_error() {
+ fn test_config_regexp_entries_failure_is_command_error() {
// A real failure (invalid pattern, exit 6) must surface as a typed
// `CommandError` — unlike exit 1, which means "no keys matched".
let test = TestRepo::with_initial_commit();
let repo = Repository::at(test.root_path()).unwrap();
- let err = repo.get_config_regexp("(").unwrap_err();
+ let err = repo.config_regexp_entries("(").unwrap_err();
let cmd_err = CommandError::find_in(&err).expect("error should carry a CommandError");
- assert_eq!(cmd_err.command_string(), "git config --get-regexp (");
+ assert_eq!(cmd_err.command_string(), "git config --null --get-regexp (");
}
#[test]
@@ -1117,7 +1113,7 @@ mod tests {
}
#[test]
- fn test_get_config_regexp_returns_matches() {
+ fn test_config_regexp_entries_returns_matches() {
let test = TestRepo::with_initial_commit();
let repo = Repository::at(test.root_path()).unwrap();
@@ -1126,11 +1122,17 @@ mod tests {
repo.set_config("worktrunk.state.bugfix.marker", r#"{"marker":"fix"}"#)
.unwrap();
- let output = repo
- .get_config_regexp(r"^worktrunk\.state\..+\.marker$")
+ let entries = repo
+ .config_regexp_entries(r"^worktrunk\.state\..+\.marker$")
.unwrap();
- assert!(output.contains("worktrunk.state.feature.marker"));
- assert!(output.contains("worktrunk.state.bugfix.marker"));
+ assert!(entries.contains(&(
+ "worktrunk.state.feature.marker".to_string(),
+ r#"{"marker":"wip"}"#.to_string()
+ )));
+ assert!(entries.contains(&(
+ "worktrunk.state.bugfix.marker".to_string(),
+ r#"{"marker":"fix"}"#.to_string()
+ )));
}
/// `mark_hint_shown` writes 1 on first call and increments on each
@@ -1187,7 +1189,7 @@ mod tests {
}
/// The snapshot read must parse the same entries as the subprocess read,
- /// including branch names that themselves contain `.vars.`.
+ /// including multiline values and branch names containing `.vars.`.
#[test]
fn test_all_vars_from_snapshot_matches_subprocess_read() {
let test = TestRepo::with_initial_commit();
@@ -1195,7 +1197,7 @@ mod tests {
repo.set_config("worktrunk.state.feature.vars.ticket", "JIRA-1")
.unwrap();
- repo.set_config("worktrunk.state.feature.vars.note", "a note")
+ repo.set_config("worktrunk.state.feature.vars.note", "a note\ncontinued")
.unwrap();
repo.set_config("worktrunk.state.weird.vars.branch.vars.key", "v")
.unwrap();
@@ -1203,7 +1205,7 @@ mod tests {
let snapshot = repo.all_vars_from_snapshot().unwrap();
assert_eq!(snapshot, repo.all_vars_entries());
assert_eq!(snapshot["feature"]["ticket"], "JIRA-1");
- assert_eq!(snapshot["feature"]["note"], "a note");
+ assert_eq!(snapshot["feature"]["note"], "a note\ncontinued");
assert_eq!(snapshot["weird.vars.branch"]["key"], "v");
}
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index d19482ac4..733b4df45 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -2596,6 +2596,42 @@ fn test_vars_set_json_value(repo: TestRepo) {
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), json);
}
+#[rstest]
+fn test_vars_list_json_preserves_multiline_value(repo: TestRepo) {
+ let value = "line one\nline two";
+ let output = wt_state_cmd(&repo, "vars", "set", &[&format!("note={value}")])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let output = wt_state_cmd(&repo, "vars", "get", &["note"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_eq!(
+ String::from_utf8_lossy(&output.stdout),
+ "line one\nline two\n"
+ );
+
+ let output = wt_state_cmd(&repo, "vars", "list", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(json["note"], value);
+
+ let output = wt_state_cmd(&repo, "vars", "clear", &["--all"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let output = wt_state_cmd(&repo, "vars", "get", &["note"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert!(output.stdout.is_empty());
+}
+
#[rstest]
fn test_vars_get_missing_key(repo: TestRepo) {
let output = wt_state_cmd(&repo, "vars", "get", &["nonexistent"])
@@ -2679,6 +2715,29 @@ fn test_vars_clear_all(repo: TestRepo) {
assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"○ No variables for main");
}
+#[rstest]
+fn test_vars_clear_all_clears_valueless_key(repo: TestRepo) {
+ let config_path = repo.root_path().join(".git/config");
+ let mut config = std::fs::OpenOptions::new()
+ .append(true)
+ .open(config_path)
+ .unwrap();
+ writeln!(config, "\n[worktrunk \"state.main.vars\"]\n\tflag").unwrap();
+ drop(config);
+
+ let output = wt_state_cmd(&repo, "vars", "clear", &["--all"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let output = repo
+ .git_command()
+ .args(["config", "--get", "worktrunk.state.main.vars.flag"])
+ .run()
+ .unwrap();
+ assert_eq!(output.status.code(), Some(1));
+}
+
#[rstest]
fn test_vars_invalid_key(repo: TestRepo) {
let output = wt_state_cmd(&repo, "vars", "set", &["foo.bar=value"])