]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/stripspace.c
revision: add --grep-reflog to filter commits by reflog messages
[thirdparty/git.git] / builtin / stripspace.c
CommitLineData
7499c996 1#include "builtin.h"
9690c118 2#include "cache.h"
a3e870f2
LT
3
4/*
975e0daf 5 * Returns the length of a line, without trailing spaces.
a3e870f2 6 *
9690c118 7 * If the line ends with newline, it will be removed too.
a3e870f2 8 */
975e0daf 9static size_t cleanup(char *line, size_t len)
a3e870f2 10{
6d69b6f6
KH
11 while (len) {
12 unsigned char c = line[len - 1];
13 if (!isspace(c))
14 break;
15 len--;
a3e870f2 16 }
6d69b6f6 17
9690c118 18 return len;
a3e870f2
LT
19}
20
9690c118
CR
21/*
22 * Remove empty lines from the beginning and end
23 * and also trailing spaces from every line.
24 *
25 * Turn multiple consecutive empty lines between paragraphs
26 * into just one empty line.
27 *
28 * If the input has only empty lines and spaces,
29 * no output will be produced.
30 *
6d69b6f6 31 * If last line does not have a newline at the end, one is added.
975e0daf 32 *
9690c118
CR
33 * Enable skip_comments to skip every line starting with "#".
34 */
6d69b6f6 35void stripspace(struct strbuf *sb, int skip_comments)
a3e870f2 36{
6d69b6f6 37 int empties = 0;
975e0daf
CR
38 size_t i, j, len, newlen;
39 char *eol;
9690c118 40
6d69b6f6
KH
41 /* We may have to add a newline. */
42 strbuf_grow(sb, 1);
a3e870f2 43
6d69b6f6
KH
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;
47
48 if (skip_comments && len && sb->buf[i] == '#') {
975e0daf 49 newlen = 0;
9690c118 50 continue;
975e0daf 51 }
6d69b6f6 52 newlen = cleanup(sb->buf + i, len);
a3e870f2
LT
53
54 /* Not just an empty line? */
975e0daf 55 if (newlen) {
6d69b6f6
KH
56 if (empties > 0 && j > 0)
57 sb->buf[j++] = '\n';
a3e870f2 58 empties = 0;
6d69b6f6
KH
59 memmove(sb->buf + j, sb->buf + i, newlen);
60 sb->buf[newlen + j++] = '\n';
61 } else {
62 empties++;
a3e870f2 63 }
a3e870f2 64 }
975e0daf 65
6d69b6f6 66 strbuf_setlen(sb, j);
7499c996
LS
67}
68
a633fca0 69int cmd_stripspace(int argc, const char **argv, const char *prefix)
7499c996 70{
f285a2d7 71 struct strbuf buf = STRBUF_INIT;
f653aee5
JS
72 int strip_comments = 0;
73
4751f112 74 if (argc == 2 && (!strcmp(argv[1], "-s") ||
f653aee5
JS
75 !strcmp(argv[1], "--strip-comments")))
76 strip_comments = 1;
4751f112 77 else if (argc > 1)
497215d8 78 usage("git stripspace [-s | --strip-comments] < input");
975e0daf 79
fd17f5b5 80 if (strbuf_read(&buf, 0, 1024) < 0)
0721c314 81 die_errno("could not read the input");
975e0daf 82
6d69b6f6 83 stripspace(&buf, strip_comments);
975e0daf 84
fd17f5b5
PH
85 write_or_die(1, buf.buf, buf.len);
86 strbuf_release(&buf);
a3e870f2
LT
87 return 0;
88}