2 #include <subcmd/help.h>
3 #include "../builtin.h"
4 #include "levenshtein.h"
6 static int autocorrect
;
7 static struct cmdnames aliases
;
9 static int perf_unknown_cmd_config(const char *var
, const char *value
, void *cb
)
11 if (!strcmp(var
, "help.autocorrect"))
12 autocorrect
= perf_config_int(var
,value
);
13 /* Also use aliases for command lookup */
14 if (!prefixcmp(var
, "alias."))
15 add_cmdname(&aliases
, var
+ 6, strlen(var
+ 6));
17 return perf_default_config(var
, value
, cb
);
20 static int levenshtein_compare(const void *p1
, const void *p2
)
22 const struct cmdname
*const *c1
= p1
, *const *c2
= p2
;
23 const char *s1
= (*c1
)->name
, *s2
= (*c2
)->name
;
26 return l1
!= l2
? l1
- l2
: strcmp(s1
, s2
);
29 static void add_cmd_list(struct cmdnames
*cmds
, struct cmdnames
*old
)
33 ALLOC_GROW(cmds
->names
, cmds
->cnt
+ old
->cnt
, cmds
->alloc
);
35 for (i
= 0; i
< old
->cnt
; i
++)
36 cmds
->names
[cmds
->cnt
++] = old
->names
[i
];
41 const char *help_unknown_cmd(const char *cmd
)
43 unsigned int i
, n
= 0, best_similarity
= 0;
44 struct cmdnames main_cmds
, other_cmds
;
46 memset(&main_cmds
, 0, sizeof(main_cmds
));
47 memset(&other_cmds
, 0, sizeof(main_cmds
));
48 memset(&aliases
, 0, sizeof(aliases
));
50 perf_config(perf_unknown_cmd_config
, NULL
);
52 load_command_list("perf-", &main_cmds
, &other_cmds
);
54 add_cmd_list(&main_cmds
, &aliases
);
55 add_cmd_list(&main_cmds
, &other_cmds
);
56 qsort(main_cmds
.names
, main_cmds
.cnt
,
57 sizeof(main_cmds
.names
), cmdname_compare
);
61 /* This reuses cmdname->len for similarity index */
62 for (i
= 0; i
< main_cmds
.cnt
; ++i
)
63 main_cmds
.names
[i
]->len
=
64 levenshtein(cmd
, main_cmds
.names
[i
]->name
, 0, 2, 1, 4);
66 qsort(main_cmds
.names
, main_cmds
.cnt
,
67 sizeof(*main_cmds
.names
), levenshtein_compare
);
69 best_similarity
= main_cmds
.names
[0]->len
;
71 while (n
< main_cmds
.cnt
&& best_similarity
== main_cmds
.names
[n
]->len
)
75 if (autocorrect
&& n
== 1) {
76 const char *assumed
= main_cmds
.names
[0]->name
;
78 main_cmds
.names
[0] = NULL
;
79 clean_cmdnames(&main_cmds
);
80 fprintf(stderr
, "WARNING: You called a perf program named '%s', "
81 "which does not exist.\n"
82 "Continuing under the assumption that you meant '%s'\n",
84 if (autocorrect
> 0) {
85 fprintf(stderr
, "in %0.1f seconds automatically...\n",
86 (float)autocorrect
/10.0);
87 poll(NULL
, 0, autocorrect
* 100);
92 fprintf(stderr
, "perf: '%s' is not a perf-command. See 'perf --help'.\n", cmd
);
94 if (main_cmds
.cnt
&& best_similarity
< 6) {
95 fprintf(stderr
, "\nDid you mean %s?\n",
96 n
< 2 ? "this": "one of these");
98 for (i
= 0; i
< n
; i
++)
99 fprintf(stderr
, "\t%s\n", main_cmds
.names
[i
]->name
);