Skip to main content

git_stk/stack/
mod.rs

1//! Stack metadata: the `branch.<name>.stkParent`/`stkBase` annotations and
2//! the structural queries built on them. Navigation lives in [`nav`], the
3//! rebase engine in [`restack`].
4
5use std::collections::{BTreeMap, BTreeSet};
6
7use anyhow::{Result, bail};
8
9use crate::git;
10use crate::settings;
11use crate::style;
12
13mod nav;
14mod restack;
15
16pub use nav::{
17    behind_parent_hint, checkout_bottom, checkout_child, checkout_parent, checkout_top,
18    print_children, print_parent, print_stack,
19};
20pub use restack::{abort_restack, continue_restack, restack};
21
22const PARENT_KEY: &str = "stkParent";
23const BASE_KEY: &str = "stkBase";
24
25pub fn create_branch(branch: &str) -> Result<()> {
26    let parent = git::current_branch()?;
27    git::create_branch(branch)?;
28    set_parent(branch, &parent)?;
29    record_base(branch, &parent);
30    anstream::println!(
31        "created {} with parent {}",
32        style::branch(branch),
33        style::branch(&parent)
34    );
35    Ok(())
36}
37
38/// The trunk branch: the remote's default branch when known locally,
39/// otherwise a conventional name that exists.
40pub fn trunk_branch(branches: &[String]) -> Option<String> {
41    let remote = settings::remote().unwrap_or_else(|_| settings::DEFAULT_REMOTE.to_owned());
42    if let Some(default) = git::remote_default_branch(&remote) {
43        return Some(default);
44    }
45
46    ["main", "master"]
47        .iter()
48        .find(|name| branches.iter().any(|branch| branch == *name))
49        .map(|name| (*name).to_owned())
50}
51
52pub fn adopt_branch(branch: &str, parent: &str) -> Result<()> {
53    if branch == parent {
54        bail!("a branch cannot be its own stack parent");
55    }
56
57    let branches: BTreeSet<_> = git::local_branches()?.into_iter().collect();
58    if !branches.contains(branch) {
59        bail!("branch {branch} does not exist");
60    }
61    if !branches.contains(parent) {
62        bail!("parent branch {parent} does not exist");
63    }
64
65    set_parent(branch, parent)?;
66    record_base(branch, parent);
67    anstream::println!(
68        "attached {} to {}",
69        style::branch(branch),
70        style::branch(parent)
71    );
72    Ok(())
73}
74
75pub fn detach_branch(branch: Option<&str>) -> Result<()> {
76    let branch = branch
77        .map(str::to_owned)
78        .map_or_else(git::current_branch, Ok)?;
79    unset_parent(&branch)?;
80    unset_base(&branch)?;
81    anstream::println!("detached {}", style::branch(&branch));
82    Ok(())
83}
84
85/// Rename a branch and keep the stack intact. Git moves the branch's own
86/// metadata with the rename; children pointing at the old name are
87/// retargeted here.
88pub fn rename_branch(old: &str, new: &str) -> Result<()> {
89    let children = children_for_branch(old)?;
90    git::rename_branch(old, new)?;
91    anstream::println!("renamed {} -> {}", style::branch(old), style::branch(new));
92
93    for child in &children {
94        set_parent_for_branch(child, new)?;
95        anstream::println!(
96            "retargeted {} -> {}",
97            style::branch(child),
98            style::branch(new)
99        );
100    }
101    Ok(())
102}
103
104pub fn parent_for_branch(branch: &str) -> Result<Option<String>> {
105    parent_of(branch)
106}
107
108pub fn children_for_branch(branch: &str) -> Result<Vec<String>> {
109    children_of(branch)
110}
111
112pub fn set_parent_for_branch(branch: &str, parent: &str) -> Result<()> {
113    set_parent(branch, parent)
114}
115
116pub fn unset_parent_for_branch(branch: &str) -> Result<()> {
117    unset_parent(branch)
118}
119
120pub fn base_for_branch(branch: &str) -> Result<Option<String>> {
121    base_of(branch)
122}
123
124pub fn set_base_for_branch(branch: &str, base: &str) -> Result<()> {
125    git::config_set(&base_key(branch), base)
126}
127
128pub fn unset_base_for_branch(branch: &str) -> Result<()> {
129    unset_base(branch)
130}
131
132/// Record the fork point between a branch and its parent (best effort; e.g.
133/// unrelated histories have no merge base, which is not an error here).
134pub fn record_base(branch: &str, parent: &str) {
135    if let Ok(base) = git::merge_base(parent, branch) {
136        let _ = git::config_set(&base_key(branch), &base);
137    }
138}
139
140/// The root of the stack containing `branch` (the base everything sits on).
141pub fn stack_root(branch: &str) -> Result<String> {
142    let parents = parent_map()?;
143    Ok(root_for(branch, &parents))
144}
145
146pub fn branch_and_descendants(branch: &str) -> Result<Vec<String>> {
147    let parents = parent_map()?;
148    let children = children_map(&parents);
149    let mut branches = vec![branch.to_owned()];
150    collect_descendants(branch, &children, &mut branches);
151    Ok(branches)
152}
153
154/// (branch, parent) pairs for the branches that have a stack parent;
155/// branches without one are skipped.
156pub fn branch_parents(branches: &[String]) -> Result<Vec<(String, String)>> {
157    let mut pairs = Vec::new();
158    for branch in branches {
159        if let Some(parent) = parent_of(branch)? {
160            pairs.push((branch.clone(), parent));
161        }
162    }
163    Ok(pairs)
164}
165
166fn parent_map() -> Result<BTreeMap<String, String>> {
167    let mut parents = BTreeMap::new();
168    for branch in git::local_branches()? {
169        if let Some(parent) = parent_of(&branch)? {
170            parents.insert(branch, parent);
171        }
172    }
173    Ok(parents)
174}
175
176fn collect_descendants(
177    branch: &str,
178    children: &BTreeMap<String, Vec<String>>,
179    branches: &mut Vec<String>,
180) {
181    if let Some(branch_children) = children.get(branch) {
182        for child in branch_children {
183            branches.push(child.to_owned());
184            collect_descendants(child, children, branches);
185        }
186    }
187}
188
189fn children_of(parent: &str) -> Result<Vec<String>> {
190    Ok(parent_map()?
191        .into_iter()
192        .filter_map(|(branch, branch_parent)| (branch_parent == parent).then_some(branch))
193        .collect())
194}
195
196fn children_map(parents: &BTreeMap<String, String>) -> BTreeMap<String, Vec<String>> {
197    let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();
198    for (branch, parent) in parents {
199        children
200            .entry(parent.to_owned())
201            .or_default()
202            .push(branch.to_owned());
203    }
204    children
205}
206
207fn root_for(branch: &str, parents: &BTreeMap<String, String>) -> String {
208    let mut root = branch.to_owned();
209    let mut seen = BTreeSet::new();
210
211    while let Some(parent) = parents.get(&root) {
212        if !seen.insert(root.clone()) {
213            break;
214        }
215        root = parent.to_owned();
216    }
217
218    root
219}
220
221fn parent_of(branch: &str) -> Result<Option<String>> {
222    git::config_get(&parent_key(branch))
223}
224
225fn base_of(branch: &str) -> Result<Option<String>> {
226    git::config_get(&base_key(branch))
227}
228
229fn set_parent(branch: &str, parent: &str) -> Result<()> {
230    git::config_set(&parent_key(branch), parent)
231}
232
233fn unset_parent(branch: &str) -> Result<()> {
234    git::config_unset(&parent_key(branch))
235}
236
237fn unset_base(branch: &str) -> Result<()> {
238    git::config_unset(&base_key(branch))
239}
240
241fn parent_key(branch: &str) -> String {
242    format!("branch.{branch}.{PARENT_KEY}")
243}
244
245fn base_key(branch: &str) -> String {
246    format!("branch.{branch}.{BASE_KEY}")
247}