builtin-stripspace.con commit Prepare for 1.5.1.5 Release Notes (52e7b74)
   1#include "builtin.h"
   2
   3/*
   4 * Remove empty lines from the beginning and end.
   5 *
   6 * Turn multiple consecutive empty lines into just one
   7 * empty line.  Return true if it is an incomplete line.
   8 */
   9static int cleanup(char *line)
  10{
  11        int len = strlen(line);
  12
  13        if (len && line[len-1] == '\n') {
  14                if (len == 1)
  15                        return 0;
  16                do {
  17                        unsigned char c = line[len-2];
  18                        if (!isspace(c))
  19                                break;
  20                        line[len-2] = '\n';
  21                        len--;
  22                        line[len] = 0;
  23                } while (len > 1);
  24                return 0;
  25        }
  26        return 1;
  27}
  28
  29void stripspace(FILE *in, FILE *out)
  30{
  31        int empties = -1;
  32        int incomplete = 0;
  33        char line[1024];
  34
  35        while (fgets(line, sizeof(line), in)) {
  36                incomplete = cleanup(line);
  37
  38                /* Not just an empty line? */
  39                if (line[0] != '\n') {
  40                        if (empties > 0)
  41                                fputc('\n', out);
  42                        empties = 0;
  43                        fputs(line, out);
  44                        continue;
  45                }
  46                if (empties < 0)
  47                        continue;
  48                empties++;
  49        }
  50        if (incomplete)
  51                fputc('\n', out);
  52}
  53
  54int cmd_stripspace(int argc, const char **argv, const char *prefix)
  55{
  56        stripspace(stdin, stdout);
  57        return 0;
  58}