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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use anyhow::{Context, Result};
use colored::Colorize;
use console;
use dialoguer::theme::ColorfulTheme;
use dialoguer::Select;
use std::fs;
use std::path::Path;
use std::process::Command;

fn run_git(cwd: &Path, args: &[&str]) -> Result<()> {
    let output = Command::new("git")
        .args(args)
        .current_dir(cwd)
        .output()
        .with_context(|| format!("Failed to run git {}", args.join(" ")))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git {} failed: {}", args.join(" "), stderr);
    }
    Ok(())
}

fn stax_exe() -> std::path::PathBuf {
    std::env::current_exe().unwrap_or_else(|_| "stax".into())
}

/// Run stax and print its output (for demo steps the user should see)
fn run_stax(cwd: &Path, args: &[&str]) -> Result<()> {
    let output = Command::new(stax_exe())
        .args(args)
        .current_dir(cwd)
        .env("STAX_DISABLE_UPDATE_CHECK", "1")
        .output()
        .with_context(|| format!("Failed to run st {}", args.join(" ")))?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    if !stdout.is_empty() {
        print!("{}", stdout);
    }
    Ok(())
}

/// Run stax silently (for setup scaffolding)
fn run_stax_quiet(cwd: &Path, args: &[&str]) -> Result<()> {
    let output = Command::new(stax_exe())
        .args(args)
        .current_dir(cwd)
        .env("STAX_DISABLE_UPDATE_CHECK", "1")
        .output()
        .with_context(|| format!("Failed to run st {}", args.join(" ")))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("st {} failed: {}", args.join(" "), stderr);
    }
    Ok(())
}

fn pause() -> Result<bool> {
    println!();
    let cont = dialoguer::Confirm::new()
        .with_prompt("Continue?")
        .default(true)
        .interact()
        .unwrap_or(false);
    println!();
    Ok(cont)
}

fn step(n: usize, total: usize, title: &str) {
    println!(
        "{}  {}",
        format!("[{}/{}]", n, total).bold().blue(),
        title.bold()
    );
    println!();
}

fn cmd(text: &str) {
    println!("  {} {}", "$".dimmed(), text.cyan());
    println!();
}

/// Initialize a temp repo with stax trunk set — no noisy doctor output
fn setup_repo() -> Result<(tempfile::TempDir, std::path::PathBuf)> {
    let tmp = tempfile::tempdir().context("Failed to create temp directory")?;
    let dir = tmp.path().to_path_buf();
    run_git(&dir, &["init", "-b", "main"])?;
    run_git(&dir, &["config", "user.email", "demo@stax.dev"])?;
    run_git(&dir, &["config", "user.name", "Stax Demo"])?;
    fs::write(dir.join("README.md"), "# My Project\n")?;
    run_git(&dir, &["add", "-A"])?;
    run_git(&dir, &["commit", "-m", "Initial commit"])?;

    // Write the trunk ref directly (same as stax init) to avoid doctor output
    let child = Command::new("git")
        .args(["hash-object", "-w", "--stdin"])
        .current_dir(&dir)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn()?;
    use std::io::Write;
    let mut child = child;
    if let Some(mut stdin) = child.stdin.take() {
        stdin.write_all(b"main")?;
    }
    let output = child.wait_with_output()?;
    let blob_hash = String::from_utf8_lossy(&output.stdout).trim().to_string();
    run_git(&dir, &["update-ref", "refs/stax/trunk", &blob_hash])?;

    Ok((tmp, dir))
}

fn commit(dir: &Path, file: &str, content: &str, msg: &str) -> Result<()> {
    fs::write(dir.join(file), content)?;
    run_git(dir, &["add", "-A"])?;
    run_git(dir, &["commit", "-m", msg])
}

/// Silently create a branch and commit (for scaffolding stacks before a demo step)
fn scaffold_branch(dir: &Path, name: &str, file: &str, code: &str, msg: &str) -> Result<()> {
    run_stax_quiet(dir, &["create", name])?;
    commit(dir, file, code, msg)
}

// ─── Demo 1: First PR ───────────────────────────────────────────────────────

fn demo_first_pr() -> Result<()> {
    let t = 4;
    println!();
    println!("{}", "Demo: Your first pull request".bold().green());
    println!(
        "{}",
        "Create a branch, commit, and see how st tracks it.".dimmed()
    );
    println!();

    let (_tmp, dir) = setup_repo()?;

    step(1, t, "Start from trunk");
    cmd("st status");
    run_stax(&dir, &["status"])?;
    if !pause()? {
        return Ok(());
    }

    step(2, t, "Create a branch and add a commit");
    cmd("st create add-login");
    run_stax(&dir, &["create", "add-login"])?;
    commit(
        &dir,
        "login.rs",
        "pub fn login(user: &str, pass: &str) -> bool { true }\n",
        "Add login function",
    )?;
    cmd("st status");
    run_stax(&dir, &["status"])?;
    println!(
        "{}",
        "st tracks the parent automatically — no manual base branches.".dimmed()
    );
    if !pause()? {
        return Ok(());
    }

    step(3, t, "See commits per branch");
    cmd("st log");
    run_stax(&dir, &["log"])?;
    if !pause()? {
        return Ok(());
    }

    step(4, t, "Submit your PR");
    println!(
        "With GitHub configured, {} pushes and creates a PR.",
        "st submit".cyan()
    );
    println!("The PR targets the correct parent branch automatically.");
    println!();
    println!(
        "{}",
        "Done! You can now create branches and submit PRs with st."
            .bold()
            .green()
    );
    println!();
    Ok(())
}

// ─── Demo 2: Stacking PRs ───────────────────────────────────────────────────

fn demo_stacking() -> Result<()> {
    let t = 5;
    println!();
    println!("{}", "Demo: Stacking multiple PRs".bold().green());
    println!(
        "{}",
        "Break a big feature into small, reviewable PRs.".dimmed()
    );
    println!();

    let (_tmp, dir) = setup_repo()?;

    step(1, t, "Build a 3-branch stack");
    cmd("st create add-models");
    run_stax(&dir, &["create", "add-models"])?;
    commit(
        &dir,
        "models.rs",
        "pub struct User { pub id: u64, pub name: String }\n",
        "Add User model",
    )?;

    cmd("st create add-api");
    run_stax(&dir, &["create", "add-api"])?;
    commit(
        &dir,
        "api.rs",
        "pub fn get_user(id: u64) -> User { todo!() }\n",
        "Add user API",
    )?;

    cmd("st create add-ui");
    run_stax(&dir, &["create", "add-ui"])?;
    commit(
        &dir,
        "ui.rs",
        "pub fn render(user: &User) { println!(\"{}\", user.name); }\n",
        "Add user UI",
    )?;

    cmd("st log");
    run_stax(&dir, &["log"])?;
    println!(
        "{}",
        "3 branches, each building on the last. Each becomes its own PR.".dimmed()
    );
    if !pause()? {
        return Ok(());
    }

    step(2, t, "Navigate the stack");
    cmd("st bottom");
    run_stax(&dir, &["bottom"])?;
    cmd("st top");
    run_stax(&dir, &["top"])?;
    if !pause()? {
        return Ok(());
    }

    step(3, t, "Edit a middle branch");
    run_stax_quiet(&dir, &["bottom"])?;
    commit(
        &dir,
        "models.rs",
        "pub struct User { pub id: u64, pub name: String, pub email: String }\n",
        "Add email to User",
    )?;
    cmd("st status");
    run_stax(&dir, &["status"])?;
    println!(
        "{}",
        "Branches above are marked as needing rebase.".dimmed()
    );
    if !pause()? {
        return Ok(());
    }

    step(4, t, "Restack everything");
    cmd("st restack --all");
    run_stax(&dir, &["restack", "--all"])?;
    cmd("st status");
    run_stax(&dir, &["status"])?;
    println!(
        "{}",
        "All branches rebased onto their updated parents.".dimmed()
    );
    if !pause()? {
        return Ok(());
    }

    step(5, t, "Submit the whole stack");
    println!(
        "{} pushes every branch and creates/updates all PRs at once.",
        "st submit".cyan()
    );
    println!("Each PR targets the correct parent — reviewers see small diffs.");
    println!();
    println!(
        "{}",
        "Done! You can build, restack, and submit entire stacks."
            .bold()
            .green()
    );
    println!();
    Ok(())
}

// ─── Demo 3: Navigating stacks ──────────────────────────────────────────────

fn demo_navigation() -> Result<()> {
    let t = 4;
    println!();
    println!("{}", "Demo: Navigating your stack".bold().green());
    println!(
        "{}",
        "Move between branches without remembering names.".dimmed()
    );
    println!();

    let (_tmp, dir) = setup_repo()?;

    // Build a 4-branch stack silently
    scaffold_branch(
        &dir,
        "feat-auth",
        "auth.rs",
        "pub fn auth() {}\n",
        "Add auth",
    )?;
    scaffold_branch(
        &dir,
        "feat-session",
        "session.rs",
        "pub fn session() {}\n",
        "Add session",
    )?;
    scaffold_branch(
        &dir,
        "feat-profile",
        "profile.rs",
        "pub fn profile() {}\n",
        "Add profile",
    )?;
    scaffold_branch(
        &dir,
        "feat-settings",
        "settings.rs",
        "pub fn settings() {}\n",
        "Add settings",
    )?;

    step(1, t, "See where you are");
    cmd("st status");
    run_stax(&dir, &["status"])?;
    println!("{}", "You're at the top of a 4-branch stack.".dimmed());
    if !pause()? {
        return Ok(());
    }

    step(2, t, "Move down and up");
    cmd("st down");
    run_stax(&dir, &["down"])?;
    cmd("st down 2");
    run_stax(&dir, &["down", "2"])?;
    cmd("st up");
    run_stax(&dir, &["up"])?;
    println!(
        "{}",
        "down/up accept a count — jump multiple levels at once.".dimmed()
    );
    if !pause()? {
        return Ok(());
    }

    step(3, t, "Jump to top and bottom");
    cmd("st bottom");
    run_stax(&dir, &["bottom"])?;
    cmd("st top");
    run_stax(&dir, &["top"])?;
    if !pause()? {
        return Ok(());
    }

    step(4, t, "Switch to trunk and back");
    cmd("st trunk");
    run_stax(&dir, &["trunk"])?;
    cmd("st prev");
    run_stax(&dir, &["prev"])?;
    println!(
        "{}",
        "prev returns to whatever branch you were on before.".dimmed()
    );
    println!();
    println!(
        "{}",
        "Done! Navigate any stack without typing branch names."
            .bold()
            .green()
    );
    println!();
    Ok(())
}

// ─── Demo 4: Undo risky operations ──────────────────────────────────────────

fn demo_undo() -> Result<()> {
    let t = 3;
    println!();
    println!("{}", "Demo: Undo and safety net".bold().green());
    println!(
        "{}",
        "Every risky operation can be reversed with st undo.".dimmed()
    );
    println!();

    let (_tmp, dir) = setup_repo()?;

    step(1, t, "Create a stack");
    scaffold_branch(
        &dir,
        "feat-payments",
        "pay.rs",
        "pub fn charge(amount: u64) {}\n",
        "Add payments",
    )?;
    scaffold_branch(
        &dir,
        "feat-receipts",
        "receipt.rs",
        "pub fn receipt() {}\n",
        "Add receipts",
    )?;
    cmd("st log");
    run_stax(&dir, &["log"])?;
    if !pause()? {
        return Ok(());
    }

    step(2, t, "Detach a branch (risky operation)");
    println!("Remove {} from the stack:", "feat-payments".cyan());
    run_stax_quiet(&dir, &["down"])?;
    cmd("st detach --yes");
    run_stax(&dir, &["detach", "--yes"])?;
    cmd("st status");
    run_stax(&dir, &["status"])?;
    println!(
        "{}",
        "feat-receipts was reparented to main automatically.".dimmed()
    );
    if !pause()? {
        return Ok(());
    }

    step(3, t, "Undo it");
    cmd("st undo --yes");
    run_stax(&dir, &["undo", "--yes"])?;
    cmd("st log");
    run_stax(&dir, &["log"])?;
    println!(
        "{}",
        "The stack is restored to its original shape.".dimmed()
    );
    println!();
    println!(
        "{}",
        "Done! Experiment freely — st undo has your back."
            .bold()
            .green()
    );
    println!();
    Ok(())
}

// ─── Demo 5: Validate and fix ───────────────────────────────────────────────

fn demo_health() -> Result<()> {
    let t = 3;
    println!();
    println!("{}", "Demo: Stack health checks".bold().green());
    println!(
        "{}",
        "Detect and fix broken metadata before it causes problems.".dimmed()
    );
    println!();

    let (_tmp, dir) = setup_repo()?;

    step(1, t, "Build a stack");
    scaffold_branch(
        &dir,
        "feat-cache",
        "cache.rs",
        "pub fn cache() {}\n",
        "Add caching",
    )?;
    scaffold_branch(
        &dir,
        "feat-ttl",
        "ttl.rs",
        "pub fn ttl() {}\n",
        "Add TTL support",
    )?;
    cmd("st status");
    run_stax(&dir, &["status"])?;
    if !pause()? {
        return Ok(());
    }

    step(2, t, "Run a health check");
    cmd("st validate");
    run_stax(&dir, &["validate"])?;
    println!(
        "{}",
        "All checks passed — no orphaned refs, no cycles, no stale parents.".dimmed()
    );
    if !pause()? {
        return Ok(());
    }

    step(3, t, "Auto-fix problems");
    println!(
        "If validate finds issues, {} repairs them automatically:",
        "st fix".cyan()
    );
    println!();
    println!(
        "  {} Deletes metadata for branches that no longer exist",
        "-".dimmed()
    );
    println!("  {} Reparents orphans to trunk", "-".dimmed());
    println!("  {} Cleans up invalid JSON refs", "-".dimmed());
    println!();
    println!(
        "Use {} to preview without changing anything.",
        "st fix --dry-run".cyan()
    );
    println!();
    println!(
        "{}",
        "Done! Keep your stacks healthy with st validate and st fix."
            .bold()
            .green()
    );
    println!();
    Ok(())
}

// ─── Entry point ────────────────────────────────────────────────────────────

pub fn run() -> Result<()> {
    println!();
    println!("{}", "Welcome to the stax interactive demo!".bold().green());
    println!(
        "{}",
        "A temporary repo is created for each demo — your projects are untouched.".dimmed()
    );
    println!();

    let demos = &[
        format!(
            "{}  {}",
            "Your first pull request".bold(),
            "(~1 min)".dimmed()
        ),
        format!(
            "{}  {}",
            "Stacking multiple PRs".bold(),
            "(~3 min)".dimmed()
        ),
        format!(
            "{}  {}",
            "Navigating your stack".bold(),
            "(~2 min)".dimmed()
        ),
        format!("{}  {}", "Undo and safety net".bold(), "(~2 min)".dimmed()),
        format!("{}  {}", "Stack health checks".bold(), "(~1 min)".dimmed()),
    ];

    let theme = ColorfulTheme {
        active_item_style: console::Style::new().for_stderr().green().bold(),
        active_item_prefix: console::style("".to_string()).for_stderr().green().bold(),
        inactive_item_prefix: console::style("  ".to_string()).for_stderr(),
        prompt_style: console::Style::new().for_stderr().bold().cyan(),
        prompt_prefix: console::style("?".to_string()).for_stderr().green().bold(),
        ..ColorfulTheme::default()
    };

    let selection = Select::with_theme(&theme)
        .with_prompt("What demo would you like to run?")
        .items(demos)
        .default(0)
        .interact_opt()
        .unwrap_or(None);

    match selection {
        Some(0) => demo_first_pr()?,
        Some(1) => demo_stacking()?,
        Some(2) => demo_navigation()?,
        Some(3) => demo_undo()?,
        Some(4) => demo_health()?,
        _ => {
            println!();
            println!("No demo selected. Run {} anytime.", "st demo".cyan());
        }
    }

    Ok(())
}