5 * Returns the length of a line, without trailing spaces.
7 * If the line ends with newline, it will be removed too.
9 static size_t cleanup(char *line
, size_t len
)
12 unsigned char c
= line
[len
- 1];
22 * Remove empty lines from the beginning and end
23 * and also trailing spaces from every line.
25 * Turn multiple consecutive empty lines between paragraphs
26 * into just one empty line.
28 * If the input has only empty lines and spaces,
29 * no output will be produced.
31 * If last line does not have a newline at the end, one is added.
33 * Enable skip_comments to skip every line starting with comment
36 void stripspace(struct strbuf
*sb
, int skip_comments
)
39 size_t i
, j
, len
, newlen
;
42 /* We may have to add a newline. */
45 for (i
= j
= 0; i
< sb
->len
; i
+= len
, j
+= newlen
) {
46 eol
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
47 len
= eol
? eol
- (sb
->buf
+ i
) + 1 : sb
->len
- i
;
49 if (skip_comments
&& len
&& sb
->buf
[i
] == comment_line_char
) {
53 newlen
= cleanup(sb
->buf
+ i
, len
);
55 /* Not just an empty line? */
57 if (empties
> 0 && j
> 0)
60 memmove(sb
->buf
+ j
, sb
->buf
+ i
, newlen
);
61 sb
->buf
[newlen
+ j
++] = '\n';
70 static void comment_lines(struct strbuf
*buf
)
75 msg
= strbuf_detach(buf
, &len
);
76 strbuf_add_commented_lines(buf
, msg
, len
);
80 static const char *usage_msg
= "\n"
81 " git stripspace [-s | --strip-comments] < input\n"
82 " git stripspace [-c | --comment-lines] < input";
84 int cmd_stripspace(int argc
, const char **argv
, const char *prefix
)
86 struct strbuf buf
= STRBUF_INIT
;
87 int strip_comments
= 0;
88 enum { INVAL
= 0, STRIP_SPACE
= 1, COMMENT_LINES
= 2 } mode
= STRIP_SPACE
;
91 if (!strcmp(argv
[1], "-s") ||
92 !strcmp(argv
[1], "--strip-comments")) {
94 } else if (!strcmp(argv
[1], "-c") ||
95 !strcmp(argv
[1], "--comment-lines")) {
100 } else if (argc
> 1) {
107 if (strip_comments
|| mode
== COMMENT_LINES
)
108 git_config(git_default_config
, NULL
);
110 if (strbuf_read(&buf
, 0, 1024) < 0)
111 die_errno("could not read the input");
113 if (mode
== STRIP_SPACE
)
114 stripspace(&buf
, strip_comments
);
118 write_or_die(1, buf
.buf
, buf
.len
);
119 strbuf_release(&buf
);