Skip to main content

git_cli/
cli.rs

1use clap::error::ErrorKind;
2use clap::{Args, CommandFactory, Parser, Subcommand};
3use nils_common::cli_contract::exit;
4use std::ffi::OsString;
5
6use crate::{branch, ci, commit, completion, open, reset, utils, worktree};
7
8#[derive(Debug, Parser)]
9#[command(
10    name = "git-cli",
11    version,
12    long_version = nils_build_info::long_version(env!("CARGO_PKG_VERSION")),
13    about = "Git helper CLI",
14    disable_help_subcommand = true,
15    override_usage = "git-cli <group> <command> [args]"
16)]
17struct Cli {
18    #[command(subcommand)]
19    group: Option<Group>,
20}
21
22#[derive(Debug, Subcommand)]
23enum Group {
24    #[command(about = "Utility helpers")]
25    Utils(UtilsGroup),
26    #[command(about = "Reset helpers")]
27    Reset(ResetGroup),
28    #[command(about = "Commit helpers")]
29    Commit(CommitGroup),
30    #[command(about = "Branch helpers")]
31    Branch(BranchGroup),
32    #[command(about = "Worktree helpers")]
33    Worktree(WorktreeGroup),
34    #[command(about = "CI helpers")]
35    Ci(CiGroup),
36    #[command(about = "Open remote pages")]
37    Open(OpenGroup),
38    #[command(about = "Export shell completion script")]
39    Completion(RawArgs),
40    #[command(about = "Display help message for git-cli")]
41    Help,
42}
43
44#[derive(Debug, Args)]
45#[command(disable_help_subcommand = true)]
46struct UtilsGroup {
47    #[command(subcommand)]
48    command: Option<UtilsCommand>,
49}
50
51#[derive(Debug, Subcommand)]
52enum UtilsCommand {
53    #[command(about = "Create zip archive from HEAD")]
54    Zip(RawArgs),
55    #[command(
56        name = "copy-staged",
57        visible_alias = "copy",
58        about = "Copy staged diff to clipboard"
59    )]
60    CopyStaged(RawArgs),
61    #[command(about = "Jump to git root")]
62    Root(RawArgs),
63    #[command(
64        name = "commit-hash",
65        visible_alias = "hash",
66        about = "Resolve commit hash"
67    )]
68    CommitHash(RawArgs),
69    #[command(about = "Display help message for utils")]
70    Help,
71}
72
73#[derive(Debug, Args)]
74#[command(disable_help_subcommand = true)]
75struct ResetGroup {
76    #[command(subcommand)]
77    command: Option<ResetCommand>,
78}
79
80#[derive(Debug, Subcommand)]
81enum ResetCommand {
82    #[command(about = "Reset to HEAD~N (soft)")]
83    Soft(RawArgs),
84    #[command(about = "Reset to HEAD~N (mixed)")]
85    Mixed(RawArgs),
86    #[command(about = "Reset to HEAD~N (hard)")]
87    Hard(RawArgs),
88    #[command(about = "Undo last reset")]
89    Undo(RawArgs),
90    #[command(name = "back-head", about = "Checkout HEAD@{1}")]
91    BackHead(RawArgs),
92    #[command(name = "back-checkout", about = "Return to previous branch")]
93    BackCheckout(RawArgs),
94    #[command(about = "Reset to remote branch")]
95    Remote(RawArgs),
96    #[command(about = "Display help message for reset")]
97    Help,
98}
99
100#[derive(Debug, Args)]
101#[command(disable_help_subcommand = true)]
102struct CommitGroup {
103    #[command(subcommand)]
104    command: Option<CommitCommand>,
105}
106
107#[derive(Debug, Subcommand)]
108enum CommitCommand {
109    #[command(about = "Print commit context")]
110    Context(RawArgs),
111    #[command(
112        name = "context-json",
113        visible_aliases = ["context_json", "contextjson", "json"],
114        about = "Print commit context as JSON"
115    )]
116    ContextJson(RawArgs),
117    #[command(
118        name = "to-stash",
119        visible_alias = "stash",
120        about = "Create stash from commit"
121    )]
122    ToStash(RawArgs),
123    #[command(about = "Display help message for commit")]
124    Help,
125}
126
127#[derive(Debug, Args)]
128#[command(disable_help_subcommand = true)]
129struct BranchGroup {
130    #[command(subcommand)]
131    command: Option<BranchCommand>,
132}
133
134#[derive(Debug, Subcommand)]
135enum BranchCommand {
136    #[command(
137        name = "cleanup",
138        visible_alias = "delete-merged",
139        about = "Delete merged branches"
140    )]
141    Cleanup(RawArgs),
142    #[command(about = "Display help message for branch")]
143    Help,
144}
145
146#[derive(Debug, Args)]
147#[command(disable_help_subcommand = true)]
148struct WorktreeGroup {
149    #[command(subcommand)]
150    command: Option<WorktreeCommand>,
151}
152
153#[derive(Debug, Subcommand)]
154enum WorktreeCommand {
155    #[command(about = "Create a managed agent worktree")]
156    Add(RawArgs),
157    #[command(about = "List git worktrees")]
158    List(RawArgs),
159    #[command(about = "Remove a managed worktree by slug or path")]
160    Remove(RawArgs),
161    #[command(about = "Prune stale git worktree metadata")]
162    Prune(RawArgs),
163    #[command(about = "Resolve a worktree path to cd into")]
164    Go(RawArgs),
165    #[command(about = "Display help message for worktree")]
166    Help,
167}
168
169#[derive(Debug, Args)]
170#[command(disable_help_subcommand = true)]
171struct CiGroup {
172    #[command(subcommand)]
173    command: Option<CiCommand>,
174}
175
176#[derive(Debug, Subcommand)]
177enum CiCommand {
178    #[command(about = "Cherry-pick into CI branch")]
179    Pick(RawArgs),
180    #[command(about = "Display help message for ci")]
181    Help,
182}
183
184#[derive(Debug, Args)]
185#[command(disable_help_subcommand = true)]
186struct OpenGroup {
187    #[command(subcommand)]
188    command: Option<OpenCommand>,
189}
190
191#[derive(Debug, Subcommand)]
192enum OpenCommand {
193    #[command(about = "Open repository page")]
194    Repo(RawArgs),
195    #[command(about = "Open branch tree page")]
196    Branch(RawArgs),
197    #[command(
198        name = "default-branch",
199        visible_alias = "default",
200        about = "Open default branch tree page"
201    )]
202    DefaultBranch(RawArgs),
203    #[command(about = "Open commit page")]
204    Commit(RawArgs),
205    #[command(about = "Open compare page")]
206    Compare(RawArgs),
207    #[command(
208        name = "pr",
209        visible_aliases = ["pull-request", "mr", "merge-request"],
210        about = "Open pull or merge request page"
211    )]
212    Pr(RawArgs),
213    #[command(
214        visible_aliases = ["prs", "merge-requests", "mrs"],
215        about = "Open pull or merge request list"
216    )]
217    Pulls(RawArgs),
218    #[command(visible_alias = "issue", about = "Open issues list/page")]
219    Issues(RawArgs),
220    #[command(visible_alias = "action", about = "Open actions page")]
221    Actions(RawArgs),
222    #[command(visible_alias = "release", about = "Open releases list/page")]
223    Releases(RawArgs),
224    #[command(visible_alias = "tag", about = "Open tags list/page")]
225    Tags(RawArgs),
226    #[command(visible_alias = "history", about = "Open commit history page")]
227    Commits(RawArgs),
228    #[command(visible_alias = "blob", about = "Open file page")]
229    File(RawArgs),
230    #[command(about = "Open blame page")]
231    Blame(RawArgs),
232    #[command(about = "Display help message for open")]
233    Help,
234}
235
236#[derive(Debug, Args)]
237#[command(disable_help_flag = true)]
238struct RawArgs {
239    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
240    args: Vec<String>,
241}
242
243pub fn run() -> i32 {
244    // Short-circuit `COMPLETE=<shell> git-cli ...` dynamic-completion requests
245    // before the hand-rolled dispatch. No-op when `COMPLETE` is unset, so
246    // ordinary invocations are unaffected.
247    completion::complete_env();
248    run_from(std::env::args())
249}
250
251fn run_from<I, T>(args: I) -> i32
252where
253    I: IntoIterator<Item = T>,
254    T: Into<OsString> + Clone,
255{
256    let cli = match Cli::try_parse_from(args) {
257        Ok(cli) => cli,
258        Err(err) => return print_parse_error(err),
259    };
260
261    match cli.group {
262        Some(Group::Utils(group)) => run_utils(group),
263        Some(Group::Reset(group)) => run_reset(group),
264        Some(Group::Commit(group)) => run_commit(group),
265        Some(Group::Branch(group)) => run_branch(group),
266        Some(Group::Worktree(group)) => run_worktree(group),
267        Some(Group::Ci(group)) => run_ci(group),
268        Some(Group::Open(group)) => run_open(group),
269        Some(Group::Completion(raw)) => run_completion(raw),
270        Some(Group::Help) | None => print_root_help(),
271    }
272}
273
274fn run_utils(group: UtilsGroup) -> i32 {
275    match group.command {
276        Some(UtilsCommand::Zip(raw)) => utils::dispatch("zip", &raw.args).unwrap_or(exit::USAGE),
277        Some(UtilsCommand::CopyStaged(raw)) => {
278            utils::dispatch("copy-staged", &raw.args).unwrap_or(exit::USAGE)
279        }
280        Some(UtilsCommand::Root(raw)) => utils::dispatch("root", &raw.args).unwrap_or(exit::USAGE),
281        Some(UtilsCommand::CommitHash(raw)) => {
282            utils::dispatch("commit-hash", &raw.args).unwrap_or(exit::USAGE)
283        }
284        Some(UtilsCommand::Help) | None => print_group_help("utils"),
285    }
286}
287
288fn run_reset(group: ResetGroup) -> i32 {
289    match group.command {
290        Some(ResetCommand::Soft(raw)) => reset::dispatch("soft", &raw.args).unwrap_or(exit::USAGE),
291        Some(ResetCommand::Mixed(raw)) => {
292            reset::dispatch("mixed", &raw.args).unwrap_or(exit::USAGE)
293        }
294        Some(ResetCommand::Hard(raw)) => reset::dispatch("hard", &raw.args).unwrap_or(exit::USAGE),
295        Some(ResetCommand::Undo(raw)) => reset::dispatch("undo", &raw.args).unwrap_or(exit::USAGE),
296        Some(ResetCommand::BackHead(raw)) => {
297            reset::dispatch("back-head", &raw.args).unwrap_or(exit::USAGE)
298        }
299        Some(ResetCommand::BackCheckout(raw)) => {
300            reset::dispatch("back-checkout", &raw.args).unwrap_or(exit::USAGE)
301        }
302        Some(ResetCommand::Remote(raw)) => {
303            reset::dispatch("remote", &raw.args).unwrap_or(exit::USAGE)
304        }
305        Some(ResetCommand::Help) | None => print_group_help("reset"),
306    }
307}
308
309fn run_commit(group: CommitGroup) -> i32 {
310    match group.command {
311        Some(CommitCommand::Context(raw)) => commit::dispatch("context", &raw.args),
312        Some(CommitCommand::ContextJson(raw)) => commit::dispatch("context-json", &raw.args),
313        Some(CommitCommand::ToStash(raw)) => commit::dispatch("to-stash", &raw.args),
314        Some(CommitCommand::Help) | None => print_group_help("commit"),
315    }
316}
317
318fn run_branch(group: BranchGroup) -> i32 {
319    match group.command {
320        Some(BranchCommand::Cleanup(raw)) => {
321            branch::dispatch("cleanup", &raw.args).unwrap_or(exit::USAGE)
322        }
323        Some(BranchCommand::Help) | None => print_group_help("branch"),
324    }
325}
326
327fn run_ci(group: CiGroup) -> i32 {
328    match group.command {
329        Some(CiCommand::Pick(raw)) => ci::dispatch("pick", &raw.args).unwrap_or(exit::USAGE),
330        Some(CiCommand::Help) | None => print_group_help("ci"),
331    }
332}
333
334fn run_worktree(group: WorktreeGroup) -> i32 {
335    match group.command {
336        Some(WorktreeCommand::Add(raw)) => {
337            worktree::dispatch("add", &raw.args).unwrap_or(exit::USAGE)
338        }
339        Some(WorktreeCommand::List(raw)) => {
340            worktree::dispatch("list", &raw.args).unwrap_or(exit::USAGE)
341        }
342        Some(WorktreeCommand::Remove(raw)) => {
343            worktree::dispatch("remove", &raw.args).unwrap_or(exit::USAGE)
344        }
345        Some(WorktreeCommand::Prune(raw)) => {
346            worktree::dispatch("prune", &raw.args).unwrap_or(exit::USAGE)
347        }
348        Some(WorktreeCommand::Go(raw)) => {
349            worktree::dispatch("go", &raw.args).unwrap_or(exit::USAGE)
350        }
351        Some(WorktreeCommand::Help) | None => print_group_help("worktree"),
352    }
353}
354
355fn run_open(group: OpenGroup) -> i32 {
356    match group.command {
357        Some(OpenCommand::Repo(raw)) => open::dispatch("repo", &raw.args).unwrap_or(exit::USAGE),
358        Some(OpenCommand::Branch(raw)) => {
359            open::dispatch("branch", &raw.args).unwrap_or(exit::USAGE)
360        }
361        Some(OpenCommand::DefaultBranch(raw)) => {
362            open::dispatch("default-branch", &raw.args).unwrap_or(exit::USAGE)
363        }
364        Some(OpenCommand::Commit(raw)) => {
365            open::dispatch("commit", &raw.args).unwrap_or(exit::USAGE)
366        }
367        Some(OpenCommand::Compare(raw)) => {
368            open::dispatch("compare", &raw.args).unwrap_or(exit::USAGE)
369        }
370        Some(OpenCommand::Pr(raw)) => open::dispatch("pr", &raw.args).unwrap_or(exit::USAGE),
371        Some(OpenCommand::Pulls(raw)) => open::dispatch("pulls", &raw.args).unwrap_or(exit::USAGE),
372        Some(OpenCommand::Issues(raw)) => {
373            open::dispatch("issues", &raw.args).unwrap_or(exit::USAGE)
374        }
375        Some(OpenCommand::Actions(raw)) => {
376            open::dispatch("actions", &raw.args).unwrap_or(exit::USAGE)
377        }
378        Some(OpenCommand::Releases(raw)) => {
379            open::dispatch("releases", &raw.args).unwrap_or(exit::USAGE)
380        }
381        Some(OpenCommand::Tags(raw)) => open::dispatch("tags", &raw.args).unwrap_or(exit::USAGE),
382        Some(OpenCommand::Commits(raw)) => {
383            open::dispatch("commits", &raw.args).unwrap_or(exit::USAGE)
384        }
385        Some(OpenCommand::File(raw)) => open::dispatch("file", &raw.args).unwrap_or(exit::USAGE),
386        Some(OpenCommand::Blame(raw)) => open::dispatch("blame", &raw.args).unwrap_or(exit::USAGE),
387        Some(OpenCommand::Help) | None => print_group_help("open"),
388    }
389}
390
391fn run_completion(raw: RawArgs) -> i32 {
392    let Some(shell) = raw.args.first() else {
393        eprintln!("usage: git-cli completion <bash|zsh>");
394        return exit::USAGE;
395    };
396    completion::dispatch(shell, &raw.args[1..])
397}
398
399fn print_parse_error(err: clap::Error) -> i32 {
400    let kind = err.kind();
401    if let Err(print_err) = err.print() {
402        eprintln!("{print_err}");
403        return exit::RUNTIME;
404    }
405
406    if matches!(kind, ErrorKind::DisplayHelp | ErrorKind::DisplayVersion) {
407        exit::SUCCESS
408    } else {
409        exit::USAGE
410    }
411}
412
413fn print_root_help() -> i32 {
414    let mut command = Cli::command();
415    if let Err(err) = command.print_help() {
416        eprintln!("{err}");
417        return exit::RUNTIME;
418    }
419    println!();
420    exit::SUCCESS
421}
422
423fn print_group_help(group: &str) -> i32 {
424    let mut command = Cli::command();
425    let Some(group_command) = command.find_subcommand_mut(group) else {
426        return exit::USAGE;
427    };
428    if let Err(err) = group_command.print_help() {
429        eprintln!("{err}");
430        return exit::RUNTIME;
431    }
432    println!();
433    exit::SUCCESS
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439
440    #[test]
441    fn clap_parses_help_when_no_command() {
442        let code = run_from(["git-cli"]);
443        assert_eq!(code, exit::SUCCESS);
444    }
445
446    #[test]
447    fn clap_parses_version_flag() {
448        let code = run_from(["git-cli", "-V"]);
449        assert_eq!(code, exit::SUCCESS);
450    }
451
452    #[test]
453    fn clap_unknown_group_exits_usage() {
454        let code = run_from(["git-cli", "nope"]);
455        assert_eq!(code, exit::USAGE);
456    }
457
458    #[test]
459    fn clap_unknown_nested_subcommand_exits_usage() {
460        let code = run_from(["git-cli", "utils", "nope"]);
461        assert_eq!(code, exit::USAGE);
462    }
463
464    #[test]
465    fn clap_dispatches_nested_subcommand_raw_args() {
466        let cli =
467            Cli::try_parse_from(["git-cli", "utils", "copy-staged", "--both"]).expect("parse");
468
469        let Some(Group::Utils(group)) = cli.group else {
470            panic!("expected utils group");
471        };
472        let Some(UtilsCommand::CopyStaged(raw)) = group.command else {
473            panic!("expected copy-staged command");
474        };
475        assert_eq!(raw.args, vec!["--both".to_string()]);
476    }
477
478    #[test]
479    fn clap_dispatches_worktree_raw_args() {
480        let cli =
481            Cli::try_parse_from(["git-cli", "worktree", "add", "topic-one", "--from", "main"])
482                .expect("parse");
483
484        let Some(Group::Worktree(group)) = cli.group else {
485            panic!("expected worktree group");
486        };
487        let Some(WorktreeCommand::Add(raw)) = group.command else {
488            panic!("expected add command");
489        };
490        assert_eq!(
491            raw.args,
492            vec![
493                "topic-one".to_string(),
494                "--from".to_string(),
495                "main".to_string()
496            ]
497        );
498    }
499}