git-loom 0.18.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
mod absorb;
mod add;
mod branch;
mod commit;
mod completions;
mod core;
mod diff;
mod drop;
mod fold;
mod git;
mod init;
mod push;
mod reword;
mod show;
mod split;
mod status;
mod swap;
mod switch;
mod trace;
mod tui;
mod update;

use crate::core::{graph, msg, repo, transaction};

use std::io::IsTerminal;

use anyhow::Context;
use clap::builder::styling::{AnsiColor, Styles};
use clap::{Args, Parser, Subcommand, ValueEnum};
use colored::control;

const STYLES: Styles = Styles::styled()
    .header(AnsiColor::Yellow.on_default().bold())
    .usage(AnsiColor::Yellow.on_default().bold())
    .literal(AnsiColor::Green.on_default())
    .placeholder(AnsiColor::Blue.on_default());

#[derive(ValueEnum, Clone, Copy)]
enum ThemeArg {
    /// Detect from terminal background color (default to dark if undetectable)
    Auto,
    /// Dark terminal background
    Dark,
    /// Light terminal background
    Light,
}

// Grouped command help — ANSI codes match STYLES (yellow bold = headers, green = literals)
const GROUPED_COMMANDS: &str = "\
\x1b[1;33mWorkflow:\x1b[0m
  \x1b[32minit\x1b[0m              Initialize a new integration branch
  \x1b[32mupdate\x1b[0m, \x1b[32mup\x1b[0m        Pull-rebase and update submodules
  \x1b[32mpush\x1b[0m, \x1b[32mpr\x1b[0m          Push a branch to remote

\x1b[1;33mStaging:\x1b[0m
  \x1b[32madd\x1b[0m               Stage files using short IDs or paths [\x1b[32m-p\x1b[0m for interactive hunks]

\x1b[1;33mCommits:\x1b[0m
  \x1b[32mcommit\x1b[0m, \x1b[32mci\x1b[0m        Create a commit on a feature branch
  \x1b[32mfold\x1b[0m              Amend, fixup, or move commits [\x1b[32mamend\x1b[0m, \x1b[32mam\x1b[0m, \x1b[32mfixup\x1b[0m, \x1b[32mmv\x1b[0m, \x1b[32mrub\x1b[0m]
  \x1b[32mabsorb\x1b[0m            Auto-distribute changes into originating commits
  \x1b[32msplit\x1b[0m             Split a commit into two
  \x1b[32mswap\x1b[0m              Swap two commits
  \x1b[32mreword\x1b[0m, \x1b[32mrw\x1b[0m        Reword a commit message or rename a branch
  \x1b[32mdrop\x1b[0m, \x1b[32mrm\x1b[0m          Drop a change, commit, or branch

\x1b[1;33mBranches:\x1b[0m
  \x1b[32mbranch\x1b[0m, \x1b[32mbr\x1b[0m        Manage feature branches (create, merge, unmerge)
  \x1b[32mswitch\x1b[0m, \x1b[32msw\x1b[0m        Switch to any branch for testing (without weaving)

\x1b[1;33mInspection:\x1b[0m
  \x1b[32mstatus\x1b[0m            Show the branch-aware status (\x1b[34mdefault\x1b[0m command)
  \x1b[32mshow\x1b[0m, \x1b[32msh\x1b[0m          Show commit details (like git show)
  \x1b[32mdiff\x1b[0m, \x1b[32mdi\x1b[0m          Show a diff using short IDs (like git diff)
  \x1b[32mtrace\x1b[0m             Show the latest command trace

\x1b[1;33mRecovery:\x1b[0m
  \x1b[32mcontinue\x1b[0m, \x1b[32mc\x1b[0m       Resume a paused operation after resolving conflicts
  \x1b[32mabort\x1b[0m, \x1b[32ma\x1b[0m          Cancel a paused operation and restore original state";

#[derive(Parser)]
#[command(
    name = "git-loom",
    about = "\x1b[34mWeave your branches together\x1b[0m\nCheckout the full docs here: https://narnaud.github.io/git-loom/",
    styles = STYLES,
    version,
    after_help = GROUPED_COMMANDS,
    help_template = "{about-with-newline}\n{usage-heading} {usage}{after-help}\n\n\x1b[1;33mOptions:\x1b[0m\n{options}\n",
)]
struct Cli {
    /// Disable colored output
    #[arg(long)]
    no_color: bool,

    /// Color theme for graph output
    #[arg(long, default_value = "auto")]
    theme: ThemeArg,

    /// Show files changed in each commit (optionally filtered to specific commits)
    #[arg(short = 'f', long = "files", num_args = 0.., hide = true)]
    files: Option<Vec<String>>,

    /// Number of context commits to show before the base
    #[arg(default_value = "1", hide = true)]
    context: usize,

    /// Show all branches including hidden ones (those matching loom.hideBranchPattern)
    #[arg(short = 'a', long = "all", hide = true)]
    all: bool,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    // -- Workflow --
    /// Initialize a new integration branch tracking a remote
    Init {
        /// Branch name (defaults to "integration")
        name: Option<String>,
    },
    /// Pull-rebase the integration branch and update submodules
    #[command(visible_alias = "up")]
    Update {
        /// Remove local branches whose upstream tracking branch was deleted on remote
        #[arg(short, long)]
        yes: bool,
    },
    /// Push a feature branch to remote and optionally create a PR or Gerrit review
    #[command(visible_alias = "pr")]
    Push {
        /// Branch name or short ID (if not provided, will prompt interactively)
        branch: Option<String>,
        /// Push branch without creating a PR or Gerrit review
        #[arg(long)]
        no_pr: bool,
    },

    // -- Staging --
    /// Stage files using short IDs, paths, or 'zz' for all
    Add {
        /// Files to stage (short IDs, filenames, or 'zz' for all)
        #[arg(num_args = 0..)]
        files: Vec<String>,
        /// Interactively select hunks to stage
        #[arg(short = 'p', long = "patch")]
        patch: bool,
    },

    // -- Commits --
    /// Create a commit on a feature branch without leaving integration
    #[command(visible_alias = "ci")]
    Commit {
        /// Target feature branch (name or short ID)
        #[arg(short = 'b', long = "branch")]
        branch: Option<String>,
        /// Commit message (if not provided, opens editor)
        #[arg(short, long)]
        message: Option<String>,
        /// Interactively select hunks to stage before committing
        #[arg(short = 'p', long = "patch")]
        patch: bool,
        /// Files to stage (short IDs, filenames, or 'zz' for all), none for all tracked changes
        files: Vec<String>,
    },
    /// Fold source(s) into a target (amend files, fixup commits, move commits, move files between commits)
    #[command(visible_aliases = ["amend", "am", "fixup", "mv", "rub"])]
    Fold {
        /// Create a new branch from the source commit and move it there
        #[arg(short = 'c', long = "create")]
        create: bool,
        /// Interactively select hunks to stage before folding
        #[arg(short = 'p', long = "patch")]
        patch: bool,
        /// Source(s) and target: files, commits, or branches (last arg is the target)
        #[arg(required = true, num_args = 1..)]
        args: Vec<String>,
    },
    /// Absorb working tree changes into the commits that introduced them
    Absorb {
        /// Show what would be absorbed without making changes
        #[arg(short = 'n', long)]
        dry_run: bool,
        /// Files to restrict absorption to (default: all tracked changed files)
        files: Vec<String>,
    },
    /// Split a commit into two sequential commits
    Split {
        /// Commit hash, short ID, or HEAD
        target: String,
        /// Message for the first commit (prompts if omitted)
        #[arg(short, long)]
        message: Option<String>,
        /// Interactively pick hunks for the first commit
        #[arg(short = 'p', long = "patch")]
        patch: bool,
        /// Files for the first commit (shows interactive picker if omitted)
        files: Vec<String>,
    },
    /// Reword a commit message or rename a branch
    #[command(visible_alias = "rw")]
    Reword {
        /// Branch name, shortID, or commit hash
        target: String,
        /// New message or branch name (if not provided, opens editor for commits)
        #[arg(short, long)]
        message: Option<String>,
    },
    /// Swap two commits within the same sequence
    Swap {
        /// First commit hash or short ID
        a: String,
        /// Second commit hash or short ID
        b: String,
    },
    /// Drop a local change, a commit, or a branch from history
    #[command(visible_alias = "rm")]
    Drop {
        /// Commit hash, branch name, or short ID to drop
        target: String,
        /// Skip confirmation prompt
        #[arg(short, long)]
        yes: bool,
    },

    // -- Branches --
    /// Manage feature branches (create, merge, unmerge)
    #[command(visible_alias = "br")]
    Branch(BranchCmd),

    /// Switch to any branch for testing without weaving it into the integration branch
    #[command(visible_alias = "sw")]
    Switch {
        /// Branch name or short ID (if not provided, shows interactive picker)
        branch: Option<String>,
    },

    // -- Inspection --
    /// Show the branch-aware status
    Status {
        /// Show files changed in each commit (optionally filtered to specific commits)
        #[arg(short = 'f', long = "files", num_args = 0.., value_name = "COMMIT")]
        files: Option<Vec<String>>,
        /// Number of context commits to show before the base
        #[arg(default_value = "1")]
        context: usize,
        /// Show all branches including hidden ones (those matching loom.hideBranchPattern)
        #[arg(short = 'a', long = "all")]
        all: bool,
    },
    /// Show the diff and metadata for a commit (like `git show`)
    #[command(visible_alias = "sh")]
    Show {
        /// Commit hash, branch name, or short ID
        target: String,
    },
    /// Show a diff using short IDs (like `git diff`)
    #[command(visible_alias = "di")]
    Diff {
        /// Files, commits, or commit ranges (short IDs supported, e.g. `ma`, `d0`, `d0..3a`)
        args: Vec<String>,
    },
    /// Show the latest command trace
    Trace,

    // -- Recovery --
    /// Resume a paused loom operation after resolving conflicts
    #[command(visible_alias = "c")]
    Continue,
    /// Cancel a paused loom operation and restore original state
    #[command(visible_alias = "a")]
    Abort,

    // -- Hidden --
    /// Generate shell completions (powershell, clink)
    #[command(hide = true)]
    Completions {
        /// Shell to generate completions for (powershell, clink)
        shell: String,
    },
    /// Internal: used as GIT_SEQUENCE_EDITOR to write a pre-generated todo file
    #[command(hide = true)]
    InternalWriteTodo {
        /// Path to the source file containing the todo content
        #[arg(long = "source")]
        source: String,
        /// Path to the git rebase todo file (provided by git)
        todo_file: String,
    },
}

#[derive(Args)]
#[command(args_conflicts_with_subcommands = true)]
struct BranchCmd {
    #[command(subcommand)]
    action: Option<BranchAction>,

    #[command(flatten)]
    new_args: BranchNewArgs,
}

#[derive(Subcommand)]
enum BranchAction {
    /// Create a new feature branch
    #[command(visible_alias = "create")]
    New(BranchNewArgs),

    /// Weave an existing branch into the integration branch
    Merge {
        /// Branch name (if not provided, shows interactive picker)
        branch: Option<String>,

        /// Also show remote branches without a local counterpart
        #[arg(short = 'a', long = "all")]
        all: bool,
    },

    /// Remove a branch from the integration branch (keeps the branch ref)
    Unmerge {
        /// Branch name or short ID (if not provided, shows interactive picker)
        branch: Option<String>,
    },
}

#[derive(Args, Clone)]
struct BranchNewArgs {
    /// Branch name (if not provided, will prompt interactively)
    name: Option<String>,

    /// Target commit, branch, or shortID (defaults to upstream base)
    #[arg(short = 't', long = "target")]
    target: Option<String>,
}

fn main() {
    let cli = Cli::parse();

    if cli.no_color
        || std::env::var_os("NO_COLOR").is_some()
        || std::env::var_os("TERM").is_some_and(|v| v == "dumb")
        || !std::io::stdout().is_terminal()
    {
        control::set_override(false);
    }

    // Completions don't need git, handle before version check
    if let Some(Command::Completions { shell }) = cli.command {
        if let Err(e) = completions::run(shell) {
            msg::error(&e.to_string());
            std::process::exit(1);
        }
        return;
    }

    if let Err(e) = git::check_git_version() {
        msg::error(&e.to_string());
        std::process::exit(1);
    }

    // Initialize logger for commands that modify the repo (skip for
    // InternalWriteTodo — it runs as a subprocess — and Status/Trace/Show which are read-only).
    let should_log = !matches!(
        cli.command,
        Some(Command::InternalWriteTodo { .. })
            | Some(Command::Trace)
            | Some(Command::Show { .. })
            | Some(Command::Diff { .. })
    );
    if should_log && let Ok(repo) = repo::open_repo() {
        let git_dir = repo.path().to_path_buf();
        let cmd_line = std::env::args().collect::<Vec<_>>().join(" ");
        if matches!(cli.command, Some(Command::Abort) | Some(Command::Continue)) {
            trace::init_appending(&git_dir, &cmd_line);
        } else {
            trace::init(&git_dir, &cmd_line);
        }
    }

    // Check for a paused loom operation and block most commands if one exists.
    // Exempt: show, trace, continue, abort, completions, internal-write-todo.
    let is_exempt = matches!(
        cli.command,
        Some(Command::Show { .. })
            | Some(Command::Diff { .. })
            | Some(Command::Trace)
            | Some(Command::Continue)
            | Some(Command::Abort)
            | Some(Command::Completions { .. })
            | Some(Command::InternalWriteTodo { .. })
    );
    if !is_exempt && let Ok(repo) = repo::open_repo() {
        let git_dir = repo.path().to_path_buf();
        if let Ok(Some(state)) = transaction::load(&git_dir) {
            msg::error(&format!(
                "A `loom {}` is paused due to conflicts.\n\
                 Run `loom continue` to resume or `loom abort` to cancel.\n\
                 If no loom operation is in progress, delete `.git/loom/state.json` to reset.",
                state.command
            ));
            std::process::exit(1);
        }
    }

    let theme = resolve_theme(cli.theme);

    let result = match cli.command {
        None => status::run(cli.files, cli.context, cli.all, theme),
        Some(Command::Status {
            files,
            context,
            all,
        }) => status::run(files, context, all, theme),
        Some(Command::Init { name }) => init::run(name),
        Some(Command::Add { files, patch }) => add::run(files, patch, &theme),
        Some(Command::Switch { branch }) => switch::run(branch),
        Some(Command::Branch(cmd)) => match cmd.action {
            Some(BranchAction::New(args)) => branch::new::run(args.name, args.target),
            Some(BranchAction::Merge { branch, all }) => branch::merge::run(branch, all),
            Some(BranchAction::Unmerge { branch }) => branch::unmerge::run(branch),
            None => branch::new::run(cmd.new_args.name, cmd.new_args.target),
        },
        Some(Command::Reword { target, message }) => reword::run(target, message),
        Some(Command::Commit {
            branch,
            message,
            patch,
            files,
        }) => commit::run(branch, message, patch, files, &theme),
        Some(Command::Swap { a, b }) => swap::run(a, b),
        Some(Command::Drop { target, yes }) => drop::run(target, yes),
        Some(Command::Absorb { dry_run, files }) => absorb::run(dry_run, files),
        Some(Command::Show { target }) => show::run(target),
        Some(Command::Diff { args }) => diff::run(args),
        Some(Command::Split {
            target,
            message,
            patch,
            files,
        }) => split::run(target, message, patch, files, &theme),
        Some(Command::Push { branch, no_pr }) => push::run(branch, no_pr),
        Some(Command::Update { yes }) => update::run(yes),
        Some(Command::Fold {
            create,
            patch,
            args,
        }) => fold::run(create, patch, args, &theme),
        Some(Command::Trace) => trace::run(),
        Some(Command::Continue) => transaction::continue_run(),
        Some(Command::Abort) => transaction::abort_run(),
        Some(Command::Completions { .. }) => unreachable!(),
        Some(Command::InternalWriteTodo { source, todo_file }) => {
            handle_write_todo(&source, &todo_file)
        }
    };

    trace::finalize();

    if let Err(e) = result {
        msg::error(&e.to_string());
        std::process::exit(1);
    }
}

fn resolve_theme(arg: ThemeArg) -> graph::Theme {
    match arg {
        ThemeArg::Dark => graph::Theme::dark(),
        ThemeArg::Light => graph::Theme::light(),
        ThemeArg::Auto => {
            if !std::io::stdout().is_terminal() {
                return graph::Theme::dark();
            }
            use terminal_colorsaurus::{QueryOptions, ThemeMode, theme_mode};
            match theme_mode(QueryOptions::default()) {
                Ok(ThemeMode::Light) => graph::Theme::light(),
                _ => graph::Theme::dark(),
            }
        }
    }
}

fn handle_write_todo(source: &str, todo_file: &str) -> anyhow::Result<()> {
    // Save the original git todo to a sidecar file (for logging)
    if let Ok(original) = std::fs::read_to_string(todo_file) {
        let sidecar = format!("{}.original", source);
        let _ = std::fs::write(sidecar, original);
    }

    let content = std::fs::read_to_string(source)
        .with_context(|| format!("Failed to read source file '{}'", source))?;
    std::fs::write(todo_file, content)
        .with_context(|| format!("Failed to write todo file '{}'", todo_file))?;
    Ok(())
}