builtin-stripspace.con commit Tweak diff colors (50f575f)
   1#include <stdio.h>
   2#include <string.h>
   3#include <ctype.h>
   4#include "builtin.h"
   5
   6/*
   7 * Remove empty lines from the beginning and end.
   8 *
   9 * Turn multiple consecutive empty lines into just one
  10 * empty line.  Return true if it is an incomplete line.
  11 */
  12static int cleanup(char *line)
  13{
  14        int len = strlen(line);
  15
  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;
  28        }
  29        return 1;
  30}
  31
  32void stripspace(FILE *in, FILE *out)
  33{
  34        int empties = -1;
  35        int incomplete = 0;
  36        char line[1024];
  37
  38        while (fgets(line, sizeof(line), in)) {
  39                incomplete = cleanup(line);
  40
  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;
  48                }
  49                if (empties < 0)
  50                        continue;
  51                empties++;
  52        }
  53        if (incomplete)
  54                fputc('\n', out);
  55}
  56
  57int cmd_stripspace(int argc, const char **argv, char **envp)
  58{
  59        stripspace(stdin, stdout);
  60        return 0;
  61}