forked from openai/codex
-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathgit_worktree.rs
More file actions
653 lines (601 loc) · 24.3 KB
/
git_worktree.rs
File metadata and controls
653 lines (601 loc) · 24.3 KB
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use base64::Engine;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::fs as stdfs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use tokio::fs::OpenOptions;
use tokio::process::Command;
/// Returns the `/.../.code/branches/<worktree>` root when `path` resides inside a branch worktree.
pub fn branch_worktree_root(path: &Path) -> Option<PathBuf> {
use std::ffi::OsStr;
let mut candidate: Option<PathBuf> = None;
for ancestor in path.ancestors() {
let parent = ancestor.parent()?;
if parent
.file_name()
.map(|name| name == OsStr::new("branches"))
.unwrap_or(false)
{
let mut higher = parent.parent();
while let Some(dir) = higher {
if dir
.file_name()
.map(|name| name == OsStr::new(".code"))
.unwrap_or(false)
{
candidate = Some(ancestor.to_path_buf());
break;
}
higher = dir.parent();
}
}
}
candidate
}
/// Returns true when `path` resides inside a `/.../.code/branches/<worktree>` directory.
pub fn is_branch_worktree_path(path: &Path) -> bool {
branch_worktree_root(path).is_some()
}
/// Sanitize a string to be used as a single git refname component.
///
/// Converts to lowercase, keeps [a-z0-9-], collapses other runs into '-'.
pub fn sanitize_ref_component(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut last_dash = false;
for ch in s.chars() {
let c = ch.to_ascii_lowercase();
let valid = c.is_ascii_alphanumeric() || c == '-';
if valid {
out.push(c);
last_dash = c == '-';
} else if !last_dash {
out.push('-');
last_dash = true;
}
}
let out = out.trim_matches('-').to_string();
if out.is_empty() { "branch".to_string() } else { out }
}
/// Generate a branch name for a generic task. If `task` is None or cannot
/// produce a meaningful slug, fall back to a timestamp.
pub fn generate_branch_name_from_task(task: Option<&str>) -> String {
if let Some(task) = task {
let stop = ["the", "and", "for", "with", "from", "into", "goal"];
let words: Vec<&str> = task
.split_whitespace()
.filter(|w| w.len() > 2 && !stop.contains(&w.to_ascii_lowercase().as_str()))
.take(4)
.collect();
if !words.is_empty() {
let mut slug = sanitize_ref_component(&words.join("-"));
if slug.len() > 48 {
slug.truncate(48);
slug = slug.trim_matches('-').to_string();
if slug.is_empty() { slug = "branch".to_string(); }
}
return format!("code-branch-{}", slug);
}
}
// Fallback: timestamped id
let ts = Utc::now().format("%Y%m%d-%H%M%S");
format!("code-branch-{}", ts)
}
pub const LOCAL_DEFAULT_REMOTE: &str = "local-default";
const BRANCH_METADATA_DIR: &str = "_branch-meta";
const REVIEW_WORKTREES_DIR: &str = "reviews";
const REVIEW_WORKTREE_PREFIX: &str = "review";
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BranchMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub base_branch: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub remote_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub remote_ref: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub remote_url: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ReviewWorktreeCleanupToken {
git_root: PathBuf,
worktree_path: PathBuf,
}
impl ReviewWorktreeCleanupToken {
pub fn git_root(&self) -> &Path {
&self.git_root
}
pub fn worktree_path(&self) -> &Path {
&self.worktree_path
}
}
/// Resolve the git repository root (top-level) for the given cwd.
pub async fn get_git_root_from(cwd: &Path) -> Result<PathBuf, String> {
let output = Command::new("git")
.arg("rev-parse")
.arg("--show-toplevel")
.current_dir(cwd)
.output()
.await
.map_err(|e| format!("Git not installed or not in a git repository: {}", e))?;
if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(PathBuf::from(path))
} else {
Err("Not in a git repository".to_string())
}
}
/// Create a new worktree for `branch_id` under `<git_root>/.code/branches/<branch_id>`.
/// If a previous worktree directory exists, remove it first.
pub async fn setup_worktree(git_root: &Path, branch_id: &str) -> Result<(PathBuf, String), String> {
// Global location: ~/.code/working/<repo_name>/branches
let repo_name = git_root
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("repo");
let mut code_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
code_dir = code_dir
.join(".code")
.join("working")
.join(repo_name)
.join("branches");
tokio::fs::create_dir_all(&code_dir)
.await
.map_err(|e| format!("Failed to create .code/branches directory: {}", e))?;
let mut effective_branch = branch_id.to_string();
let mut worktree_path = code_dir.join(&effective_branch);
if worktree_path.exists() {
// If the worktree directory already exists, re-use it to avoid the cost
// of removing and re-adding a worktree. This makes repeated agent runs
// start much faster.
record_worktree_in_session(git_root, &worktree_path).await;
return Ok((worktree_path, effective_branch));
}
let output = Command::new("git")
.current_dir(git_root)
.args(["worktree", "add", "-b", &effective_branch, worktree_path.to_str().unwrap()])
.output()
.await
.map_err(|e| format!("Failed to create git worktree: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
// If the branch already exists, generate a unique name and retry once.
if stderr.contains("already exists") {
effective_branch = format!("{}-{}", effective_branch, Utc::now().format("%Y%m%d-%H%M%S"));
worktree_path = code_dir.join(&effective_branch);
// Ensure target path is clean
if worktree_path.exists() {
let _ = Command::new("git")
.arg("worktree")
.arg("remove")
.arg(worktree_path.to_str().unwrap())
.arg("--force")
.current_dir(git_root)
.output()
.await;
}
let retry = Command::new("git")
.current_dir(git_root)
.args(["worktree", "add", "-b", &effective_branch, worktree_path.to_str().unwrap()])
.output()
.await
.map_err(|e| format!("Failed to create git worktree (retry): {}", e))?;
if !retry.status.success() {
let retry_err = String::from_utf8_lossy(&retry.stderr);
return Err(format!("Failed to create worktree: {}", retry_err));
}
record_worktree_in_session(git_root, &worktree_path).await;
} else {
return Err(format!("Failed to create worktree: {}", stderr));
}
}
// Skip remote alias setup for speed; we don't need it during agent runs.
// Record created worktree for this process; best-effort.
record_worktree_in_session(git_root, &worktree_path).await;
Ok((worktree_path, effective_branch))
}
pub async fn setup_review_worktree(
git_root: &Path,
revision: &str,
name_hint: Option<&str>,
) -> Result<(PathBuf, ReviewWorktreeCleanupToken), String> {
let repo_name = git_root
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("repo");
let mut base_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
base_dir = base_dir
.join(".code")
.join("working")
.join(repo_name)
.join(REVIEW_WORKTREES_DIR);
tokio::fs::create_dir_all(&base_dir)
.await
.map_err(|e| format!("Failed to create review worktree directory: {}", e))?;
let slug = name_hint
.map(sanitize_ref_component)
.filter(|candidate| !candidate.is_empty());
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
let base_name = match slug {
Some(ref slug) => format!("{REVIEW_WORKTREE_PREFIX}-{slug}-{timestamp}"),
None => format!("{REVIEW_WORKTREE_PREFIX}-{timestamp}"),
};
let mut worktree_name = base_name.clone();
let mut worktree_path = base_dir.join(&worktree_name);
let mut suffix = 1usize;
while worktree_path.exists() {
worktree_name = format!("{base_name}-{suffix}");
worktree_path = base_dir.join(&worktree_name);
suffix += 1;
}
let worktree_str = worktree_path
.to_str()
.ok_or_else(|| format!("Review worktree path not valid UTF-8: {}", worktree_path.display()))?
.to_string();
let output = Command::new("git")
.current_dir(git_root)
.args(["worktree", "add", "--detach", &worktree_str, revision])
.output()
.await
.map_err(|e| format!("Failed to create review worktree: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(format!("Failed to create review worktree: {stderr}"));
}
record_worktree_in_session(git_root, &worktree_path).await;
let token = ReviewWorktreeCleanupToken {
git_root: git_root.to_path_buf(),
worktree_path: worktree_path.clone(),
};
Ok((worktree_path, token))
}
/// Append the created worktree to a per-process session file so the TUI can
/// clean it up on exit without touching worktrees from other processes.
async fn record_worktree_in_session(git_root: &Path, worktree_path: &Path) {
let pid = std::process::id();
let mut base = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
// Global session registry: ~/.code/working/_session
base = base.join(".code").join("working").join("_session");
if let Err(_e) = tokio::fs::create_dir_all(&base).await { return; }
let file = base.join(format!("pid-{}.txt", pid));
// Store git_root and worktree_path separated by a tab; one entry per line.
if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(&file).await {
let line = format!("{}\t{}\n", git_root.display(), worktree_path.display());
let _ = tokio::io::AsyncWriteExt::write_all(&mut f, line.as_bytes()).await;
}
}
pub async fn ensure_local_default_remote(
git_root: &Path,
base_branch: Option<&str>,
) -> Result<Option<BranchMetadata>, String> {
let remote_name = LOCAL_DEFAULT_REMOTE;
let canonical_root = tokio::fs::canonicalize(git_root)
.await
.unwrap_or_else(|_| git_root.to_path_buf());
let remote_url = canonical_root.to_string_lossy().to_string();
let remote_check = Command::new("git")
.current_dir(git_root)
.args(["remote", "get-url", remote_name])
.output()
.await;
match remote_check {
Ok(out) if out.status.success() => {
let existing = String::from_utf8_lossy(&out.stdout).trim().to_string();
if existing != remote_url {
let update = Command::new("git")
.current_dir(git_root)
.args(["remote", "set-url", remote_name, &remote_url])
.output()
.await
.map_err(|e| format!("Failed to set {remote_name} URL: {e}"))?;
if !update.status.success() {
let stderr = String::from_utf8_lossy(&update.stderr).trim().to_string();
return Err(format!("Failed to set {remote_name} URL: {stderr}"));
}
}
}
_ => {
let add = Command::new("git")
.current_dir(git_root)
.args(["remote", "add", remote_name, &remote_url])
.output()
.await
.map_err(|e| format!("Failed to add {remote_name}: {e}"))?;
if !add.status.success() {
let stderr = String::from_utf8_lossy(&add.stderr).trim().to_string();
return Err(format!("Failed to add {remote_name}: {stderr}"));
}
}
}
let base_branch_clean = base_branch
.map(|s| s.trim())
.filter(|s| !s.is_empty() && *s != "HEAD")
.map(|s| s.to_string());
let base_branch_clean = match base_branch_clean {
Some(value) => Some(value),
None => detect_default_branch(git_root).await,
};
let mut metadata = BranchMetadata {
base_branch: base_branch_clean.clone(),
remote_name: Some(remote_name.to_string()),
remote_ref: None,
remote_url: Some(remote_url),
};
if let Some(base) = base_branch_clean {
let commit = Command::new("git")
.current_dir(git_root)
.args(["rev-parse", "--verify", &base])
.output()
.await
.map_err(|e| format!("Failed to resolve base branch {base}: {e}"))?;
if commit.status.success() {
let sha = String::from_utf8_lossy(&commit.stdout).trim().to_string();
if !sha.is_empty() {
let remote_ref = format!("refs/remotes/{remote_name}/{base}");
let update = Command::new("git")
.current_dir(git_root)
.args(["update-ref", &remote_ref, &sha])
.output()
.await
.map_err(|e| format!("Failed to update {remote_ref}: {e}"))?;
if update.status.success() {
metadata.remote_ref = Some(format!("{remote_name}/{base}"));
}
}
}
}
Ok(Some(metadata))
}
fn canonical_worktree_path(worktree_path: &Path) -> Option<PathBuf> {
stdfs::canonicalize(worktree_path)
.ok()
.or_else(|| Some(worktree_path.to_path_buf()))
}
fn metadata_file_path(worktree_path: &Path) -> Option<PathBuf> {
let canonical = canonical_worktree_path(worktree_path)?;
let mut base = dirs::home_dir()?;
base = base
.join(".code")
.join("working")
.join(BRANCH_METADATA_DIR);
let key = canonical.to_string_lossy();
let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(key.as_bytes());
Some(base.join(encoded).with_extension("json"))
}
pub async fn write_branch_metadata(
worktree_path: &Path,
metadata: &BranchMetadata,
) -> Result<(), String> {
let Some(path) = metadata_file_path(worktree_path) else { return Ok(()); };
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent)
.await
.map_err(|e| format!("Failed to prepare branch metadata directory: {e}"))?;
}
let serialised = serde_json::to_vec_pretty(metadata)
.map_err(|e| format!("Failed to serialise branch metadata: {e}"))?;
let legacy_path = worktree_path.join(".codex-branch.json");
let _ = tokio::fs::remove_file(&legacy_path).await;
tokio::fs::write(&path, serialised)
.await
.map_err(|e| format!("Failed to write branch metadata: {e}"))
}
pub fn load_branch_metadata(worktree_path: &Path) -> Option<BranchMetadata> {
if let Some(path) = metadata_file_path(worktree_path) {
if let Ok(bytes) = stdfs::read(&path) {
if let Ok(parsed) = serde_json::from_slice(&bytes) {
return Some(parsed);
}
}
}
let legacy_path = worktree_path.join(".codex-branch.json");
let bytes = stdfs::read(legacy_path).ok()?;
serde_json::from_slice(&bytes).ok()
}
pub fn remove_branch_metadata(worktree_path: &Path) {
if let Some(path) = metadata_file_path(worktree_path) {
let _ = stdfs::remove_file(path);
}
let legacy_path = worktree_path.join(".codex-branch.json");
let _ = stdfs::remove_file(legacy_path);
}
/// Ensure a remote named `origin` exists. If it's missing, choose a likely
/// writable remote (prefer `fork`, then `upstream-push`, then the first push
/// URL we find) and alias it as `origin`. Finally, set the remote HEAD so
/// `origin/HEAD` points at the default branch.
async fn _ensure_origin_remote(git_root: &Path) -> Result<(), String> {
// Check existing remotes
let remotes_out = Command::new("git")
.current_dir(git_root)
.args(["remote"])
.output()
.await
.map_err(|e| format!("git remote failed: {}", e))?;
if !remotes_out.status.success() {
return Err("git remote returned error".to_string());
}
let remotes: Vec<String> = String::from_utf8_lossy(&remotes_out.stdout)
.lines()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if remotes.iter().any(|r| r == "origin") {
// Make sure origin/HEAD is set; ignore errors
let _ = Command::new("git")
.current_dir(git_root)
.args(["remote", "set-head", "origin", "-a"])
.output()
.await;
return Ok(());
}
// Prefer candidates in this order
let mut candidates = vec!["fork", "upstream-push", "upstream"]; // typical setups
// Append any other remotes as fallbacks
for r in &remotes {
if !candidates.contains(&r.as_str()) { candidates.push(r); }
}
// Find a candidate with a URL
for cand in candidates {
let url_out = Command::new("git")
.current_dir(git_root)
.args(["remote", "get-url", cand])
.output()
.await;
if let Ok(out) = url_out {
if out.status.success() {
let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !url.is_empty() {
// Add origin pointing to this URL
let add = Command::new("git")
.current_dir(git_root)
.args(["remote", "add", "origin", &url])
.output()
.await
.map_err(|e| format!("git remote add origin failed: {}", e))?;
if !add.status.success() {
return Err("failed to add origin".to_string());
}
let _ = Command::new("git")
.current_dir(git_root)
.args(["remote", "set-head", "origin", "-a"])
.output()
.await;
return Ok(());
}
}
}
}
// No usable remote found; leave as-is
Err("no suitable remote to alias as origin".to_string())
}
/// Copy uncommitted (modified + untracked) files from `src_root` into the `worktree_path`.
/// Returns the number of files copied.
pub async fn copy_uncommitted_to_worktree(src_root: &Path, worktree_path: &Path) -> Result<usize, String> {
// List modified and other (untracked) files relative to repo root
let output = Command::new("git")
.current_dir(src_root)
.args(["ls-files", "-om", "--exclude-standard", "-z"])
.output()
.await
.map_err(|e| format!("Failed to list changes: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("git ls-files failed: {}", stderr));
}
let bytes = output.stdout;
let mut count = 0usize;
for path_bytes in bytes.split(|b| *b == 0) {
if path_bytes.is_empty() { continue; }
let rel = match String::from_utf8(path_bytes.to_vec()) { Ok(s) => s, Err(_) => continue };
// Avoid copying .git files explicitly
if rel.starts_with(".git/") { continue; }
let from = src_root.join(&rel);
let to = worktree_path.join(&rel);
let meta = match tokio::fs::metadata(&from).await { Ok(m) => m, Err(_) => continue };
if !meta.is_file() { continue; }
if let Some(parent) = to.parent() { tokio::fs::create_dir_all(parent).await.map_err(|e| format!("Failed to create dir {}: {}", parent.display(), e))?; }
// Use copy for files; skip if it's a directory (shouldn't appear from ls-files)
match tokio::fs::copy(&from, &to).await {
Ok(_) => count += 1,
Err(e) => return Err(format!("Failed to copy {} -> {}: {}", from.display(), to.display(), e)),
}
}
// Opt-in: mirror modified submodule pointers into the worktree index (no checkout/network).
// Enable via CODEX_BRANCH_INCLUDE_SUBMODULES=1|true|yes.
let include_submods = std::env::var("CODEX_BRANCH_INCLUDE_SUBMODULES")
.ok()
.map(|v| v.to_ascii_lowercase())
.map(|v| v == "1" || v == "true" || v == "yes")
.unwrap_or(false);
if include_submods {
if let Ok(out) = Command::new("git")
.current_dir(src_root)
.args(["submodule", "status", "--recursive"])
.output()
.await
{
if out.status.success() {
let text = String::from_utf8_lossy(&out.stdout);
for line in text.lines() {
let line = line.trim();
if !line.starts_with('+') { continue; }
let rest = &line[1..];
let mut parts = rest.split_whitespace();
let sha = match parts.next() { Some(s) => s, None => continue };
let path = match parts.next() { Some(p) => p, None => continue };
let spec = format!("160000,{},{}", sha, path);
let _ = Command::new("git")
.current_dir(worktree_path)
.args(["update-index", "--add", "--cacheinfo", &spec])
.output()
.await;
}
}
}
}
Ok(count)
}
pub async fn cleanup_review_worktree(token: ReviewWorktreeCleanupToken) -> Result<(), String> {
cleanup_review_worktree_at(token.git_root(), token.worktree_path()).await
}
pub async fn cleanup_review_worktree_at(
git_root: &Path,
worktree_path: &Path,
) -> Result<(), String> {
let worktree_str = worktree_path
.to_str()
.ok_or_else(|| format!("Review worktree path not valid UTF-8: {}", worktree_path.display()))?
.to_string();
let output = Command::new("git")
.current_dir(git_root)
.args(["worktree", "remove", "--force", &worktree_str])
.output()
.await
.map_err(|e| format!("Failed to remove review worktree: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let trimmed = stderr.trim();
if !trimmed.is_empty()
&& !trimmed.contains("not found")
&& !trimmed.contains("No such file or directory")
&& !trimmed.contains("not a worktree")
{
return Err(format!("Failed to remove review worktree: {trimmed}"));
}
}
match tokio::fs::remove_dir_all(worktree_path).await {
Ok(_) => {}
Err(err) if err.kind() == ErrorKind::NotFound => {}
Err(err) => return Err(format!("Failed to delete review worktree directory: {err}")),
}
if let Some(parent) = worktree_path.parent() {
let _ = tokio::fs::remove_dir(parent).await;
}
Ok(())
}
/// Determine repository default branch. Prefers `origin/HEAD` symbolic ref, then local `main`/`master`.
pub async fn detect_default_branch(cwd: &Path) -> Option<String> {
// Try origin/HEAD first
let sym = Command::new("git")
.current_dir(cwd)
.args(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"])
.output()
.await
.ok()?;
if sym.status.success() {
if let Ok(s) = String::from_utf8(sym.stdout) {
if let Some((_, name)) = s.trim().rsplit_once('/') { return Some(name.to_string()); }
}
}
// Fallback to local main/master
for candidate in ["main", "master"] {
let out = Command::new("git")
.current_dir(cwd)
.args(["rev-parse", "--verify", "--quiet", &format!("refs/heads/{candidate}")])
.output()
.await
.ok()?;
if out.status.success() { return Some(candidate.to_string()); }
}
None
}