1use std::{
5 collections::{BTreeMap, BTreeSet},
6 fs,
7 path::{Path, PathBuf},
8};
9
10use anyhow::{Context, Result, bail};
11
12use super::{children_map, collect_descendants, fork_point, line_base, parent_map, record_base};
13use crate::cli::{FetchMode, PushMode, UpdateRefsMode};
14use crate::git;
15use crate::prompt;
16use crate::providers::detect_review_provider;
17use crate::settings;
18use crate::style;
19
20const STATE_FILE: &str = "stack-state";
21
22pub fn restack(
23 fetch_mode: FetchMode,
24 update_refs_mode: UpdateRefsMode,
25 push_mode: PushMode,
26 dry_run: bool,
27) -> Result<()> {
28 let current = git::current_branch()?;
29 let parents = parent_map()?;
30 let base = line_base(¤t)?;
36 let branches = restack_order(&base, &parents);
37
38 if branches.is_empty() {
39 anstream::println!("{}", style::dim("nothing to restack"));
40 return Ok(());
41 }
42
43 if settings::fetch_enabled(fetch_mode)? {
47 fetch_trunk(dry_run)?;
48 }
49 warn_bases_behind_remote(&branches, &parents)?;
50
51 let update_refs = resolve_update_refs(update_refs_mode)?;
52 let push = settings::push_enabled(push_mode, settings::PUSH_ON_RESTACK_KEY)?;
53 let frozen = with_frozen_ancestors(frozen_branches(&branches), &branches, &parents);
54
55 ensure_no_worktree_blocks(&branches, &parents, &frozen, &BTreeSet::new())?;
59
60 if dry_run {
61 reconcile_diverged_remotes(&branches, &frozen, push, true)?;
62 return print_restack_plan(&branches, &parents, &frozen, update_refs, push);
63 }
64
65 super::snapshot("restack");
66 reconcile_diverged_remotes(&branches, &frozen, push, false)?;
70 clear_state()?;
71 let all = branches.clone();
72 restack_branches(branches, &parents, &frozen, update_refs, push, &all)
73}
74
75fn frozen_branches(branches: &[String]) -> BTreeSet<String> {
81 let Ok((_, provider)) = detect_review_provider() else {
82 return BTreeSet::new();
83 };
84 provider.enqueued_branches(branches).unwrap_or_default()
85}
86
87fn with_frozen_ancestors(
94 queued: BTreeSet<String>,
95 branches: &[String],
96 parents: &BTreeMap<String, String>,
97) -> BTreeSet<String> {
98 let in_set: BTreeSet<&str> = branches.iter().map(String::as_str).collect();
99 let mut frozen = queued.clone();
100 for branch in &queued {
101 let mut current = branch.clone();
102 while let Some(parent) = parents.get(¤t) {
103 if !in_set.contains(parent.as_str()) || !frozen.insert(parent.clone()) {
106 break;
107 }
108 current = parent.clone();
109 }
110 }
111 frozen
112}
113
114fn frozen_note(branch: &str) -> String {
118 format!(
119 "{} {}: not rebased or pushed (a branch in this stack is in a merge queue; dequeue it to continue)",
120 style::warn("frozen"),
121 style::branch(branch),
122 )
123}
124
125fn print_restack_plan(
128 branches: &[String],
129 parents: &BTreeMap<String, String>,
130 frozen: &BTreeSet<String>,
131 update_refs: bool,
132 push: bool,
133) -> Result<()> {
134 for branch in branches {
135 if frozen.contains(branch) {
136 anstream::println!("{}", frozen_note(branch));
137 continue;
138 }
139
140 let Some(parent) = parents.get(branch) else {
141 bail!("{branch} has no stack parent");
142 };
143
144 if up_to_date(branch, parent)? {
145 anstream::println!(
146 "{} already up to date with {}",
147 style::branch(branch),
148 style::branch(parent)
149 );
150 } else {
151 anstream::println!(
152 "would rebase {} onto {}{}",
153 style::branch(branch),
154 style::branch(parent),
155 if update_refs {
156 " with --update-refs"
157 } else {
158 ""
159 }
160 );
161 }
162 }
163
164 if push {
165 let pushable: Vec<&str> = branches
166 .iter()
167 .filter(|branch| !frozen.contains(*branch))
168 .map(String::as_str)
169 .collect();
170 if pushable.is_empty() {
171 anstream::println!(
172 "{}",
173 style::dim("nothing to push: every branch is in a merge queue")
174 );
175 } else {
176 anstream::println!(
177 "would push {} to {}",
178 style::branch(&pushable.join(" ")),
179 settings::remote()?
180 );
181 }
182 }
183 Ok(())
184}
185
186fn ensure_no_worktree_blocks(
193 branches: &[String],
194 parents: &BTreeMap<String, String>,
195 frozen: &BTreeSet<String>,
196 already_moving: &BTreeSet<String>,
197) -> Result<()> {
198 let held = git::worktree_branches()?;
199 if held.is_empty() {
200 return Ok(());
201 }
202
203 let mut rebasing: BTreeSet<&str> = already_moving.iter().map(String::as_str).collect();
209 let mut blocked = Vec::new();
210 for branch in branches {
211 if frozen.contains(branch) {
212 continue;
213 }
214 let Some(parent) = parents.get(branch) else {
215 continue;
216 };
217 if !rebasing.contains(parent.as_str()) && up_to_date(branch, parent)? {
221 continue;
222 }
223 rebasing.insert(branch.as_str());
224 if let Some((_, path)) = held.iter().find(|(name, _)| name == branch) {
225 blocked.push((branch.clone(), path.clone()));
226 }
227 }
228
229 if blocked.is_empty() {
230 return Ok(());
231 }
232
233 let held_by = git::distinct_paths(blocked.iter().map(|(_, path)| path.as_path()));
238 let here_moves = git::current_branch()
239 .ok()
240 .is_some_and(|branch| rebasing.contains(branch.as_str()));
241 let delegate = match held_by.as_slice() {
242 [only] if !here_moves => Some(only.as_path()),
243 _ => None,
244 };
245
246 bail!(worktree_block_message(&blocked, &held_by, delegate));
247}
248
249fn worktree_block_message(
254 blocked: &[(String, PathBuf)],
255 held_by: &[PathBuf],
256 delegate: Option<&Path>,
257) -> String {
258 let mut message =
259 String::from("restack would rebase branches checked out in other worktrees:\n");
260 for (branch, path) in blocked {
261 message.push_str(&format!(" {branch} in {}\n", git::describe_worktree(path)));
262 }
263 message.push_str("git cannot rebase a branch another worktree holds. Free ");
264 message.push_str(if held_by.len() == 1 { "it" } else { "each one" });
265 message.push_str(" by detaching there:\n");
266 for path in held_by {
267 message.push_str(&format!(" {}\n", git::detach_command(path)));
268 }
269 message.push_str("then check ");
270 message.push_str(if blocked.len() == 1 {
271 "the branch"
272 } else {
273 "those branches"
274 });
275 message.push_str(" out again once the restack finishes");
276 if let Some(path) = delegate {
277 message.push_str(&format!(
278 ",\nor run the restack from {} instead",
279 git::display_path(path)
280 ));
281 }
282 message
283}
284
285fn up_to_date(branch: &str, parent: &str) -> Result<bool> {
287 let parent_tip = git::rev_parse(parent)?;
288 Ok(
289 fork_point(branch, parent)?.as_deref() == Some(parent_tip.as_str())
290 && git::is_ancestor(parent, branch).unwrap_or(false),
291 )
292}
293
294fn fetch_trunk(dry_run: bool) -> Result<()> {
299 let Some(trunk) = super::trunk_branch(&git::local_branches()?) else {
300 return Ok(());
301 };
302 let remote = settings::remote()?;
303 if git::remote_url(&remote)?.is_none() {
304 anstream::println!(
305 "{}",
306 style::dim(&format!("no remote {remote}; skipped fetch"))
307 );
308 return Ok(());
309 }
310 if super::trunk_held_elsewhere(&trunk)? {
311 return Ok(());
312 }
313
314 if dry_run {
315 anstream::println!("would fetch {} from {remote}", style::branch(&trunk));
316 return Ok(());
317 }
318 if git::current_branch()? == trunk {
319 git::pull_ff_only()?;
320 } else {
321 git::fetch_branch(&remote, &trunk)?;
322 }
323 anstream::println!("fetched {} from {remote}", style::branch(&trunk));
324 Ok(())
325}
326
327fn warn_bases_behind_remote(branches: &[String], parents: &BTreeMap<String, String>) -> Result<()> {
333 let remote = settings::remote()?;
334 if git::remote_url(&remote)?.is_none() {
335 return Ok(());
336 }
337
338 let in_stack: BTreeSet<&String> = branches.iter().collect();
339 let external: BTreeSet<&String> = branches
340 .iter()
341 .filter_map(|branch| parents.get(branch))
342 .filter(|parent| !in_stack.contains(parent))
343 .collect();
344
345 for base in external {
346 let tracking = format!("{remote}/{base}");
347 if git::rev_parse(&tracking).is_err() {
348 continue;
349 }
350 let behind = git::commits_behind(base, &tracking).unwrap_or(0);
351 if behind > 0 {
352 anstream::eprintln!(
353 "{}",
354 style::warn(&format!(
355 "{base} is {behind} commit{} behind {tracking}; run `git stk restack --fetch` or `git stk sync` to update it first",
356 if behind == 1 { "" } else { "s" }
357 ))
358 );
359 }
360 }
361 Ok(())
362}
363
364fn reconcile_diverged_remotes(
382 branches: &[String],
383 frozen: &BTreeSet<String>,
384 push: bool,
385 dry_run: bool,
386) -> Result<()> {
387 if !push {
388 return Ok(());
389 }
390 let remote = settings::remote()?;
391 if git::remote_url(&remote)?.is_none() {
392 return Ok(());
393 }
394
395 let pushable: Vec<String> = branches
398 .iter()
399 .filter(|branch| !frozen.contains(*branch))
400 .cloned()
401 .collect();
402 if pushable.is_empty() {
403 return Ok(());
404 }
405
406 if !dry_run {
411 git::fetch_tracking(&remote, &pushable)?;
412 }
413
414 let mut diverged: Vec<(String, Vec<(String, String)>)> = Vec::new();
415 for branch in &pushable {
416 let tracking = format!("{remote}/{branch}");
417 if git::rev_parse(&tracking).is_err() {
420 continue;
421 }
422 let extra = git::remote_only_commits(branch, &tracking)?;
423 if extra.is_empty() {
424 continue;
425 }
426 if git::merge_adds_nothing(branch, &tracking)? {
433 continue;
434 }
435 diverged.push((branch.clone(), extra));
436 }
437
438 if diverged.is_empty() {
439 return Ok(());
440 }
441
442 for (branch, commits) in &diverged {
443 anstream::eprintln!(
444 "{}",
445 style::warn(&format!(
446 "{remote}/{branch} has {} commit{} not in your local {branch}:",
447 commits.len(),
448 if commits.len() == 1 { "" } else { "s" },
449 ))
450 );
451 for (sha, subject) in commits {
452 anstream::eprintln!(" {} {subject}", style::dim(sha));
453 }
454 }
455
456 if dry_run {
457 anstream::println!(
458 "{}",
459 style::dim(
460 "would offer to cherry-pick these into your local branches before pushing, \
461 or to discard them and overwrite the remote",
462 )
463 );
464 return Ok(());
465 }
466
467 if !prompt::confirm("cherry-pick these into your local branches before pushing? [y/N] ")? {
468 if prompt::confirm("discard them and overwrite the remote branches instead? [y/N] ")? {
474 return Ok(());
475 }
476 bail!(
477 "remote branches have commits not in your local stack\n\
478 incorporate them (`git switch <branch> && git cherry-pick <sha>`) and re-run, \
479 or discard them with `git push --force-with-lease {remote} <branch>`"
480 );
481 }
482
483 let start = git::current_branch()?;
487 for (branch, commits) in &diverged {
488 git::checkout(branch)?;
489 for (sha, _) in commits {
490 if let Err(error) = git::cherry_pick(sha) {
491 anstream::eprintln!(
492 "{}",
493 style::warn(&format!("conflict cherry-picking {sha} onto {branch}"))
494 );
495 eprintln!("resolve conflicts, run `git cherry-pick --continue`, then re-run");
496 eprintln!("or run `git cherry-pick --abort` to bail out");
497 return Err(error);
498 }
499 }
500 }
501 git::checkout(&start)?;
502 anstream::println!(
503 "{}",
504 style::success(&format!(
505 "incorporated remote commits into {}",
506 diverged
507 .iter()
508 .map(|(branch, _)| branch.as_str())
509 .collect::<Vec<_>>()
510 .join(" ")
511 ))
512 );
513 Ok(())
514}
515
516pub fn continue_restack() -> Result<()> {
517 let Some(state) = RestackState::read()? else {
518 bail!("no interrupted restack found");
519 };
520
521 if !git::rebase_in_progress() {
525 clear_state()?;
526 bail!(
527 "no rebase is in progress, so there is nothing to continue\n\
528 cleared the leftover restack state; re-run `git stk restack` to pick up where it stopped"
529 );
530 }
531
532 ensure_no_worktree_blocks(
533 &state.remaining,
534 &parent_map()?,
535 &state.frozen.iter().cloned().collect(),
536 &BTreeSet::from([state.branch.clone()]),
537 )?;
538
539 if let Err(error) = git::rebase_continue() {
540 anstream::eprintln!("{}", style::warn("restack still has conflicts"));
541 eprintln!("resolve conflicts, then run `git stk continue`");
542 eprintln!("or run `git stk abort`");
543 return Err(error);
544 }
545
546 record_base(&state.branch, &state.parent);
547
548 let frozen: BTreeSet<String> = state.frozen.iter().cloned().collect();
549 if state.remaining.is_empty() {
550 clear_state()?;
551 finish_restack(&state.all, &frozen, state.push)?;
552 return Ok(());
553 }
554
555 let parents = parent_map()?;
556 restack_branches(
557 state.remaining,
558 &parents,
559 &frozen,
560 state.update_refs,
561 state.push,
562 &state.all,
563 )
564}
565
566pub fn abort_restack() -> Result<()> {
567 if !git::rebase_in_progress() {
570 if RestackState::read()?.is_none() {
571 bail!("no restack to abort");
572 }
573 clear_state()?;
574 anstream::println!("cleared leftover restack state; no rebase was in progress");
575 return Ok(());
576 }
577
578 git::rebase_abort()?;
579 clear_state()?;
580 anstream::println!("restack aborted");
581 Ok(())
582}
583
584fn restack_order(current: &str, parents: &BTreeMap<String, String>) -> Vec<String> {
585 let children = children_map(parents);
586 let mut branches = Vec::new();
587
588 if parents.contains_key(current) {
589 branches.push(current.to_owned());
590 }
591
592 let mut visited = BTreeSet::from([current.to_owned()]);
593 collect_descendants(current, &children, &mut branches, &mut visited);
594 branches
595}
596
597fn restack_branches(
598 branches: Vec<String>,
599 parents: &BTreeMap<String, String>,
600 frozen: &BTreeSet<String>,
601 update_refs: bool,
602 push: bool,
603 all: &[String],
604) -> Result<()> {
605 for (index, branch) in branches.iter().enumerate() {
606 if frozen.contains(branch) {
607 anstream::println!("{}", frozen_note(branch));
608 continue;
609 }
610
611 let Some(parent) = parents.get(branch) else {
612 bail!("{branch} has no stack parent");
613 };
614
615 let base = fork_point(branch, parent)?;
620
621 if up_to_date(branch, parent)? {
625 anstream::println!(
626 "{} already up to date with {}",
627 style::branch(branch),
628 style::branch(parent)
629 );
630 continue;
631 }
632
633 if update_refs {
634 anstream::println!(
635 "rebasing {} onto {} with --update-refs",
636 style::branch(branch),
637 style::branch(parent)
638 );
639 } else {
640 anstream::println!(
641 "rebasing {} onto {}",
642 style::branch(branch),
643 style::branch(parent)
644 );
645 }
646 let rebase_result = match &base {
647 Some(base) => git::rebase_onto(parent, base, branch, update_refs),
648 None => git::rebase(parent, branch, update_refs),
649 };
650
651 if let Err(error) = rebase_result {
652 if !git::rebase_in_progress() {
656 return Err(error);
657 }
658
659 let remaining = branches[index + 1..].to_vec();
660 RestackState {
661 branch: branch.to_owned(),
662 parent: parent.to_owned(),
663 remaining,
664 update_refs,
665 push,
666 all: all.to_vec(),
667 frozen: frozen.iter().cloned().collect(),
668 }
669 .write()?;
670
671 anstream::eprintln!(
672 "{}",
673 style::warn(&format!("conflict while rebasing {branch} onto {parent}"))
674 );
675 eprintln!("resolve conflicts, then run `git stk continue`");
676 eprintln!("or run `git stk abort`");
677 return Err(error);
678 }
679
680 record_base(branch, parent);
681 }
682
683 clear_state()?;
684 finish_restack(all, frozen, push)
685}
686
687fn finish_restack(branches: &[String], frozen: &BTreeSet<String>, push: bool) -> Result<()> {
693 anstream::println!("{}", style::success("restack complete"));
694
695 let remote = settings::remote()?;
696 let pushable: Vec<String> = branches
697 .iter()
698 .filter(|branch| !frozen.contains(*branch))
699 .cloned()
700 .collect();
701 if pushable.is_empty() {
702 anstream::println!(
703 "{}",
704 style::dim("nothing to push: every branch is in a merge queue")
705 );
706 return Ok(());
707 }
708
709 if push {
710 let pushed = git::push_force_with_lease(&remote, &pushable)?;
714 if pushed.is_empty() {
715 anstream::println!(
716 "{}",
717 style::dim("nothing pushed: every branch is in a merge queue")
718 );
719 } else {
720 anstream::println!("pushed {} to {remote}", style::branch(&pushed.join(" ")));
721 super::publish_metadata(&remote);
723 }
724 } else {
725 anstream::println!("remote branches may be stale; push them with:");
726 anstream::println!(
727 "{}",
728 style::dim(&format!(
729 " git push --force-with-lease {remote} {}",
730 pushable.join(" ")
731 ))
732 );
733 }
734 Ok(())
735}
736
737fn resolve_update_refs(mode: UpdateRefsMode) -> Result<bool> {
738 match mode {
739 UpdateRefsMode::Config => {
740 let configured = git::config_get_bool(settings::UPDATE_REFS_KEY)?.unwrap_or(false);
741 if configured && !git::supports_rebase_update_refs()? {
742 eprintln!("stk.updateRefs is true, but this Git does not support --update-refs");
743 return Ok(false);
744 }
745 Ok(configured)
746 }
747 UpdateRefsMode::Enabled => {
748 if !git::supports_rebase_update_refs()? {
749 bail!("--update-refs was requested, but this Git does not support it");
750 }
751 Ok(true)
752 }
753 UpdateRefsMode::Disabled => Ok(false),
754 }
755}
756
757#[derive(Debug, Eq, PartialEq)]
758struct RestackState {
759 branch: String,
760 parent: String,
761 remaining: Vec<String>,
762 update_refs: bool,
763 push: bool,
764 all: Vec<String>,
767 frozen: Vec<String>,
770}
771
772impl RestackState {
773 fn read() -> Result<Option<Self>> {
774 let path = state_path()?;
775 if !path.exists() {
776 return Ok(None);
777 }
778
779 let contents = fs::read_to_string(&path)
780 .with_context(|| format!("failed to read {}", path.display()))?;
781 let mut branch = None;
782 let mut parent = None;
783 let mut remaining = Vec::new();
784 let mut update_refs = false;
785 let mut push = false;
786 let mut all = Vec::new();
787 let mut frozen = Vec::new();
788
789 for line in contents.lines() {
790 if let Some(value) = line.strip_prefix("branch=") {
791 branch = Some(value.to_owned());
792 } else if let Some(value) = line.strip_prefix("parent=") {
793 parent = Some(value.to_owned());
794 } else if let Some(value) = line.strip_prefix("updateRefs=") {
795 update_refs = value == "true";
796 } else if let Some(value) = line.strip_prefix("push=") {
797 push = value == "true";
798 } else if let Some(value) = line.strip_prefix("remaining=") {
799 remaining = value
800 .split('\t')
801 .filter(|branch| !branch.is_empty())
802 .map(str::to_owned)
803 .collect();
804 } else if let Some(value) = line.strip_prefix("all=") {
805 all = value
806 .split('\t')
807 .filter(|branch| !branch.is_empty())
808 .map(str::to_owned)
809 .collect();
810 } else if let Some(value) = line.strip_prefix("frozen=") {
811 frozen = value
812 .split('\t')
813 .filter(|branch| !branch.is_empty())
814 .map(str::to_owned)
815 .collect();
816 }
817 }
818
819 let Some(branch) = branch else {
820 bail!("restack state is missing current branch");
821 };
822 let Some(parent) = parent else {
823 bail!("restack state is missing parent branch");
824 };
825
826 Ok(Some(Self {
827 branch,
828 parent,
829 remaining,
830 update_refs,
831 push,
832 all,
833 frozen,
834 }))
835 }
836
837 fn write(&self) -> Result<()> {
838 let path = state_path()?;
839 let contents = format!(
840 "branch={}\nparent={}\nupdateRefs={}\npush={}\nremaining={}\nall={}\nfrozen={}\n",
841 self.branch,
842 self.parent,
843 self.update_refs,
844 self.push,
845 self.remaining.join("\t"),
846 self.all.join("\t"),
847 self.frozen.join("\t")
848 );
849 fs::write(&path, contents).with_context(|| format!("failed to write {}", path.display()))
850 }
851}
852
853fn clear_state() -> Result<()> {
854 let path = state_path()?;
855 if path.exists() {
856 fs::remove_file(&path).with_context(|| format!("failed to remove {}", path.display()))?;
857 }
858 Ok(())
859}
860
861fn state_path() -> Result<PathBuf> {
862 Ok(PathBuf::from(git::git_path(STATE_FILE)?))
863}
864
865pub(super) fn in_progress() -> bool {
870 state_path().map(|path| path.exists()).unwrap_or(false) && git::rebase_in_progress()
871}
872
873#[cfg(test)]
874mod tests {
875 use super::*;
876
877 fn linear_parents() -> BTreeMap<String, String> {
880 BTreeMap::from([
881 ("a".to_owned(), "main".to_owned()),
882 ("b".to_owned(), "a".to_owned()),
883 ("c".to_owned(), "b".to_owned()),
884 ])
885 }
886
887 fn set(branches: &[&str]) -> BTreeSet<String> {
888 branches.iter().map(|b| (*b).to_owned()).collect()
889 }
890
891 #[test]
892 fn a_queued_middle_branch_freezes_everything_below_it() {
893 let branches = vec!["a".to_owned(), "b".to_owned(), "c".to_owned()];
896 let frozen = with_frozen_ancestors(set(&["b"]), &branches, &linear_parents());
897 assert_eq!(frozen, set(&["a", "b"]));
898 }
899
900 #[test]
901 fn a_queued_bottom_branch_freezes_only_itself() {
902 let branches = vec!["a".to_owned(), "b".to_owned(), "c".to_owned()];
905 let frozen = with_frozen_ancestors(set(&["a"]), &branches, &linear_parents());
906 assert_eq!(frozen, set(&["a"]));
907 }
908
909 #[test]
910 fn freeze_stops_at_the_line_base_not_the_trunk() {
911 let branches = vec!["b".to_owned(), "c".to_owned()];
914 let frozen = with_frozen_ancestors(set(&["c"]), &branches, &linear_parents());
915 assert_eq!(frozen, set(&["b", "c"]));
916 }
917
918 #[test]
919 fn nothing_queued_freezes_nothing() {
920 let branches = vec!["a".to_owned(), "b".to_owned(), "c".to_owned()];
921 let frozen = with_frozen_ancestors(BTreeSet::new(), &branches, &linear_parents());
922 assert!(frozen.is_empty());
923 }
924}