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 = "Display help message for worktree")]
164    Help,
165}
166
167#[derive(Debug, Args)]
168#[command(disable_help_subcommand = true)]
169struct CiGroup {
170    #[command(subcommand)]
171    command: Option<CiCommand>,
172}
173
174#[derive(Debug, Subcommand)]
175enum CiCommand {
176    #[command(about = "Cherry-pick into CI branch")]
177    Pick(RawArgs),
178    #[command(about = "Display help message for ci")]
179    Help,
180}
181
182#[derive(Debug, Args)]
183#[command(disable_help_subcommand = true)]
184struct OpenGroup {
185    #[command(subcommand)]
186    command: Option<OpenCommand>,
187}
188
189#[derive(Debug, Subcommand)]
190enum OpenCommand {
191    #[command(about = "Open repository page")]
192    Repo(RawArgs),
193    #[command(about = "Open branch tree page")]
194    Branch(RawArgs),
195    #[command(
196        name = "default-branch",
197        visible_alias = "default",
198        about = "Open default branch tree page"
199    )]
200    DefaultBranch(RawArgs),
201    #[command(about = "Open commit page")]
202    Commit(RawArgs),
203    #[command(about = "Open compare page")]
204    Compare(RawArgs),
205    #[command(
206        name = "pr",
207        visible_aliases = ["pull-request", "mr", "merge-request"],
208        about = "Open pull or merge request page"
209    )]
210    Pr(RawArgs),
211    #[command(
212        visible_aliases = ["prs", "merge-requests", "mrs"],
213        about = "Open pull or merge request list"
214    )]
215    Pulls(RawArgs),
216    #[command(visible_alias = "issue", about = "Open issues list/page")]
217    Issues(RawArgs),
218    #[command(visible_alias = "action", about = "Open actions page")]
219    Actions(RawArgs),
220    #[command(visible_alias = "release", about = "Open releases list/page")]
221    Releases(RawArgs),
222    #[command(visible_alias = "tag", about = "Open tags list/page")]
223    Tags(RawArgs),
224    #[command(visible_alias = "history", about = "Open commit history page")]
225    Commits(RawArgs),
226    #[command(visible_alias = "blob", about = "Open file page")]
227    File(RawArgs),
228    #[command(about = "Open blame page")]
229    Blame(RawArgs),
230    #[command(about = "Display help message for open")]
231    Help,
232}
233
234#[derive(Debug, Args)]
235#[command(disable_help_flag = true)]
236struct RawArgs {
237    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
238    args: Vec<String>,
239}
240
241pub fn run() -> i32 {
242    run_from(std::env::args())
243}
244
245fn run_from<I, T>(args: I) -> i32
246where
247    I: IntoIterator<Item = T>,
248    T: Into<OsString> + Clone,
249{
250    let cli = match Cli::try_parse_from(args) {
251        Ok(cli) => cli,
252        Err(err) => return print_parse_error(err),
253    };
254
255    match cli.group {
256        Some(Group::Utils(group)) => run_utils(group),
257        Some(Group::Reset(group)) => run_reset(group),
258        Some(Group::Commit(group)) => run_commit(group),
259        Some(Group::Branch(group)) => run_branch(group),
260        Some(Group::Worktree(group)) => run_worktree(group),
261        Some(Group::Ci(group)) => run_ci(group),
262        Some(Group::Open(group)) => run_open(group),
263        Some(Group::Completion(raw)) => run_completion(raw),
264        Some(Group::Help) | None => print_root_help(),
265    }
266}
267
268fn run_utils(group: UtilsGroup) -> i32 {
269    match group.command {
270        Some(UtilsCommand::Zip(raw)) => utils::dispatch("zip", &raw.args).unwrap_or(exit::USAGE),
271        Some(UtilsCommand::CopyStaged(raw)) => {
272            utils::dispatch("copy-staged", &raw.args).unwrap_or(exit::USAGE)
273        }
274        Some(UtilsCommand::Root(raw)) => utils::dispatch("root", &raw.args).unwrap_or(exit::USAGE),
275        Some(UtilsCommand::CommitHash(raw)) => {
276            utils::dispatch("commit-hash", &raw.args).unwrap_or(exit::USAGE)
277        }
278        Some(UtilsCommand::Help) | None => print_group_help("utils"),
279    }
280}
281
282fn run_reset(group: ResetGroup) -> i32 {
283    match group.command {
284        Some(ResetCommand::Soft(raw)) => reset::dispatch("soft", &raw.args).unwrap_or(exit::USAGE),
285        Some(ResetCommand::Mixed(raw)) => {
286            reset::dispatch("mixed", &raw.args).unwrap_or(exit::USAGE)
287        }
288        Some(ResetCommand::Hard(raw)) => reset::dispatch("hard", &raw.args).unwrap_or(exit::USAGE),
289        Some(ResetCommand::Undo(raw)) => reset::dispatch("undo", &raw.args).unwrap_or(exit::USAGE),
290        Some(ResetCommand::BackHead(raw)) => {
291            reset::dispatch("back-head", &raw.args).unwrap_or(exit::USAGE)
292        }
293        Some(ResetCommand::BackCheckout(raw)) => {
294            reset::dispatch("back-checkout", &raw.args).unwrap_or(exit::USAGE)
295        }
296        Some(ResetCommand::Remote(raw)) => {
297            reset::dispatch("remote", &raw.args).unwrap_or(exit::USAGE)
298        }
299        Some(ResetCommand::Help) | None => print_group_help("reset"),
300    }
301}
302
303fn run_commit(group: CommitGroup) -> i32 {
304    match group.command {
305        Some(CommitCommand::Context(raw)) => commit::dispatch("context", &raw.args),
306        Some(CommitCommand::ContextJson(raw)) => commit::dispatch("context-json", &raw.args),
307        Some(CommitCommand::ToStash(raw)) => commit::dispatch("to-stash", &raw.args),
308        Some(CommitCommand::Help) | None => print_group_help("commit"),
309    }
310}
311
312fn run_branch(group: BranchGroup) -> i32 {
313    match group.command {
314        Some(BranchCommand::Cleanup(raw)) => {
315            branch::dispatch("cleanup", &raw.args).unwrap_or(exit::USAGE)
316        }
317        Some(BranchCommand::Help) | None => print_group_help("branch"),
318    }
319}
320
321fn run_ci(group: CiGroup) -> i32 {
322    match group.command {
323        Some(CiCommand::Pick(raw)) => ci::dispatch("pick", &raw.args).unwrap_or(exit::USAGE),
324        Some(CiCommand::Help) | None => print_group_help("ci"),
325    }
326}
327
328fn run_worktree(group: WorktreeGroup) -> i32 {
329    match group.command {
330        Some(WorktreeCommand::Add(raw)) => {
331            worktree::dispatch("add", &raw.args).unwrap_or(exit::USAGE)
332        }
333        Some(WorktreeCommand::List(raw)) => {
334            worktree::dispatch("list", &raw.args).unwrap_or(exit::USAGE)
335        }
336        Some(WorktreeCommand::Remove(raw)) => {
337            worktree::dispatch("remove", &raw.args).unwrap_or(exit::USAGE)
338        }
339        Some(WorktreeCommand::Prune(raw)) => {
340            worktree::dispatch("prune", &raw.args).unwrap_or(exit::USAGE)
341        }
342        Some(WorktreeCommand::Help) | None => print_group_help("worktree"),
343    }
344}
345
346fn run_open(group: OpenGroup) -> i32 {
347    match group.command {
348        Some(OpenCommand::Repo(raw)) => open::dispatch("repo", &raw.args).unwrap_or(exit::USAGE),
349        Some(OpenCommand::Branch(raw)) => {
350            open::dispatch("branch", &raw.args).unwrap_or(exit::USAGE)
351        }
352        Some(OpenCommand::DefaultBranch(raw)) => {
353            open::dispatch("default-branch", &raw.args).unwrap_or(exit::USAGE)
354        }
355        Some(OpenCommand::Commit(raw)) => {
356            open::dispatch("commit", &raw.args).unwrap_or(exit::USAGE)
357        }
358        Some(OpenCommand::Compare(raw)) => {
359            open::dispatch("compare", &raw.args).unwrap_or(exit::USAGE)
360        }
361        Some(OpenCommand::Pr(raw)) => open::dispatch("pr", &raw.args).unwrap_or(exit::USAGE),
362        Some(OpenCommand::Pulls(raw)) => open::dispatch("pulls", &raw.args).unwrap_or(exit::USAGE),
363        Some(OpenCommand::Issues(raw)) => {
364            open::dispatch("issues", &raw.args).unwrap_or(exit::USAGE)
365        }
366        Some(OpenCommand::Actions(raw)) => {
367            open::dispatch("actions", &raw.args).unwrap_or(exit::USAGE)
368        }
369        Some(OpenCommand::Releases(raw)) => {
370            open::dispatch("releases", &raw.args).unwrap_or(exit::USAGE)
371        }
372        Some(OpenCommand::Tags(raw)) => open::dispatch("tags", &raw.args).unwrap_or(exit::USAGE),
373        Some(OpenCommand::Commits(raw)) => {
374            open::dispatch("commits", &raw.args).unwrap_or(exit::USAGE)
375        }
376        Some(OpenCommand::File(raw)) => open::dispatch("file", &raw.args).unwrap_or(exit::USAGE),
377        Some(OpenCommand::Blame(raw)) => open::dispatch("blame", &raw.args).unwrap_or(exit::USAGE),
378        Some(OpenCommand::Help) | None => print_group_help("open"),
379    }
380}
381
382fn run_completion(raw: RawArgs) -> i32 {
383    let Some(shell) = raw.args.first() else {
384        eprintln!("usage: git-cli completion <bash|zsh>");
385        return exit::USAGE;
386    };
387    completion::dispatch(shell, &raw.args[1..])
388}
389
390fn print_parse_error(err: clap::Error) -> i32 {
391    let kind = err.kind();
392    if let Err(print_err) = err.print() {
393        eprintln!("{print_err}");
394        return exit::RUNTIME;
395    }
396
397    if matches!(kind, ErrorKind::DisplayHelp | ErrorKind::DisplayVersion) {
398        exit::SUCCESS
399    } else {
400        exit::USAGE
401    }
402}
403
404fn print_root_help() -> i32 {
405    let mut command = Cli::command();
406    if let Err(err) = command.print_help() {
407        eprintln!("{err}");
408        return exit::RUNTIME;
409    }
410    println!();
411    exit::SUCCESS
412}
413
414fn print_group_help(group: &str) -> i32 {
415    let mut command = Cli::command();
416    let Some(group_command) = command.find_subcommand_mut(group) else {
417        return exit::USAGE;
418    };
419    if let Err(err) = group_command.print_help() {
420        eprintln!("{err}");
421        return exit::RUNTIME;
422    }
423    println!();
424    exit::SUCCESS
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430
431    #[test]
432    fn clap_parses_help_when_no_command() {
433        let code = run_from(["git-cli"]);
434        assert_eq!(code, exit::SUCCESS);
435    }
436
437    #[test]
438    fn clap_parses_version_flag() {
439        let code = run_from(["git-cli", "-V"]);
440        assert_eq!(code, exit::SUCCESS);
441    }
442
443    #[test]
444    fn clap_unknown_group_exits_usage() {
445        let code = run_from(["git-cli", "nope"]);
446        assert_eq!(code, exit::USAGE);
447    }
448
449    #[test]
450    fn clap_unknown_nested_subcommand_exits_usage() {
451        let code = run_from(["git-cli", "utils", "nope"]);
452        assert_eq!(code, exit::USAGE);
453    }
454
455    #[test]
456    fn clap_dispatches_nested_subcommand_raw_args() {
457        let cli =
458            Cli::try_parse_from(["git-cli", "utils", "copy-staged", "--both"]).expect("parse");
459
460        let Some(Group::Utils(group)) = cli.group else {
461            panic!("expected utils group");
462        };
463        let Some(UtilsCommand::CopyStaged(raw)) = group.command else {
464            panic!("expected copy-staged command");
465        };
466        assert_eq!(raw.args, vec!["--both".to_string()]);
467    }
468
469    #[test]
470    fn clap_dispatches_worktree_raw_args() {
471        let cli =
472            Cli::try_parse_from(["git-cli", "worktree", "add", "topic-one", "--from", "main"])
473                .expect("parse");
474
475        let Some(Group::Worktree(group)) = cli.group else {
476            panic!("expected worktree group");
477        };
478        let Some(WorktreeCommand::Add(raw)) = group.command else {
479            panic!("expected add command");
480        };
481        assert_eq!(
482            raw.args,
483            vec![
484                "topic-one".to_string(),
485                "--from".to_string(),
486                "main".to_string()
487            ]
488        );
489    }
490}