summaryrefslogtreecommitdiff
path: root/skiphead.re
blob: f7f48e58ee2d2a53f38873895f600fef89e46b44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// Copyright 2022 Benjamin Barenblat
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <algorithm>
#include <array>
#include <ios>
#include <iostream>
#include <string_view>

#include "goldfishlocale.h"

namespace {

constexpr std::string_view kShortUsage =
    "Usage: skiphead [OPTION...] COMMAND [ARGS...]\n";

constexpr std::u8string_view kHelp =
    u8R"(
With no options, copy the first line of standard input to standard output, and
then execute the specified command. This is useful for processing the output of
commands that emit headers; for example, “ps -ef | skiphead grep systemd” will
print the headers from “ps” before grepping for “systemd” in the remaining
output.

Like head(1), skiphead accepts -NUM, -n, and --lines arguments to control the
number of lines printed before invoking COMMAND.

If your COMMAND starts with -, you may terminate skiphead’s option processing
with --.

Options:
      -NUM, -n NUM, --lines=NUM  print NUM header lines instead of 1
      --                      terminate option processing
      --help                  display this help and exit
      --version               display version information and exit

Please report bugs to Benjamin Barenblat <bbarenblat@gmail.com>.
)";

constexpr std::u8string_view kAskForHelp =
    u8"Try “skiphead --help” for more information.\n";

constexpr std::string_view kVersionInfo = R"(skiphead 1.0.0
Copyright 2022 Benjamin Barenblat
Licensed under the Apache License, Version 2.0
)";

int ParseOptionsAndAdvanceArgv(char**& argv) {
  int lines_to_skip = 1;
  bool expect_bare_number = false;
  for (++argv; argv[0] != nullptr; ++argv) {
    const char* YYCURSOR = argv[0];
    const char* a;
    /*!stags:re2c format = "const char* @@;"; */

    /*!re2c
      re2c:define:YYCTYPE = char;
      re2c:flags:tags = 1;
      re2c:yyfill:enable = 0;

      ("-" | "-n" | "--lines=") @a [0-9]+ {
        lines_to_skip = atoi(a);
        continue;
      }

      "-n" | "--lines" {
        expect_bare_number = true;
        continue;
      }

      [0-9]+ {
        if (expect_bare_number) {
          lines_to_skip = atoi(argv[0]);
          expect_bare_number = false;
          continue;
        }
        break;
      }

      "--help" {
        std::cout << kShortUsage << goldfishlocale::ToSystem(kHelp);
        exit(0);
      }

      "--version" {
        std::cout << kVersionInfo;
        exit(0);
      }

      "--" {
        ++argv;
        break;
      }

      "-" [^\x00]+ {
        std::clog << goldfishlocale::ToSystem(
                         u8"skiphead: Unrecognized option “")
                  << argv[0] << goldfishlocale::ToSystem(u8"”\n")
                  << goldfishlocale::ToSystem(kAskForHelp);
        exit(1);
      }

      * {
        break;
      }
     */
  }
  return lines_to_skip;
}

int Read(int fd, void* buf, size_t count) {
  ssize_t bytes_read = read(fd, buf, count);
  if (bytes_read < 0) {
    if (errno == EINTR) {
      return Read(fd, buf, count);  // Just try again.
    }
    std::clog << "skiphead: Read failed: " << strerror(errno) << '\n';
    exit(1);
  }
  return bytes_read;
}

void CopyLines(int lines_to_skip) {
  std::array<char, 16> buffer;
  while (lines_to_skip > 0) {
    int bytes_read =
        Read(STDIN_FILENO, buffer.data(),
             std::min(static_cast<int>(buffer.size()), lines_to_skip));
    if (bytes_read == 0) {
      // Standard input got closed. Just move on.
      break;
    }

    for (int i = 0; i < bytes_read; ++i) {
      if (buffer[i] == '\n') {
        --lines_to_skip;
      }
    }

    std::cout.write(buffer.data(), bytes_read);
  }
}

}  // namespace

int main(int argc, char* argv[]) {
  goldfishlocale::SetLocaleFromEnvironment();

  // We're not using the C stdio functions in this program, so enable extra
  // userspace buffering to reduce syscall overhead.
  std::ios_base::sync_with_stdio(false);

  if (argc < 2) {
    std::clog << kShortUsage << goldfishlocale::ToSystem(kAskForHelp);
    return 1;
  }

  int lines_to_skip = ParseOptionsAndAdvanceArgv(argv);
  assert(lines_to_skip >= 0);
  if (argv[0] == nullptr) {
    std::clog << kShortUsage << goldfishlocale::ToSystem(kAskForHelp);
    return 1;
  }

  CopyLines(lines_to_skip);
  std::cout.flush();

  execvp(argv[0], argv);

  int r = errno;
  std::clog << goldfishlocale::ToSystem(
                   u8"skiphead: Failed to execute command “")
            << argv[0] << goldfishlocale::ToSystem(u8"”: ") << strerror(r)
            << '\n';
  return r;
}