Clean up trailing whitespace when pretty-printing commits
[git/spearce.git] / stripspace.c
blob65a6346452bb924d203724a9bfeb1c4ed98025e1
1 #include <stdio.h>
2 #include <string.h>
3 #include <ctype.h>
5 /*
6 * Remove empty lines from the beginning and end.
8 * Turn multiple consecutive empty lines into just one
9 * empty line. Return true if it is an incomplete line.
11 static int cleanup(char *line)
13 int len = strlen(line);
15 if (len && line[len-1] == '\n') {
16 if (len == 1)
17 return 0;
18 do {
19 unsigned char c = line[len-2];
20 if (!isspace(c))
21 break;
22 line[len-2] = '\n';
23 len--;
24 line[len] = 0;
25 } while (len > 1);
26 return 0;
28 return 1;
31 int main(int argc, char **argv)
33 int empties = -1;
34 int incomplete = 0;
35 char line[1024];
37 while (fgets(line, sizeof(line), stdin)) {
38 incomplete = cleanup(line);
40 /* Not just an empty line? */
41 if (line[0] != '\n') {
42 if (empties > 0)
43 putchar('\n');
44 empties = 0;
45 fputs(line, stdout);
46 continue;
48 if (empties < 0)
49 continue;
50 empties++;
52 if (incomplete)
53 putchar('\n');
54 return 0;