blob: 2ce1264f7b4bfb5baf85f82907e2a8f7219846fa [file] [log] [blame]
Linus Torvaldsa3e870f2005-05-30 12:51:00 -07001#include <stdio.h>
2#include <string.h>
3#include <ctype.h>
Lukas Sandström7499c992006-06-13 22:21:53 +02004#include "builtin.h"
Linus Torvaldsa3e870f2005-05-30 12:51:00 -07005
6/*
7 * Remove empty lines from the beginning and end.
8 *
9 * Turn multiple consecutive empty lines into just one
Junio C Hamanof4ee3eb2006-04-12 13:10:27 -070010 * empty line. Return true if it is an incomplete line.
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070011 */
Junio C Hamanof4ee3eb2006-04-12 13:10:27 -070012static int cleanup(char *line)
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070013{
14 int len = strlen(line);
15
Junio C Hamano5cf7e212006-04-14 12:41:51 -070016 if (len && line[len-1] == '\n') {
17 if (len == 1)
18 return 0;
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070019 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);
Junio C Hamanof4ee3eb2006-04-12 13:10:27 -070027 return 0;
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070028 }
Junio C Hamanof4ee3eb2006-04-12 13:10:27 -070029 return 1;
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070030}
31
Lukas Sandström7499c992006-06-13 22:21:53 +020032void stripspace(FILE *in, FILE *out)
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070033{
34 int empties = -1;
Junio C Hamanof4ee3eb2006-04-12 13:10:27 -070035 int incomplete = 0;
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070036 char line[1024];
37
Lukas Sandström7499c992006-06-13 22:21:53 +020038 while (fgets(line, sizeof(line), in)) {
Junio C Hamanof4ee3eb2006-04-12 13:10:27 -070039 incomplete = cleanup(line);
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070040
41 /* Not just an empty line? */
42 if (line[0] != '\n') {
43 if (empties > 0)
Lukas Sandström7499c992006-06-13 22:21:53 +020044 fputc('\n', out);
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070045 empties = 0;
Lukas Sandström7499c992006-06-13 22:21:53 +020046 fputs(line, out);
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070047 continue;
48 }
49 if (empties < 0)
50 continue;
51 empties++;
52 }
Junio C Hamanof4ee3eb2006-04-12 13:10:27 -070053 if (incomplete)
Lukas Sandström7499c992006-06-13 22:21:53 +020054 fputc('\n', out);
55}
56
57int cmd_stripspace(int argc, const char **argv, char **envp)
58{
59 stripspace(stdin, stdout);
Linus Torvaldsa3e870f2005-05-30 12:51:00 -070060 return 0;
61}