]> git.ipfire.org Git - thirdparty/git.git/blame - builtin-stripspace.c
Documentation: minor cleanups to branch/checkout wording
[thirdparty/git.git] / builtin-stripspace.c
CommitLineData
7499c996 1#include "builtin.h"
9690c118 2#include "cache.h"
a3e870f2
LT
3
4/*
9690c118 5 * Remove trailing spaces from a line.
a3e870f2 6 *
9690c118
CR
7 * If the line ends with newline, it will be removed too.
8 * Returns the new length of the string.
a3e870f2 9 */
9690c118 10static int cleanup(char *line, int len)
a3e870f2 11{
9690c118
CR
12 if (len) {
13 if (line[len - 1] == '\n')
14 len--;
a3e870f2 15
9690c118
CR
16 while (len) {
17 unsigned char c = line[len - 1];
a3e870f2
LT
18 if (!isspace(c))
19 break;
a3e870f2 20 len--;
9690c118
CR
21 }
22 line[len] = 0;
a3e870f2 23 }
9690c118 24 return len;
a3e870f2
LT
25}
26
9690c118
CR
27/*
28 * Remove empty lines from the beginning and end
29 * and also trailing spaces from every line.
30 *
31 * Turn multiple consecutive empty lines between paragraphs
32 * into just one empty line.
33 *
34 * If the input has only empty lines and spaces,
35 * no output will be produced.
36 *
37 * Enable skip_comments to skip every line starting with "#".
38 */
39void stripspace(FILE *in, FILE *out, int skip_comments)
a3e870f2
LT
40{
41 int empties = -1;
9690c118
CR
42 int alloc = 1024;
43 char *line = xmalloc(alloc);
44
45 while (fgets(line, alloc, in)) {
46 int len = strlen(line);
a3e870f2 47
9690c118
CR
48 while (len == alloc - 1 && line[len - 1] != '\n') {
49 alloc = alloc_nr(alloc);
50 line = xrealloc(line, alloc);
51 fgets(line + len, alloc - len, in);
52 len += strlen(line + len);
53 }
54
55 if (skip_comments && line[0] == '#')
56 continue;
57 len = cleanup(line, len);
a3e870f2
LT
58
59 /* Not just an empty line? */
9690c118 60 if (len) {
a3e870f2 61 if (empties > 0)
7499c996 62 fputc('\n', out);
a3e870f2 63 empties = 0;
7499c996 64 fputs(line, out);
9690c118 65 fputc('\n', out);
a3e870f2
LT
66 continue;
67 }
68 if (empties < 0)
69 continue;
70 empties++;
71 }
9690c118 72 free(line);
7499c996
LS
73}
74
a633fca0 75int cmd_stripspace(int argc, const char **argv, const char *prefix)
7499c996 76{
9690c118 77 stripspace(stdin, stdout, 0);
a3e870f2
LT
78 return 0;
79}