workon/stack.rs
1//! Stacked diff workflow support.
2//!
3//! This module provides the infrastructure for detecting and interacting with
4//! stacked-diff tools alongside git-workon's worktree management.
5//!
6//! ## Model
7//!
8//! Stack awareness is two-dimensional:
9//!
10//! - [`StackModel`] — which tool manages stacks (v1: Graphite, and metadata-less git-inference
11//! via [`StackModel::Git`]; future: branchless, sapling, spr)
12//! - [`Granularity`] — how worktrees map to stacks (v1: [`Granularity::Stack`], one per stack)
13//!
14//! ## Default-on behavior
15//!
16//! When `workon.stackModel` resolves to anything other than [`StackModel::None`] (by explicit
17//! config or auto-detection), every command that has a meaningful stack-aware variant uses it
18//! by default. A `--no-stack` CLI flag (global across subcommands) downgrades any single
19//! invocation back to branch-flat behavior.
20//!
21//! ## Graphite (v1)
22//!
23//! Stack metadata is read directly from `refs/branch-metadata/*` git refs — blobs containing
24//! JSON written by the `gt` CLI. No `gt` process is needed for detection or visualization.
25//! `gt track` is invoked only when registering a new branch (in `workon new` when creating a
26//! fork off a stack-worktree's branch).
27//!
28//! ## Git-inference (v1)
29//!
30//! [`StackModel::Git`] covers repositories with no stack tool at all: [`enumerate_stacks`] and
31//! [`current_stack`] treat it exactly like [`StackModel::None`] (no branch-level topology to
32//! report), but [`crate::assemble_changesets`] gives it meaning by walking `upstream..HEAD`,
33//! emitting one changeset per commit. It exists purely as an assembly-time model — see
34//! [`StackModel::detect`] for why it is never auto-detected.
35//!
36//! ## Cross-worktree grouping
37//!
38//! [`group_by_stack`] partitions a parallel slice of [`Option<Stack>`] values (one per worktree)
39//! into [`StackGrouping`]: a list of [`StackGroup`]s (each covering one connected stack) plus an
40//! `ungrouped` list for trunk/untracked worktrees. The grouping key is `(trunk, sorted diff
41//! set)`, so two worktrees in the same connected stack always collapse into one group regardless
42//! of the [`Stack::diffs`] vector order returned by [`current_stack`].
43
44pub(crate) mod graphite;
45
46use std::collections::{BTreeMap, HashMap};
47
48use git2::Repository;
49
50use crate::error::Result;
51
52/// Which stacked-diff tool is managing stacks in this repository.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum StackModel {
55 /// No stack tool; today's branch-flat behavior.
56 None,
57 /// Graphite (`gt`) manages stacks via `refs/branch-metadata/*`.
58 Graphite,
59 /// No stack-metadata tool; changesets are inferred purely from git, one per commit in
60 /// `upstream..HEAD`. Unlike [`StackModel::Graphite`], this carries no branch-level stack
61 /// topology: [`enumerate_stacks`] and [`current_stack`] treat it as flat (same as
62 /// [`StackModel::None`]), since there is no metadata to enumerate stacks from or to
63 /// group branches into. Only [`crate::assemble_changesets`] (M1 changeset assembly)
64 /// gives this variant meaning, walking `upstream..HEAD` per-commit.
65 ///
66 /// Not reachable via [`StackModel::detect`] — see the module docs' Default-on-behavior
67 /// note on why auto-detection never resolves to `Git`.
68 Git,
69}
70
71impl StackModel {
72 /// Auto-detect the active stack model from the repository environment.
73 ///
74 /// Returns [`StackModel::Graphite`] when `gt` is on PATH **and** the repo has been
75 /// initialized with `gt init` (`.graphite_repo_config` exists). Otherwise returns
76 /// [`StackModel::None`].
77 ///
78 /// Never returns [`StackModel::Git`]: auto-detection only distinguishes "a stack tool is
79 /// active" from "no stack tool," since CLI routing treats any non-`None` model as
80 /// stack-active. Auto-resolving to `Git` for every repository with an upstream-tracking
81 /// branch would silently flip that routing for nearly every user. `Git` is reachable via
82 /// explicit `workon.stackModel = git` config, or a caller mapping `None` to `Git` before
83 /// calling [`crate::assemble_changesets`] (the review crate does this from M3 onward).
84 pub fn detect(repo: &Repository) -> Self {
85 if graphite::detect_gt() && graphite::is_graphite_repo(repo) {
86 Self::Graphite
87 } else {
88 Self::None
89 }
90 }
91}
92
93/// How worktrees map to stacks.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum Granularity {
96 /// One worktree hosts an entire stack. The user navigates between branches inside it
97 /// using the stack tool's own commands (e.g. `gt up` / `gt down`).
98 Stack,
99}
100
101/// A stack of branches rooted at a trunk branch.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct Stack {
104 /// The trunk branch this stack is rooted on (e.g., `"main"`).
105 pub trunk: String,
106 /// All non-trunk diffs (branches) in the stack, in BFS order from bottom to top.
107 pub diffs: Vec<String>,
108 /// The branch that is currently HEAD in the worktree.
109 pub current: String,
110 /// Parent map for the diffs in this stack: `diff → parent_branch`.
111 ///
112 /// The parent may be another diff or the trunk itself. Only covers diffs in
113 /// [`Stack::diffs`]; the trunk's own parent is not recorded. Used to reconstruct
114 /// the branching tree structure (a flat [`diffs`] list cannot represent forks).
115 pub parents: HashMap<String, String>,
116}
117
118/// Return all stacks present in metadata, one per connected component.
119///
120/// Each returned [`Stack`] corresponds to one potential [`StackGroup`] — the same `(trunk,
121/// sorted diffs)` key used by [`group_by_stack`]. Used by the `list` command to surface
122/// stacks that have no checked-out worktrees.
123pub fn enumerate_stacks(repo: &Repository, model: StackModel) -> Result<Vec<Stack>> {
124 match model {
125 StackModel::None => Ok(vec![]),
126 StackModel::Graphite => graphite::enumerate_stacks(repo).map_err(Into::into),
127 // Git-inference has no branch-level stack topology to enumerate — flat, like None.
128 StackModel::Git => Ok(vec![]),
129 }
130}
131
132/// Return the stack for the worktree whose HEAD is `head_branch`, or `None` if the branch
133/// is not part of a tracked stack under `model`.
134///
135/// The returned [`Stack`] includes all branches reachable from the same stack root, not just
136/// the ancestors of `head_branch`, so branching stacks are fully represented.
137pub fn current_stack(
138 repo: &Repository,
139 head_branch: &str,
140 model: StackModel,
141) -> Result<Option<Stack>> {
142 match model {
143 StackModel::None => Ok(None),
144 StackModel::Graphite => graphite::current_stack(repo, head_branch).map_err(Into::into),
145 // Git-inference has no branch-level stack topology — flat, like None.
146 StackModel::Git => Ok(None),
147 }
148}
149
150/// Returns `true` if `gt` is on PATH and this repository has been Graphite-initialized.
151pub fn is_graphite_active(repo: &Repository) -> bool {
152 graphite::detect_gt() && graphite::is_graphite_repo(repo)
153}
154
155/// Return the first trunk branch name from `.graphite_repo_config`, or `None` if
156/// the file is missing, unparseable, or contains no trunk entries.
157///
158/// Use this when you need to pass `--parent <trunk>` to `gt track` and want to
159/// avoid hardcoding `"main"`. Returns `None` rather than a hardcoded fallback so
160/// callers can omit `--parent` entirely and let `gt` infer when the trunk is unknown.
161pub fn graphite_trunk(repo: &Repository) -> Option<String> {
162 graphite::graphite_trunk(repo)
163}
164
165/// One group of worktrees that share a connected stack, identified by trunk + diff set.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct StackGroup {
168 /// Representative stack (trunk + diffs in BFS bottom→top order) for the group.
169 pub stack: Stack,
170 /// Indices into the caller's worktree slice for members of this stack, ordered by
171 /// the member branch's position in `stack.diffs` (bottom→top). Members whose
172 /// branch isn't found in `stack.diffs` sort last, in original input order.
173 pub members: Vec<usize>,
174}
175
176/// Result of partitioning a worktree slice by stacks via [`group_by_stack`].
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct StackGrouping {
179 /// Groups of worktrees sharing a connected stack, ordered by `(trunk, sorted branch set)`.
180 pub groups: Vec<StackGroup>,
181 /// Indices of worktrees with no stack (trunk branches, untracked branches), in input order.
182 pub ungrouped: Vec<usize>,
183}
184
185/// Partition a slice of optional stack descriptors into groups sharing the same connected stack.
186///
187/// The grouping key is `(trunk, sorted diff set)`, so worktrees in the same connected stack
188/// always collapse into one group regardless of the [`Stack::diffs`] vector order returned
189/// by [`current_stack`]. Members within each group are ordered by their branch's position in
190/// the representative stack's `diffs` list (bottom→top).
191///
192/// Groups are returned in deterministic order: sorted by `(trunk, sorted branch set)`.
193///
194/// When all entries are `None` (stack model inactive or `--no-stack`), `groups` is empty and
195/// every index appears in `ungrouped` — callers get identical flat-list behavior.
196pub fn group_by_stack(stacks: &[Option<Stack>]) -> StackGrouping {
197 // BTreeMap provides sorted iteration: (trunk, branch_set) order automatically.
198 let mut map: BTreeMap<(String, Vec<String>), (Stack, Vec<usize>)> = BTreeMap::new();
199 let mut ungrouped: Vec<usize> = Vec::new();
200
201 for (i, opt) in stacks.iter().enumerate() {
202 match opt {
203 None => ungrouped.push(i),
204 Some(stack) => {
205 let mut key_branches = stack.diffs.clone();
206 key_branches.sort();
207 let key = (stack.trunk.clone(), key_branches);
208 let entry = map
209 .entry(key)
210 .or_insert_with(|| (stack.clone(), Vec::new()));
211 entry.1.push(i);
212 }
213 }
214 }
215
216 let groups = map
217 .into_values()
218 .map(|(rep_stack, mut members)| {
219 // Sort members by their branch's position in rep_stack.diffs (bottom→top).
220 members.sort_by_key(|&idx| {
221 let branch = stacks[idx]
222 .as_ref()
223 .map(|s| s.current.as_str())
224 .unwrap_or("");
225 rep_stack
226 .diffs
227 .iter()
228 .position(|b| b == branch)
229 .unwrap_or(usize::MAX)
230 });
231 StackGroup {
232 stack: rep_stack,
233 members,
234 }
235 })
236 .collect();
237
238 StackGrouping { groups, ungrouped }
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 fn stack(trunk: &str, diffs: &[&str], current: &str) -> Stack {
246 Stack {
247 trunk: trunk.to_string(),
248 diffs: diffs.iter().map(|s| s.to_string()).collect(),
249 current: current.to_string(),
250 parents: HashMap::new(),
251 }
252 }
253
254 #[test]
255 fn empty_input_yields_empty_grouping() {
256 let result = group_by_stack(&[]);
257 assert!(result.groups.is_empty());
258 assert!(result.ungrouped.is_empty());
259 }
260
261 #[test]
262 fn all_none_yields_all_ungrouped() {
263 let stacks: Vec<Option<Stack>> = vec![None, None, None];
264 let result = group_by_stack(&stacks);
265 assert!(result.groups.is_empty());
266 assert_eq!(result.ungrouped, vec![0, 1, 2]);
267 }
268
269 #[test]
270 fn single_stacked_worktree_forms_one_group() {
271 let stacks = vec![Some(stack("main", &["feat-a"], "feat-a"))];
272 let result = group_by_stack(&stacks);
273 assert!(result.ungrouped.is_empty());
274 assert_eq!(result.groups.len(), 1);
275 assert_eq!(result.groups[0].members, vec![0]);
276 assert_eq!(result.groups[0].stack.trunk, "main");
277 }
278
279 #[test]
280 fn two_worktrees_same_stack_collapse_into_one_group_ordered_bottom_to_top() {
281 // Two worktrees in the same 2-branch stack: feat-b is bottom, feat-a is top.
282 // Input idx 0 has current="feat-a" (position 1), input idx 1 has current="feat-b" (position 0).
283 let stacks = vec![
284 Some(stack("main", &["feat-b", "feat-a"], "feat-a")), // top worktree
285 Some(stack("main", &["feat-b", "feat-a"], "feat-b")), // bottom worktree
286 ];
287 let result = group_by_stack(&stacks);
288 assert!(result.ungrouped.is_empty());
289 assert_eq!(result.groups.len(), 1);
290 // Members ordered by branch position: idx 1 (feat-b, pos 0) first, idx 0 (feat-a, pos 1) second.
291 assert_eq!(result.groups[0].members, vec![1, 0]);
292 }
293
294 #[test]
295 fn same_stack_different_branches_vector_order_still_collapses() {
296 // The two Stacks have the same set but different vector orderings — must collapse.
297 let stacks = vec![
298 Some(stack("main", &["feat-a", "feat-b"], "feat-a")),
299 Some(stack("main", &["feat-b", "feat-a"], "feat-b")),
300 ];
301 let result = group_by_stack(&stacks);
302 assert_eq!(
303 result.groups.len(),
304 1,
305 "different branch vector order must still collapse"
306 );
307 assert!(result.ungrouped.is_empty());
308 }
309
310 #[test]
311 fn two_distinct_stacks_on_same_trunk_stay_separate() {
312 let stacks = vec![
313 Some(stack("main", &["stack1-a"], "stack1-a")),
314 Some(stack("main", &["stack2-a"], "stack2-a")),
315 ];
316 let result = group_by_stack(&stacks);
317 assert_eq!(result.groups.len(), 2);
318 assert!(result.ungrouped.is_empty());
319 }
320
321 #[test]
322 fn mixed_stacked_and_ungrouped() {
323 let stacks = vec![
324 None, // trunk worktree
325 Some(stack("main", &["feat-a", "feat-b"], "feat-a")),
326 None, // another ungrouped
327 Some(stack("main", &["feat-a", "feat-b"], "feat-b")),
328 ];
329 let result = group_by_stack(&stacks);
330 assert_eq!(result.ungrouped, vec![0, 2]);
331 assert_eq!(result.groups.len(), 1);
332 // feat-a is position 0, feat-b is position 1 → member idx 1 (current=feat-a) first, then idx 3
333 assert_eq!(result.groups[0].members, vec![1, 3]);
334 }
335
336 #[test]
337 fn groups_ordered_deterministically_by_trunk_then_branch_set() {
338 let stacks = vec![
339 Some(stack("main", &["z-feat"], "z-feat")),
340 Some(stack("dev", &["d-feat"], "d-feat")),
341 Some(stack("main", &["a-feat"], "a-feat")),
342 ];
343 let result = group_by_stack(&stacks);
344 assert_eq!(result.groups.len(), 3);
345 // Ordered: (dev, [d-feat]), (main, [a-feat]), (main, [z-feat])
346 assert_eq!(result.groups[0].stack.trunk, "dev");
347 assert_eq!(result.groups[1].stack.diffs, vec!["a-feat"]);
348 assert_eq!(result.groups[2].stack.diffs, vec!["z-feat"]);
349 }
350}