Merge branch 'jc/am-parseopt-fix'
[git.git] / builtin / stripspace.c
blob7b700a9fb1c2a355af6ee6935edbeec49f3f4135
1 #include "builtin.h"
2 #include "config.h"
3 #include "environment.h"
4 #include "gettext.h"
5 #include "parse-options.h"
6 #include "setup.h"
7 #include "strbuf.h"
8 #include "write-or-die.h"
10 static void comment_lines(struct strbuf *buf)
12 char *msg;
13 size_t len;
15 msg = strbuf_detach(buf, &len);
16 strbuf_add_commented_lines(buf, msg, len, comment_line_char);
17 free(msg);
20 static const char * const stripspace_usage[] = {
21 "git stripspace [-s | --strip-comments]",
22 "git stripspace [-c | --comment-lines]",
23 NULL
26 enum stripspace_mode {
27 STRIP_DEFAULT = 0,
28 STRIP_COMMENTS,
29 COMMENT_LINES
32 int cmd_stripspace(int argc, const char **argv, const char *prefix)
34 struct strbuf buf = STRBUF_INIT;
35 enum stripspace_mode mode = STRIP_DEFAULT;
36 int nongit;
38 const struct option options[] = {
39 OPT_CMDMODE('s', "strip-comments", &mode,
40 N_("skip and remove all lines starting with comment character"),
41 STRIP_COMMENTS),
42 OPT_CMDMODE('c', "comment-lines", &mode,
43 N_("prepend comment character and space to each line"),
44 COMMENT_LINES),
45 OPT_END()
48 argc = parse_options(argc, argv, prefix, options, stripspace_usage, 0);
49 if (argc)
50 usage_with_options(stripspace_usage, options);
52 if (mode == STRIP_COMMENTS || mode == COMMENT_LINES) {
53 setup_git_directory_gently(&nongit);
54 git_config(git_default_config, NULL);
57 if (strbuf_read(&buf, 0, 1024) < 0)
58 die_errno("could not read the input");
60 if (mode == STRIP_DEFAULT || mode == STRIP_COMMENTS)
61 strbuf_stripspace(&buf,
62 mode == STRIP_COMMENTS ? comment_line_char : '\0');
63 else
64 comment_lines(&buf);
66 write_or_die(1, buf.buf, buf.len);
67 strbuf_release(&buf);
68 return 0;