-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsed.cpp
More file actions
368 lines (325 loc) · 10.5 KB
/
sed.cpp
File metadata and controls
368 lines (325 loc) · 10.5 KB
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// sed — stream editor
// Supported: s/pattern/replacement/[g|p|d], line addresses (single, range, $),
// -n (suppress auto-print), -e SCRIPT, multiple commands
// Known differences from GNU sed: no branching/labels, no y (transliterate),
// no a/i/c commands, no hold space, no multi-line pattern space.
#include <cstdio>
#include <cstring>
#include <string>
#include <string_view>
#include <vector>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/io.hpp>
#include <cfbox/regex.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "sed",
.version = CFBOX_VERSION_STRING,
.one_line = "stream editor for filtering and transforming text",
.usage = "sed [OPTIONS] SCRIPT [FILE]...",
.options = " -e SCRIPT add the script to the commands to be executed\n"
" -n suppress automatic printing of pattern space",
.extra = "",
};
struct Address {
enum Type { None, Line, Last, Range };
Type type = None;
std::size_t line1 = 0;
std::size_t line2 = 0; // only used for Range
};
struct SedCommand {
Address addr;
enum Action { Substitute, Delete, Print } action = Substitute;
std::string pattern;
std::string replacement;
bool global = false; // g flag
bool print_flag = false; // p flag
bool delete_flag = false; // d flag (for substitute context)
};
auto parse_address(std::string_view& s) -> Address {
Address addr;
if (s.empty()) return addr;
if (s[0] == '$') {
s.remove_prefix(1);
addr.type = Address::Last;
// Check for range: $,\d+
if (s.size() >= 2 && s[0] == ',') {
// $ is the end — unusual but handle as range
}
return addr;
}
if (s[0] >= '0' && s[0] <= '9') {
std::size_t n = 0;
std::size_t i = 0;
while (i < s.size() && s[i] >= '0' && s[i] <= '9') {
n = n * 10 + (s[i] - '0');
++i;
}
s.remove_prefix(i);
if (!s.empty() && s[0] == ',') {
s.remove_prefix(1);
addr.type = Address::Range;
addr.line1 = n;
if (!s.empty() && s[0] == '$') {
s.remove_prefix(1);
addr.line2 = static_cast<std::size_t>(-1); // sentinel for "last"
} else if (!s.empty() && s[0] >= '0' && s[0] <= '9') {
std::size_t n2 = 0;
std::size_t j = 0;
while (j < s.size() && s[j] >= '0' && s[j] <= '9') {
n2 = n2 * 10 + (s[j] - '0');
++j;
}
s.remove_prefix(j);
addr.line2 = n2;
}
} else {
addr.type = Address::Line;
addr.line1 = n;
}
return addr;
}
return addr;
}
auto parse_substitute(std::string_view s) -> SedCommand {
// s/PATTERN/REPLACEMENT/FLAGS
SedCommand cmd;
cmd.action = SedCommand::Substitute;
if (s.empty() || s[0] != 's') return cmd;
s.remove_prefix(1);
if (s.empty()) return cmd;
char delim = s[0];
s.remove_prefix(1);
// Extract pattern
std::string pattern;
for (std::size_t i = 0; i < s.size(); ++i) {
if (s[i] == delim) {
s.remove_prefix(i + 1);
break;
}
if (s[i] == '\\' && i + 1 < s.size()) {
pattern += s[i + 1];
++i;
} else {
pattern += s[i];
}
if (i + 1 == s.size()) {
s.remove_prefix(i + 1);
}
}
cmd.pattern = pattern;
// Extract replacement
std::string replacement;
for (std::size_t i = 0; i < s.size(); ++i) {
if (s[i] == delim) {
s.remove_prefix(i + 1);
break;
}
if (s[i] == '\\' && i + 1 < s.size()) {
if (s[i + 1] == '&') {
replacement += '&';
++i;
} else if (s[i + 1] == '\\') {
replacement += '\\';
++i;
} else if (s[i + 1] == 'n') {
replacement += '\n';
++i;
} else {
replacement += s[i + 1];
++i;
}
} else if (s[i] == '&') {
replacement += "&"; // placeholder for matched text — handled in apply
} else {
replacement += s[i];
}
if (i + 1 == s.size()) {
s.remove_prefix(i + 1);
}
}
cmd.replacement = replacement;
// Parse flags
for (char c : s) {
switch (c) {
case 'g': cmd.global = true; break;
case 'p': cmd.print_flag = true; break;
case 'd': cmd.delete_flag = true; break;
}
}
return cmd;
}
auto parse_command(std::string_view script) -> SedCommand {
std::string_view s = script;
SedCommand cmd;
cmd.addr = parse_address(s);
if (s.empty()) return cmd;
if (s[0] == 's') {
auto sub = parse_substitute(s);
cmd.action = SedCommand::Substitute;
cmd.pattern = sub.pattern;
cmd.replacement = sub.replacement;
cmd.global = sub.global;
cmd.print_flag = sub.print_flag;
cmd.delete_flag = sub.delete_flag;
} else if (s[0] == 'd') {
cmd.action = SedCommand::Delete;
} else if (s[0] == 'p') {
cmd.action = SedCommand::Print;
}
return cmd;
}
auto parse_script(const std::string& script) -> std::vector<SedCommand> {
std::vector<SedCommand> commands;
// Split by newlines and semicolons (simple)
std::string_view sv{script};
std::string token;
for (std::size_t i = 0; i < sv.size(); ++i) {
if (sv[i] == ';' || sv[i] == '\n') {
if (!token.empty()) {
commands.push_back(parse_command(token));
token.clear();
}
} else {
token += sv[i];
}
}
if (!token.empty()) {
commands.push_back(parse_command(token));
}
return commands;
}
auto address_matches(const Address& addr, std::size_t line, std::size_t total_lines) -> bool {
switch (addr.type) {
case Address::None: return true;
case Address::Line: return line == addr.line1;
case Address::Last: return line == total_lines;
case Address::Range: return line >= addr.line1 && line <= addr.line2;
}
return false;
}
auto apply_substitute(std::string& line, const SedCommand& cmd) -> bool {
cfbox::util::scoped_regex re;
if (re.compile(cmd.pattern.c_str(), REG_EXTENDED) != 0) return false;
regmatch_t m;
if (re.exec(line.c_str(), 1, &m, 0) != 0) return false;
if (!cmd.global) {
// Single replacement
std::string result;
auto* p = line.c_str();
result.append(p, static_cast<std::size_t>(m.rm_so));
result.append(cmd.replacement);
result.append(p + m.rm_eo);
line = result;
} else {
// Global replacement
std::string result;
auto* p = line.c_str();
auto offset = p;
while (re.exec(offset, 1, &m, 0) == 0 && m.rm_so >= 0) {
result.append(offset, static_cast<std::size_t>(m.rm_so));
result.append(cmd.replacement);
offset += m.rm_eo;
if (m.rm_so == m.rm_eo) {
if (*offset) result += *offset++;
else break;
}
}
result.append(offset);
line = result;
}
return true;
}
auto process_lines(const std::vector<std::string>& lines,
const std::vector<SedCommand>& commands, bool suppress) -> void {
std::size_t total = lines.size();
for (std::size_t li = 0; li < total; ++li) {
std::string line = lines[li];
bool deleted = false;
bool extra_print = false;
for (const auto& cmd : commands) {
if (!address_matches(cmd.addr, li + 1, total)) continue;
switch (cmd.action) {
case SedCommand::Substitute: {
bool changed = apply_substitute(line, cmd);
if (changed && cmd.print_flag) {
extra_print = true;
}
if (cmd.delete_flag && changed) {
deleted = true;
}
break;
}
case SedCommand::Delete:
deleted = true;
break;
case SedCommand::Print:
extra_print = true;
break;
}
}
if (extra_print) {
std::printf("%s\n", line.c_str());
}
if (!deleted && !suppress) {
std::printf("%s\n", line.c_str());
}
}
}
} // namespace
auto sed_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'n', false},
cfbox::args::OptSpec{'e', true},
});
if (parsed.has_long("help")) { cfbox::help::print_help(HELP); return 0; }
if (parsed.has_long("version")) { cfbox::help::print_version(HELP); return 0; }
bool suppress = parsed.has('n');
std::string script;
std::vector<std::string_view> files;
if (parsed.has('e')) {
script = std::string{parsed.get('e').value_or("")};
for (const auto& p : parsed.positional()) {
files.push_back(p);
}
} else {
// First positional arg is the script
const auto& pos = parsed.positional();
if (pos.empty()) {
CFBOX_ERR("sed", "missing script");
return 1;
}
script = std::string{pos[0]};
for (std::size_t i = 1; i < pos.size(); ++i) {
files.push_back(pos[i]);
}
}
auto commands = parse_script(script);
if (commands.empty()) {
CFBOX_ERR("sed", "empty command");
return 1;
}
if (files.empty()) {
// Read from stdin
auto result = cfbox::io::read_all_stdin();
if (!result) {
CFBOX_ERR("sed", "%s", result.error().msg.c_str());
return 1;
}
auto lines = cfbox::io::split_lines(result.value());
process_lines(lines, commands, suppress);
} else {
for (const auto& f : files) {
auto result = (f == "-") ? cfbox::io::read_all_stdin() : cfbox::io::read_all(f);
if (!result) {
CFBOX_ERR("sed", "%s", result.error().msg.c_str());
return 1;
}
auto lines = cfbox::io::split_lines(result.value());
process_lines(lines, commands, suppress);
}
}
return 0;
}