-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpand.cpp
More file actions
65 lines (58 loc) · 1.88 KB
/
expand.cpp
File metadata and controls
65 lines (58 loc) · 1.88 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
#include <cstdio>
#include <string>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/stream.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "expand",
.version = CFBOX_VERSION_STRING,
.one_line = "convert tabs to spaces",
.usage = "expand [-t N] [FILE]...",
.options = " -t N have tabs N characters apart (default 8)",
.extra = "",
};
} // namespace
auto expand_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'t', true, "tabs"},
});
if (parsed.has_long("help")) { cfbox::help::print_help(HELP); return 0; }
if (parsed.has_long("version")) { cfbox::help::print_version(HELP); return 0; }
int tab_stop = 8;
if (auto t = parsed.get_any('t', "tabs")) {
tab_stop = std::stoi(std::string{*t});
if (tab_stop <= 0) {
CFBOX_ERR("expand", "invalid tab stop: %d", tab_stop);
return 1;
}
}
const auto& pos = parsed.positional();
auto paths = pos.empty() ? std::vector<std::string_view>{"-"} : pos;
int rc = 0;
for (auto p : paths) {
auto result = cfbox::stream::for_each_line(p, [&](const std::string& line, std::size_t) {
int col = 0;
for (char c : line) {
if (c == '\t') {
int spaces = tab_stop - (col % tab_stop);
for (int i = 0; i < spaces; ++i) {
std::putchar(' ');
}
col += spaces;
} else {
std::putchar(c);
++col;
}
}
std::putchar('\n');
return true;
});
if (!result) {
CFBOX_ERR("expand", "%s", result.error().msg.c_str());
rc = 1;
}
}
return rc;
}