Skip to main content

git_cli/
completion.rs

1use clap::{Arg, ArgAction, Command, ValueHint};
2use clap_complete::CompleteEnv;
3use clap_complete::engine::{ArgValueCandidates, CompletionCandidate};
4use clap_complete::env::{Bash, EnvCompleter, Zsh};
5use std::io;
6
7pub fn dispatch(shell_raw: &str, extra: &[String]) -> i32 {
8    if !extra.is_empty() {
9        eprintln!("git-cli: error: expected `git-cli completion <bash|zsh>`");
10        return 1;
11    }
12
13    match shell_raw {
14        "bash" => emit_registration(&Bash),
15        "zsh" => emit_registration(&Zsh),
16        other => {
17            eprintln!("git-cli: error: unsupported completion shell '{other}'");
18            eprintln!("usage: git-cli completion <bash|zsh>");
19            1
20        }
21    }
22}
23
24/// Emit a `clap_complete` `CompleteEnv` dynamic-completion registration stub for
25/// the given shell.
26///
27/// git-cli is a `completion_engine=dynamic` CLI (see the completion coverage
28/// matrix): candidates such as live worktree names and branches are computed at
29/// TAB time by the binary itself, so the exported script is a thin registration
30/// that calls back into `git-cli` rather than a static `generate()` script. This
31/// remains a single completion path per the completion development standard.
32fn emit_registration<C: EnvCompleter>(completer: &C) -> i32 {
33    match completer.write_registration(
34        "COMPLETE",
35        "git-cli",
36        "git-cli",
37        "git-cli",
38        &mut io::stdout(),
39    ) {
40        Ok(()) => 0,
41        Err(err) => {
42            eprintln!("git-cli: error: failed to emit completion registration: {err}");
43            1
44        }
45    }
46}
47
48/// Intercept `COMPLETE=<shell> git-cli ...` completion requests before the
49/// hand-rolled dispatch.
50///
51/// On a completion request `CompleteEnv::complete()` prints the registration
52/// stub (or the runtime candidates) and exits the process itself; when
53/// `COMPLETE` is unset it returns and the normal application path proceeds
54/// unchanged, so this is a no-op for ordinary invocations.
55pub(crate) fn complete_env() {
56    CompleteEnv::with_factory(build_command_model).complete();
57}
58
59/// Live completion candidates for `git-cli worktree go|remove <target>`:
60/// managed worktree slugs and their branch names, sourced at TAB time from the
61/// real `git worktree list`. Supersedes the static `gxwcd` workaround.
62fn worktree_target_candidates() -> Vec<CompletionCandidate> {
63    crate::worktree::go_target_candidates()
64        .into_iter()
65        .map(CompletionCandidate::new)
66        .collect()
67}
68
69fn build_command_model() -> Command {
70    Command::new("git-cli")
71        .version(env!("CARGO_PKG_VERSION"))
72        .long_version(nils_build_info::long_version(env!("CARGO_PKG_VERSION")))
73        .about("Git helper CLI")
74        .disable_help_subcommand(true)
75        .subcommand(build_utils_group())
76        .subcommand(build_reset_group())
77        .subcommand(build_commit_group())
78        .subcommand(build_branch_group())
79        .subcommand(build_worktree_group())
80        .subcommand(build_ci_group())
81        .subcommand(build_open_group())
82        .subcommand(Command::new("help").about("Display help message for git-cli"))
83        .subcommand(
84            Command::new("completion")
85                .about("Export shell completion script")
86                .arg(
87                    Arg::new("shell")
88                        .value_name("shell")
89                        .value_parser(["bash", "zsh"])
90                        .required(true),
91                ),
92        )
93}
94
95fn build_utils_group() -> Command {
96    Command::new("utils")
97        .about("Utility helpers")
98        .subcommand(Command::new("zip").about("Create zip archive from HEAD"))
99        .subcommand(
100            Command::new("copy-staged")
101                .visible_alias("copy")
102                .about("Copy staged diff to clipboard")
103                .arg(
104                    Arg::new("stdout")
105                        .long("stdout")
106                        .help("Print staged diff to stdout")
107                        .action(ArgAction::SetTrue),
108                )
109                .arg(
110                    Arg::new("print")
111                        .short('p')
112                        .long("print")
113                        .help("Alias for --stdout")
114                        .action(ArgAction::SetTrue),
115                )
116                .arg(
117                    Arg::new("both")
118                        .long("both")
119                        .help("Print diff and copy it to clipboard")
120                        .action(ArgAction::SetTrue),
121                ),
122        )
123        .subcommand(
124            Command::new("root").about("Jump to git root").arg(
125                Arg::new("shell")
126                    .long("shell")
127                    .help("Print shell command instead of plain output")
128                    .action(ArgAction::SetTrue),
129            ),
130        )
131        .subcommand(
132            Command::new("commit-hash")
133                .visible_alias("hash")
134                .about("Resolve commit hash")
135                .arg(Arg::new("ref").value_name("ref")),
136        )
137        .subcommand(Command::new("help").about("Display help message for utils"))
138}
139
140fn build_reset_group() -> Command {
141    let count_arg = || Arg::new("count").value_name("count");
142
143    Command::new("reset")
144        .about("Reset helpers")
145        .subcommand(
146            Command::new("soft")
147                .about("Reset to HEAD~N (soft)")
148                .arg(count_arg()),
149        )
150        .subcommand(
151            Command::new("mixed")
152                .about("Reset to HEAD~N (mixed)")
153                .arg(count_arg()),
154        )
155        .subcommand(
156            Command::new("hard")
157                .about("Reset to HEAD~N (hard)")
158                .arg(count_arg()),
159        )
160        .subcommand(Command::new("undo").about("Undo last reset"))
161        .subcommand(Command::new("back-head").about("Checkout HEAD@{1}"))
162        .subcommand(Command::new("back-checkout").about("Return to previous branch"))
163        .subcommand(
164            Command::new("remote")
165                .about("Reset to remote branch")
166                .arg(
167                    Arg::new("ref")
168                        .long("ref")
169                        .help("Remote ref in <remote>/<branch> form")
170                        .value_name("ref"),
171                )
172                .arg(
173                    Arg::new("remote")
174                        .short('r')
175                        .long("remote")
176                        .help("Remote name")
177                        .value_name("remote"),
178                )
179                .arg(
180                    Arg::new("branch")
181                        .short('b')
182                        .long("branch")
183                        .help("Remote branch name")
184                        .value_name("branch"),
185                )
186                .arg(
187                    Arg::new("no-fetch")
188                        .long("no-fetch")
189                        .help("Skip fetching remote refs")
190                        .action(ArgAction::SetTrue),
191                )
192                .arg(
193                    Arg::new("prune")
194                        .long("prune")
195                        .help("Run fetch with --prune")
196                        .action(ArgAction::SetTrue),
197                )
198                .arg(
199                    Arg::new("clean")
200                        .long("clean")
201                        .help("Run git clean -fd after reset")
202                        .action(ArgAction::SetTrue),
203                )
204                .arg(
205                    Arg::new("set-upstream")
206                        .long("set-upstream")
207                        .help("Set upstream to the target remote branch")
208                        .action(ArgAction::SetTrue),
209                )
210                .arg(
211                    Arg::new("yes")
212                        .short('y')
213                        .long("yes")
214                        .help("Skip confirmation prompts")
215                        .action(ArgAction::SetTrue),
216                ),
217        )
218        .subcommand(Command::new("help").about("Display help message for reset"))
219}
220
221fn build_commit_group() -> Command {
222    Command::new("commit")
223        .about("Commit helpers")
224        .subcommand(
225            Command::new("context")
226                .about("Print commit context")
227                .arg(
228                    Arg::new("stdout")
229                        .long("stdout")
230                        .help("Print report to stdout")
231                        .action(ArgAction::SetTrue),
232                )
233                .arg(
234                    Arg::new("both")
235                        .long("both")
236                        .help("Print report and write output file")
237                        .action(ArgAction::SetTrue),
238                )
239                .arg(
240                    Arg::new("no-color")
241                        .long("no-color")
242                        .help("Disable ANSI colors")
243                        .action(ArgAction::SetTrue),
244                )
245                .arg(
246                    Arg::new("include")
247                        .long("include")
248                        .help("Additional glob(s) to include")
249                        .value_name("glob")
250                        .num_args(1..),
251                ),
252        )
253        .subcommand(
254            Command::new("context-json")
255                .visible_aliases(["context_json", "contextjson", "json"])
256                .about("Print commit context as JSON")
257                .arg(
258                    Arg::new("stdout")
259                        .long("stdout")
260                        .help("Print JSON to stdout")
261                        .action(ArgAction::SetTrue),
262                )
263                .arg(
264                    Arg::new("both")
265                        .long("both")
266                        .help("Print JSON and write files")
267                        .action(ArgAction::SetTrue),
268                )
269                .arg(
270                    Arg::new("pretty")
271                        .long("pretty")
272                        .help("Pretty-print JSON output")
273                        .action(ArgAction::SetTrue),
274                )
275                .arg(
276                    Arg::new("bundle")
277                        .long("bundle")
278                        .help("Write bundle files to output directory")
279                        .action(ArgAction::SetTrue),
280                )
281                .arg(
282                    Arg::new("out-dir")
283                        .long("out-dir")
284                        .help("Output directory for generated files")
285                        .value_name("path"),
286                ),
287        )
288        .subcommand(
289            Command::new("to-stash")
290                .visible_alias("stash")
291                .about("Create stash from commit")
292                .arg(Arg::new("ref").value_name("ref")),
293        )
294        .subcommand(Command::new("help").about("Display help message for commit"))
295}
296
297fn build_branch_group() -> Command {
298    Command::new("branch")
299        .about("Branch helpers")
300        .subcommand(
301            Command::new("cleanup")
302                .visible_alias("delete-merged")
303                .about("Delete merged branches")
304                .arg(
305                    Arg::new("base")
306                        .short('b')
307                        .long("base")
308                        .help("Base ref used to determine merged branches")
309                        .value_name("base"),
310                )
311                .arg(
312                    Arg::new("squash")
313                        .short('s')
314                        .long("squash")
315                        .help("Include branches already applied via squash")
316                        .action(ArgAction::SetTrue),
317                )
318                .arg(
319                    Arg::new("remove-worktrees")
320                        .short('w')
321                        .long("remove-worktrees")
322                        .help("Force-remove linked worktrees for candidate branches")
323                        .action(ArgAction::SetTrue),
324                ),
325        )
326        .subcommand(Command::new("help").about("Display help message for branch"))
327}
328
329fn build_worktree_group() -> Command {
330    Command::new("worktree")
331        .about("Worktree helpers")
332        .subcommand(
333            Command::new("add")
334                .about("Create a managed agent worktree")
335                .arg(Arg::new("slug").value_name("slug").required(true))
336                .arg(
337                    Arg::new("from")
338                        .long("from")
339                        .help("Base ref for the new branch")
340                        .value_name("ref"),
341                )
342                .arg(kind_arg())
343                .arg(format_arg()),
344        )
345        .subcommand(
346            Command::new("list")
347                .about("List git worktrees")
348                .arg(format_arg()),
349        )
350        .subcommand(
351            Command::new("go")
352                .about("Resolve a worktree path to cd into")
353                .arg(
354                    Arg::new("target")
355                        .value_name("slug-or-branch-or-path")
356                        .required(true)
357                        .add(ArgValueCandidates::new(worktree_target_candidates)),
358                )
359                .arg(
360                    Arg::new("shell")
361                        .long("shell")
362                        .help("Print an evaluable cd command instead of the bare path")
363                        .action(ArgAction::SetTrue),
364                )
365                .arg(format_arg()),
366        )
367        .subcommand(
368            Command::new("remove")
369                .about("Remove a managed worktree by slug or path")
370                .arg(
371                    Arg::new("target")
372                        .value_name("slug-or-path")
373                        .required(true)
374                        .add(ArgValueCandidates::new(worktree_target_candidates)),
375                )
376                .arg(format_arg()),
377        )
378        .subcommand(
379            Command::new("prune")
380                .about("Prune stale git worktree metadata")
381                .arg(format_arg()),
382        )
383        .subcommand(Command::new("help").about("Display help message for worktree"))
384}
385
386fn build_ci_group() -> Command {
387    Command::new("ci")
388        .about("CI helpers")
389        .subcommand(
390            Command::new("pick")
391                .about("Cherry-pick into CI branch")
392                .arg(
393                    Arg::new("remote")
394                        .short('r')
395                        .long("remote")
396                        .help("Remote used for fetch/push")
397                        .value_name("name"),
398                )
399                .arg(
400                    Arg::new("no-fetch")
401                        .long("no-fetch")
402                        .help("Skip remote fetch before branch creation")
403                        .action(ArgAction::SetTrue),
404                )
405                .arg(
406                    Arg::new("force")
407                        .short('f')
408                        .long("force")
409                        .help("Reset existing CI branch and force push")
410                        .action(ArgAction::SetTrue),
411                )
412                .arg(
413                    Arg::new("stay")
414                        .long("stay")
415                        .help("Stay on CI branch after push")
416                        .action(ArgAction::SetTrue),
417                ),
418        )
419        .subcommand(Command::new("help").about("Display help message for ci"))
420}
421
422fn build_open_group() -> Command {
423    Command::new("open")
424        .about("Open remote pages")
425        .subcommand(
426            Command::new("repo")
427                .about("Open repository page")
428                .arg(remotes_arg()),
429        )
430        .subcommand(
431            Command::new("branch")
432                .about("Open branch tree page")
433                .arg(Arg::new("ref").value_name("ref")),
434        )
435        .subcommand(
436            Command::new("default-branch")
437                .visible_alias("default")
438                .about("Open default branch tree page")
439                .arg(remotes_arg()),
440        )
441        .subcommand(
442            Command::new("commit")
443                .about("Open commit page")
444                .arg(Arg::new("ref").value_name("ref")),
445        )
446        .subcommand(
447            Command::new("compare")
448                .about("Open compare page")
449                .arg(Arg::new("from").value_name("from"))
450                .arg(Arg::new("to").value_name("to")),
451        )
452        .subcommand(
453            Command::new("pr")
454                .visible_aliases(["pull-request", "mr", "merge-request"])
455                .about("Open pull or merge request page")
456                .arg(Arg::new("id").value_name("id")),
457        )
458        .subcommand(
459            Command::new("pulls")
460                .visible_aliases(["prs", "merge-requests", "mrs"])
461                .about("Open pull or merge request list"),
462        )
463        .subcommand(
464            Command::new("issues")
465                .visible_alias("issue")
466                .about("Open issues list/page")
467                .arg(Arg::new("id").value_name("id")),
468        )
469        .subcommand(
470            Command::new("actions")
471                .visible_alias("action")
472                .about("Open actions page")
473                .arg(Arg::new("workflow").value_name("workflow")),
474        )
475        .subcommand(
476            Command::new("releases")
477                .visible_alias("release")
478                .about("Open releases list/page")
479                .arg(Arg::new("tag").value_name("tag")),
480        )
481        .subcommand(
482            Command::new("tags")
483                .visible_alias("tag")
484                .about("Open tags list/page")
485                .arg(Arg::new("tag").value_name("tag")),
486        )
487        .subcommand(
488            Command::new("commits")
489                .visible_alias("history")
490                .about("Open commit history page")
491                .arg(Arg::new("ref").value_name("ref")),
492        )
493        .subcommand(
494            Command::new("file")
495                .visible_alias("blob")
496                .about("Open file page")
497                .arg(
498                    Arg::new("path")
499                        .value_name("path")
500                        .value_hint(ValueHint::FilePath),
501                )
502                .arg(Arg::new("ref").value_name("ref")),
503        )
504        .subcommand(
505            Command::new("blame")
506                .about("Open blame page")
507                .arg(
508                    Arg::new("path")
509                        .value_name("path")
510                        .value_hint(ValueHint::FilePath),
511                )
512                .arg(Arg::new("ref").value_name("ref")),
513        )
514        .subcommand(Command::new("help").about("Display help message for open"))
515}
516
517fn remotes_arg() -> Arg {
518    Arg::new("remote").value_name("remote")
519}
520
521fn format_arg() -> Arg {
522    Arg::new("format")
523        .long("format")
524        .help("Output format")
525        .value_name("format")
526        .value_parser(["text", "json"])
527}
528
529fn kind_arg() -> Arg {
530    Arg::new("kind")
531        .long("kind")
532        .help("Branch prefix kind")
533        .value_name("kind")
534        .value_parser(["feature", "bug", "chore", "docs", "ci", "refactor"])
535}
536
537#[cfg(test)]
538mod tests {
539    use super::build_command_model;
540
541    #[test]
542    fn worktree_group_exposes_go_subcommand() {
543        let cmd = build_command_model();
544        let worktree = cmd
545            .find_subcommand("worktree")
546            .expect("worktree group present");
547        let go = worktree
548            .find_subcommand("go")
549            .expect("worktree go subcommand present in completion model");
550        assert!(
551            go.get_arguments().any(|arg| arg.get_id() == "shell"),
552            "worktree go should advertise --shell in completion"
553        );
554    }
555
556    #[test]
557    fn worktree_add_kind_advertises_value_candidates() {
558        let cmd = build_command_model();
559        let worktree = cmd
560            .find_subcommand("worktree")
561            .expect("worktree group present");
562        let add = worktree
563            .find_subcommand("add")
564            .expect("worktree add subcommand present");
565        let kind = add
566            .get_arguments()
567            .find(|arg| arg.get_id() == "kind")
568            .expect("worktree add --kind arg present in completion model");
569        let values: Vec<String> = kind
570            .get_possible_values()
571            .iter()
572            .map(|value| value.get_name().to_string())
573            .collect();
574        for expected in ["feature", "bug", "chore", "docs", "ci", "refactor"] {
575            assert!(
576                values.iter().any(|value| value == expected),
577                "kind candidate `{expected}` should be present, got {values:?}"
578            );
579        }
580    }
581}