cvsserver: Determinize output to combat Perl 5.18 hash randomization
[alt-git.git] / builtin / stripspace.c
blobf16986c0ae811f6b998d20be39da1af6095fcfe8
1 #include "builtin.h"
2 #include "cache.h"
4 /*
5 * Returns the length of a line, without trailing spaces.
7 * If the line ends with newline, it will be removed too.
8 */
9 static size_t cleanup(char *line, size_t len)
11 while (len) {
12 unsigned char c = line[len - 1];
13 if (!isspace(c))
14 break;
15 len--;
18 return len;
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 "#".
35 void stripspace(struct strbuf *sb, int skip_comments)
37 int empties = 0;
38 size_t i, j, len, newlen;
39 char *eol;
41 /* We may have to add a newline. */
42 strbuf_grow(sb, 1);
44 for (i = j = 0; i < sb->len; i += len, j += newlen) {
45 eol = memchr(sb->buf + i, '\n', sb->len - i);
46 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
48 if (skip_comments && len && sb->buf[i] == '#') {
49 newlen = 0;
50 continue;
52 newlen = cleanup(sb->buf + i, len);
54 /* Not just an empty line? */
55 if (newlen) {
56 if (empties > 0 && j > 0)
57 sb->buf[j++] = '\n';
58 empties = 0;
59 memmove(sb->buf + j, sb->buf + i, newlen);
60 sb->buf[newlen + j++] = '\n';
61 } else {
62 empties++;
66 strbuf_setlen(sb, j);
69 int cmd_stripspace(int argc, const char **argv, const char *prefix)
71 struct strbuf buf = STRBUF_INIT;
72 int strip_comments = 0;
74 if (argc == 2 && (!strcmp(argv[1], "-s") ||
75 !strcmp(argv[1], "--strip-comments")))
76 strip_comments = 1;
77 else if (argc > 1)
78 usage("git stripspace [-s | --strip-comments] < input");
80 if (strbuf_read(&buf, 0, 1024) < 0)
81 die_errno("could not read the input");
83 stripspace(&buf, strip_comments);
85 write_or_die(1, buf.buf, buf.len);
86 strbuf_release(&buf);
87 return 0;