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};
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 = "CI helpers")]
33    Ci(CiGroup),
34    #[command(about = "Open remote pages")]
35    Open(OpenGroup),
36    #[command(about = "Export shell completion script")]
37    Completion(RawArgs),
38    #[command(about = "Display help message for git-cli")]
39    Help,
40}
41
42#[derive(Debug, Args)]
43#[command(disable_help_subcommand = true)]
44struct UtilsGroup {
45    #[command(subcommand)]
46    command: Option<UtilsCommand>,
47}
48
49#[derive(Debug, Subcommand)]
50enum UtilsCommand {
51    #[command(about = "Create zip archive from HEAD")]
52    Zip(RawArgs),
53    #[command(
54        name = "copy-staged",
55        visible_alias = "copy",
56        about = "Copy staged diff to clipboard"
57    )]
58    CopyStaged(RawArgs),
59    #[command(about = "Jump to git root")]
60    Root(RawArgs),
61    #[command(
62        name = "commit-hash",
63        visible_alias = "hash",
64        about = "Resolve commit hash"
65    )]
66    CommitHash(RawArgs),
67    #[command(about = "Display help message for utils")]
68    Help,
69}
70
71#[derive(Debug, Args)]
72#[command(disable_help_subcommand = true)]
73struct ResetGroup {
74    #[command(subcommand)]
75    command: Option<ResetCommand>,
76}
77
78#[derive(Debug, Subcommand)]
79enum ResetCommand {
80    #[command(about = "Reset to HEAD~N (soft)")]
81    Soft(RawArgs),
82    #[command(about = "Reset to HEAD~N (mixed)")]
83    Mixed(RawArgs),
84    #[command(about = "Reset to HEAD~N (hard)")]
85    Hard(RawArgs),
86    #[command(about = "Undo last reset")]
87    Undo(RawArgs),
88    #[command(name = "back-head", about = "Checkout HEAD@{1}")]
89    BackHead(RawArgs),
90    #[command(name = "back-checkout", about = "Return to previous branch")]
91    BackCheckout(RawArgs),
92    #[command(about = "Reset to remote branch")]
93    Remote(RawArgs),
94    #[command(about = "Display help message for reset")]
95    Help,
96}
97
98#[derive(Debug, Args)]
99#[command(disable_help_subcommand = true)]
100struct CommitGroup {
101    #[command(subcommand)]
102    command: Option<CommitCommand>,
103}
104
105#[derive(Debug, Subcommand)]
106enum CommitCommand {
107    #[command(about = "Print commit context")]
108    Context(RawArgs),
109    #[command(
110        name = "context-json",
111        visible_aliases = ["context_json", "contextjson", "json"],
112        about = "Print commit context as JSON"
113    )]
114    ContextJson(RawArgs),
115    #[command(
116        name = "to-stash",
117        visible_alias = "stash",
118        about = "Create stash from commit"
119    )]
120    ToStash(RawArgs),
121    #[command(about = "Display help message for commit")]
122    Help,
123}
124
125#[derive(Debug, Args)]
126#[command(disable_help_subcommand = true)]
127struct BranchGroup {
128    #[command(subcommand)]
129    command: Option<BranchCommand>,
130}
131
132#[derive(Debug, Subcommand)]
133enum BranchCommand {
134    #[command(
135        name = "cleanup",
136        visible_alias = "delete-merged",
137        about = "Delete merged branches"
138    )]
139    Cleanup(RawArgs),
140    #[command(about = "Display help message for branch")]
141    Help,
142}
143
144#[derive(Debug, Args)]
145#[command(disable_help_subcommand = true)]
146struct CiGroup {
147    #[command(subcommand)]
148    command: Option<CiCommand>,
149}
150
151#[derive(Debug, Subcommand)]
152enum CiCommand {
153    #[command(about = "Cherry-pick into CI branch")]
154    Pick(RawArgs),
155    #[command(about = "Display help message for ci")]
156    Help,
157}
158
159#[derive(Debug, Args)]
160#[command(disable_help_subcommand = true)]
161struct OpenGroup {
162    #[command(subcommand)]
163    command: Option<OpenCommand>,
164}
165
166#[derive(Debug, Subcommand)]
167enum OpenCommand {
168    #[command(about = "Open repository page")]
169    Repo(RawArgs),
170    #[command(about = "Open branch tree page")]
171    Branch(RawArgs),
172    #[command(
173        name = "default-branch",
174        visible_alias = "default",
175        about = "Open default branch tree page"
176    )]
177    DefaultBranch(RawArgs),
178    #[command(about = "Open commit page")]
179    Commit(RawArgs),
180    #[command(about = "Open compare page")]
181    Compare(RawArgs),
182    #[command(
183        name = "pr",
184        visible_aliases = ["pull-request", "mr", "merge-request"],
185        about = "Open pull or merge request page"
186    )]
187    Pr(RawArgs),
188    #[command(
189        visible_aliases = ["prs", "merge-requests", "mrs"],
190        about = "Open pull or merge request list"
191    )]
192    Pulls(RawArgs),
193    #[command(visible_alias = "issue", about = "Open issues list/page")]
194    Issues(RawArgs),
195    #[command(visible_alias = "action", about = "Open actions page")]
196    Actions(RawArgs),
197    #[command(visible_alias = "release", about = "Open releases list/page")]
198    Releases(RawArgs),
199    #[command(visible_alias = "tag", about = "Open tags list/page")]
200    Tags(RawArgs),
201    #[command(visible_alias = "history", about = "Open commit history page")]
202    Commits(RawArgs),
203    #[command(visible_alias = "blob", about = "Open file page")]
204    File(RawArgs),
205    #[command(about = "Open blame page")]
206    Blame(RawArgs),
207    #[command(about = "Display help message for open")]
208    Help,
209}
210
211#[derive(Debug, Args)]
212#[command(disable_help_flag = true)]
213struct RawArgs {
214    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
215    args: Vec<String>,
216}
217
218pub fn run() -> i32 {
219    run_from(std::env::args())
220}
221
222fn run_from<I, T>(args: I) -> i32
223where
224    I: IntoIterator<Item = T>,
225    T: Into<OsString> + Clone,
226{
227    let cli = match Cli::try_parse_from(args) {
228        Ok(cli) => cli,
229        Err(err) => return print_parse_error(err),
230    };
231
232    match cli.group {
233        Some(Group::Utils(group)) => run_utils(group),
234        Some(Group::Reset(group)) => run_reset(group),
235        Some(Group::Commit(group)) => run_commit(group),
236        Some(Group::Branch(group)) => run_branch(group),
237        Some(Group::Ci(group)) => run_ci(group),
238        Some(Group::Open(group)) => run_open(group),
239        Some(Group::Completion(raw)) => run_completion(raw),
240        Some(Group::Help) | None => print_root_help(),
241    }
242}
243
244fn run_utils(group: UtilsGroup) -> i32 {
245    match group.command {
246        Some(UtilsCommand::Zip(raw)) => utils::dispatch("zip", &raw.args).unwrap_or(exit::USAGE),
247        Some(UtilsCommand::CopyStaged(raw)) => {
248            utils::dispatch("copy-staged", &raw.args).unwrap_or(exit::USAGE)
249        }
250        Some(UtilsCommand::Root(raw)) => utils::dispatch("root", &raw.args).unwrap_or(exit::USAGE),
251        Some(UtilsCommand::CommitHash(raw)) => {
252            utils::dispatch("commit-hash", &raw.args).unwrap_or(exit::USAGE)
253        }
254        Some(UtilsCommand::Help) | None => print_group_help("utils"),
255    }
256}
257
258fn run_reset(group: ResetGroup) -> i32 {
259    match group.command {
260        Some(ResetCommand::Soft(raw)) => reset::dispatch("soft", &raw.args).unwrap_or(exit::USAGE),
261        Some(ResetCommand::Mixed(raw)) => {
262            reset::dispatch("mixed", &raw.args).unwrap_or(exit::USAGE)
263        }
264        Some(ResetCommand::Hard(raw)) => reset::dispatch("hard", &raw.args).unwrap_or(exit::USAGE),
265        Some(ResetCommand::Undo(raw)) => reset::dispatch("undo", &raw.args).unwrap_or(exit::USAGE),
266        Some(ResetCommand::BackHead(raw)) => {
267            reset::dispatch("back-head", &raw.args).unwrap_or(exit::USAGE)
268        }
269        Some(ResetCommand::BackCheckout(raw)) => {
270            reset::dispatch("back-checkout", &raw.args).unwrap_or(exit::USAGE)
271        }
272        Some(ResetCommand::Remote(raw)) => {
273            reset::dispatch("remote", &raw.args).unwrap_or(exit::USAGE)
274        }
275        Some(ResetCommand::Help) | None => print_group_help("reset"),
276    }
277}
278
279fn run_commit(group: CommitGroup) -> i32 {
280    match group.command {
281        Some(CommitCommand::Context(raw)) => commit::dispatch("context", &raw.args),
282        Some(CommitCommand::ContextJson(raw)) => commit::dispatch("context-json", &raw.args),
283        Some(CommitCommand::ToStash(raw)) => commit::dispatch("to-stash", &raw.args),
284        Some(CommitCommand::Help) | None => print_group_help("commit"),
285    }
286}
287
288fn run_branch(group: BranchGroup) -> i32 {
289    match group.command {
290        Some(BranchCommand::Cleanup(raw)) => {
291            branch::dispatch("cleanup", &raw.args).unwrap_or(exit::USAGE)
292        }
293        Some(BranchCommand::Help) | None => print_group_help("branch"),
294    }
295}
296
297fn run_ci(group: CiGroup) -> i32 {
298    match group.command {
299        Some(CiCommand::Pick(raw)) => ci::dispatch("pick", &raw.args).unwrap_or(exit::USAGE),
300        Some(CiCommand::Help) | None => print_group_help("ci"),
301    }
302}
303
304fn run_open(group: OpenGroup) -> i32 {
305    match group.command {
306        Some(OpenCommand::Repo(raw)) => open::dispatch("repo", &raw.args).unwrap_or(exit::USAGE),
307        Some(OpenCommand::Branch(raw)) => {
308            open::dispatch("branch", &raw.args).unwrap_or(exit::USAGE)
309        }
310        Some(OpenCommand::DefaultBranch(raw)) => {
311            open::dispatch("default-branch", &raw.args).unwrap_or(exit::USAGE)
312        }
313        Some(OpenCommand::Commit(raw)) => {
314            open::dispatch("commit", &raw.args).unwrap_or(exit::USAGE)
315        }
316        Some(OpenCommand::Compare(raw)) => {
317            open::dispatch("compare", &raw.args).unwrap_or(exit::USAGE)
318        }
319        Some(OpenCommand::Pr(raw)) => open::dispatch("pr", &raw.args).unwrap_or(exit::USAGE),
320        Some(OpenCommand::Pulls(raw)) => open::dispatch("pulls", &raw.args).unwrap_or(exit::USAGE),
321        Some(OpenCommand::Issues(raw)) => {
322            open::dispatch("issues", &raw.args).unwrap_or(exit::USAGE)
323        }
324        Some(OpenCommand::Actions(raw)) => {
325            open::dispatch("actions", &raw.args).unwrap_or(exit::USAGE)
326        }
327        Some(OpenCommand::Releases(raw)) => {
328            open::dispatch("releases", &raw.args).unwrap_or(exit::USAGE)
329        }
330        Some(OpenCommand::Tags(raw)) => open::dispatch("tags", &raw.args).unwrap_or(exit::USAGE),
331        Some(OpenCommand::Commits(raw)) => {
332            open::dispatch("commits", &raw.args).unwrap_or(exit::USAGE)
333        }
334        Some(OpenCommand::File(raw)) => open::dispatch("file", &raw.args).unwrap_or(exit::USAGE),
335        Some(OpenCommand::Blame(raw)) => open::dispatch("blame", &raw.args).unwrap_or(exit::USAGE),
336        Some(OpenCommand::Help) | None => print_group_help("open"),
337    }
338}
339
340fn run_completion(raw: RawArgs) -> i32 {
341    let Some(shell) = raw.args.first() else {
342        eprintln!("usage: git-cli completion <bash|zsh>");
343        return exit::USAGE;
344    };
345    completion::dispatch(shell, &raw.args[1..])
346}
347
348fn print_parse_error(err: clap::Error) -> i32 {
349    let kind = err.kind();
350    if let Err(print_err) = err.print() {
351        eprintln!("{print_err}");
352        return exit::RUNTIME;
353    }
354
355    if matches!(kind, ErrorKind::DisplayHelp | ErrorKind::DisplayVersion) {
356        exit::SUCCESS
357    } else {
358        exit::USAGE
359    }
360}
361
362fn print_root_help() -> i32 {
363    let mut command = Cli::command();
364    if let Err(err) = command.print_help() {
365        eprintln!("{err}");
366        return exit::RUNTIME;
367    }
368    println!();
369    exit::SUCCESS
370}
371
372fn print_group_help(group: &str) -> i32 {
373    let mut command = Cli::command();
374    let Some(group_command) = command.find_subcommand_mut(group) else {
375        return exit::USAGE;
376    };
377    if let Err(err) = group_command.print_help() {
378        eprintln!("{err}");
379        return exit::RUNTIME;
380    }
381    println!();
382    exit::SUCCESS
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    #[test]
390    fn clap_parses_help_when_no_command() {
391        let code = run_from(["git-cli"]);
392        assert_eq!(code, exit::SUCCESS);
393    }
394
395    #[test]
396    fn clap_parses_version_flag() {
397        let code = run_from(["git-cli", "-V"]);
398        assert_eq!(code, exit::SUCCESS);
399    }
400
401    #[test]
402    fn clap_unknown_group_exits_usage() {
403        let code = run_from(["git-cli", "nope"]);
404        assert_eq!(code, exit::USAGE);
405    }
406
407    #[test]
408    fn clap_unknown_nested_subcommand_exits_usage() {
409        let code = run_from(["git-cli", "utils", "nope"]);
410        assert_eq!(code, exit::USAGE);
411    }
412
413    #[test]
414    fn clap_dispatches_nested_subcommand_raw_args() {
415        let cli =
416            Cli::try_parse_from(["git-cli", "utils", "copy-staged", "--both"]).expect("parse");
417
418        let Some(Group::Utils(group)) = cli.group else {
419            panic!("expected utils group");
420        };
421        let Some(UtilsCommand::CopyStaged(raw)) = group.command else {
422            panic!("expected copy-staged command");
423        };
424        assert_eq!(raw.args, vec!["--both".to_string()]);
425    }
426}