1#include "cache.h"
2#include "config.h"
3#include "builtin.h"
4#include "exec-cmd.h"
5#include "run-command.h"
6#include "levenshtein.h"
7#include "help.h"
8#include "command-list.h"
9#include "string-list.h"
10#include "column.h"
11#include "version.h"
12#include "refs.h"
13#include "parse-options.h"
14
15struct category_description {
16 uint32_t category;
17 const char *desc;
18};
19static uint32_t common_mask =
20 CAT_init | CAT_worktree | CAT_info |
21 CAT_history | CAT_remote;
22static struct category_description common_categories[] = {
23 { CAT_init, N_("start a working area (see also: git help tutorial)") },
24 { CAT_worktree, N_("work on the current change (see also: git help everyday)") },
25 { CAT_info, N_("examine the history and state (see also: git help revisions)") },
26 { CAT_history, N_("grow, mark and tweak your common history") },
27 { CAT_remote, N_("collaborate (see also: git help workflows)") },
28 { 0, NULL }
29};
30static struct category_description main_categories[] = {
31 { CAT_mainporcelain, N_("Main Porcelain Commands") },
32 { CAT_ancillarymanipulators, N_("Ancillary Commands / Manipulators") },
33 { CAT_ancillaryinterrogators, N_("Ancillary Commands / Interrogators") },
34 { CAT_foreignscminterface, N_("Interacting with Others") },
35 { CAT_plumbingmanipulators, N_("Low-level Commands / Manipulators") },
36 { CAT_plumbinginterrogators, N_("Low-level Commands / Interrogators") },
37 { CAT_synchingrepositories, N_("Low-level Commands / Synching Repositories") },
38 { CAT_purehelpers, N_("Low-level Commands / Internal Helpers") },
39 { 0, NULL }
40};
41
42static const char *drop_prefix(const char *name, uint32_t category)
43{
44 const char *new_name;
45
46 if (skip_prefix(name, "git-", &new_name))
47 return new_name;
48 if (category == CAT_guide && skip_prefix(name, "git", &new_name))
49 return new_name;
50 return name;
51
52}
53
54static void extract_cmds(struct cmdname_help **p_cmds, uint32_t mask)
55{
56 int i, nr = 0;
57 struct cmdname_help *cmds;
58
59 if (ARRAY_SIZE(command_list) == 0)
60 BUG("empty command_list[] is a sign of broken generate-cmdlist.sh");
61
62 ALLOC_ARRAY(cmds, ARRAY_SIZE(command_list) + 1);
63
64 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
65 const struct cmdname_help *cmd = command_list + i;
66
67 if (!(cmd->category & mask))
68 continue;
69
70 cmds[nr] = *cmd;
71 cmds[nr].name = drop_prefix(cmd->name, cmd->category);
72
73 nr++;
74 }
75 cmds[nr].name = NULL;
76 *p_cmds = cmds;
77}
78
79static void print_command_list(const struct cmdname_help *cmds,
80 uint32_t mask, int longest)
81{
82 int i;
83
84 for (i = 0; cmds[i].name; i++) {
85 if (cmds[i].category & mask) {
86 printf(" %s ", cmds[i].name);
87 mput_char(' ', longest - strlen(cmds[i].name));
88 puts(_(cmds[i].help));
89 }
90 }
91}
92
93static int cmd_name_cmp(const void *elem1, const void *elem2)
94{
95 const struct cmdname_help *e1 = elem1;
96 const struct cmdname_help *e2 = elem2;
97
98 return strcmp(e1->name, e2->name);
99}
100
101static void print_cmd_by_category(const struct category_description *catdesc)
102{
103 struct cmdname_help *cmds;
104 int longest = 0;
105 int i, nr = 0;
106 uint32_t mask = 0;
107
108 for (i = 0; catdesc[i].desc; i++)
109 mask |= catdesc[i].category;
110
111 extract_cmds(&cmds, mask);
112
113 for (i = 0; cmds[i].name; i++, nr++) {
114 if (longest < strlen(cmds[i].name))
115 longest = strlen(cmds[i].name);
116 }
117 QSORT(cmds, nr, cmd_name_cmp);
118
119 for (i = 0; catdesc[i].desc; i++) {
120 uint32_t mask = catdesc[i].category;
121 const char *desc = catdesc[i].desc;
122
123 printf("\n%s\n", _(desc));
124 print_command_list(cmds, mask, longest);
125 }
126 free(cmds);
127}
128
129void add_cmdname(struct cmdnames *cmds, const char *name, int len)
130{
131 struct cmdname *ent;
132 FLEX_ALLOC_MEM(ent, name, name, len);
133 ent->len = len;
134
135 ALLOC_GROW(cmds->names, cmds->cnt + 1, cmds->alloc);
136 cmds->names[cmds->cnt++] = ent;
137}
138
139static void clean_cmdnames(struct cmdnames *cmds)
140{
141 int i;
142 for (i = 0; i < cmds->cnt; ++i)
143 free(cmds->names[i]);
144 free(cmds->names);
145 cmds->cnt = 0;
146 cmds->alloc = 0;
147}
148
149static int cmdname_compare(const void *a_, const void *b_)
150{
151 struct cmdname *a = *(struct cmdname **)a_;
152 struct cmdname *b = *(struct cmdname **)b_;
153 return strcmp(a->name, b->name);
154}
155
156static void uniq(struct cmdnames *cmds)
157{
158 int i, j;
159
160 if (!cmds->cnt)
161 return;
162
163 for (i = j = 1; i < cmds->cnt; i++) {
164 if (!strcmp(cmds->names[i]->name, cmds->names[j-1]->name))
165 free(cmds->names[i]);
166 else
167 cmds->names[j++] = cmds->names[i];
168 }
169
170 cmds->cnt = j;
171}
172
173void exclude_cmds(struct cmdnames *cmds, struct cmdnames *excludes)
174{
175 int ci, cj, ei;
176 int cmp;
177
178 ci = cj = ei = 0;
179 while (ci < cmds->cnt && ei < excludes->cnt) {
180 cmp = strcmp(cmds->names[ci]->name, excludes->names[ei]->name);
181 if (cmp < 0)
182 cmds->names[cj++] = cmds->names[ci++];
183 else if (cmp == 0) {
184 ei++;
185 free(cmds->names[ci++]);
186 } else if (cmp > 0)
187 ei++;
188 }
189
190 while (ci < cmds->cnt)
191 cmds->names[cj++] = cmds->names[ci++];
192
193 cmds->cnt = cj;
194}
195
196static void pretty_print_cmdnames(struct cmdnames *cmds, unsigned int colopts)
197{
198 struct string_list list = STRING_LIST_INIT_NODUP;
199 struct column_options copts;
200 int i;
201
202 for (i = 0; i < cmds->cnt; i++)
203 string_list_append(&list, cmds->names[i]->name);
204 /*
205 * always enable column display, we only consult column.*
206 * about layout strategy and stuff
207 */
208 colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
209 memset(&copts, 0, sizeof(copts));
210 copts.indent = " ";
211 copts.padding = 2;
212 print_columns(&list, colopts, &copts);
213 string_list_clear(&list, 0);
214}
215
216static void list_commands_in_dir(struct cmdnames *cmds,
217 const char *path,
218 const char *prefix)
219{
220 DIR *dir = opendir(path);
221 struct dirent *de;
222 struct strbuf buf = STRBUF_INIT;
223 int len;
224
225 if (!dir)
226 return;
227 if (!prefix)
228 prefix = "git-";
229
230 strbuf_addf(&buf, "%s/", path);
231 len = buf.len;
232
233 while ((de = readdir(dir)) != NULL) {
234 const char *ent;
235 size_t entlen;
236
237 if (!skip_prefix(de->d_name, prefix, &ent))
238 continue;
239
240 strbuf_setlen(&buf, len);
241 strbuf_addstr(&buf, de->d_name);
242 if (!is_executable(buf.buf))
243 continue;
244
245 entlen = strlen(ent);
246 strip_suffix(ent, ".exe", &entlen);
247
248 add_cmdname(cmds, ent, entlen);
249 }
250 closedir(dir);
251 strbuf_release(&buf);
252}
253
254void load_command_list(const char *prefix,
255 struct cmdnames *main_cmds,
256 struct cmdnames *other_cmds)
257{
258 const char *env_path = getenv("PATH");
259 const char *exec_path = git_exec_path();
260
261 if (exec_path) {
262 list_commands_in_dir(main_cmds, exec_path, prefix);
263 QSORT(main_cmds->names, main_cmds->cnt, cmdname_compare);
264 uniq(main_cmds);
265 }
266
267 if (env_path) {
268 char *paths, *path, *colon;
269 path = paths = xstrdup(env_path);
270 while (1) {
271 if ((colon = strchr(path, PATH_SEP)))
272 *colon = 0;
273 if (!exec_path || strcmp(path, exec_path))
274 list_commands_in_dir(other_cmds, path, prefix);
275
276 if (!colon)
277 break;
278 path = colon + 1;
279 }
280 free(paths);
281
282 QSORT(other_cmds->names, other_cmds->cnt, cmdname_compare);
283 uniq(other_cmds);
284 }
285 exclude_cmds(other_cmds, main_cmds);
286}
287
288void list_commands(unsigned int colopts,
289 struct cmdnames *main_cmds, struct cmdnames *other_cmds)
290{
291 if (main_cmds->cnt) {
292 const char *exec_path = git_exec_path();
293 printf_ln(_("available git commands in '%s'"), exec_path);
294 putchar('\n');
295 pretty_print_cmdnames(main_cmds, colopts);
296 putchar('\n');
297 }
298
299 if (other_cmds->cnt) {
300 printf_ln(_("git commands available from elsewhere on your $PATH"));
301 putchar('\n');
302 pretty_print_cmdnames(other_cmds, colopts);
303 putchar('\n');
304 }
305}
306
307void list_common_cmds_help(void)
308{
309 puts(_("These are common Git commands used in various situations:"));
310 print_cmd_by_category(common_categories);
311}
312
313void list_all_main_cmds(struct string_list *list)
314{
315 struct cmdnames main_cmds, other_cmds;
316 int i;
317
318 memset(&main_cmds, 0, sizeof(main_cmds));
319 memset(&other_cmds, 0, sizeof(other_cmds));
320 load_command_list("git-", &main_cmds, &other_cmds);
321
322 for (i = 0; i < main_cmds.cnt; i++)
323 string_list_append(list, main_cmds.names[i]->name);
324
325 clean_cmdnames(&main_cmds);
326 clean_cmdnames(&other_cmds);
327}
328
329void list_all_other_cmds(struct string_list *list)
330{
331 struct cmdnames main_cmds, other_cmds;
332 int i;
333
334 memset(&main_cmds, 0, sizeof(main_cmds));
335 memset(&other_cmds, 0, sizeof(other_cmds));
336 load_command_list("git-", &main_cmds, &other_cmds);
337
338 for (i = 0; i < other_cmds.cnt; i++)
339 string_list_append(list, other_cmds.names[i]->name);
340
341 clean_cmdnames(&main_cmds);
342 clean_cmdnames(&other_cmds);
343}
344
345void list_cmds_by_category(struct string_list *list,
346 const char *cat)
347{
348 int i, n = ARRAY_SIZE(command_list);
349 uint32_t cat_id = 0;
350
351 for (i = 0; category_names[i]; i++) {
352 if (!strcmp(cat, category_names[i])) {
353 cat_id = 1UL << i;
354 break;
355 }
356 }
357 if (!cat_id)
358 die(_("unsupported command listing type '%s'"), cat);
359
360 for (i = 0; i < n; i++) {
361 struct cmdname_help *cmd = command_list + i;
362
363 if (!(cmd->category & cat_id))
364 continue;
365 string_list_append(list, drop_prefix(cmd->name, cmd->category));
366 }
367}
368
369void list_cmds_by_config(struct string_list *list)
370{
371 const char *cmd_list;
372
373 /*
374 * There's no actual repository setup at this point (and even
375 * if there is, we don't really care; only global config
376 * matters). If we accidentally set up a repository, it's ok
377 * too since the caller (git --list-cmds=) should exit shortly
378 * anyway.
379 */
380 if (git_config_get_string_const("completion.commands", &cmd_list))
381 return;
382
383 string_list_sort(list);
384 string_list_remove_duplicates(list, 0);
385
386 while (*cmd_list) {
387 struct strbuf sb = STRBUF_INIT;
388 const char *p = strchrnul(cmd_list, ' ');
389
390 strbuf_add(&sb, cmd_list, p - cmd_list);
391 if (*cmd_list == '-')
392 string_list_remove(list, cmd_list + 1, 0);
393 else
394 string_list_insert(list, sb.buf);
395 strbuf_release(&sb);
396 while (*p == ' ')
397 p++;
398 cmd_list = p;
399 }
400}
401
402void list_common_guides_help(void)
403{
404 struct category_description catdesc[] = {
405 { CAT_guide, N_("The common Git guides are:") },
406 { 0, NULL }
407 };
408 print_cmd_by_category(catdesc);
409 putchar('\n');
410}
411
412struct slot_expansion {
413 const char *prefix;
414 const char *placeholder;
415 void (*fn)(struct string_list *list, const char *prefix);
416 int found;
417};
418
419void list_config_help(int for_human)
420{
421 struct slot_expansion slot_expansions[] = {
422 { "advice", "*", list_config_advices },
423 { "color.branch", "<slot>", list_config_color_branch_slots },
424 { "color.decorate", "<slot>", list_config_color_decorate_slots },
425 { "color.diff", "<slot>", list_config_color_diff_slots },
426 { "color.grep", "<slot>", list_config_color_grep_slots },
427 { "color.interactive", "<slot>", list_config_color_interactive_slots },
428 { "color.remote", "<slot>", list_config_color_sideband_slots },
429 { "color.status", "<slot>", list_config_color_status_slots },
430 { "fsck", "<msg-id>", list_config_fsck_msg_ids },
431 { "receive.fsck", "<msg-id>", list_config_fsck_msg_ids },
432 { NULL, NULL, NULL }
433 };
434 const char **p;
435 struct slot_expansion *e;
436 struct string_list keys = STRING_LIST_INIT_DUP;
437 int i;
438
439 for (p = config_name_list; *p; p++) {
440 const char *var = *p;
441 struct strbuf sb = STRBUF_INIT;
442
443 for (e = slot_expansions; e->prefix; e++) {
444
445 strbuf_reset(&sb);
446 strbuf_addf(&sb, "%s.%s", e->prefix, e->placeholder);
447 if (!strcasecmp(var, sb.buf)) {
448 e->fn(&keys, e->prefix);
449 e->found++;
450 break;
451 }
452 }
453 strbuf_release(&sb);
454 if (!e->prefix)
455 string_list_append(&keys, var);
456 }
457
458 for (e = slot_expansions; e->prefix; e++)
459 if (!e->found)
460 BUG("slot_expansion %s.%s is not used",
461 e->prefix, e->placeholder);
462
463 string_list_sort(&keys);
464 for (i = 0; i < keys.nr; i++) {
465 const char *var = keys.items[i].string;
466 const char *wildcard, *tag, *cut;
467
468 if (for_human) {
469 puts(var);
470 continue;
471 }
472
473 wildcard = strchr(var, '*');
474 tag = strchr(var, '<');
475
476 if (!wildcard && !tag) {
477 puts(var);
478 continue;
479 }
480
481 if (wildcard && !tag)
482 cut = wildcard;
483 else if (!wildcard && tag)
484 cut = tag;
485 else
486 cut = wildcard < tag ? wildcard : tag;
487
488 /*
489 * We may produce duplicates, but that's up to
490 * git-completion.bash to handle
491 */
492 printf("%.*s\n", (int)(cut - var), var);
493 }
494 string_list_clear(&keys, 0);
495}
496
497void list_all_cmds_help(void)
498{
499 print_cmd_by_category(main_categories);
500}
501
502int is_in_cmdlist(struct cmdnames *c, const char *s)
503{
504 int i;
505 for (i = 0; i < c->cnt; i++)
506 if (!strcmp(s, c->names[i]->name))
507 return 1;
508 return 0;
509}
510
511static int autocorrect;
512static struct cmdnames aliases;
513
514static int git_unknown_cmd_config(const char *var, const char *value, void *cb)
515{
516 const char *p;
517
518 if (!strcmp(var, "help.autocorrect"))
519 autocorrect = git_config_int(var,value);
520 /* Also use aliases for command lookup */
521 if (skip_prefix(var, "alias.", &p))
522 add_cmdname(&aliases, p, strlen(p));
523
524 return git_default_config(var, value, cb);
525}
526
527static int levenshtein_compare(const void *p1, const void *p2)
528{
529 const struct cmdname *const *c1 = p1, *const *c2 = p2;
530 const char *s1 = (*c1)->name, *s2 = (*c2)->name;
531 int l1 = (*c1)->len;
532 int l2 = (*c2)->len;
533 return l1 != l2 ? l1 - l2 : strcmp(s1, s2);
534}
535
536static void add_cmd_list(struct cmdnames *cmds, struct cmdnames *old)
537{
538 int i;
539 ALLOC_GROW(cmds->names, cmds->cnt + old->cnt, cmds->alloc);
540
541 for (i = 0; i < old->cnt; i++)
542 cmds->names[cmds->cnt++] = old->names[i];
543 FREE_AND_NULL(old->names);
544 old->cnt = 0;
545}
546
547/* An empirically derived magic number */
548#define SIMILARITY_FLOOR 7
549#define SIMILAR_ENOUGH(x) ((x) < SIMILARITY_FLOOR)
550
551static const char bad_interpreter_advice[] =
552 N_("'%s' appears to be a git command, but we were not\n"
553 "able to execute it. Maybe git-%s is broken?");
554
555const char *help_unknown_cmd(const char *cmd)
556{
557 int i, n, best_similarity = 0;
558 struct cmdnames main_cmds, other_cmds;
559 struct cmdname_help *common_cmds;
560
561 memset(&main_cmds, 0, sizeof(main_cmds));
562 memset(&other_cmds, 0, sizeof(other_cmds));
563 memset(&aliases, 0, sizeof(aliases));
564
565 read_early_config(git_unknown_cmd_config, NULL);
566
567 load_command_list("git-", &main_cmds, &other_cmds);
568
569 add_cmd_list(&main_cmds, &aliases);
570 add_cmd_list(&main_cmds, &other_cmds);
571 QSORT(main_cmds.names, main_cmds.cnt, cmdname_compare);
572 uniq(&main_cmds);
573
574 extract_cmds(&common_cmds, common_mask);
575
576 /* This abuses cmdname->len for levenshtein distance */
577 for (i = 0, n = 0; i < main_cmds.cnt; i++) {
578 int cmp = 0; /* avoid compiler stupidity */
579 const char *candidate = main_cmds.names[i]->name;
580
581 /*
582 * An exact match means we have the command, but
583 * for some reason exec'ing it gave us ENOENT; probably
584 * it's a bad interpreter in the #! line.
585 */
586 if (!strcmp(candidate, cmd))
587 die(_(bad_interpreter_advice), cmd, cmd);
588
589 /* Does the candidate appear in common_cmds list? */
590 while (common_cmds[n].name &&
591 (cmp = strcmp(common_cmds[n].name, candidate)) < 0)
592 n++;
593 if (common_cmds[n].name && !cmp) {
594 /* Yes, this is one of the common commands */
595 n++; /* use the entry from common_cmds[] */
596 if (starts_with(candidate, cmd)) {
597 /* Give prefix match a very good score */
598 main_cmds.names[i]->len = 0;
599 continue;
600 }
601 }
602
603 main_cmds.names[i]->len =
604 levenshtein(cmd, candidate, 0, 2, 1, 3) + 1;
605 }
606 FREE_AND_NULL(common_cmds);
607
608 QSORT(main_cmds.names, main_cmds.cnt, levenshtein_compare);
609
610 if (!main_cmds.cnt)
611 die(_("Uh oh. Your system reports no Git commands at all."));
612
613 /* skip and count prefix matches */
614 for (n = 0; n < main_cmds.cnt && !main_cmds.names[n]->len; n++)
615 ; /* still counting */
616
617 if (main_cmds.cnt <= n) {
618 /* prefix matches with everything? that is too ambiguous */
619 best_similarity = SIMILARITY_FLOOR + 1;
620 } else {
621 /* count all the most similar ones */
622 for (best_similarity = main_cmds.names[n++]->len;
623 (n < main_cmds.cnt &&
624 best_similarity == main_cmds.names[n]->len);
625 n++)
626 ; /* still counting */
627 }
628 if (autocorrect && n == 1 && SIMILAR_ENOUGH(best_similarity)) {
629 const char *assumed = main_cmds.names[0]->name;
630 main_cmds.names[0] = NULL;
631 clean_cmdnames(&main_cmds);
632 fprintf_ln(stderr,
633 _("WARNING: You called a Git command named '%s', "
634 "which does not exist."),
635 cmd);
636 if (autocorrect < 0)
637 fprintf_ln(stderr,
638 _("Continuing under the assumption that "
639 "you meant '%s'."),
640 assumed);
641 else {
642 fprintf_ln(stderr,
643 _("Continuing in %0.1f seconds, "
644 "assuming that you meant '%s'."),
645 (float)autocorrect/10.0, assumed);
646 sleep_millisec(autocorrect * 100);
647 }
648 return assumed;
649 }
650
651 fprintf_ln(stderr, _("git: '%s' is not a git command. See 'git --help'."), cmd);
652
653 if (SIMILAR_ENOUGH(best_similarity)) {
654 fprintf_ln(stderr,
655 Q_("\nThe most similar command is",
656 "\nThe most similar commands are",
657 n));
658
659 for (i = 0; i < n; i++)
660 fprintf(stderr, "\t%s\n", main_cmds.names[i]->name);
661 }
662
663 exit(1);
664}
665
666int cmd_version(int argc, const char **argv, const char *prefix)
667{
668 int build_options = 0;
669 const char * const usage[] = {
670 N_("git version [<options>]"),
671 NULL
672 };
673 struct option options[] = {
674 OPT_BOOL(0, "build-options", &build_options,
675 "also print build options"),
676 OPT_END()
677 };
678
679 argc = parse_options(argc, argv, prefix, options, usage, 0);
680
681 /*
682 * The format of this string should be kept stable for compatibility
683 * with external projects that rely on the output of "git version".
684 *
685 * Always show the version, even if other options are given.
686 */
687 printf("git version %s\n", git_version_string);
688
689 if (build_options) {
690 printf("cpu: %s\n", GIT_HOST_CPU);
691 if (git_built_from_commit_string[0])
692 printf("built from commit: %s\n",
693 git_built_from_commit_string);
694 else
695 printf("no commit associated with this build\n");
696 printf("sizeof-long: %d\n", (int)sizeof(long));
697 printf("sizeof-size_t: %d\n", (int)sizeof(size_t));
698 /* NEEDSWORK: also save and output GIT-BUILD_OPTIONS? */
699 }
700 return 0;
701}
702
703struct similar_ref_cb {
704 const char *base_ref;
705 struct string_list *similar_refs;
706};
707
708static int append_similar_ref(const char *refname, const struct object_id *oid,
709 int flags, void *cb_data)
710{
711 struct similar_ref_cb *cb = (struct similar_ref_cb *)(cb_data);
712 char *branch = strrchr(refname, '/') + 1;
713 const char *remote;
714
715 /* A remote branch of the same name is deemed similar */
716 if (skip_prefix(refname, "refs/remotes/", &remote) &&
717 !strcmp(branch, cb->base_ref))
718 string_list_append(cb->similar_refs, remote);
719 return 0;
720}
721
722static struct string_list guess_refs(const char *ref)
723{
724 struct similar_ref_cb ref_cb;
725 struct string_list similar_refs = STRING_LIST_INIT_NODUP;
726
727 ref_cb.base_ref = ref;
728 ref_cb.similar_refs = &similar_refs;
729 for_each_ref(append_similar_ref, &ref_cb);
730 return similar_refs;
731}
732
733void help_unknown_ref(const char *ref, const char *cmd, const char *error)
734{
735 int i;
736 struct string_list suggested_refs = guess_refs(ref);
737
738 fprintf_ln(stderr, _("%s: %s - %s"), cmd, ref, error);
739
740 if (suggested_refs.nr > 0) {
741 fprintf_ln(stderr,
742 Q_("\nDid you mean this?",
743 "\nDid you mean one of these?",
744 suggested_refs.nr));
745 for (i = 0; i < suggested_refs.nr; i++)
746 fprintf(stderr, "\t%s\n", suggested_refs.items[i].string);
747 }
748
749 string_list_clear(&suggested_refs, 0);
750 exit(1);
751}