Documentation: updates to "Everyday GIT"
[git/jrn.git] / builtin-stripspace.c
blob09cc9108cdaf2aa20dc10788bccd2fee0ae9b02a
1 #include <stdio.h>
2 #include <string.h>
3 #include <ctype.h>
4 #include "builtin.h"
6 /*
7 * Remove empty lines from the beginning and end.
9 * Turn multiple consecutive empty lines into just one
10 * empty line. Return true if it is an incomplete line.
12 static int cleanup(char *line)
14 int len = strlen(line);
16 if (len && line[len-1] == '\n') {
17 if (len == 1)
18 return 0;
19 do {
20 unsigned char c = line[len-2];
21 if (!isspace(c))
22 break;
23 line[len-2] = '\n';
24 len--;
25 line[len] = 0;
26 } while (len > 1);
27 return 0;
29 return 1;
32 void stripspace(FILE *in, FILE *out)
34 int empties = -1;
35 int incomplete = 0;
36 char line[1024];
38 while (fgets(line, sizeof(line), in)) {
39 incomplete = cleanup(line);
41 /* Not just an empty line? */
42 if (line[0] != '\n') {
43 if (empties > 0)
44 fputc('\n', out);
45 empties = 0;
46 fputs(line, out);
47 continue;
49 if (empties < 0)
50 continue;
51 empties++;
53 if (incomplete)
54 fputc('\n', out);
57 int cmd_stripspace(int argc, const char **argv, const char *prefix)
59 stripspace(stdin, stdout);
60 return 0;