help.con commit version: convert to parse-options (b48cbfc)
   1#include "cache.h"
   2#include "builtin.h"
   3#include "exec_cmd.h"
   4#include "levenshtein.h"
   5#include "help.h"
   6#include "common-cmds.h"
   7#include "string-list.h"
   8#include "column.h"
   9#include "version.h"
  10#include "refs.h"
  11#include "parse-options.h"
  12
  13void add_cmdname(struct cmdnames *cmds, const char *name, int len)
  14{
  15        struct cmdname *ent;
  16        FLEX_ALLOC_MEM(ent, name, name, len);
  17        ent->len = len;
  18
  19        ALLOC_GROW(cmds->names, cmds->cnt + 1, cmds->alloc);
  20        cmds->names[cmds->cnt++] = ent;
  21}
  22
  23static void clean_cmdnames(struct cmdnames *cmds)
  24{
  25        int i;
  26        for (i = 0; i < cmds->cnt; ++i)
  27                free(cmds->names[i]);
  28        free(cmds->names);
  29        cmds->cnt = 0;
  30        cmds->alloc = 0;
  31}
  32
  33static int cmdname_compare(const void *a_, const void *b_)
  34{
  35        struct cmdname *a = *(struct cmdname **)a_;
  36        struct cmdname *b = *(struct cmdname **)b_;
  37        return strcmp(a->name, b->name);
  38}
  39
  40static void uniq(struct cmdnames *cmds)
  41{
  42        int i, j;
  43
  44        if (!cmds->cnt)
  45                return;
  46
  47        for (i = j = 1; i < cmds->cnt; i++) {
  48                if (!strcmp(cmds->names[i]->name, cmds->names[j-1]->name))
  49                        free(cmds->names[i]);
  50                else
  51                        cmds->names[j++] = cmds->names[i];
  52        }
  53
  54        cmds->cnt = j;
  55}
  56
  57void exclude_cmds(struct cmdnames *cmds, struct cmdnames *excludes)
  58{
  59        int ci, cj, ei;
  60        int cmp;
  61
  62        ci = cj = ei = 0;
  63        while (ci < cmds->cnt && ei < excludes->cnt) {
  64                cmp = strcmp(cmds->names[ci]->name, excludes->names[ei]->name);
  65                if (cmp < 0)
  66                        cmds->names[cj++] = cmds->names[ci++];
  67                else if (cmp == 0) {
  68                        ei++;
  69                        free(cmds->names[ci++]);
  70                } else if (cmp > 0)
  71                        ei++;
  72        }
  73
  74        while (ci < cmds->cnt)
  75                cmds->names[cj++] = cmds->names[ci++];
  76
  77        cmds->cnt = cj;
  78}
  79
  80static void pretty_print_cmdnames(struct cmdnames *cmds, unsigned int colopts)
  81{
  82        struct string_list list = STRING_LIST_INIT_NODUP;
  83        struct column_options copts;
  84        int i;
  85
  86        for (i = 0; i < cmds->cnt; i++)
  87                string_list_append(&list, cmds->names[i]->name);
  88        /*
  89         * always enable column display, we only consult column.*
  90         * about layout strategy and stuff
  91         */
  92        colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
  93        memset(&copts, 0, sizeof(copts));
  94        copts.indent = "  ";
  95        copts.padding = 2;
  96        print_columns(&list, colopts, &copts);
  97        string_list_clear(&list, 0);
  98}
  99
 100static int is_executable(const char *name)
 101{
 102        struct stat st;
 103
 104        if (stat(name, &st) || /* stat, not lstat */
 105            !S_ISREG(st.st_mode))
 106                return 0;
 107
 108#if defined(GIT_WINDOWS_NATIVE)
 109        /*
 110         * On Windows there is no executable bit. The file extension
 111         * indicates whether it can be run as an executable, and Git
 112         * has special-handling to detect scripts and launch them
 113         * through the indicated script interpreter. We test for the
 114         * file extension first because virus scanners may make
 115         * it quite expensive to open many files.
 116         */
 117        if (ends_with(name, ".exe"))
 118                return S_IXUSR;
 119
 120{
 121        /*
 122         * Now that we know it does not have an executable extension,
 123         * peek into the file instead.
 124         */
 125        char buf[3] = { 0 };
 126        int n;
 127        int fd = open(name, O_RDONLY);
 128        st.st_mode &= ~S_IXUSR;
 129        if (fd >= 0) {
 130                n = read(fd, buf, 2);
 131                if (n == 2)
 132                        /* look for a she-bang */
 133                        if (!strcmp(buf, "#!"))
 134                                st.st_mode |= S_IXUSR;
 135                close(fd);
 136        }
 137}
 138#endif
 139        return st.st_mode & S_IXUSR;
 140}
 141
 142static void list_commands_in_dir(struct cmdnames *cmds,
 143                                         const char *path,
 144                                         const char *prefix)
 145{
 146        DIR *dir = opendir(path);
 147        struct dirent *de;
 148        struct strbuf buf = STRBUF_INIT;
 149        int len;
 150
 151        if (!dir)
 152                return;
 153        if (!prefix)
 154                prefix = "git-";
 155
 156        strbuf_addf(&buf, "%s/", path);
 157        len = buf.len;
 158
 159        while ((de = readdir(dir)) != NULL) {
 160                const char *ent;
 161                size_t entlen;
 162
 163                if (!skip_prefix(de->d_name, prefix, &ent))
 164                        continue;
 165
 166                strbuf_setlen(&buf, len);
 167                strbuf_addstr(&buf, de->d_name);
 168                if (!is_executable(buf.buf))
 169                        continue;
 170
 171                entlen = strlen(ent);
 172                strip_suffix(ent, ".exe", &entlen);
 173
 174                add_cmdname(cmds, ent, entlen);
 175        }
 176        closedir(dir);
 177        strbuf_release(&buf);
 178}
 179
 180void load_command_list(const char *prefix,
 181                struct cmdnames *main_cmds,
 182                struct cmdnames *other_cmds)
 183{
 184        const char *env_path = getenv("PATH");
 185        const char *exec_path = git_exec_path();
 186
 187        if (exec_path) {
 188                list_commands_in_dir(main_cmds, exec_path, prefix);
 189                QSORT(main_cmds->names, main_cmds->cnt, cmdname_compare);
 190                uniq(main_cmds);
 191        }
 192
 193        if (env_path) {
 194                char *paths, *path, *colon;
 195                path = paths = xstrdup(env_path);
 196                while (1) {
 197                        if ((colon = strchr(path, PATH_SEP)))
 198                                *colon = 0;
 199                        if (!exec_path || strcmp(path, exec_path))
 200                                list_commands_in_dir(other_cmds, path, prefix);
 201
 202                        if (!colon)
 203                                break;
 204                        path = colon + 1;
 205                }
 206                free(paths);
 207
 208                QSORT(other_cmds->names, other_cmds->cnt, cmdname_compare);
 209                uniq(other_cmds);
 210        }
 211        exclude_cmds(other_cmds, main_cmds);
 212}
 213
 214void list_commands(unsigned int colopts,
 215                   struct cmdnames *main_cmds, struct cmdnames *other_cmds)
 216{
 217        if (main_cmds->cnt) {
 218                const char *exec_path = git_exec_path();
 219                printf_ln(_("available git commands in '%s'"), exec_path);
 220                putchar('\n');
 221                pretty_print_cmdnames(main_cmds, colopts);
 222                putchar('\n');
 223        }
 224
 225        if (other_cmds->cnt) {
 226                printf_ln(_("git commands available from elsewhere on your $PATH"));
 227                putchar('\n');
 228                pretty_print_cmdnames(other_cmds, colopts);
 229                putchar('\n');
 230        }
 231}
 232
 233static int cmd_group_cmp(const void *elem1, const void *elem2)
 234{
 235        const struct cmdname_help *e1 = elem1;
 236        const struct cmdname_help *e2 = elem2;
 237
 238        if (e1->group < e2->group)
 239                return -1;
 240        if (e1->group > e2->group)
 241                return 1;
 242        return strcmp(e1->name, e2->name);
 243}
 244
 245void list_common_cmds_help(void)
 246{
 247        int i, longest = 0;
 248        int current_grp = -1;
 249
 250        for (i = 0; i < ARRAY_SIZE(common_cmds); i++) {
 251                if (longest < strlen(common_cmds[i].name))
 252                        longest = strlen(common_cmds[i].name);
 253        }
 254
 255        QSORT(common_cmds, ARRAY_SIZE(common_cmds), cmd_group_cmp);
 256
 257        puts(_("These are common Git commands used in various situations:"));
 258
 259        for (i = 0; i < ARRAY_SIZE(common_cmds); i++) {
 260                if (common_cmds[i].group != current_grp) {
 261                        printf("\n%s\n", _(common_cmd_groups[common_cmds[i].group]));
 262                        current_grp = common_cmds[i].group;
 263                }
 264
 265                printf("   %s   ", common_cmds[i].name);
 266                mput_char(' ', longest - strlen(common_cmds[i].name));
 267                puts(_(common_cmds[i].help));
 268        }
 269}
 270
 271int is_in_cmdlist(struct cmdnames *c, const char *s)
 272{
 273        int i;
 274        for (i = 0; i < c->cnt; i++)
 275                if (!strcmp(s, c->names[i]->name))
 276                        return 1;
 277        return 0;
 278}
 279
 280static int autocorrect;
 281static struct cmdnames aliases;
 282
 283static int git_unknown_cmd_config(const char *var, const char *value, void *cb)
 284{
 285        const char *p;
 286
 287        if (!strcmp(var, "help.autocorrect"))
 288                autocorrect = git_config_int(var,value);
 289        /* Also use aliases for command lookup */
 290        if (skip_prefix(var, "alias.", &p))
 291                add_cmdname(&aliases, p, strlen(p));
 292
 293        return git_default_config(var, value, cb);
 294}
 295
 296static int levenshtein_compare(const void *p1, const void *p2)
 297{
 298        const struct cmdname *const *c1 = p1, *const *c2 = p2;
 299        const char *s1 = (*c1)->name, *s2 = (*c2)->name;
 300        int l1 = (*c1)->len;
 301        int l2 = (*c2)->len;
 302        return l1 != l2 ? l1 - l2 : strcmp(s1, s2);
 303}
 304
 305static void add_cmd_list(struct cmdnames *cmds, struct cmdnames *old)
 306{
 307        int i;
 308        ALLOC_GROW(cmds->names, cmds->cnt + old->cnt, cmds->alloc);
 309
 310        for (i = 0; i < old->cnt; i++)
 311                cmds->names[cmds->cnt++] = old->names[i];
 312        free(old->names);
 313        old->cnt = 0;
 314        old->names = NULL;
 315}
 316
 317/* An empirically derived magic number */
 318#define SIMILARITY_FLOOR 7
 319#define SIMILAR_ENOUGH(x) ((x) < SIMILARITY_FLOOR)
 320
 321static const char bad_interpreter_advice[] =
 322        N_("'%s' appears to be a git command, but we were not\n"
 323        "able to execute it. Maybe git-%s is broken?");
 324
 325const char *help_unknown_cmd(const char *cmd)
 326{
 327        int i, n, best_similarity = 0;
 328        struct cmdnames main_cmds, other_cmds;
 329
 330        memset(&main_cmds, 0, sizeof(main_cmds));
 331        memset(&other_cmds, 0, sizeof(other_cmds));
 332        memset(&aliases, 0, sizeof(aliases));
 333
 334        git_config(git_unknown_cmd_config, NULL);
 335
 336        load_command_list("git-", &main_cmds, &other_cmds);
 337
 338        add_cmd_list(&main_cmds, &aliases);
 339        add_cmd_list(&main_cmds, &other_cmds);
 340        QSORT(main_cmds.names, main_cmds.cnt, cmdname_compare);
 341        uniq(&main_cmds);
 342
 343        /* This abuses cmdname->len for levenshtein distance */
 344        for (i = 0, n = 0; i < main_cmds.cnt; i++) {
 345                int cmp = 0; /* avoid compiler stupidity */
 346                const char *candidate = main_cmds.names[i]->name;
 347
 348                /*
 349                 * An exact match means we have the command, but
 350                 * for some reason exec'ing it gave us ENOENT; probably
 351                 * it's a bad interpreter in the #! line.
 352                 */
 353                if (!strcmp(candidate, cmd))
 354                        die(_(bad_interpreter_advice), cmd, cmd);
 355
 356                /* Does the candidate appear in common_cmds list? */
 357                while (n < ARRAY_SIZE(common_cmds) &&
 358                       (cmp = strcmp(common_cmds[n].name, candidate)) < 0)
 359                        n++;
 360                if ((n < ARRAY_SIZE(common_cmds)) && !cmp) {
 361                        /* Yes, this is one of the common commands */
 362                        n++; /* use the entry from common_cmds[] */
 363                        if (starts_with(candidate, cmd)) {
 364                                /* Give prefix match a very good score */
 365                                main_cmds.names[i]->len = 0;
 366                                continue;
 367                        }
 368                }
 369
 370                main_cmds.names[i]->len =
 371                        levenshtein(cmd, candidate, 0, 2, 1, 3) + 1;
 372        }
 373
 374        QSORT(main_cmds.names, main_cmds.cnt, levenshtein_compare);
 375
 376        if (!main_cmds.cnt)
 377                die(_("Uh oh. Your system reports no Git commands at all."));
 378
 379        /* skip and count prefix matches */
 380        for (n = 0; n < main_cmds.cnt && !main_cmds.names[n]->len; n++)
 381                ; /* still counting */
 382
 383        if (main_cmds.cnt <= n) {
 384                /* prefix matches with everything? that is too ambiguous */
 385                best_similarity = SIMILARITY_FLOOR + 1;
 386        } else {
 387                /* count all the most similar ones */
 388                for (best_similarity = main_cmds.names[n++]->len;
 389                     (n < main_cmds.cnt &&
 390                      best_similarity == main_cmds.names[n]->len);
 391                     n++)
 392                        ; /* still counting */
 393        }
 394        if (autocorrect && n == 1 && SIMILAR_ENOUGH(best_similarity)) {
 395                const char *assumed = main_cmds.names[0]->name;
 396                main_cmds.names[0] = NULL;
 397                clean_cmdnames(&main_cmds);
 398                fprintf_ln(stderr,
 399                           _("WARNING: You called a Git command named '%s', "
 400                             "which does not exist.\n"
 401                             "Continuing under the assumption that you meant '%s'"),
 402                        cmd, assumed);
 403                if (autocorrect > 0) {
 404                        fprintf_ln(stderr, _("in %0.1f seconds automatically..."),
 405                                (float)autocorrect/10.0);
 406                        sleep_millisec(autocorrect * 100);
 407                }
 408                return assumed;
 409        }
 410
 411        fprintf_ln(stderr, _("git: '%s' is not a git command. See 'git --help'."), cmd);
 412
 413        if (SIMILAR_ENOUGH(best_similarity)) {
 414                fprintf_ln(stderr,
 415                           Q_("\nDid you mean this?",
 416                              "\nDid you mean one of these?",
 417                           n));
 418
 419                for (i = 0; i < n; i++)
 420                        fprintf(stderr, "\t%s\n", main_cmds.names[i]->name);
 421        }
 422
 423        exit(1);
 424}
 425
 426int cmd_version(int argc, const char **argv, const char *prefix)
 427{
 428        int build_options = 0;
 429        const char * const usage[] = {
 430                N_("git version [<options>]"),
 431                NULL
 432        };
 433        struct option options[] = {
 434                OPT_BOOL(0, "build-options", &build_options,
 435                         "also print build options"),
 436                OPT_END()
 437        };
 438
 439        argc = parse_options(argc, argv, prefix, options, usage, 0);
 440
 441        /*
 442         * The format of this string should be kept stable for compatibility
 443         * with external projects that rely on the output of "git version".
 444         *
 445         * Always show the version, even if other options are given.
 446         */
 447        printf("git version %s\n", git_version_string);
 448
 449        if (build_options) {
 450                printf("sizeof-long: %d\n", (int)sizeof(long));
 451                /* NEEDSWORK: also save and output GIT-BUILD_OPTIONS? */
 452        }
 453        return 0;
 454}
 455
 456struct similar_ref_cb {
 457        const char *base_ref;
 458        struct string_list *similar_refs;
 459};
 460
 461static int append_similar_ref(const char *refname, const struct object_id *oid,
 462                              int flags, void *cb_data)
 463{
 464        struct similar_ref_cb *cb = (struct similar_ref_cb *)(cb_data);
 465        char *branch = strrchr(refname, '/') + 1;
 466        const char *remote;
 467
 468        /* A remote branch of the same name is deemed similar */
 469        if (skip_prefix(refname, "refs/remotes/", &remote) &&
 470            !strcmp(branch, cb->base_ref))
 471                string_list_append(cb->similar_refs, remote);
 472        return 0;
 473}
 474
 475static struct string_list guess_refs(const char *ref)
 476{
 477        struct similar_ref_cb ref_cb;
 478        struct string_list similar_refs = STRING_LIST_INIT_NODUP;
 479
 480        ref_cb.base_ref = ref;
 481        ref_cb.similar_refs = &similar_refs;
 482        for_each_ref(append_similar_ref, &ref_cb);
 483        return similar_refs;
 484}
 485
 486void help_unknown_ref(const char *ref, const char *cmd, const char *error)
 487{
 488        int i;
 489        struct string_list suggested_refs = guess_refs(ref);
 490
 491        fprintf_ln(stderr, _("%s: %s - %s"), cmd, ref, error);
 492
 493        if (suggested_refs.nr > 0) {
 494                fprintf_ln(stderr,
 495                           Q_("\nDid you mean this?",
 496                              "\nDid you mean one of these?",
 497                              suggested_refs.nr));
 498                for (i = 0; i < suggested_refs.nr; i++)
 499                        fprintf(stderr, "\t%s\n", suggested_refs.items[i].string);
 500        }
 501
 502        string_list_clear(&suggested_refs, 0);
 503        exit(1);
 504}