1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Git config, hints, marker, and default branch operations for Repository.
use std::path::PathBuf;
use anyhow::Context;
use color_print::cformat;
use crate::config::ProjectConfig;
use super::{DefaultBranchName, GitError, Repository};
impl Repository {
/// Get a git config value. Returns None if the key doesn't exist.
///
/// Distinguishes "key not found" (exit code 1) from actual errors
/// (corrupt config, permission denied, etc.) which are propagated.
pub fn config_value(&self, key: &str) -> anyhow::Result<Option<String>> {
let output = self.run_command_output(&["config", key])?;
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
Ok(Some(stdout.trim().to_string()))
} else if output.status.code() == Some(1) {
Ok(None) // Config key doesn't exist
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("git config {}: {}", key, stderr.trim());
}
}
/// Set a git config value.
pub fn set_config(&self, key: &str, value: &str) -> anyhow::Result<()> {
self.run_command(&["config", key, value])?;
Ok(())
}
/// Read a user-defined marker from `worktrunk.state.<branch>.marker` in git config.
///
/// Markers are stored as JSON: `{"marker": "text", "set_at": unix_timestamp}`.
pub fn branch_marker(&self, branch: &str) -> Option<String> {
#[derive(serde::Deserialize)]
struct MarkerValue {
marker: Option<String>,
}
let config_key = format!("worktrunk.state.{branch}.marker");
let raw = self
.run_command(&["config", "--get", &config_key])
.ok()
.map(|output| output.trim().to_string())
.filter(|s| !s.is_empty())?;
let parsed: MarkerValue = serde_json::from_str(&raw).ok()?;
parsed.marker
}
/// Read user-defined branch-keyed marker.
pub fn user_marker(&self, branch: Option<&str>) -> Option<String> {
branch.and_then(|branch| self.branch_marker(branch))
}
/// Get all vars entries for a branch, sorted by key name.
///
/// Returns a `BTreeMap` so it serializes to a minijinja object for template access
/// via `{{ vars.key }}`.
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
.run_command(&["config", "--get-regexp", &pattern])
.unwrap_or_default();
let prefix = format!("worktrunk.state.{branch}.vars.");
output
.lines()
.filter_map(|line| {
let (config_key, value) = line.split_once(' ')?;
let key = config_key.strip_prefix(&prefix)?;
Some((key.to_string(), value.to_string()))
})
.collect()
}
/// Get all vars entries across all branches in a single git call.
///
/// Returns a map of branch → (key → value). Uses one `git config --get-regexp`
/// instead of N per-branch calls, avoiding N+1 subprocess spawns in `wt list --format=json`.
pub fn all_vars_entries(
&self,
) -> std::collections::HashMap<String, std::collections::BTreeMap<String, String>> {
let output = self
.run_command(&["config", "--get-regexp", 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(rest) = config_key.strip_prefix("worktrunk.state.") else {
continue;
};
// Use rsplit_once: var keys cannot contain dots (validated by
// validate_vars_key), so the last `.vars.` is always the real separator.
// split_once would misparse branch names containing `.vars.`.
let Some((branch, key)) = rest.rsplit_once(".vars.") else {
continue;
};
result
.entry(branch.to_string())
.or_default()
.insert(key.to_string(), value.to_string());
}
result
}
/// Set the previous branch in worktrunk.history for `wt switch -` support.
///
/// Stores the branch we're switching FROM, so `wt switch -` can return to it.
pub fn set_switch_previous(&self, previous: Option<&str>) -> anyhow::Result<()> {
if let Some(prev) = previous {
self.run_command(&["config", "worktrunk.history", prev])?;
}
// If previous is None (detached HEAD), don't update history
Ok(())
}
/// Get the previous branch from worktrunk.history for `wt switch -`.
///
/// Returns the branch we came from, enabling ping-pong switching.
pub fn switch_previous(&self) -> Option<String> {
self.run_command(&["config", "--get", "worktrunk.history"])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
/// Check if a hint has been shown in this repo.
///
/// Hints are stored as `worktrunk.hints.<name> = true`.
/// TODO: Could move to global git config if we accumulate more global hints.
pub fn has_shown_hint(&self, name: &str) -> bool {
self.run_command(&["config", "--get", &format!("worktrunk.hints.{name}")])
.is_ok()
}
/// Mark a hint as shown in this repo.
pub fn mark_hint_shown(&self, name: &str) -> anyhow::Result<()> {
self.run_command(&["config", &format!("worktrunk.hints.{name}"), "true"])?;
Ok(())
}
/// Clear a hint so it will show again.
///
/// Returns `true` if the hint was cleared, `false` if it didn't exist.
/// Propagates actual git config errors (corrupt config, permission denied).
pub fn clear_hint(&self, name: &str) -> anyhow::Result<bool> {
let key = format!("worktrunk.hints.{name}");
let output = self.run_command_output(&["config", "--unset", &key])?;
if output.status.success() {
Ok(true)
} else if output.status.code() == Some(5) {
Ok(false) // Key didn't exist (--unset uses exit code 5)
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("git config --unset {}: {}", key, stderr.trim());
}
}
/// List all hints that have been shown in this repo.
pub fn list_shown_hints(&self) -> Vec<String> {
self.run_command(&["config", "--get-regexp", r"^worktrunk\.hints\."])
.unwrap_or_default()
.lines()
.filter_map(|line| {
// Format: "worktrunk.hints.worktree-path true"
line.split_whitespace()
.next()
.and_then(|key| key.strip_prefix("worktrunk.hints."))
.map(String::from)
})
.collect()
}
/// Clear all hints so they will show again.
pub fn clear_all_hints(&self) -> anyhow::Result<usize> {
let hints = self.list_shown_hints();
let count = hints.len();
for hint in hints {
self.clear_hint(&hint)?;
}
Ok(count)
}
// =========================================================================
// Default branch detection
// =========================================================================
/// Get the default branch name for the repository.
///
/// **Performance note:** This method may trigger a network call on first invocation
/// if the remote HEAD is not cached locally. The result is then cached in git's
/// config for subsequent calls. To minimize latency:
/// - Defer calling this until after fast, local checks (see e497f0f for example)
/// - Consider passing the result as a parameter if needed multiple times
/// - For optional operations, provide a fallback (e.g., `.unwrap_or("main")`)
///
/// Detection strategy:
/// 1. Check worktrunk cache (`git config worktrunk.default-branch`)
/// 2. Try primary remote's local cache (e.g., `origin/HEAD`)
/// 3. Query remote (`git ls-remote`) — may take 100ms-2s
/// 4. Infer from local branches if no remote
///
/// Detection results are cached to `worktrunk.default-branch` for future calls.
/// Result is also cached in the shared repo cache (shared across all worktrees).
///
/// Returns `None` if the default branch cannot be determined.
pub fn default_branch(&self) -> Option<String> {
self.cache
.default_branch
.get_or_init(|| {
// Fast path: check worktrunk's persistent cache (git config)
let configured = self
.run_command(&["config", "--get", "worktrunk.default-branch"])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
// If configured, validate it exists locally
if let Some(ref branch) = configured {
if self.branch(branch).exists_locally().unwrap_or(false) {
let _ = self.cache.invalid_default_branch.set(None);
return Some(branch.clone());
}
// Check if this is the unborn default branch (HEAD points to it but no commits yet)
if self.is_unborn_head_branch(branch) {
let _ = self.cache.invalid_default_branch.set(None);
return Some(branch.clone());
}
// Configured branch doesn't exist - cache for warning, return None
let _ = self.cache.invalid_default_branch.set(Some(branch.clone()));
log::debug!(
"Configured default branch '{}' doesn't exist locally",
branch
);
return None;
}
// Not configured - no invalid branch to report
let _ = self.cache.invalid_default_branch.set(None);
// Detect: try remote, then local inference
let detected = self.detect_from_remote().or_else(|| {
self.infer_default_branch_locally()
.inspect_err(|e| log::debug!("Local inference failed: {e}"))
.ok()
});
// Cache detected result to git config for future runs
if let Some(ref branch) = detected {
let _ = self.run_command(&["config", "worktrunk.default-branch", branch]);
}
detected
})
.clone()
}
/// Check if user configured an invalid default branch.
///
/// Returns `Some(branch_name)` if user set `worktrunk.default-branch` to a branch
/// that doesn't exist locally. Returns `None` if:
/// - No branch is configured (detection will be used)
/// - Configured branch exists locally
///
/// Used to show warnings when the configured branch is invalid.
///
/// This is a cache read - `default_branch()` populates both caches when it runs.
pub fn invalid_default_branch_config(&self) -> Option<String> {
// Ensure default_branch() has run (populates both caches, no-op if already called)
let _ = self.default_branch();
self.cache
.invalid_default_branch
.get()
.and_then(|opt| opt.clone())
}
/// Try to detect default branch from remote.
fn detect_from_remote(&self) -> Option<String> {
let remote = self.primary_remote().ok()?;
// Try git's local cache for this remote (e.g., origin/HEAD)
if let Ok(branch) = self.local_default_branch(&remote) {
return Some(branch);
}
// Query remote directly (may be slow)
self.query_remote_default_branch(&remote).ok()
}
/// Resolve a target branch from an optional override
///
/// If target is Some, expands special symbols ("@", "-", "^") via `resolve_worktree_name`.
/// Otherwise, queries the default branch.
/// This is a common pattern used throughout commands that accept an optional --target flag.
///
/// Note: This does not validate that the target exists. Use `require_target_branch` or
/// `require_target_ref` for validation before approval prompts.
pub fn resolve_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {
match target {
Some(b) => self.resolve_worktree_name(b),
None => self.default_branch().ok_or_else(|| {
GitError::Other {
message: cformat!(
"Cannot determine default branch. Specify target explicitly or run <bold>wt config state default-branch set BRANCH</>"
),
}
.into()
}),
}
}
/// Resolve and validate a target that must be a branch.
///
/// Use this for commands that update a branch ref (merge, push).
/// Validates before approval prompts to avoid wasting user time.
pub fn require_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {
let branch = self.resolve_target_branch(target)?;
if !self.branch(&branch).exists()? {
return Err(GitError::BranchNotFound {
branch,
show_create_hint: true,
last_fetch_ago: None,
}
.into());
}
Ok(branch)
}
/// Resolve and validate a target that can be any commit-ish.
///
/// Use this for commands that reference a commit (rebase, squash).
/// Validates before approval prompts to avoid wasting user time.
pub fn require_target_ref(&self, target: Option<&str>) -> anyhow::Result<String> {
let reference = self.resolve_target_branch(target)?;
if !self.ref_exists(&reference)? {
return Err(GitError::ReferenceNotFound { reference }.into());
}
Ok(reference)
}
/// Infer the default branch locally (without remote).
///
/// Uses local heuristics when no remote is available:
/// 1. If only one local branch exists, use it
/// 2. Check symbolic-ref HEAD (authoritative for bare repos, works before first commit)
/// 3. Check user's git config init.defaultBranch (if branch exists)
/// 4. Look for common branch names (main, master, develop, trunk)
/// 5. Fail if none of the above work
fn infer_default_branch_locally(&self) -> anyhow::Result<String> {
// 1. If there's only one local branch, use it
let branches = self.all_branches()?;
if branches.len() == 1 {
return Ok(branches[0].clone());
}
// 2. Check symbolic-ref HEAD - authoritative for bare repos and empty repos
// - Bare repo directory: HEAD always points to the default branch
// - Empty repos: No branches exist yet, but HEAD tells us the intended default
// - Linked worktrees: HEAD points to CURRENT branch, so skip this heuristic
// - Normal repos: HEAD points to CURRENT branch, so skip this heuristic
let is_bare = self.is_bare()?;
let in_linked_worktree = self.current_worktree().is_linked()?;
if ((is_bare && !in_linked_worktree) || branches.is_empty())
&& let Ok(head_ref) = self.run_command(&["symbolic-ref", "HEAD"])
&& let Some(branch) = head_ref.trim().strip_prefix("refs/heads/")
{
return Ok(branch.to_string());
}
// 3. Check git config init.defaultBranch (if branch exists)
if let Ok(default) = self.run_command(&["config", "--get", "init.defaultBranch"]) {
let branch = default.trim().to_string();
if !branch.is_empty() && branches.contains(&branch) {
return Ok(branch);
}
}
// 4. Look for common branch names
for name in ["main", "master", "develop", "trunk"] {
if branches.contains(&name.to_string()) {
return Ok(name.to_string());
}
}
// 5. Give up — can't infer
Err(GitError::Other {
message:
"Could not infer default branch. Please specify target branch explicitly or set up a remote."
.into(),
}
.into())
}
// Private helpers for default_branch detection
/// Check if a branch is the unborn default branch (HEAD points to it but no commits exist).
///
/// This is the case in a freshly `git init`-ed repo: HEAD is `refs/heads/main` but the
/// branch doesn't exist yet (no commits). We accept this as a valid default branch.
fn is_unborn_head_branch(&self, branch: &str) -> bool {
self.run_command(&["symbolic-ref", "HEAD"])
.ok()
.and_then(|s| s.trim().strip_prefix("refs/heads/").map(String::from))
.is_some_and(|head_branch| head_branch == branch)
&& self.all_branches().is_ok_and(|b| b.is_empty())
}
fn local_default_branch(&self, remote: &str) -> anyhow::Result<String> {
let stdout =
self.run_command(&["rev-parse", "--abbrev-ref", &format!("{}/HEAD", remote)])?;
DefaultBranchName::from_local(remote, &stdout).map(DefaultBranchName::into_string)
}
pub(super) fn query_remote_default_branch(&self, remote: &str) -> anyhow::Result<String> {
let stdout = self.run_command(&["ls-remote", "--symref", remote, "HEAD"])?;
DefaultBranchName::from_remote(&stdout).map(DefaultBranchName::into_string)
}
/// Set the default branch manually.
///
/// This sets worktrunk's cache (`worktrunk.default-branch`). Use `clear` then
/// `get` to re-detect from remote.
pub fn set_default_branch(&self, branch: &str) -> anyhow::Result<()> {
self.run_command(&["config", "worktrunk.default-branch", branch])?;
Ok(())
}
/// Clear the default branch cache.
///
/// Clears worktrunk's cache (`worktrunk.default-branch`). The next call to
/// `default_branch()` will re-detect (using git's cache or querying remote).
///
/// Returns `true` if cache was cleared, `false` if no cache existed.
/// Propagates actual git config errors (corrupt config, permission denied).
pub fn clear_default_branch_cache(&self) -> anyhow::Result<bool> {
let output = self.run_command_output(&["config", "--unset", "worktrunk.default-branch"])?;
if output.status.success() {
Ok(true)
} else if output.status.code() == Some(5) {
Ok(false) // Key didn't exist (--unset uses exit code 5)
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!(
"git config --unset worktrunk.default-branch: {}",
stderr.trim()
);
}
}
// =========================================================================
// Project config
// =========================================================================
/// Return the path for the project config file.
///
/// If `WORKTRUNK_PROJECT_CONFIG_PATH` is set, returns that path (used for
/// test isolation so the spawned `wt` does not pick up this repo's
/// `.config/wt.toml`). A missing file at that path still resolves to
/// `Ok(None)` via `ProjectConfig::load`, matching the no-config case.
///
/// Otherwise: uses the current worktree when inside one (both normal and
/// bare repos). For bare repos at the bare root (outside any worktree),
/// falls back to the primary worktree. Returns `None` when no worktree can
/// be determined (bare repo with no linked worktrees).
pub fn project_config_path(&self) -> anyhow::Result<Option<PathBuf>> {
if let Ok(path) = std::env::var("WORKTRUNK_PROJECT_CONFIG_PATH") {
return Ok(Some(PathBuf::from(path)));
}
let in_worktree = self
.current_worktree()
.run_command(&["rev-parse", "--is-inside-work-tree"])
.map(|s| s.trim() == "true")
.unwrap_or(false);
if in_worktree {
// Inside a worktree — use it (normal repo or linked worktree in bare repo)
return Ok(Some(
self.current_worktree()
.root()?
.join(".config")
.join("wt.toml"),
));
}
if self.is_bare().unwrap_or(false) {
// At bare repo root — use primary worktree
return Ok(self
.primary_worktree()?
.map(|p| p.join(".config").join("wt.toml")));
}
Ok(None)
}
/// Load the project configuration (.config/wt.toml) if it exists.
///
/// Result is cached in the repository's shared cache (same for all clones).
/// Returns `None` if not in a worktree or if no config file exists.
pub fn load_project_config(&self) -> anyhow::Result<Option<ProjectConfig>> {
self.cache
.project_config
.get_or_try_init(|| {
match self.current_worktree().root() {
Ok(_) => {
ProjectConfig::load(self, true).context("Failed to load project config")
}
Err(_) => Ok(None), // Not in a worktree, no project config
}
})
.cloned()
}
}