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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
use crate::commands::ci::{fetch_ci_statuses, record_ci_history};
use crate::commands::restack_conflict::{print_restack_conflict, RestackConflictContext};
use crate::config::Config;
use crate::engine::{BranchMetadata, Stack};
use crate::git::{GitRepo, RebaseResult};
use crate::github::GitHubClient;
use crate::ops::receipt::{OpKind, PlanSummary};
use crate::ops::tx::{self, Transaction};
use crate::progress::LiveTimer;
use crate::remote::RemoteInfo;
use anyhow::{Context, Result};
use colored::Colorize;
use dialoguer::{theme::ColorfulTheme, Confirm};
use std::process::Command;
use std::time::{Duration, Instant};
/// Sync repo: pull trunk from remote, delete merged branches, optionally restack
pub fn run(
restack: bool,
prune: bool,
delete_merged: bool,
delete_upstream_gone: bool,
force: bool,
safe: bool,
r#continue: bool,
quiet: bool,
verbose: bool,
auto_stash_pop: bool,
) -> Result<()> {
let sync_started_at = Instant::now();
let mut step_timings: Vec<(String, Duration)> = Vec::new();
let repo = GitRepo::open()?;
let stack = Stack::load(&repo)?;
let current = repo.current_branch()?;
let workdir = repo.workdir()?;
let config = Config::load()?;
let remote_name = config.remote_name().to_string();
let remote_trunk_ref = format!("{}/{}", remote_name, stack.trunk);
if r#continue {
crate::commands::continue_cmd::run()?;
if repo.rebase_in_progress()? {
return Ok(());
}
}
let auto_confirm = force;
let mut stashed = false;
if repo.is_dirty()? {
if quiet {
anyhow::bail!("Working tree is dirty. Please stash or commit changes first.");
}
let stash = if auto_confirm {
true
} else {
Confirm::with_theme(&ColorfulTheme::default())
.with_prompt("Working tree has uncommitted changes. Stash them before sync?")
.default(true)
.interact()?
};
if stash {
let stash_started_at = Instant::now();
stashed = repo.stash_push()?;
step_timings.push(("stash working tree".to_string(), stash_started_at.elapsed()));
if !quiet {
println!("{}", "✓ Stashed working tree changes.".green());
}
} else {
println!("{}", "Aborted.".red());
return Ok(());
}
}
if !quiet {
println!("{}", "Syncing repository...".bold());
}
// 1. Fetch from remote
let fetch_timer = LiveTimer::maybe_new(!quiet, &format!("Fetch {}", remote_name));
let fetch_started_at = Instant::now();
let fetch_args: Vec<&str> = if prune {
vec!["fetch", "--prune", "--no-tags", &remote_name]
} else {
vec!["fetch", "--no-tags", &remote_name]
};
let output = Command::new("git")
.args(&fetch_args)
.current_dir(workdir)
.output()
.context("Failed to fetch")?;
step_timings.push((format!("fetch {}", remote_name), fetch_started_at.elapsed()));
if output.status.success() {
LiveTimer::maybe_finish_timed(fetch_timer);
if !quiet && verbose {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
for line in stderr.lines() {
println!(" {}", line.dimmed());
}
}
}
} else {
// Fetch may fail partially (lock files, etc.) but still update most refs
LiveTimer::maybe_finish_warn(fetch_timer, "done (with warnings)");
if !quiet && verbose {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
for line in stderr.lines() {
println!(" {}", line.dimmed());
}
}
}
}
// 2. Update trunk branch (before merged branch detection, so detection works correctly)
// Note: If we're not on trunk, we use a refspec fetch which may fail if local trunk
// has diverged. This is fine - we'll retry after branch deletions if we end up on trunk.
let was_on_trunk = current == stack.trunk;
let mut trunk_update_deferred = false;
let update_trunk_started_at = Instant::now();
if was_on_trunk {
// We're on trunk - pull directly
let update_timer = LiveTimer::maybe_new(!quiet, &format!("Update {}", stack.trunk));
let output = Command::new("git")
.args(["merge", "--ff-only", &remote_trunk_ref])
.current_dir(workdir)
.output()
.context("Failed to fast-forward trunk")?;
if output.status.success() {
LiveTimer::maybe_finish_timed(update_timer);
if !quiet && verbose {
let stdout = String::from_utf8_lossy(&output.stdout);
if !stdout.trim().is_empty() {
for line in stdout.lines() {
println!(" {}", line.dimmed());
}
}
}
} else if safe {
LiveTimer::maybe_finish_warn(update_timer, "failed (safe mode, no reset)");
if !quiet && verbose {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
for line in stderr.lines() {
println!(" {}", line.dimmed());
}
}
}
} else {
// Try reset to remote
let reset_output = Command::new("git")
.args(["reset", "--hard", &remote_trunk_ref])
.current_dir(workdir)
.output()
.context("Failed to reset trunk")?;
if reset_output.status.success() {
LiveTimer::maybe_finish_warn(update_timer, "reset to remote");
} else {
LiveTimer::maybe_finish_err(update_timer, "failed");
if !quiet && verbose {
let stderr = String::from_utf8_lossy(&reset_output.stderr);
if !stderr.trim().is_empty() {
for line in stderr.lines() {
println!(" {}", line.dimmed());
}
}
}
}
}
} else {
let update_timer = LiveTimer::maybe_new(!quiet, &format!("Update {}", stack.trunk));
if let Some(trunk_worktree_path) = repo.branch_worktree_path(&stack.trunk)? {
let output = Command::new("git")
.args(["merge", "--ff-only", &remote_trunk_ref])
.current_dir(&trunk_worktree_path)
.output()
.context("Failed to fast-forward trunk in its worktree")?;
if output.status.success() {
LiveTimer::maybe_finish_timed(update_timer);
} else if safe {
LiveTimer::maybe_finish_warn(update_timer, "failed (safe mode, no reset)");
if !quiet && verbose {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
for line in stderr.lines() {
println!(" {}", line.dimmed());
}
}
}
} else {
let reset_output = Command::new("git")
.args(["reset", "--hard", &remote_trunk_ref])
.current_dir(&trunk_worktree_path)
.output()
.context("Failed to reset trunk in its worktree")?;
if reset_output.status.success() {
LiveTimer::maybe_finish_warn(update_timer, "reset to remote");
} else {
LiveTimer::maybe_finish_err(update_timer, "failed");
if !quiet && verbose {
let stderr = String::from_utf8_lossy(&reset_output.stderr);
if !stderr.trim().is_empty() {
for line in stderr.lines() {
println!(" {}", line.dimmed());
}
}
}
}
}
} else {
// Trunk isn't checked out in any worktree.
// Resolve the two SHAs so we can give an accurate status message.
let local_sha = Command::new("git")
.args(["rev-parse", &stack.trunk])
.current_dir(workdir)
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());
let remote_sha = Command::new("git")
.args(["rev-parse", &remote_trunk_ref])
.current_dir(workdir)
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());
match (local_sha, remote_sha) {
(Some(ref local), Some(ref remote)) if local == remote => {
// Already up to date — nothing to do.
LiveTimer::maybe_finish_timed(update_timer);
}
(Some(_), Some(_)) => {
// Check if a fast-forward is safe (local trunk is an ancestor of remote).
let ff_possible = Command::new("git")
.args([
"merge-base",
"--is-ancestor",
&stack.trunk,
&remote_trunk_ref,
])
.current_dir(workdir)
.status()
.map(|s| s.success())
.unwrap_or(false);
if ff_possible {
let output = Command::new("git")
.args([
"update-ref",
&format!("refs/heads/{}", stack.trunk),
&format!("refs/remotes/{}/{}", remote_name, stack.trunk),
])
.current_dir(workdir)
.output()
.context("Failed to fast-forward local trunk ref")?;
if output.status.success() {
LiveTimer::maybe_finish_timed(update_timer);
} else {
trunk_update_deferred = true;
LiveTimer::maybe_finish_skipped(
update_timer,
"couldn't update — run 'stax trunk' to pull",
);
}
} else {
// Local trunk has commits not on the remote — can't fast-forward.
trunk_update_deferred = true;
LiveTimer::maybe_finish_skipped(
update_timer,
&format!(
"local {} has unpushed commits — run 'stax trunk' to sync",
stack.trunk
),
);
}
}
_ => {
// Couldn't resolve one or both refs (shouldn't happen after a successful fetch).
trunk_update_deferred = true;
LiveTimer::maybe_finish_skipped(
update_timer,
"couldn't resolve ref — run 'stax trunk' to pull",
);
}
}
}
}
step_timings.push((
format!("update {}", stack.trunk),
update_trunk_started_at.elapsed(),
));
// 3. Delete merged branches
if delete_merged {
let detect_merged_started_at = Instant::now();
let detect_timer = LiveTimer::maybe_new(!quiet, "Detect merged branches");
let merged = find_merged_branches(workdir, &stack, &remote_name)?;
step_timings.push((
"detect merged branches".to_string(),
detect_merged_started_at.elapsed(),
));
LiveTimer::maybe_finish_timed(detect_timer);
let delete_merged_started_at = Instant::now();
// Lazy-initialize GitHub client for updating PR bases (only if needed)
let github_client: Option<(tokio::runtime::Runtime, GitHubClient)> = {
let remote_info = RemoteInfo::from_repo(&repo, &config).ok();
let has_github_token = Config::github_token().is_some();
if has_github_token {
if let Some(info) = remote_info {
tokio::runtime::Runtime::new().ok().and_then(|rt| {
// Must create client inside block_on - Octocrab requires runtime context
rt.block_on(async {
GitHubClient::new(info.owner(), &info.repo, info.api_base_url.clone())
.ok()
})
.map(|client| (rt, client))
})
} else {
None
}
} else {
None
}
};
if !merged.is_empty() {
if !quiet {
let branch_word = if merged.len() == 1 {
"branch"
} else {
"branches"
};
println!(
" Found {} merged {}:",
merged.len().to_string().cyan(),
branch_word
);
for branch in &merged {
println!(" {} {}", "â–¸".bright_black(), branch);
}
println!();
}
// Record CI history for merged branches before deleting them
if let Some((ref rt, ref client)) = github_client {
record_ci_history_for_merged(&repo, rt, client, &merged, &stack, quiet);
}
for branch in &merged {
let is_current_branch = branch == ¤t;
// Resolve parent branch for checkout/reparent.
// Metadata can reference a deleted branch; in that case fall back to trunk.
let recorded_parent_branch = stack
.branches
.get(branch)
.and_then(|b| b.parent.clone())
.unwrap_or_else(|| stack.trunk.clone());
let (parent_branch, parent_fallback_from) =
resolve_effective_parent(workdir, &recorded_parent_branch, &stack.trunk);
let parent_exists_locally = local_branch_exists(workdir, &parent_branch);
if !quiet {
if let Some(missing_parent) = &parent_fallback_from {
println!(
" {} parent {} not found locally; using {}",
"↪".yellow(),
missing_parent.yellow(),
parent_branch.cyan()
);
}
}
if !parent_exists_locally {
if !quiet {
println!(
" {} {}",
branch.bright_black(),
format!(
"couldn't resolve a local parent branch (wanted '{}'), skipping",
parent_branch
)
.red()
);
}
continue;
}
let prompt = if is_current_branch {
format!("Delete '{}' and checkout '{}'?", branch, parent_branch)
} else {
format!("Delete '{}'?", branch)
};
let confirm = if auto_confirm {
true
} else if quiet {
false
} else {
Confirm::with_theme(&ColorfulTheme::default())
.with_prompt(prompt)
.default(true)
.interact()?
};
if confirm {
// If we're on this branch, checkout parent first
if is_current_branch {
let checkout_status = Command::new("git")
.args(["checkout", &parent_branch])
.current_dir(workdir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status();
if checkout_status.map(|s| s.success()).unwrap_or(false) {
if !quiet {
println!(" {} checked out {}", "→".cyan(), parent_branch.cyan());
}
// Pull latest changes for the parent branch
let pull_status = Command::new("git")
.args(["pull", "--ff-only", &remote_name, &parent_branch])
.current_dir(workdir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status();
if let Ok(status) = pull_status {
if status.success() && !quiet {
println!(
" {} pulled latest {}",
"↓".cyan(),
parent_branch.cyan()
);
}
}
} else {
if !quiet {
println!(
" {} {}",
branch.bright_black(),
format!("failed to checkout '{}', skipping", parent_branch)
.red()
);
}
continue;
}
}
// Reparent children of this branch to its parent before deleting
let children: Vec<String> = stack
.branches
.iter()
.filter(|(_, info)| info.parent.as_deref() == Some(branch))
.map(|(name, _)| name.clone())
.collect();
let merged_branch_tip = repo.branch_commit(branch).ok();
for child in &children {
if let Some(child_meta) = BranchMetadata::read(repo.inner(), child)? {
// Preserve the old-parent boundary so restack can run
// `git rebase --onto <new> <old>` precisely.
let old_parent_boundary = merged_branch_tip
.clone()
.unwrap_or_else(|| child_meta.parent_branch_revision.clone());
let updated_meta = BranchMetadata {
parent_branch_name: parent_branch.clone(),
parent_branch_revision: old_parent_boundary,
..child_meta.clone()
};
updated_meta.write(repo.inner(), child)?;
// Update PR base on GitHub if this branch has a PR
if let Some(pr_info) = &child_meta.pr_info {
if let Some((rt, client)) = &github_client {
match rt.block_on(
client.update_pr_base(pr_info.number, &parent_branch),
) {
Ok(()) => {
if !quiet {
println!(
" {} updated PR #{} base → {}",
"↪".cyan(),
pr_info.number,
parent_branch.cyan()
);
}
}
Err(e) => {
// Log warning but don't fail - PR might already be closed/merged
if !quiet {
println!(
" {} couldn't update PR #{} base: {}",
"âš ".yellow(),
pr_info.number,
e
);
}
}
}
}
}
if !quiet {
println!(
" {} reparented {} → {}",
"↪".cyan(),
child.cyan(),
parent_branch.cyan()
);
}
}
}
// Delete local branch (force delete since we confirmed)
let local_output = Command::new("git")
.args(["branch", "-D", branch])
.current_dir(workdir)
.output();
let (local_deleted, local_worktree_blocked) = match local_output {
Ok(out) => {
let stderr = String::from_utf8_lossy(&out.stderr).to_string();
(out.status.success(), stderr.contains("used by worktree"))
}
Err(_) => (false, false),
};
// Delete remote branch
let remote_status = Command::new("git")
.args(["push", &remote_name, "--delete", branch])
.current_dir(workdir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status();
let remote_deleted = remote_status.map(|s| s.success()).unwrap_or(false);
// Only delete metadata if branch no longer exists locally.
let local_ref = format!("refs/heads/{}", branch);
let local_still_exists = Command::new("git")
.args(["show-ref", "--verify", "--quiet", &local_ref])
.current_dir(workdir)
.status()
.map(|s| s.success())
.unwrap_or(true);
let metadata_deleted = if !local_still_exists {
let _ = crate::git::refs::delete_metadata(repo.inner(), branch);
true
} else {
false
};
if !quiet {
if local_deleted && remote_deleted {
println!(
" {} {}",
branch.bright_black(),
"deleted (local + remote)".green()
);
} else if local_deleted {
println!(
" {} {}",
branch.bright_black(),
"deleted (local only)".green()
);
} else if remote_deleted {
println!(
" {} {}",
branch.bright_black(),
"deleted (remote only)".green()
);
if !metadata_deleted {
println!(
" {} {}",
"↷".yellow(),
"local branch still exists, metadata kept".dimmed()
);
}
} else {
if local_worktree_blocked {
println!(
" {} {}",
branch.bright_black(),
"not deleted locally (checked out in another worktree)"
.yellow()
);
} else {
println!(" {} {}", branch.bright_black(), "skipped".dimmed());
}
if !metadata_deleted {
println!(
" {} {}",
"↷".yellow(),
"metadata kept because local branch still exists".dimmed()
);
}
}
}
} else if !quiet {
println!(" {} {}", branch.bright_black(), "skipped".dimmed());
}
}
} else if !quiet {
println!(" {}", "No merged branches to delete.".dimmed());
}
let delete_elapsed = delete_merged_started_at.elapsed();
step_timings.push(("delete merged branches".to_string(), delete_elapsed));
if !quiet && !merged.is_empty() {
println!(
" {:<35} {}",
"delete merged branches",
format!("{:.3}s", delete_elapsed.as_secs_f64()).dimmed()
);
}
}
// Re-check current branch since it may have changed during branch deletion
let mut current_after_deletions = repo.current_branch()?;
// 3b. Optionally delete local branches whose upstream is gone
if delete_upstream_gone {
let detect_gone_started_at = Instant::now();
let detect_timer = LiveTimer::maybe_new(!quiet, "Detect upstream-gone branches");
let gone = find_upstream_gone_branches(workdir, &stack.trunk)?;
step_timings.push((
"detect upstream-gone branches".to_string(),
detect_gone_started_at.elapsed(),
));
LiveTimer::maybe_finish_timed(detect_timer);
let delete_gone_started_at = Instant::now();
if !gone.is_empty() {
if !quiet {
let branch_word = if gone.len() == 1 {
"branch"
} else {
"branches"
};
println!(
" Found {} upstream-gone {}:",
gone.len().to_string().cyan(),
branch_word
);
for branch in &gone {
println!(" {} {}", "â–¸".bright_black(), branch);
}
println!();
}
for branch in &gone {
if !local_branch_exists(workdir, branch) {
continue;
}
let is_current_branch = branch == ¤t_after_deletions;
let fallback_parent = &stack.trunk;
let prompt = if is_current_branch {
format!(
"Delete '{}' (upstream gone) and checkout '{}'?",
branch, fallback_parent
)
} else {
format!("Delete '{}' (upstream gone)?", branch)
};
let confirm = if auto_confirm {
true
} else if quiet {
false
} else {
Confirm::with_theme(&ColorfulTheme::default())
.with_prompt(prompt)
.default(true)
.interact()?
};
if !confirm {
if !quiet {
println!(" {} {}", branch.bright_black(), "skipped".dimmed());
}
continue;
}
if is_current_branch {
let checkout_status = Command::new("git")
.args(["checkout", fallback_parent])
.current_dir(workdir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status();
if checkout_status.map(|s| s.success()).unwrap_or(false) {
current_after_deletions = fallback_parent.clone();
if !quiet {
println!(" {} checked out {}", "→".cyan(), fallback_parent.cyan());
}
} else {
if !quiet {
println!(
" {} {}",
branch.bright_black(),
format!("failed to checkout '{}', skipping", fallback_parent).red()
);
}
continue;
}
}
let local_output = Command::new("git")
.args(["branch", "-D", branch])
.current_dir(workdir)
.output();
let (local_deleted, local_worktree_blocked) = match local_output {
Ok(out) => {
let stderr = String::from_utf8_lossy(&out.stderr).to_string();
(out.status.success(), stderr.contains("used by worktree"))
}
Err(_) => (false, false),
};
// Only delete metadata if branch no longer exists locally.
let local_ref = format!("refs/heads/{}", branch);
let local_still_exists = Command::new("git")
.args(["show-ref", "--verify", "--quiet", &local_ref])
.current_dir(workdir)
.status()
.map(|s| s.success())
.unwrap_or(true);
let metadata_deleted = if !local_still_exists {
let _ = crate::git::refs::delete_metadata(repo.inner(), branch);
true
} else {
false
};
if !quiet {
if local_deleted {
println!(
" {} {}",
branch.bright_black(),
"deleted (local only)".green()
);
} else if local_worktree_blocked {
println!(
" {} {}",
branch.bright_black(),
"not deleted locally (checked out in another worktree)".yellow()
);
} else {
println!(" {} {}", branch.bright_black(), "skipped".dimmed());
}
if !metadata_deleted && local_still_exists {
println!(
" {} {}",
"↷".yellow(),
"metadata kept because local branch still exists".dimmed()
);
}
}
}
} else if !quiet {
println!(" {}", "No upstream-gone branches to delete.".dimmed());
}
let delete_elapsed = delete_gone_started_at.elapsed();
step_timings.push(("delete upstream-gone branches".to_string(), delete_elapsed));
if !quiet && !gone.is_empty() {
println!(
" {:<35} {}",
"delete upstream-gone branches",
format!("{:.3}s", delete_elapsed.as_secs_f64()).dimmed()
);
}
}
// If we deferred trunk update (refspec fetch failed while not on trunk) and we're
// now on trunk after branch deletions, retry with git pull which is more reliable
if trunk_update_deferred && current_after_deletions == stack.trunk {
let deferred_update_started_at = Instant::now();
let deferred_timer = LiveTimer::maybe_new(!quiet, &format!("Update {}", stack.trunk));
let output = Command::new("git")
.args(["merge", "--ff-only", &remote_trunk_ref])
.current_dir(workdir)
.output()
.context("Failed to fast-forward trunk")?;
if output.status.success() {
LiveTimer::maybe_finish_timed(deferred_timer);
if !quiet && verbose {
let stdout = String::from_utf8_lossy(&output.stdout);
if !stdout.trim().is_empty() {
for line in stdout.lines() {
println!(" {}", line.dimmed());
}
}
}
} else if safe {
LiveTimer::maybe_finish_warn(deferred_timer, "failed (safe mode, no reset)");
if !quiet && verbose {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
for line in stderr.lines() {
println!(" {}", line.dimmed());
}
}
}
} else {
// Try reset to remote
let reset_output = Command::new("git")
.args(["reset", "--hard", &remote_trunk_ref])
.current_dir(workdir)
.output()
.context("Failed to reset trunk")?;
if reset_output.status.success() {
LiveTimer::maybe_finish_warn(deferred_timer, "reset to remote");
} else {
LiveTimer::maybe_finish_err(deferred_timer, "failed");
if !quiet && verbose {
let stderr = String::from_utf8_lossy(&reset_output.stderr);
if !stderr.trim().is_empty() {
for line in stderr.lines() {
println!(" {}", line.dimmed());
}
}
}
}
}
step_timings.push((
format!("retry update {}", stack.trunk),
deferred_update_started_at.elapsed(),
));
}
// 4. Optionally restack
if restack {
let restack_started_at = Instant::now();
if !quiet {
println!();
println!("{}", "Restacking...".bold());
}
// Scope restacking to the stack we started on, even if sync switched branches
// (for example, if the current branch was deleted after merge).
let scope_order: Vec<String> =
if current != stack.trunk && stack.branches.contains_key(¤t) {
stack.current_stack(¤t)
} else {
Vec::new()
};
// Reload stack to use fresh metadata after sync/deletion steps.
let restack_stack = Stack::load(&repo)?;
let branches_to_restack: Vec<String> = scope_order
.into_iter()
.filter(|branch| {
restack_stack
.branches
.get(branch)
.map(|br| br.needs_restack)
.unwrap_or(false)
})
.collect();
if branches_to_restack.is_empty() {
if !quiet {
println!(" {}", "All branches up to date.".dimmed());
}
} else {
// Begin transaction for restack phase
let mut tx = Transaction::begin(OpKind::SyncRestack, &repo, quiet)?;
tx.plan_branches(&repo, &branches_to_restack)?;
let restack_count = branches_to_restack.len();
let summary = PlanSummary {
branches_to_rebase: restack_count,
branches_to_push: 0,
description: vec![format!(
"Sync restack {} {}",
restack_count,
if restack_count == 1 {
"branch"
} else {
"branches"
}
)],
};
tx::print_plan(tx.kind(), &summary, quiet);
tx.set_plan_summary(summary);
tx.snapshot()?;
let mut summary: Vec<(String, String)> = Vec::new();
for (index, branch) in branches_to_restack.iter().enumerate() {
let restack_timer = LiveTimer::maybe_new(!quiet, &format!("Restack {}", branch));
let meta = match BranchMetadata::read(repo.inner(), branch)? {
Some(meta) => meta,
None => continue,
};
match repo.rebase_branch_onto_with_provenance(
branch,
&meta.parent_branch_name,
&meta.parent_branch_revision,
auto_stash_pop,
)? {
RebaseResult::Success => {
let parent_commit = repo.branch_commit(&meta.parent_branch_name)?;
let updated_meta = BranchMetadata {
parent_branch_revision: parent_commit,
..meta
};
updated_meta.write(repo.inner(), branch)?;
// Record after-OID
tx.record_after(&repo, branch)?;
LiveTimer::maybe_finish_timed(restack_timer);
summary.push((branch.clone(), "ok".to_string()));
}
RebaseResult::Conflict => {
LiveTimer::maybe_finish_warn(restack_timer, "conflict");
let completed_branches: Vec<String> = summary
.iter()
.filter(|(_, status)| status == "ok")
.map(|(name, _)| name.clone())
.collect();
print_restack_conflict(
&repo,
&RestackConflictContext {
branch,
parent_branch: &meta.parent_branch_name,
completed_branches: &completed_branches,
remaining_branches: branches_to_restack
.len()
.saturating_sub(index + 1),
continue_commands: &[
"stax resolve",
"stax continue",
"stax sync --continue",
],
},
);
if stashed {
println!("{}", "Stash kept to avoid conflicts.".yellow());
}
summary.push((branch.clone(), "conflict".to_string()));
// Finish transaction with error
tx.finish_err("Rebase conflict", Some("restack"), Some(branch))?;
return Ok(());
}
}
}
repo.checkout(¤t_after_deletions)?;
// Finish transaction successfully
tx.finish_ok()?;
if !quiet && !summary.is_empty() {
println!();
println!("{}", "Restack summary:".dimmed());
for (branch, status) in &summary {
let symbol = if status == "ok" { "✓" } else { "✗" };
println!(" {} {} {}", symbol, branch, status);
}
}
}
step_timings.push(("restack".to_string(), restack_started_at.elapsed()));
}
if stashed {
let stash_pop_started_at = Instant::now();
repo.stash_pop()?;
step_timings.push(("restore stash".to_string(), stash_pop_started_at.elapsed()));
if !quiet {
println!("{}", "✓ Restored stashed changes.".green());
}
}
if verbose && !quiet {
println!();
println!("{}", "Sync timing summary:".bold());
for (step, duration) in &step_timings {
println!(" {:<35} {}", step, format_duration(*duration).dimmed());
}
println!(
" {:<35} {}",
"total",
format_duration(sync_started_at.elapsed()).cyan()
);
}
if !quiet {
println!();
println!("{}", "Sync complete!".green().bold());
}
Ok(())
}
/// Find branches that have been merged into trunk or are orphaned (no longer exist locally/remotely)
fn find_merged_branches(
workdir: &std::path::Path,
stack: &Stack,
remote_name: &str,
) -> Result<Vec<String>> {
let mut merged = Vec::new();
let remote_trunk_ref = format!("{}/{}", remote_name, stack.trunk);
// Method 1: git branch --merged (finds local branches merged into trunk)
let output = Command::new("git")
.args(["branch", "--merged", &stack.trunk])
.current_dir(workdir)
.output()
.context("Failed to list merged branches")?;
let merged_output = String::from_utf8_lossy(&output.stdout);
for line in merged_output.lines() {
let branch = line.trim().trim_start_matches("* ");
// Skip trunk itself and any non-tracked branches
if branch == stack.trunk || branch.is_empty() {
continue;
}
// Only include branches we're tracking
if stack.branches.contains_key(branch) {
merged.push(branch.to_string());
}
}
// Method 1b: git branch --merged origin/trunk (handles stale/diverged local trunk)
let output = Command::new("git")
.args(["branch", "--merged", &remote_trunk_ref])
.current_dir(workdir)
.output();
if let Ok(output) = output {
let merged_output = String::from_utf8_lossy(&output.stdout);
for line in merged_output.lines() {
let branch = line.trim().trim_start_matches("* ");
// Skip trunk itself and any non-tracked branches
if branch == stack.trunk || branch.is_empty() {
continue;
}
// Only include branches we're tracking (and avoid duplicates)
if stack.branches.contains_key(branch) && !merged.iter().any(|b| b == branch) {
merged.push(branch.to_string());
}
}
}
// Method 2: Check PR state from metadata - if PR is merged, branch should be deleted
for (branch, info) in &stack.branches {
// Skip trunk
if branch == &stack.trunk {
continue;
}
// Skip if already in merged list
if merged.contains(branch) {
continue;
}
// Check if PR state is "merged" (case-insensitive)
if matches!(
info.pr_state.as_deref(),
Some(state) if state.eq_ignore_ascii_case("merged")
) {
merged.push(branch.clone());
}
}
// Method 3: Check if branch has empty diff against origin/trunk
// (catches squash/rebase merges and avoids local-trunk drift issues).
// First get list of local branches to avoid diffing non-existent branches
let local_output = Command::new("git")
.args(["branch", "--format=%(refname:short)"])
.current_dir(workdir)
.output()
.context("Failed to list local branches")?;
let local_branches: std::collections::HashSet<String> =
String::from_utf8_lossy(&local_output.stdout)
.lines()
.map(|s| s.trim().to_string())
.collect();
let diff_candidates: Vec<String> = stack
.branches
.keys()
.filter(|branch| {
*branch != &stack.trunk && !merged.contains(*branch) && local_branches.contains(*branch)
})
.cloned()
.collect();
let worker_count = std::thread::available_parallelism()
.map(|n| n.get().min(8))
.unwrap_or(1);
if worker_count <= 1 || diff_candidates.len() < 2 {
for branch in diff_candidates {
let diff_output = Command::new("git")
.args(["diff", "--quiet", &remote_trunk_ref, &branch])
.current_dir(workdir)
.stderr(std::process::Stdio::null())
.status();
if diff_output.map(|s| s.success()).unwrap_or(false) {
merged.push(branch);
}
}
} else {
let chunk_size = (diff_candidates.len() + worker_count - 1) / worker_count;
let mut handles = Vec::new();
for chunk in diff_candidates.chunks(chunk_size) {
let chunk_branches = chunk.to_vec();
let workdir = workdir.to_path_buf();
let remote_trunk_ref = remote_trunk_ref.clone();
handles.push(std::thread::spawn(move || {
let mut chunk_merged = Vec::new();
for branch in chunk_branches {
let diff_output = Command::new("git")
.args(["diff", "--quiet", &remote_trunk_ref, &branch])
.current_dir(&workdir)
.stderr(std::process::Stdio::null())
.status();
if diff_output.map(|s| s.success()).unwrap_or(false) {
chunk_merged.push(branch);
}
}
chunk_merged
}));
}
for handle in handles {
if let Ok(chunk_merged) = handle.join() {
merged.extend(chunk_merged);
}
}
}
// Method 4: Check if remote branch was deleted (GitHub deletes branch after merge)
// Get list of remote branches
let remote_output = Command::new("git")
.args(["branch", "-r", "--format=%(refname:short)"])
.current_dir(workdir)
.output()
.context("Failed to list remote branches")?;
let remote_branches: std::collections::HashSet<String> =
String::from_utf8_lossy(&remote_output.stdout)
.lines()
.map(|s| s.trim().to_string())
.collect();
for (branch, info) in &stack.branches {
// Skip trunk
if branch == &stack.trunk {
continue;
}
// Skip if already in merged list
if merged.contains(branch) {
continue;
}
// Only consider "remote deleted" if branch had a PR before (was pushed)
// This prevents false positives for branches that were never pushed
if info.pr_number.is_none() {
continue;
}
// Check if remote branch was deleted (strong signal it was merged)
let remote_ref = format!("{}/{}", remote_name, branch);
if !remote_branches.contains(&remote_ref) {
// Remote branch doesn't exist and had a PR - likely merged and deleted
merged.push(branch.clone());
}
}
// Method 5: Find orphaned branches (tracked but no longer exist locally or remotely)
// Reuse local_branches from Method 3, remote_branches from Method 4
for branch in stack.branches.keys() {
// Skip trunk
if branch == &stack.trunk {
continue;
}
// Skip if already in merged list
if merged.contains(branch) {
continue;
}
let local_exists = local_branches.contains(branch);
let remote_ref = format!("{}/{}", remote_name, branch);
let remote_exists = remote_branches.contains(&remote_ref);
// If branch doesn't exist locally AND doesn't exist remotely, it's orphaned
if !local_exists && !remote_exists {
merged.push(branch.clone());
}
}
Ok(merged)
}
fn find_upstream_gone_branches(workdir: &std::path::Path, trunk: &str) -> Result<Vec<String>> {
let output = Command::new("git")
.args([
"for-each-ref",
"--format=%(refname:short)%00%(upstream:short)%00%(upstream:track)",
"refs/heads",
])
.current_dir(workdir)
.output()
.context("Failed to list local branches with upstream tracking info")?;
let mut branches = std::collections::BTreeSet::new();
let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() {
let mut fields = line.split('\0');
let branch = fields.next().unwrap_or("").trim();
let _upstream = fields.next().unwrap_or("").trim();
let tracking = fields.next().unwrap_or("").trim();
if branch.is_empty() || branch == trunk {
continue;
}
if tracking.contains("[gone]") {
branches.insert(branch.to_string());
}
}
Ok(branches.into_iter().collect())
}
fn local_branch_exists(workdir: &std::path::Path, branch: &str) -> bool {
let local_ref = format!("refs/heads/{}", branch);
Command::new("git")
.args(["show-ref", "--verify", "--quiet", &local_ref])
.current_dir(workdir)
.status()
.map(|s| s.success())
.unwrap_or(false)
}
fn resolve_effective_parent(
workdir: &std::path::Path,
recorded_parent: &str,
trunk: &str,
) -> (String, Option<String>) {
if local_branch_exists(workdir, recorded_parent) {
return (recorded_parent.to_string(), None);
}
if recorded_parent != trunk && local_branch_exists(workdir, trunk) {
return (trunk.to_string(), Some(recorded_parent.to_string()));
}
(recorded_parent.to_string(), None)
}
/// Record CI history for merged branches before they are deleted
fn record_ci_history_for_merged(
repo: &GitRepo,
rt: &tokio::runtime::Runtime,
client: &GitHubClient,
merged_branches: &[String],
stack: &Stack,
quiet: bool,
) {
// Only process branches that still exist locally (can get their commit SHA)
let branches_to_check: Vec<String> = merged_branches
.iter()
.filter(|b| repo.branch_commit(b).is_ok())
.cloned()
.collect();
if branches_to_check.is_empty() {
return;
}
let ci_timer = LiveTimer::maybe_new(!quiet, "Record CI history");
// Fetch CI statuses for merged branches
match fetch_ci_statuses(repo, rt, client, stack, &branches_to_check) {
Ok(statuses) => {
record_ci_history(repo, &statuses);
LiveTimer::maybe_finish_timed(ci_timer);
}
Err(_) => {
LiveTimer::maybe_finish_warn(ci_timer, "skipped (couldn't fetch)");
}
}
}
fn format_duration(duration: Duration) -> String {
format!("{:.3}s", duration.as_secs_f64())
}