-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cc
97 lines (73 loc) · 2.02 KB
/
main.cc
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
#include <cerrno>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <set>
#include "serialize.hh"
namespace fs = std::filesystem;
using std::cerr, std::cout, std::endl;
/** Dump file contents as NAR. */
static void dumpContents(const fs::path &path) {
auto size = fs::file_size(path);
cout << NarStr{"contents"} << NarInt{size};
std::ifstream ifs(path);
char buf[65536];
size_t left = size;
while (ifs && left > 0) {
auto n = std::min(left, sizeof(buf));
ifs.read(buf, n);
left -= n;
cout.write(buf, n);
}
if (!ifs) {
cerr << "Error reading file " << path << ": " << std::strerror(errno)
<< endl;
exit(1);
}
cout << NarPad{size};
}
/** Dump a path as NAR. */
static void dump(const fs::path &path) {
auto st = fs::symlink_status(path);
cout << NarStr{"("};
switch (st.type()) {
case fs::file_type::regular:
cout << NarStr{"type"} << NarStr{"regular"};
if ((st.permissions() & fs::perms::owner_exec) != fs::perms::none) {
cout << NarStr{"executable"} << NarStr{""};
}
dumpContents(path);
break;
case fs::file_type::directory: {
cout << NarStr{"type"} << NarStr{"directory"};
std::set<std::string> sorted;
for (const auto &entry : fs::directory_iterator(path)) {
sorted.emplace(entry.path().filename());
}
for (auto &filename : sorted) {
cout << NarStr{"entry"} << NarStr{"("} << NarStr{"name"}
<< NarStr{filename} << NarStr{"node"};
dump(path / filename);
cout << NarStr{")"};
}
break;
}
case fs::file_type::symlink:
cout << NarStr{"type"} << NarStr{"symlink"} << NarStr{"target"}
<< NarStr{fs::read_symlink(path).string()};
break;
default:
cerr << "File " << path << " has an unsupported type" << endl;
exit(1);
}
cout << NarStr{")"};
}
int main(int argc, char **argv) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <path>" << endl;
exit(64);
}
cout << NarStr{"nix-archive-1"};
dump(argv[1]);
}