stax 0.29.4

Fast stacked Git branches and PRs
Documentation
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
use crate::engine::BranchMetadata;
use crate::git::{refs, GitRepo};
use anyhow::Result;
use git2::BranchType;
use std::collections::{HashMap, HashSet};

/// Represents a branch in the stack
#[derive(Debug, Clone)]
pub struct StackBranch {
    pub name: String,
    pub parent: Option<String>,
    pub children: Vec<String>,
    pub needs_restack: bool,
    pub pr_number: Option<u64>,
    pub pr_state: Option<String>,
    pub pr_is_draft: Option<bool>,
}

/// The full stack structure
pub struct Stack {
    pub branches: HashMap<String, StackBranch>,
    pub trunk: String,
}

impl Stack {
    /// Load the stack from git metadata
    pub fn load(repo: &GitRepo) -> Result<Self> {
        let trunk = repo.trunk_branch()?;
        let tracked_branches = refs::list_metadata_branches(repo.inner())?;

        let mut branches: HashMap<String, StackBranch> = HashMap::new();

        // First pass: load all metadata
        for branch_name in &tracked_branches {
            // Metadata can outlive branches (e.g. interrupted delete). Ignore and prune it.
            if repo
                .inner()
                .find_branch(branch_name, BranchType::Local)
                .is_err()
            {
                let _ = BranchMetadata::delete(repo.inner(), branch_name);
                continue;
            }

            if let Some(meta) = BranchMetadata::read(repo.inner(), branch_name)? {
                let needs_restack = meta.needs_restack(repo.inner()).unwrap_or(false);
                branches.insert(
                    branch_name.clone(),
                    StackBranch {
                        name: branch_name.clone(),
                        parent: Some(meta.parent_branch_name.clone()),
                        children: Vec::new(),
                        needs_restack,
                        pr_number: meta.pr_info.as_ref().map(|p| p.number),
                        pr_state: meta.pr_info.as_ref().map(|p| p.state.clone()),
                        pr_is_draft: meta.pr_info.as_ref().and_then(|p| p.is_draft),
                    },
                );
            }
        }

        // Second pass: populate children and find orphans
        let branch_names: Vec<String> = branches.keys().cloned().collect();
        let mut orphaned_branches: Vec<String> = Vec::new();

        for name in branch_names {
            if let Some(parent_name) = branches.get(&name).and_then(|b| b.parent.clone()) {
                if parent_name == trunk {
                    // Direct child of trunk - will be handled below
                    continue;
                }
                if let Some(parent) = branches.get_mut(&parent_name) {
                    parent.children.push(name.clone());
                } else {
                    // Parent doesn't exist - this branch is orphaned
                    // Treat it as a direct child of trunk
                    orphaned_branches.push(name.clone());
                }
            }
        }

        // Collect direct children of trunk (including orphaned branches)
        let mut trunk_children: Vec<String> = branches
            .values()
            .filter(|b| b.parent.as_ref() == Some(&trunk))
            .map(|b| b.name.clone())
            .collect();
        trunk_children.extend(orphaned_branches);

        // Add trunk as a root
        branches.insert(
            trunk.clone(),
            StackBranch {
                name: trunk.clone(),
                parent: None,
                children: trunk_children,
                needs_restack: false,
                pr_number: None,
                pr_state: None,
                pr_is_draft: None,
            },
        );

        Ok(Self { branches, trunk })
    }

    /// Get the ancestors of a branch (up to trunk)
    pub fn ancestors(&self, branch: &str) -> Vec<String> {
        let mut result = Vec::new();
        let mut current = branch.to_string();
        let mut visited = HashSet::from([current.clone()]);

        while let Some(b) = self.branches.get(&current) {
            if let Some(parent) = &b.parent {
                if !visited.insert(parent.clone()) {
                    break;
                }
                result.push(parent.clone());
                current = parent.clone();
            } else {
                break;
            }
        }

        result
    }

    /// Get all descendants of a branch
    pub fn descendants(&self, branch: &str) -> Vec<String> {
        let mut result = Vec::new();
        let mut to_visit = vec![branch.to_string()];
        let mut visited = HashSet::from([branch.to_string()]);

        while let Some(current) = to_visit.pop() {
            if let Some(b) = self.branches.get(&current) {
                for child in &b.children {
                    if !visited.insert(child.clone()) {
                        continue;
                    }
                    result.push(child.clone());
                    to_visit.push(child.clone());
                }
            }
        }

        result
    }

    /// Get the current stack (ancestors + current + descendants)
    pub fn current_stack(&self, branch: &str) -> Vec<String> {
        let mut seen = HashSet::new();
        let mut result = Vec::new();
        let mut ancestors = self.ancestors(branch);
        ancestors.reverse();

        for name in ancestors {
            if seen.insert(name.clone()) {
                result.push(name);
            }
        }

        if seen.insert(branch.to_string()) {
            result.push(branch.to_string());
        }

        for name in self.descendants(branch) {
            if seen.insert(name.clone()) {
                result.push(name);
            }
        }

        result
    }

    /// Get branches that need restacking
    pub fn needs_restack(&self) -> Vec<String> {
        self.branches
            .values()
            .filter(|b| b.needs_restack)
            .map(|b| b.name.clone())
            .collect()
    }

    /// Get siblings of a branch (other branches with the same parent)
    #[allow(dead_code)] // Useful utility for future features
    pub fn get_siblings(&self, branch: &str) -> Vec<String> {
        let branch_info = match self.branches.get(branch) {
            Some(b) => b,
            None => return vec![branch.to_string()],
        };

        let parent = match &branch_info.parent {
            Some(p) => p,
            None => return vec![branch.to_string()], // trunk has no siblings
        };

        // Get all children of the parent (including the branch itself)
        let parent_info = match self.branches.get(parent) {
            Some(p) => p,
            None => {
                // Parent not in stack - find other branches with same parent
                let mut siblings: Vec<String> = self
                    .branches
                    .values()
                    .filter(|b| b.parent.as_ref() == Some(&parent.to_string()))
                    .map(|b| b.name.clone())
                    .collect();
                siblings.sort();
                return siblings;
            }
        };

        let mut siblings = parent_info.children.clone();
        siblings.sort();
        siblings
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_stack() -> Stack {
        // Creates a stack structure:
        // main (trunk)
        //  ├── feature-a
        //  │   └── feature-a-1
        //  │       └── feature-a-2
        //  └── feature-b
        let mut branches = HashMap::new();

        branches.insert(
            "main".to_string(),
            StackBranch {
                name: "main".to_string(),
                parent: None,
                children: vec!["feature-a".to_string(), "feature-b".to_string()],
                needs_restack: false,
                pr_number: None,
                pr_state: None,
                pr_is_draft: None,
            },
        );

        branches.insert(
            "feature-a".to_string(),
            StackBranch {
                name: "feature-a".to_string(),
                parent: Some("main".to_string()),
                children: vec!["feature-a-1".to_string()],
                needs_restack: false,
                pr_number: Some(1),
                pr_state: Some("OPEN".to_string()),
                pr_is_draft: Some(false),
            },
        );

        branches.insert(
            "feature-a-1".to_string(),
            StackBranch {
                name: "feature-a-1".to_string(),
                parent: Some("feature-a".to_string()),
                children: vec!["feature-a-2".to_string()],
                needs_restack: true,
                pr_number: Some(2),
                pr_state: Some("OPEN".to_string()),
                pr_is_draft: Some(true),
            },
        );

        branches.insert(
            "feature-a-2".to_string(),
            StackBranch {
                name: "feature-a-2".to_string(),
                parent: Some("feature-a-1".to_string()),
                children: vec![],
                needs_restack: false,
                pr_number: None,
                pr_state: None,
                pr_is_draft: None,
            },
        );

        branches.insert(
            "feature-b".to_string(),
            StackBranch {
                name: "feature-b".to_string(),
                parent: Some("main".to_string()),
                children: vec![],
                needs_restack: true,
                pr_number: Some(3),
                pr_state: Some("MERGED".to_string()),
                pr_is_draft: None,
            },
        );

        Stack {
            branches,
            trunk: "main".to_string(),
        }
    }

    #[test]
    fn test_ancestors_from_leaf() {
        let stack = create_test_stack();
        let ancestors = stack.ancestors("feature-a-2");
        assert_eq!(ancestors, vec!["feature-a-1", "feature-a", "main"]);
    }

    #[test]
    fn test_ancestors_from_middle() {
        let stack = create_test_stack();
        let ancestors = stack.ancestors("feature-a-1");
        assert_eq!(ancestors, vec!["feature-a", "main"]);
    }

    #[test]
    fn test_ancestors_from_first_level() {
        let stack = create_test_stack();
        let ancestors = stack.ancestors("feature-a");
        assert_eq!(ancestors, vec!["main"]);
    }

    #[test]
    fn test_ancestors_from_trunk() {
        let stack = create_test_stack();
        let ancestors = stack.ancestors("main");
        assert!(ancestors.is_empty());
    }

    #[test]
    fn test_ancestors_nonexistent() {
        let stack = create_test_stack();
        let ancestors = stack.ancestors("nonexistent");
        assert!(ancestors.is_empty());
    }

    #[test]
    fn test_descendants_from_trunk() {
        let stack = create_test_stack();
        let mut descendants = stack.descendants("main");
        descendants.sort();
        assert_eq!(
            descendants,
            vec!["feature-a", "feature-a-1", "feature-a-2", "feature-b"]
        );
    }

    #[test]
    fn test_descendants_from_middle() {
        let stack = create_test_stack();
        let mut descendants = stack.descendants("feature-a");
        descendants.sort();
        assert_eq!(descendants, vec!["feature-a-1", "feature-a-2"]);
    }

    #[test]
    fn test_descendants_from_leaf() {
        let stack = create_test_stack();
        let descendants = stack.descendants("feature-a-2");
        assert!(descendants.is_empty());
    }

    #[test]
    fn test_descendants_from_branch_with_no_children() {
        let stack = create_test_stack();
        let descendants = stack.descendants("feature-b");
        assert!(descendants.is_empty());
    }

    #[test]
    fn test_current_stack_from_leaf() {
        let stack = create_test_stack();
        let current = stack.current_stack("feature-a-2");
        assert_eq!(
            current,
            vec!["main", "feature-a", "feature-a-1", "feature-a-2"]
        );
    }

    #[test]
    fn test_current_stack_from_middle() {
        let stack = create_test_stack();
        let current = stack.current_stack("feature-a-1");
        assert_eq!(
            current,
            vec!["main", "feature-a", "feature-a-1", "feature-a-2"]
        );
    }

    #[test]
    fn test_current_stack_from_first_level() {
        let stack = create_test_stack();
        let current = stack.current_stack("feature-b");
        assert_eq!(current, vec!["main", "feature-b"]);
    }

    #[test]
    fn test_ancestors_breaks_parent_cycles() {
        let mut branches = HashMap::new();
        branches.insert(
            "main".to_string(),
            StackBranch {
                name: "main".to_string(),
                parent: None,
                children: vec![],
                needs_restack: false,
                pr_number: None,
                pr_state: None,
                pr_is_draft: None,
            },
        );
        branches.insert(
            "a".to_string(),
            StackBranch {
                name: "a".to_string(),
                parent: Some("b".to_string()),
                children: vec!["b".to_string()],
                needs_restack: false,
                pr_number: None,
                pr_state: None,
                pr_is_draft: None,
            },
        );
        branches.insert(
            "b".to_string(),
            StackBranch {
                name: "b".to_string(),
                parent: Some("a".to_string()),
                children: vec!["a".to_string()],
                needs_restack: false,
                pr_number: None,
                pr_state: None,
                pr_is_draft: None,
            },
        );

        let stack = Stack {
            branches,
            trunk: "main".to_string(),
        };

        assert_eq!(stack.ancestors("a"), vec!["b"]);
        assert_eq!(stack.current_stack("a"), vec!["b", "a"]);
    }

    #[test]
    fn test_descendants_breaks_child_cycles() {
        let mut branches = HashMap::new();
        branches.insert(
            "main".to_string(),
            StackBranch {
                name: "main".to_string(),
                parent: None,
                children: vec!["a".to_string()],
                needs_restack: false,
                pr_number: None,
                pr_state: None,
                pr_is_draft: None,
            },
        );
        branches.insert(
            "a".to_string(),
            StackBranch {
                name: "a".to_string(),
                parent: Some("main".to_string()),
                children: vec!["b".to_string()],
                needs_restack: false,
                pr_number: None,
                pr_state: None,
                pr_is_draft: None,
            },
        );
        branches.insert(
            "b".to_string(),
            StackBranch {
                name: "b".to_string(),
                parent: Some("a".to_string()),
                children: vec!["a".to_string()],
                needs_restack: false,
                pr_number: None,
                pr_state: None,
                pr_is_draft: None,
            },
        );

        let stack = Stack {
            branches,
            trunk: "main".to_string(),
        };

        assert_eq!(stack.descendants("a"), vec!["b"]);
    }

    #[test]
    fn test_needs_restack() {
        let stack = create_test_stack();
        let mut needs = stack.needs_restack();
        needs.sort();
        assert_eq!(needs, vec!["feature-a-1", "feature-b"]);
    }

    #[test]
    fn test_get_siblings_with_one_sibling() {
        let stack = create_test_stack();
        let siblings = stack.get_siblings("feature-a");
        assert!(siblings.contains(&"feature-a".to_string()));
        assert!(siblings.contains(&"feature-b".to_string()));
        assert_eq!(siblings.len(), 2);
    }

    #[test]
    fn test_get_siblings_only_child() {
        let stack = create_test_stack();
        let siblings = stack.get_siblings("feature-a-1");
        assert_eq!(siblings, vec!["feature-a-1"]);
    }

    #[test]
    fn test_get_siblings_trunk() {
        let stack = create_test_stack();
        let siblings = stack.get_siblings("main");
        assert_eq!(siblings, vec!["main"]);
    }

    #[test]
    fn test_get_siblings_nonexistent() {
        let stack = create_test_stack();
        let siblings = stack.get_siblings("nonexistent");
        assert_eq!(siblings, vec!["nonexistent"]);
    }

    #[test]
    fn test_stack_branch_clone() {
        let branch = StackBranch {
            name: "test".to_string(),
            parent: Some("parent".to_string()),
            children: vec!["child".to_string()],
            needs_restack: true,
            pr_number: Some(42),
            pr_state: Some("OPEN".to_string()),
            pr_is_draft: Some(false),
        };
        let cloned = branch.clone();
        assert_eq!(cloned.name, branch.name);
        assert_eq!(cloned.pr_number, branch.pr_number);
    }

    #[test]
    fn test_stack_branch_debug() {
        let branch = StackBranch {
            name: "test".to_string(),
            parent: None,
            children: vec![],
            needs_restack: false,
            pr_number: None,
            pr_state: None,
            pr_is_draft: None,
        };
        let debug_str = format!("{:?}", branch);
        assert!(debug_str.contains("test"));
    }
}