help.c::uniq: plug a leak
[git.git] / help.c
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
11 void add_cmdname(struct cmdnames *cmds, const char *name, int len)
12 {
13         struct cmdname *ent = xmalloc(sizeof(*ent) + len + 1);
14
15         ent->len = len;
16         memcpy(ent->name, name, len);
17         ent->name[len] = 0;
18
19         ALLOC_GROW(cmds->names, cmds->cnt + 1, cmds->alloc);
20         cmds->names[cmds->cnt++] = ent;
21 }
22
23 static 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
33 static 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
40 static 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
57 void 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                         ci++, ei++;
69                 else if (cmp > 0)
70                         ei++;
71         }
72
73         while (ci < cmds->cnt)
74                 cmds->names[cj++] = cmds->names[ci++];
75
76         cmds->cnt = cj;
77 }
78
79 static void pretty_print_string_list(struct cmdnames *cmds,
80                                      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
100 static 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(WIN32) || defined(__CYGWIN__)
109 #if defined(__CYGWIN__)
110 if ((st.st_mode & S_IXUSR) == 0)
111 #endif
112 {       /* cannot trust the executable bit, peek into the file instead */
113         char buf[3] = { 0 };
114         int n;
115         int fd = open(name, O_RDONLY);
116         st.st_mode &= ~S_IXUSR;
117         if (fd >= 0) {
118                 n = read(fd, buf, 2);
119                 if (n == 2)
120                         /* DOS executables start with "MZ" */
121                         if (!strcmp(buf, "#!") || !strcmp(buf, "MZ"))
122                                 st.st_mode |= S_IXUSR;
123                 close(fd);
124         }
125 }
126 #endif
127         return st.st_mode & S_IXUSR;
128 }
129
130 static void list_commands_in_dir(struct cmdnames *cmds,
131                                          const char *path,
132                                          const char *prefix)
133 {
134         int prefix_len;
135         DIR *dir = opendir(path);
136         struct dirent *de;
137         struct strbuf buf = STRBUF_INIT;
138         int len;
139
140         if (!dir)
141                 return;
142         if (!prefix)
143                 prefix = "git-";
144         prefix_len = strlen(prefix);
145
146         strbuf_addf(&buf, "%s/", path);
147         len = buf.len;
148
149         while ((de = readdir(dir)) != NULL) {
150                 int entlen;
151
152                 if (prefixcmp(de->d_name, prefix))
153                         continue;
154
155                 strbuf_setlen(&buf, len);
156                 strbuf_addstr(&buf, de->d_name);
157                 if (!is_executable(buf.buf))
158                         continue;
159
160                 entlen = strlen(de->d_name) - prefix_len;
161                 if (has_extension(de->d_name, ".exe"))
162                         entlen -= 4;
163
164                 add_cmdname(cmds, de->d_name + prefix_len, entlen);
165         }
166         closedir(dir);
167         strbuf_release(&buf);
168 }
169
170 void load_command_list(const char *prefix,
171                 struct cmdnames *main_cmds,
172                 struct cmdnames *other_cmds)
173 {
174         const char *env_path = getenv("PATH");
175         const char *exec_path = git_exec_path();
176
177         if (exec_path) {
178                 list_commands_in_dir(main_cmds, exec_path, prefix);
179                 qsort(main_cmds->names, main_cmds->cnt,
180                       sizeof(*main_cmds->names), cmdname_compare);
181                 uniq(main_cmds);
182         }
183
184         if (env_path) {
185                 char *paths, *path, *colon;
186                 path = paths = xstrdup(env_path);
187                 while (1) {
188                         if ((colon = strchr(path, PATH_SEP)))
189                                 *colon = 0;
190                         if (!exec_path || strcmp(path, exec_path))
191                                 list_commands_in_dir(other_cmds, path, prefix);
192
193                         if (!colon)
194                                 break;
195                         path = colon + 1;
196                 }
197                 free(paths);
198
199                 qsort(other_cmds->names, other_cmds->cnt,
200                       sizeof(*other_cmds->names), cmdname_compare);
201                 uniq(other_cmds);
202         }
203         exclude_cmds(other_cmds, main_cmds);
204 }
205
206 void list_commands(unsigned int colopts,
207                    struct cmdnames *main_cmds, struct cmdnames *other_cmds)
208 {
209         if (main_cmds->cnt) {
210                 const char *exec_path = git_exec_path();
211                 printf_ln(_("available git commands in '%s'"), exec_path);
212                 putchar('\n');
213                 pretty_print_string_list(main_cmds, colopts);
214                 putchar('\n');
215         }
216
217         if (other_cmds->cnt) {
218                 printf_ln(_("git commands available from elsewhere on your $PATH"));
219                 putchar('\n');
220                 pretty_print_string_list(other_cmds, colopts);
221                 putchar('\n');
222         }
223 }
224
225 int is_in_cmdlist(struct cmdnames *c, const char *s)
226 {
227         int i;
228         for (i = 0; i < c->cnt; i++)
229                 if (!strcmp(s, c->names[i]->name))
230                         return 1;
231         return 0;
232 }
233
234 static int autocorrect;
235 static struct cmdnames aliases;
236
237 static int git_unknown_cmd_config(const char *var, const char *value, void *cb)
238 {
239         if (!strcmp(var, "help.autocorrect"))
240                 autocorrect = git_config_int(var,value);
241         /* Also use aliases for command lookup */
242         if (!prefixcmp(var, "alias."))
243                 add_cmdname(&aliases, var + 6, strlen(var + 6));
244
245         return git_default_config(var, value, cb);
246 }
247
248 static int levenshtein_compare(const void *p1, const void *p2)
249 {
250         const struct cmdname *const *c1 = p1, *const *c2 = p2;
251         const char *s1 = (*c1)->name, *s2 = (*c2)->name;
252         int l1 = (*c1)->len;
253         int l2 = (*c2)->len;
254         return l1 != l2 ? l1 - l2 : strcmp(s1, s2);
255 }
256
257 static void add_cmd_list(struct cmdnames *cmds, struct cmdnames *old)
258 {
259         int i;
260         ALLOC_GROW(cmds->names, cmds->cnt + old->cnt, cmds->alloc);
261
262         for (i = 0; i < old->cnt; i++)
263                 cmds->names[cmds->cnt++] = old->names[i];
264         free(old->names);
265         old->cnt = 0;
266         old->names = NULL;
267 }
268
269 /* An empirically derived magic number */
270 #define SIMILARITY_FLOOR 7
271 #define SIMILAR_ENOUGH(x) ((x) < SIMILARITY_FLOOR)
272
273 static const char bad_interpreter_advice[] =
274         N_("'%s' appears to be a git command, but we were not\n"
275         "able to execute it. Maybe git-%s is broken?");
276
277 const char *help_unknown_cmd(const char *cmd)
278 {
279         int i, n, best_similarity = 0;
280         struct cmdnames main_cmds, other_cmds;
281
282         memset(&main_cmds, 0, sizeof(main_cmds));
283         memset(&other_cmds, 0, sizeof(other_cmds));
284         memset(&aliases, 0, sizeof(aliases));
285
286         git_config(git_unknown_cmd_config, NULL);
287
288         load_command_list("git-", &main_cmds, &other_cmds);
289
290         add_cmd_list(&main_cmds, &aliases);
291         add_cmd_list(&main_cmds, &other_cmds);
292         qsort(main_cmds.names, main_cmds.cnt,
293               sizeof(main_cmds.names), cmdname_compare);
294         uniq(&main_cmds);
295
296         /* This abuses cmdname->len for levenshtein distance */
297         for (i = 0, n = 0; i < main_cmds.cnt; i++) {
298                 int cmp = 0; /* avoid compiler stupidity */
299                 const char *candidate = main_cmds.names[i]->name;
300
301                 /*
302                  * An exact match means we have the command, but
303                  * for some reason exec'ing it gave us ENOENT; probably
304                  * it's a bad interpreter in the #! line.
305                  */
306                 if (!strcmp(candidate, cmd))
307                         die(_(bad_interpreter_advice), cmd, cmd);
308
309                 /* Does the candidate appear in common_cmds list? */
310                 while (n < ARRAY_SIZE(common_cmds) &&
311                        (cmp = strcmp(common_cmds[n].name, candidate)) < 0)
312                         n++;
313                 if ((n < ARRAY_SIZE(common_cmds)) && !cmp) {
314                         /* Yes, this is one of the common commands */
315                         n++; /* use the entry from common_cmds[] */
316                         if (!prefixcmp(candidate, cmd)) {
317                                 /* Give prefix match a very good score */
318                                 main_cmds.names[i]->len = 0;
319                                 continue;
320                         }
321                 }
322
323                 main_cmds.names[i]->len =
324                         levenshtein(cmd, candidate, 0, 2, 1, 3) + 1;
325         }
326
327         qsort(main_cmds.names, main_cmds.cnt,
328               sizeof(*main_cmds.names), levenshtein_compare);
329
330         if (!main_cmds.cnt)
331                 die(_("Uh oh. Your system reports no Git commands at all."));
332
333         /* skip and count prefix matches */
334         for (n = 0; n < main_cmds.cnt && !main_cmds.names[n]->len; n++)
335                 ; /* still counting */
336
337         if (main_cmds.cnt <= n) {
338                 /* prefix matches with everything? that is too ambiguous */
339                 best_similarity = SIMILARITY_FLOOR + 1;
340         } else {
341                 /* count all the most similar ones */
342                 for (best_similarity = main_cmds.names[n++]->len;
343                      (n < main_cmds.cnt &&
344                       best_similarity == main_cmds.names[n]->len);
345                      n++)
346                         ; /* still counting */
347         }
348         if (autocorrect && n == 1 && SIMILAR_ENOUGH(best_similarity)) {
349                 const char *assumed = main_cmds.names[0]->name;
350                 main_cmds.names[0] = NULL;
351                 clean_cmdnames(&main_cmds);
352                 fprintf_ln(stderr,
353                            _("WARNING: You called a Git command named '%s', "
354                              "which does not exist.\n"
355                              "Continuing under the assumption that you meant '%s'"),
356                         cmd, assumed);
357                 if (autocorrect > 0) {
358                         fprintf_ln(stderr, _("in %0.1f seconds automatically..."),
359                                 (float)autocorrect/10.0);
360                         poll(NULL, 0, autocorrect * 100);
361                 }
362                 return assumed;
363         }
364
365         fprintf_ln(stderr, _("git: '%s' is not a git command. See 'git --help'."), cmd);
366
367         if (SIMILAR_ENOUGH(best_similarity)) {
368                 fprintf_ln(stderr,
369                            Q_("\nDid you mean this?",
370                               "\nDid you mean one of these?",
371                            n));
372
373                 for (i = 0; i < n; i++)
374                         fprintf(stderr, "\t%s\n", main_cmds.names[i]->name);
375         }
376
377         exit(1);
378 }
379
380 int cmd_version(int argc, const char **argv, const char *prefix)
381 {
382         printf("git version %s\n", git_version_string);
383         return 0;
384 }