builtin-stripspace.c 1.04 KB
Newer Older
Linus Torvalds's avatar
Linus Torvalds committed
1 2 3
#include <stdio.h>
#include <string.h>
#include <ctype.h>
4
#include "builtin.h"
Linus Torvalds's avatar
Linus Torvalds committed
5 6 7 8 9

/*
 * Remove empty lines from the beginning and end.
 *
 * Turn multiple consecutive empty lines into just one
10
 * empty line.  Return true if it is an incomplete line.
Linus Torvalds's avatar
Linus Torvalds committed
11
 */
12
static int cleanup(char *line)
Linus Torvalds's avatar
Linus Torvalds committed
13 14 15
{
	int len = strlen(line);

16 17 18
	if (len && line[len-1] == '\n') {
		if (len == 1)
			return 0;
Linus Torvalds's avatar
Linus Torvalds committed
19 20 21 22 23 24 25 26
		do {
			unsigned char c = line[len-2];
			if (!isspace(c))
				break;
			line[len-2] = '\n';
			len--;
			line[len] = 0;
		} while (len > 1);
27
		return 0;
Linus Torvalds's avatar
Linus Torvalds committed
28
	}
29
	return 1;
Linus Torvalds's avatar
Linus Torvalds committed
30 31
}

32
void stripspace(FILE *in, FILE *out)
Linus Torvalds's avatar
Linus Torvalds committed
33 34
{
	int empties = -1;
35
	int incomplete = 0;
Linus Torvalds's avatar
Linus Torvalds committed
36 37
	char line[1024];

38
	while (fgets(line, sizeof(line), in)) {
39
		incomplete = cleanup(line);
Linus Torvalds's avatar
Linus Torvalds committed
40 41 42 43

		/* Not just an empty line? */
		if (line[0] != '\n') {
			if (empties > 0)
44
				fputc('\n', out);
Linus Torvalds's avatar
Linus Torvalds committed
45
			empties = 0;
46
			fputs(line, out);
Linus Torvalds's avatar
Linus Torvalds committed
47 48 49 50 51 52
			continue;
		}
		if (empties < 0)
			continue;
		empties++;
	}
53
	if (incomplete)
54 55 56
		fputc('\n', out);
}

57
int cmd_stripspace(int argc, const char **argv, const char *prefix)
58 59
{
	stripspace(stdin, stdout);
Linus Torvalds's avatar
Linus Torvalds committed
60 61
	return 0;
}