1use std::collections::{BTreeMap, BTreeSet};
4
5use anyhow::{Result, bail};
6
7use super::{
8 branch_and_descendants, children_map, children_of, parent_map, parent_of, root_for,
9 trunk_branch,
10};
11use crate::git;
12use crate::prompt;
13use crate::style;
14
15fn pick_child(title: &str, children: &[String]) -> anyhow::Result<Option<String>> {
18 let painted: Vec<String> = children
19 .iter()
20 .map(|child| style::paint(style::BRANCH, child))
21 .collect();
22 Ok(prompt::pick(title, &painted)?.map(|index| children[index].clone()))
23}
24
25pub fn print_parent(branch: Option<&str>) -> Result<()> {
26 let branch = branch
27 .map(str::to_owned)
28 .map_or_else(git::current_branch, Ok)?;
29 match parent_of(&branch)? {
30 Some(parent) => println!("{parent}"),
31 None => bail!("{branch} has no stack parent"),
32 }
33 Ok(())
34}
35
36pub fn print_children(branch: Option<&str>) -> Result<()> {
37 let branch = branch
38 .map(str::to_owned)
39 .map_or_else(git::current_branch, Ok)?;
40 for child in children_of(&branch)? {
41 println!("{child}");
42 }
43 Ok(())
44}
45
46pub fn checkout_parent() -> Result<()> {
47 let current = git::current_branch()?;
48 let Some(parent) = parent_of(¤t)? else {
49 bail!("{current} has no stack parent");
50 };
51
52 git::checkout(&parent)
53}
54
55pub fn checkout_child(branch: Option<&str>) -> Result<()> {
56 let current = git::current_branch()?;
57 let children = children_of(¤t)?;
58 let child = match (branch, children.as_slice()) {
59 (Some(branch), _) => {
60 if children.iter().any(|child| child == branch) {
61 branch.to_owned()
62 } else {
63 bail!("{branch} is not a stack child of {current}");
64 }
65 }
66 (None, [child]) => child.to_owned(),
67 (None, []) => bail!("{current} has no stack children"),
68 (None, _) => {
69 match pick_child(
70 &format!("{current} has multiple stack children:"),
71 &children,
72 )? {
73 Some(child) => child,
74 None => bail!("choose one with `git stk up <branch>`"),
75 }
76 }
77 };
78
79 git::checkout(&child)
80}
81
82pub fn checkout_top() -> Result<()> {
85 let current = git::current_branch()?;
86 let mut top = current.clone();
87 loop {
88 let children = children_of(&top)?;
89 match children.as_slice() {
90 [] => break,
91 [child] => top = child.clone(),
92 _ => match pick_child(&format!("{top} has multiple stack children:"), &children)? {
94 Some(child) => top = child,
95 None => bail!("walk up from {top} with `git stk up <branch>`"),
96 },
97 }
98 }
99
100 if top == current {
101 if children_of(¤t)?.is_empty() && parent_of(¤t)?.is_none() {
102 bail!("{current} is not in a stack");
103 }
104 anstream::println!("{current} is already at the top of the stack");
105 return Ok(());
106 }
107 git::checkout(&top)
108}
109
110pub fn checkout_bottom() -> Result<()> {
113 let current = git::current_branch()?;
114 let trunk = trunk_branch(&git::local_branches()?);
115
116 let bottom = if Some(¤t) == trunk.as_ref() {
117 let children = children_of(¤t)?;
118 match children.as_slice() {
119 [child] => child.clone(),
120 [] => bail!("{current} has no stacked branches"),
121 _ => {
122 match pick_child(
123 &format!("{current} has multiple stack children:"),
124 &children,
125 )? {
126 Some(child) => child,
127 None => bail!("choose one with `git stk up <branch>`"),
128 }
129 }
130 }
131 } else {
132 let mut bottom = current.clone();
133 while let Some(parent) = parent_of(&bottom)? {
134 if Some(&parent) == trunk.as_ref() {
135 break;
136 }
137 bottom = parent;
138 }
139 bottom
140 };
141
142 if bottom == current {
143 if parent_of(¤t)?.is_none() && children_of(¤t)?.is_empty() {
144 bail!("{current} is not in a stack");
145 }
146 anstream::println!("{current} is already at the bottom of the stack");
147 return Ok(());
148 }
149 git::checkout(&bottom)
150}
151
152pub fn print_stack(reviews: &BTreeMap<String, String>) -> Result<()> {
153 let current = git::current_branch()?;
154 let parents = parent_map()?;
155 let root = root_for(¤t, &parents);
156 let children = children_map(&parents);
157 let trunk = trunk_branch(&git::local_branches()?);
158
159 let descendants = branch_and_descendants(&root)?;
160 let sizes = diff_sizes(descendants.iter().cloned(), &parents);
161 let ctx = TreeCtx {
162 current: ¤t,
163 trunk: trunk.as_deref(),
164 children: &children,
165 reviews,
166 sizes: &sizes,
167 };
168 let mut lines = Vec::new();
169 collect_tree_lines(&ctx, &root, 0, &mut BTreeSet::new(), &mut lines);
170
171 for line in lines.iter().rev() {
174 anstream::println!("{line}");
175 }
176
177 for branch in &descendants {
178 if let Some(parent) = parents.get(branch)
179 && let Some(hint) = behind_parent_hint(branch, parent)
180 {
181 anstream::println!("{} {hint}", style::paint(style::HINT, "hint:"));
182 }
183 }
184 Ok(())
185}
186
187pub fn print_all_stacks(reviews: &BTreeMap<String, String>) -> Result<()> {
191 let current = git::current_branch()?;
192 let parents = parent_map()?;
193 let children = children_map(&parents);
194 let trunk = trunk_branch(&git::local_branches()?);
195
196 let mut roots = Vec::new();
201 let mut seen = BTreeSet::new();
202 for branch in parents
203 .iter()
204 .flat_map(|(child, parent)| [child.clone(), parent.clone()])
205 {
206 let root = root_for(&branch, &parents);
207 if seen.insert(root.clone()) {
208 roots.push(root);
209 }
210 }
211
212 if roots.is_empty() {
213 anstream::println!("no stacked branches");
214 return Ok(());
215 }
216
217 roots.sort_by_key(|root| Some(root.as_str()) == trunk.as_deref());
220
221 let sizes = diff_sizes(parents.keys().cloned(), &parents);
222 let ctx = TreeCtx {
223 current: ¤t,
224 trunk: trunk.as_deref(),
225 children: &children,
226 reviews,
227 sizes: &sizes,
228 };
229 for (index, root) in roots.iter().enumerate() {
230 if index > 0 {
231 anstream::println!();
232 }
233 let mut lines = Vec::new();
234 collect_tree_lines(&ctx, root, 0, &mut BTreeSet::new(), &mut lines);
235 for line in lines.iter().rev() {
236 anstream::println!("{line}");
237 }
238 }
239
240 for (branch, parent) in &parents {
242 if let Some(hint) = behind_parent_hint(branch, parent) {
243 anstream::println!("{} {hint}", style::paint(style::HINT, "hint:"));
244 }
245 }
246 Ok(())
247}
248
249pub fn behind_parent_hint(branch: &str, parent: &str) -> Option<String> {
252 let behind = git::commits_behind(branch, parent)
253 .ok()
254 .filter(|count| *count > 0)?;
255 Some(format!(
256 "{branch} is {behind} commit{} behind {parent} - run `git stk restack`",
257 if behind == 1 { "" } else { "s" }
258 ))
259}
260
261struct TreeCtx<'a> {
264 current: &'a str,
265 trunk: Option<&'a str>,
266 children: &'a BTreeMap<String, Vec<String>>,
267 reviews: &'a BTreeMap<String, String>,
268 sizes: &'a BTreeMap<String, (usize, usize)>,
269}
270
271fn diff_sizes(
275 branches: impl IntoIterator<Item = String>,
276 parents: &BTreeMap<String, String>,
277) -> BTreeMap<String, (usize, usize)> {
278 let mut sizes = BTreeMap::new();
279 for branch in branches {
280 if let Some(parent) = parents.get(&branch)
281 && let Ok(size) = git::diff_numstat(parent, &branch)
282 {
283 sizes.insert(branch, size);
284 }
285 }
286 sizes
287}
288
289fn collect_tree_lines(
290 ctx: &TreeCtx,
291 branch: &str,
292 depth: usize,
293 seen: &mut BTreeSet<String>,
294 lines: &mut Vec<String>,
295) {
296 let mut line = " ".repeat(depth);
298 if branch == ctx.current {
299 line.push_str(&style::paint(style::CURRENT, &format!("\u{25c9} {branch}")));
300 } else {
301 line.push_str("\u{25cb} ");
302 line.push_str(&style::paint(style::BRANCH, branch));
303 }
304 if Some(branch) == ctx.trunk {
305 line.push_str(&style::paint(style::DIM, " (trunk)"));
306 }
307 let mut tags: Vec<String> = Vec::new();
310 if let Some(id) = ctx.reviews.get(branch) {
311 tags.push(style::paint(style::DIM, id));
312 }
313 if let Some((added, deleted)) = ctx.sizes.get(branch)
316 && (*added > 0 || *deleted > 0)
317 {
318 tags.push(format!(
319 "{}{}{}",
320 style::paint(style::ADDED, &format!("+{added}")),
321 style::paint(style::DIM, "/"),
322 style::paint(style::REMOVED, &format!("-{deleted}")),
323 ));
324 }
325 if !tags.is_empty() {
326 let separator = style::paint(style::DIM, ", ");
327 line.push_str(&style::paint(style::DIM, " ("));
328 line.push_str(&tags.join(&separator));
329 line.push_str(&style::paint(style::DIM, ")"));
330 }
331 lines.push(line);
332
333 if !seen.insert(branch.to_owned()) {
334 lines.push(format!("{}<cycle detected>", " ".repeat(depth + 1)));
335 return;
336 }
337
338 if let Some(branch_children) = ctx.children.get(branch) {
339 for child in branch_children {
340 collect_tree_lines(ctx, child, depth + 1, seen, lines);
341 }
342 }
343}