stripspace: use parse-options for command-line parsing

Use parse-options to parse command-line options instead of a hand-crafted implementation. The users can now use a unique prefix of the long option to say e.g. "git stripspace --strip". Signed-off-by: Tobias Klauser <tklauser@distanz.ch> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Tobias Klauser committed Oct 16, 2015 at 17:16 UTC bed4452468cc564adc5ab99dfdbee0eb0f7cfb97
1 file changed +31 -26
builtin/stripspace.c
+31 -26
@@ -1,5 +1,6 @@
1 #include "builtin.h"
2 #include "cache.h"
3 +#include "parse-options.h"
4 #include "strbuf.h"
5
6 static void comment_lines(struct strbuf *buf)
@@ -12,41 +13,45 @@ static void comment_lines(struct strbuf *buf)
13 free(msg);
14 }
15
15 -static const char *usage_msg = "\n"
16 -" git stripspace [-s | --strip-comments] < input\n"
17 -" git stripspace [-c | --comment-lines] < input";
16 +static const char * const stripspace_usage[] = {
17 + N_("git stripspace [-s | --strip-comments] < input"),
18 + N_("git stripspace [-c | --comment-lines] < input"),
19 + NULL
20 +};
21 +
22 +enum stripspace_mode {
23 + STRIP_DEFAULT = 0,
24 + STRIP_COMMENTS,
25 + COMMENT_LINES
26 +};
27
28 int cmd_stripspace(int argc, const char **argv, const char *prefix)
29 {
30 struct strbuf buf = STRBUF_INIT;
22 - int strip_comments = 0;
23 - enum { INVAL = 0, STRIP_SPACE = 1, COMMENT_LINES = 2 } mode = STRIP_SPACE;
24 -
25 - if (argc == 2) {
26 - if (!strcmp(argv[1], "-s") ||
27 - !strcmp(argv[1], "--strip-comments")) {
28 - strip_comments = 1;
29 - } else if (!strcmp(argv[1], "-c") ||
30 - !strcmp(argv[1], "--comment-lines")) {
31 - mode = COMMENT_LINES;
32 - } else {
33 - mode = INVAL;
34 - }
35 - } else if (argc > 1) {
36 - mode = INVAL;
37 - }
38 -
39 - if (mode == INVAL)
40 - usage(usage_msg);
41 -
42 - if (strip_comments || mode == COMMENT_LINES)
31 + enum stripspace_mode mode = STRIP_DEFAULT;
32 +
33 + const struct option options[] = {
34 + OPT_CMDMODE('s', "strip-comments", &mode,
35 + N_("skip and remove all lines starting with comment character"),
36 + STRIP_COMMENTS),
37 + OPT_CMDMODE('c', "comment-lines", &mode,
38 + N_("prepend comment character and blank to each line"),
39 + COMMENT_LINES),
40 + OPT_END()
41 + };
42 +
43 + argc = parse_options(argc, argv, prefix, options, stripspace_usage, 0);
44 + if (argc)
45 + usage_with_options(stripspace_usage, options);
46 +
47 + if (mode == STRIP_COMMENTS || mode == COMMENT_LINES)
48 git_config(git_default_config, NULL);
49
50 if (strbuf_read(&buf, 0, 1024) < 0)
51 die_errno("could not read the input");
52
48 - if (mode == STRIP_SPACE)
49 - strbuf_stripspace(&buf, strip_comments);
53 + if (mode == STRIP_DEFAULT || mode == STRIP_COMMENTS)
54 + strbuf_stripspace(&buf, mode == STRIP_COMMENTS);
55 else
56 comment_lines(&buf);
57