Skip to content

Commit bed4452

Browse files
tklausergitster
authored andcommitted
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 <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 63af4a8 commit bed4452

File tree

1 file changed

+31
-26
lines changed

1 file changed

+31
-26
lines changed

builtin/stripspace.c

Lines changed: 31 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include "builtin.h"
22
#include "cache.h"
3+
#include "parse-options.h"
34
#include "strbuf.h"
45

56
static void comment_lines(struct strbuf *buf)
@@ -12,41 +13,45 @@ static void comment_lines(struct strbuf *buf)
1213
free(msg);
1314
}
1415

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+
};
1827

1928
int cmd_stripspace(int argc, const char **argv, const char *prefix)
2029
{
2130
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)
4348
git_config(git_default_config, NULL);
4449

4550
if (strbuf_read(&buf, 0, 1024) < 0)
4651
die_errno("could not read the input");
4752

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);
5055
else
5156
comment_lines(&buf);
5257

0 commit comments

Comments
 (0)