stax 0.96.7

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
use crate::config::Config;
use crate::engine::branch_detect::{
    MergeType, MergedBranchInfo, StaleBranchInfo, find_merged_branches_all, find_stale_branches,
    find_upstream_gone_branches, has_unique_commits_since_any_base,
};
use crate::engine::{BranchMetadata, Stack};
use crate::git::GitRepo;
use crate::remote;
use anyhow::{Context, Result};
use colored::Colorize;
use dialoguer::{Confirm, theme::ColorfulTheme};
use serde::Serialize;
use std::collections::HashSet;
use std::process::Command;

const DEFAULT_STALE_DAYS: u64 = 30;

pub fn run(
    delete: bool,
    include_stale: bool,
    force: bool,
    stale_days: Option<u64>,
    json: bool,
) -> Result<()> {
    let repo = GitRepo::open()?;
    let stack = Stack::load(&repo)?;
    let current = repo.current_branch()?;
    let trunk = stack.trunk.clone();
    let workdir = repo.workdir()?.to_path_buf();
    let config = Config::load()?;

    let remote_name = config.remote_name();
    let remote_trunk_ref = format!("{}/{}", remote_name, trunk);
    let effective_stale_days = stale_days.unwrap_or(config.branch.stale_days);

    // --- Classify all local branches ---

    // 1. Merged (git ancestry plus tracked PR cleanup signals)
    let mut merged_infos: Vec<_> =
        find_merged_branches_all(&repo, &workdir, &trunk, Some(remote_trunk_ref.as_str()))?
            .into_iter()
            .filter(|m| m.branch != trunk && m.branch != current)
            .collect();

    // 2. Upstream-gone
    let gone_branches = find_upstream_gone_branches(&workdir, &trunk)?;
    let gone_branch_set: HashSet<String> = gone_branches.iter().cloned().collect();
    let remote_heads = if stack.branches.values().any(|info| info.pr_number.is_some()) {
        remote::ls_remote_heads(&workdir, remote_name).ok()
    } else {
        None
    };

    for (branch, info) in &stack.branches {
        if branch == &trunk
            || branch == &current
            || merged_infos.iter().any(|m| &m.branch == branch)
        {
            continue;
        }

        let pr_is_merged = matches!(
            info.pr_state.as_deref(),
            Some(state) if state.eq_ignore_ascii_case("merged")
        );
        let pr_upstream_deleted = info.pr_number.is_some()
            && (gone_branch_set.contains(branch)
                || remote_heads
                    .as_ref()
                    .is_some_and(|heads| !heads.contains(branch)));
        if pr_is_merged || pr_upstream_deleted {
            merged_infos.push(MergedBranchInfo {
                branch: branch.clone(),
                merge_type: MergeType::Ancestor,
            });
        }
    }

    let merged_set: HashSet<String> = merged_infos.iter().map(|m| m.branch.clone()).collect();

    // Merged takes precedence over upstream-gone; trunk/current are never candidates.
    let mut gone_set: HashSet<String> = HashSet::new();
    let mut protected_gone_set: HashSet<String> = HashSet::new();
    for branch in gone_branches {
        if branch == trunk || branch == current || merged_set.contains(&branch) {
            continue;
        }

        if has_unique_commits_since_any_base(&workdir, &branch, &[&trunk, &remote_trunk_ref])? {
            protected_gone_set.insert(branch);
        } else {
            gone_set.insert(branch);
        }
    }

    // 3. Stale (old commits, not merged or gone)
    let already_classified: HashSet<String> = merged_set
        .iter()
        .chain(gone_set.iter())
        .chain(protected_gone_set.iter())
        .cloned()
        .collect();
    let stale_infos = find_stale_branches(
        &workdir,
        &trunk,
        &current,
        effective_stale_days,
        &already_classified,
    )?;
    let stale_set: HashSet<String> = stale_infos.iter().map(|s| s.branch.clone()).collect();

    // 4. Active = everything else except trunk + current
    let all_branches = repo.list_branches()?;
    let active_branches: Vec<String> = all_branches
        .into_iter()
        .filter(|b| {
            b != &trunk
                && b != &current
                && !merged_set.contains(b)
                && !gone_set.contains(b)
                && !stale_set.contains(b)
        })
        .collect();

    let total_classified =
        merged_set.len() + gone_set.len() + stale_set.len() + active_branches.len();

    // --- JSON output ---
    if json {
        return print_json(
            &merged_infos
                .iter()
                .map(|m| m.branch.clone())
                .collect::<Vec<_>>(),
            &gone_set.iter().cloned().collect::<Vec<_>>(),
            &stale_infos,
            &active_branches,
            &stack,
        );
    }

    // --- Human-readable output ---

    if total_classified == 0 {
        println!(
            "{}",
            "No local branches found (other than trunk and current).".dimmed()
        );
        return Ok(());
    }

    println!(
        "{} {} {}",
        "Branch sweep".bold(),
        "—".dimmed(),
        format!("stale threshold: {} days", effective_stale_days).dimmed()
    );
    println!();

    // Merged branches
    if !merged_set.is_empty() {
        let mut sorted: Vec<&String> = merged_set.iter().collect();
        sorted.sort();
        println!(
            "{} {}",
            format!("  merged  ({})", sorted.len()).green().bold(),
            "— safe to delete".dimmed()
        );
        for b in &sorted {
            let tracked_marker = if stack.branches.contains_key(*b) {
                " tracked".dimmed()
            } else {
                "".normal()
            };
            let merge_label = merged_infos
                .iter()
                .find(|m| &m.branch == *b)
                .map(|m| match m.merge_type {
                    MergeType::Ancestor => "",
                    MergeType::SquashMerge => " squash",
                })
                .unwrap_or("");
            println!(
                "    {} {}{}{}",
                "✓".green(),
                b.green(),
                merge_label.dimmed(),
                tracked_marker,
            );
        }
        println!();
    }

    // Upstream-gone branches
    if !gone_set.is_empty() {
        let mut sorted: Vec<&String> = gone_set.iter().collect();
        sorted.sort();
        println!(
            "{} {}",
            format!("  upstream-gone  ({})", sorted.len())
                .yellow()
                .bold(),
            "— remote deleted, safe to delete".dimmed()
        );
        for b in &sorted {
            let tracked_marker = if stack.branches.contains_key(*b) {
                " tracked".dimmed()
            } else {
                "".normal()
            };
            println!("    {} {}{}", "âš‘".yellow(), b.yellow(), tracked_marker);
        }
        println!();
    }

    // Stale branches
    if !stale_infos.is_empty() {
        let mut sorted = stale_infos.clone();
        sorted.sort_by_key(|s| std::cmp::Reverse(s.days_old));
        println!(
            "{} {}",
            format!("  stale  ({})", sorted.len()).bright_black().bold(),
            format!("— no commits in {}+ days", effective_stale_days).dimmed()
        );
        for info in &sorted {
            let tracked_marker = if stack.branches.contains_key(&info.branch) {
                " tracked".dimmed()
            } else {
                "".normal()
            };
            let age = format_age(info.days_old);
            println!(
                "    {} {} {}{}",
                "â—‹".bright_black(),
                info.branch.bright_black(),
                age.dimmed(),
                tracked_marker,
            );
        }
        println!();
    }

    // Active branches
    if !active_branches.is_empty() {
        let mut sorted = active_branches.clone();
        sorted.sort();
        println!("{}", format!("  active  ({})", sorted.len()).cyan().bold());
        for b in &sorted {
            let tracked_marker = if stack.branches.contains_key(b) {
                " tracked".dimmed()
            } else {
                "".normal()
            };
            println!("    {} {}{}", "â—‹".cyan(), b.cyan(), tracked_marker);
        }
        println!();
    }

    // Summary / hints
    print_summary(
        &merged_set,
        &gone_set,
        &stale_set,
        effective_stale_days,
        delete,
    );

    // --- Deletion ---
    if delete {
        let mut to_delete: Vec<String> =
            merged_set.iter().chain(gone_set.iter()).cloned().collect();
        if include_stale {
            to_delete.extend(stale_set.iter().cloned());
        }
        to_delete.retain(|b| b != &current && b != &trunk);
        to_delete.sort();

        if to_delete.is_empty() {
            println!("{}", "Nothing to delete.".dimmed());
            return Ok(());
        }

        if !force {
            println!();
            println!(
                "Will delete {} branch{}:",
                to_delete.len().to_string().bold(),
                if to_delete.len() == 1 { "" } else { "es" }
            );
            for b in &to_delete {
                println!("  {} {}", "â–¸".bright_black(), b.red());
            }
            println!();
            let confirm = Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt("Proceed with deletion?")
                .default(false)
                .interact()?;
            if !confirm {
                println!("{}", "Cancelled.".dimmed());
                return Ok(());
            }
        }

        let mut deleted = 0usize;
        let mut skipped = 0usize;

        for branch in &to_delete {
            let is_tracked = stack.branches.contains_key(branch);

            if is_tracked {
                let _ = reparent_children_to_trunk(&repo, &stack, branch, &to_delete);
            }

            match delete_branch_subprocess(&workdir, branch) {
                Ok(()) => {
                    if is_tracked {
                        let _ = BranchMetadata::delete(repo.inner(), branch);
                    }
                    println!("  {} {}", "✓".green(), branch.red());
                    deleted += 1;
                }
                Err(e) => {
                    println!(
                        "  {} skipped {} — {}",
                        "âš ".yellow(),
                        branch.yellow(),
                        e.to_string().dimmed()
                    );
                    skipped += 1;
                }
            }
        }

        println!();
        if deleted > 0 {
            println!(
                "Deleted {} branch{}{}.",
                deleted.to_string().bold(),
                if deleted == 1 { "" } else { "es" },
                if skipped > 0 {
                    format!(", {} skipped", skipped)
                } else {
                    String::new()
                }
            );
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// JSON output
// ---------------------------------------------------------------------------

#[derive(Serialize)]
struct SweepJsonBranch {
    name: String,
    status: &'static str,
    tracked: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    days_old: Option<u64>,
}

#[derive(Serialize)]
struct SweepJson {
    branches: Vec<SweepJsonBranch>,
}

fn print_json(
    merged: &[String],
    gone: &[String],
    stale: &[StaleBranchInfo],
    active: &[String],
    stack: &Stack,
) -> Result<()> {
    let mut branches: Vec<SweepJsonBranch> = Vec::new();

    for b in merged {
        branches.push(SweepJsonBranch {
            name: b.clone(),
            status: "merged",
            tracked: stack.branches.contains_key(b),
            days_old: None,
        });
    }
    for b in gone {
        branches.push(SweepJsonBranch {
            name: b.clone(),
            status: "upstream-gone",
            tracked: stack.branches.contains_key(b),
            days_old: None,
        });
    }
    for s in stale {
        branches.push(SweepJsonBranch {
            name: s.branch.clone(),
            status: "stale",
            tracked: stack.branches.contains_key(&s.branch),
            days_old: Some(s.days_old),
        });
    }
    for b in active {
        branches.push(SweepJsonBranch {
            name: b.clone(),
            status: "active",
            tracked: stack.branches.contains_key(b),
            days_old: None,
        });
    }

    branches.sort_by(|a, b| a.name.cmp(&b.name));

    let out = SweepJson { branches };
    println!("{}", serde_json::to_string_pretty(&out)?);
    Ok(())
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn print_summary(
    merged: &HashSet<String>,
    gone: &HashSet<String>,
    stale: &HashSet<String>,
    stale_days: u64,
    delete_mode: bool,
) {
    let deletable = merged.len() + gone.len();
    if deletable == 0 && stale.is_empty() {
        println!("{}", "All branches are active.".green());
        return;
    }

    if delete_mode {
        return;
    }

    let mut hints: Vec<String> = Vec::new();

    if deletable > 0 {
        hints.push(format!(
            "run {} to delete {} merged/gone branch{}",
            "stax sweep --delete".bold(),
            deletable.to_string().bold(),
            if deletable == 1 { "" } else { "es" },
        ));
    }
    if !stale.is_empty() {
        hints.push(format!(
            "add {} to also delete {} stale branch{}",
            "--include-stale".bold(),
            stale.len().to_string().bold(),
            if stale.len() == 1 { "" } else { "es" },
        ));
    }
    if !stale.is_empty() && stale_days == DEFAULT_STALE_DAYS {
        hints.push(format!(
            "set {} in {} to change the stale threshold",
            "branch.stale_days".bold(),
            "~/.config/stax/config.toml".dimmed()
        ));
    }

    for (i, hint) in hints.iter().enumerate() {
        if i == 0 {
            println!("Tip: {}", hint);
        } else {
            println!("     {}", hint);
        }
    }
}

fn format_age(days: u64) -> String {
    if days < 7 {
        format!("({} day{})", days, if days == 1 { "" } else { "s" })
    } else if days < 31 {
        let weeks = days / 7;
        format!("({} week{})", weeks, if weeks == 1 { "" } else { "s" })
    } else if days < 365 {
        let months = days / 30;
        format!("({} month{})", months, if months == 1 { "" } else { "s" })
    } else {
        let years = days / 365;
        format!("({} year{})", years, if years == 1 { "" } else { "s" })
    }
}

/// Reparent stax-tracked children of `branch` to trunk before deleting it.
fn reparent_children_to_trunk(
    repo: &GitRepo,
    stack: &Stack,
    branch: &str,
    doomed_set: &[String],
) -> Result<()> {
    let trunk = &stack.trunk;
    let doomed: HashSet<&str> = doomed_set.iter().map(|s| s.as_str()).collect();

    let children: Vec<String> = stack
        .branches
        .iter()
        .filter(|(_, info)| info.parent.as_deref() == Some(branch))
        .map(|(name, _)| name.clone())
        .filter(|name| !doomed.contains(name.as_str()))
        .collect();

    if children.is_empty() {
        return Ok(());
    }

    let branch_tip = repo.branch_commit(branch).ok();

    for child in &children {
        let Some(child_meta) = BranchMetadata::read(repo.inner(), child)? else {
            continue;
        };

        let old_parent_boundary = branch_tip
            .clone()
            .filter(|tip| repo.is_ancestor(tip, child).unwrap_or(false))
            .unwrap_or_else(|| child_meta.parent_branch_revision.clone());

        let updated_meta = BranchMetadata {
            parent_branch_name: trunk.clone(),
            parent_branch_revision: old_parent_boundary,
            ..child_meta
        };
        updated_meta.write(repo.inner(), child)?;
    }

    Ok(())
}

fn delete_branch_subprocess(workdir: &std::path::Path, branch: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["branch", "-D", branch])
        .current_dir(workdir)
        .output()
        .with_context(|| format!("Failed to delete branch '{}'", branch))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("{}", stderr.trim());
    }
    Ok(())
}