-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmkdir.cpp
More file actions
74 lines (63 loc) · 2.26 KB
/
mkdir.cpp
File metadata and controls
74 lines (63 loc) · 2.26 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
#include <cstdio>
#include <cstdlib>
#include <string>
#include <string_view>
#include <cfbox/args.hpp>
#include <cfbox/fs_util.hpp>
#include <cfbox/help.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "mkdir",
.version = CFBOX_VERSION_STRING,
.one_line = "create directories",
.usage = "mkdir [OPTIONS] DIRECTORY...",
.options = " -p no error if existing, make parent directories as needed\n"
" -m MODE set file mode (as in chmod), not a=rwx - umask",
.extra = "",
};
auto parse_mode(std::string_view mode_str) -> std::filesystem::perms {
unsigned long mode = std::strtoul(std::string{mode_str}.c_str(), nullptr, 8);
return static_cast<std::filesystem::perms>(mode);
}
} // namespace
auto mkdir_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'p', false, "parents"},
cfbox::args::OptSpec{'m', true, "mode"},
});
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 recursive = parsed.has('p');
auto mode_val = std::filesystem::perms::all;
if (parsed.has('m')) {
mode_val = parse_mode(parsed.get('m').value_or("755"));
}
const auto& pos = parsed.positional();
if (pos.empty()) {
CFBOX_ERR("mkdir", "missing operand");
return 1;
}
int rc = 0;
for (const auto& dir : pos) {
if (recursive) {
auto result = cfbox::fs::mkdir_recursive(dir, mode_val);
if (!result) {
CFBOX_ERR("mkdir", "cannot create directory '%s': %s", dir.data(), result.error().msg.c_str());
rc = 1;
}
} else {
if (cfbox::fs::exists(dir)) {
CFBOX_ERR("mkdir", "cannot create directory '%s': File exists", dir.data());
rc = 1;
continue;
}
auto result = cfbox::fs::mkdir_single(dir, mode_val);
if (!result) {
CFBOX_ERR("mkdir", "cannot create directory '%s': %s", dir.data(), result.error().msg.c_str());
rc = 1;
}
}
}
return rc;
}