stax 0.50.2

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
use crate::config::Config;
use crate::engine::{BranchMetadata, Stack};
use crate::git::GitRepo;
use crate::remote;
use anyhow::{bail, Result};
use colored::Colorize;
use console::Term;
use dialoguer::{theme::ColorfulTheme, Confirm, Input, Select};
use std::path::Path;
use std::process::Command;

pub fn run(
    name: Option<String>,
    message: Option<String>,
    from: Option<String>,
    prefix: Option<String>,
    all: bool,
    insert: bool,
) -> Result<()> {
    let repo = GitRepo::open()?;
    let config = Config::load()?;
    let current = repo.current_branch()?;
    let parent_branch = from.unwrap_or_else(|| current.clone());
    let generated_from_message = name.is_none() && message.is_some();

    if repo.branch_commit(&parent_branch).is_err() {
        anyhow::bail!("Branch '{}' does not exist", parent_branch);
    }

    // Get the branch name from either name or message
    // When using -m, the message is used for both branch name and commit message.
    // `stax create -m` respects already-staged changes. When nothing is staged
    // it prompts interactively (or bails in non-TTY). Use -a/--all to skip the prompt.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum StageMode {
        None,
        ExistingOnly,
        All,
    }

    // When neither name nor message is provided, launch interactive wizard.
    let (input, commit_message, stage_mode) = match (&name, &message) {
        (Some(n), _) => (
            n.clone(),
            None,
            if all { StageMode::All } else { StageMode::None },
        ),
        (None, Some(m)) => (
            m.clone(),
            Some(m.clone()),
            if all {
                StageMode::All
            } else {
                StageMode::ExistingOnly
            },
        ),
        (None, None) => {
            // Check if we're in an interactive terminal
            if !Term::stderr().is_term() {
                bail!(
                    "Branch name required. Use: stax create <name> or stax create -m \"message\""
                );
            }
            // Launch interactive wizard
            let (wizard_name, wizard_msg, wizard_stage_all) =
                run_wizard(repo.workdir()?, &parent_branch)?;
            (
                wizard_name,
                wizard_msg,
                if wizard_stage_all {
                    StageMode::All
                } else {
                    StageMode::None
                },
            )
        }
    };

    // Format the branch name according to config
    let branch_name = match prefix.as_deref() {
        Some(_) => config.format_branch_name_with_prefix_override(&input, prefix.as_deref()),
        None => config.format_branch_name(&input),
    };
    let existing_branches = repo.list_branches()?;
    let branch_name =
        resolve_branch_name_conflicts(&branch_name, &existing_branches, generated_from_message)?;

    // Before creating the branch, check if we need to prompt about staging.
    // Doing this early means declining is a clean no-op (no orphaned branch).
    let needs_stage_all = if stage_mode == StageMode::ExistingOnly {
        let workdir = repo.workdir()?;
        if is_staging_area_empty(workdir) && has_uncommitted_changes(workdir) {
            if Term::stderr().is_term() {
                let change_count = count_uncommitted_changes(workdir);
                let prompt = if change_count > 0 {
                    format!(
                        "No files staged. Stage all changes ({} files modified)?",
                        change_count
                    )
                } else {
                    "No files staged. Stage all changes?".to_string()
                };

                let should_stage = Confirm::with_theme(&ColorfulTheme::default())
                    .with_prompt(prompt)
                    .default(true)
                    .interact()?;

                if !should_stage {
                    println!(
                        "{}",
                        "Aborted. Stage files with `git add` first, or use `stax create -a -m \"message\"`."
                            .dimmed()
                    );
                    return Ok(());
                }
                true
            } else {
                bail!(
                    "No files staged. Stage files with `git add` first, or use `stax create -a -m \"message\"`."
                );
            }
        } else {
            false
        }
    } else {
        false
    };

    // Create the branch
    if parent_branch == current {
        repo.create_branch(&branch_name)?;
    } else {
        repo.create_branch_at(&branch_name, &parent_branch)?;
    }

    // Track it with current branch as parent
    let parent_rev = repo.branch_commit(&parent_branch)?;
    let meta = BranchMetadata::new(&parent_branch, &parent_rev);
    if let Err(e) = meta.write(repo.inner(), &branch_name) {
        rollback_create(&repo, &current, &branch_name);
        return Err(e);
    }

    // If --insert, reparent children of the parent branch to the new branch
    if insert {
        let stack = Stack::load(&repo)?;
        if let Some(parent_info) = stack.branches.get(&parent_branch) {
            let children: Vec<String> = parent_info
                .children
                .iter()
                .filter(|c| *c != &branch_name)
                .cloned()
                .collect();

            if !children.is_empty() {
                let new_parent_rev = repo.branch_commit(&branch_name)?;
                for child in &children {
                    if let Some(child_meta) = BranchMetadata::read(repo.inner(), child)? {
                        let updated = BranchMetadata {
                            parent_branch_name: branch_name.clone(),
                            parent_branch_revision: new_parent_rev.clone(),
                            ..child_meta
                        };
                        updated.write(repo.inner(), child)?;
                    }
                }

                println!(
                    "Reparented {} child branch(es) to '{}'",
                    children.len(),
                    branch_name.green()
                );
                for child in &children {
                    println!("  {} -> {}", child.cyan(), branch_name.green());
                }
                println!(
                    "{}",
                    "Run `stax restack --all` to rebase the reparented branches.".yellow()
                );
            }
        }
    }

    // Checkout the new branch
    if let Err(e) = repo.checkout(&branch_name) {
        rollback_create(&repo, &current, &branch_name);
        return Err(e);
    }

    if let Ok(remote_branches) = remote::get_remote_branches(repo.workdir()?, config.remote_name())
    {
        if !remote_branches.contains(&parent_branch) {
            println!(
                "{}",
                format!(
                    "Warning: parent '{}' is not on remote '{}'.",
                    parent_branch,
                    config.remote_name()
                )
                .yellow()
            );
        }
    }

    println!(
        "Created and switched to branch '{}' (stacked on {})",
        branch_name.green(),
        parent_branch.blue()
    );

    // Stage/commit behavior:
    // - StageMode::All / needs_stage_all => run `git add -A`
    // - StageMode::ExistingOnly (files already staged) => keep current index
    // - StageMode::None => no staging/committing
    if stage_mode != StageMode::None {
        let workdir = repo.workdir()?;

        if stage_mode == StageMode::All || needs_stage_all {
            if let Err(e) = stage_all(workdir) {
                rollback_create(&repo, &current, &branch_name);
                return Err(e);
            }
        }

        // Only commit if -m was provided
        if let Some(msg) = commit_message {
            // Check if there are staged changes to commit
            let diff_output = Command::new("git")
                .args(["diff", "--cached", "--quiet"])
                .current_dir(workdir)
                .status();

            let diff_output = match diff_output {
                Ok(status) => status,
                Err(e) => {
                    rollback_create(&repo, &current, &branch_name);
                    return Err(e.into());
                }
            };

            if !diff_output.success() {
                // There are staged changes, commit them
                let commit_status = Command::new("git")
                    .args(["commit", "-m", &msg])
                    .current_dir(workdir)
                    .status();

                let commit_status = match commit_status {
                    Ok(status) => status,
                    Err(e) => {
                        rollback_create(&repo, &current, &branch_name);
                        return Err(e.into());
                    }
                };

                if !commit_status.success() {
                    rollback_create(&repo, &current, &branch_name);
                    bail!(
                        "Commit failed (pre-commit hook or other error). \
                         Branch rolled back. Fix the issue and retry."
                    );
                }

                println!("Committed: {}", msg.cyan());
            } else {
                println!("{}", "No changes to commit".dimmed());
            }
        } else if stage_mode == StageMode::All {
            println!("{}", "Changes staged".dimmed());
        }
    }

    if config.ui.tips {
        println!(
            "{}",
            "Hint: Run `st ss` to submit, or add changes with `st modify -a -m \"message\"`"
                .dimmed()
        );
    }

    Ok(())
}

/// Best-effort rollback: unstage changes, checkout the original branch,
/// delete the new branch and its metadata.
/// Errors during rollback are intentionally ignored (matching the pattern in split_hunk/app.rs).
fn rollback_create(repo: &GitRepo, original_branch: &str, new_branch: &str) {
    if let Ok(workdir) = repo.workdir() {
        // Reset index first so staged changes from stage_all don't block checkout
        // or leak onto the original branch. This preserves working tree files.
        let _ = Command::new("git")
            .args(["reset"])
            .current_dir(workdir)
            .status();
        let _ = Command::new("git")
            .args(["checkout", original_branch])
            .current_dir(workdir)
            .status();
    }
    let _ = repo.delete_branch(new_branch, true);
    let _ = BranchMetadata::delete(repo.inner(), new_branch);
}

#[derive(Clone, Copy)]
enum BranchNameConflict<'a> {
    Exact(&'a str),
    ExistingIsAncestor(&'a str),
    ExistingIsDescendant(&'a str),
}

fn resolve_branch_name_conflicts(
    branch_name: &str,
    existing_branches: &[String],
    generated_from_message: bool,
) -> Result<String> {
    match detect_branch_name_conflict(branch_name, existing_branches) {
        None => Ok(branch_name.to_string()),
        Some(BranchNameConflict::Exact(_) | BranchNameConflict::ExistingIsDescendant(_))
            if generated_from_message =>
        {
            for suffix in 2..1000 {
                let candidate = append_branch_suffix(branch_name, suffix);
                if detect_branch_name_conflict(&candidate, existing_branches).is_none() {
                    return Ok(candidate);
                }
            }

            bail!(
                "Cannot create a unique branch name from '{}'. Too many similarly named branches already exist.",
                branch_name
            );
        }
        Some(conflict) => bail!("{}", branch_name_conflict_message(branch_name, conflict)),
    }
}

fn detect_branch_name_conflict<'a>(
    branch_name: &str,
    existing_branches: &'a [String],
) -> Option<BranchNameConflict<'a>> {
    for existing in existing_branches {
        if branch_name == existing {
            return Some(BranchNameConflict::Exact(existing));
        }

        if branch_name.starts_with(&format!("{}/", existing)) {
            return Some(BranchNameConflict::ExistingIsAncestor(existing));
        }

        if existing.starts_with(&format!("{}/", branch_name)) {
            return Some(BranchNameConflict::ExistingIsDescendant(existing));
        }
    }

    None
}

fn branch_name_conflict_message(branch_name: &str, conflict: BranchNameConflict<'_>) -> String {
    match conflict {
        BranchNameConflict::Exact(existing) => format!(
            "Cannot create '{}': branch '{}' already exists.\n\
             Use `st checkout {}` or choose a different name.",
            branch_name, existing, existing
        ),
        BranchNameConflict::ExistingIsAncestor(existing) => format!(
            "Cannot create '{}': branch '{}' already exists.\n\
             Git doesn't allow a branch and its sub-path to coexist.\n\
             Either delete '{}' first, or use a different name like '{}-ui'.",
            branch_name, existing, existing, existing
        ),
        BranchNameConflict::ExistingIsDescendant(existing) => format!(
            "Cannot create '{}': branch '{}' already exists.\n\
             Git doesn't allow a branch and its sub-path to coexist.\n\
             Either delete '{}' first, or use a different name.",
            branch_name, existing, existing
        ),
    }
}

fn append_branch_suffix(branch_name: &str, suffix: usize) -> String {
    match branch_name.rsplit_once('/') {
        Some((prefix, leaf)) => format!("{}/{}-{}", prefix, leaf, suffix),
        None => format!("{}-{}", branch_name, suffix),
    }
}

/// Interactive wizard for branch creation when no arguments provided
fn run_wizard(workdir: &Path, parent_branch: &str) -> Result<(String, Option<String>, bool)> {
    // Show header
    println!();
    println!("╭─ Create Stacked Branch ─────────────────────────────╮");
    println!(
        "│ Parent: {:<43} │",
        format!("{} (current branch)", parent_branch.cyan())
    );
    println!("╰─────────────────────────────────────────────────────╯");
    println!();

    // 1. Branch name prompt (required)
    let name: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Branch name")
        .interact_text()?;

    if name.trim().is_empty() {
        bail!("Branch name cannot be empty");
    }

    // 2. Check for uncommitted changes
    let has_changes = has_uncommitted_changes(workdir);
    let change_count = count_uncommitted_changes(workdir);

    let (should_stage, commit_message) = if has_changes {
        println!();

        // Show staging options with change count
        let stage_label = if change_count > 0 {
            format!("Stage all changes ({} files modified)", change_count)
        } else {
            "Stage all changes".to_string()
        };

        let options = vec![stage_label.as_str(), "Empty branch (no changes)"];

        let choice = Select::with_theme(&ColorfulTheme::default())
            .with_prompt("What to include")
            .items(&options)
            .default(0)
            .interact()?;

        let stage = choice == 0;

        // 3. Optional commit message (only if staging)
        let msg = if stage {
            println!();
            let m: String = Input::with_theme(&ColorfulTheme::default())
                .with_prompt("Commit message (Enter to skip)")
                .allow_empty(true)
                .interact_text()?;
            if m.is_empty() {
                None
            } else {
                Some(m)
            }
        } else {
            None
        };

        (stage, msg)
    } else {
        (false, None)
    };

    println!();
    Ok((name, commit_message, should_stage))
}

/// Run `git add -A` to stage all changes (tracked, modified, untracked).
fn stage_all(workdir: &Path) -> Result<()> {
    let status = Command::new("git")
        .args(["add", "-A"])
        .current_dir(workdir)
        .status()?;
    if !status.success() {
        bail!("Failed to stage changes");
    }
    Ok(())
}

/// Returns true when the staging area has no changes relative to HEAD.
fn is_staging_area_empty(workdir: &Path) -> bool {
    Command::new("git")
        .args(["diff", "--cached", "--quiet"])
        .current_dir(workdir)
        .status()
        .map(|s| s.success())
        .unwrap_or(true)
}

/// Check if there are uncommitted changes in the working directory
fn has_uncommitted_changes(workdir: &Path) -> bool {
    Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(workdir)
        .output()
        .map(|o| !o.stdout.is_empty())
        .unwrap_or(false)
}

/// Count the number of files with uncommitted changes
fn count_uncommitted_changes(workdir: &Path) -> usize {
    Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(workdir)
        .output()
        .map(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .filter(|l| !l.is_empty())
                .count()
        })
        .unwrap_or(0)
}