Repository navigation
Expand file tree
/
Copy pathscan.cpp
More file actions
86 lines (63 loc) · 2.1 KB
/
Copy pathscan.cpp
File metadata and controls
86 lines (63 loc) · 2.1 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
#include "scan.h"
#include "hash.h"
#include <algorithm>
#include <stdexcept>
#include <system_error>
namespace HashGuard
{
ScanResult ScanDirectory(
const std::filesystem::path& directory)
{
namespace fs = std::filesystem;
ScanResult result;
std::error_code ec;
if (!fs::is_directory(directory, ec))
{
throw std::runtime_error("invalid or inaccessible directory");
}
fs::recursive_directory_iterator it(directory, fs::directory_options::skip_permission_denied, ec);
fs::recursive_directory_iterator end;
if (ec)
{
throw fs::filesystem_error("cannot start directory scan", directory, ec);
}
while (it != end)
{
const fs::path currentPath = it->path();
ec.clear();
const bool regularFile = it->is_regular_file(ec);
if (ec)
{
result.errors.push_back({currentPath,ec.message()});
}
else if (regularFile)
{
try
{
FileInfo info;
info.path = fs::relative(currentPath, directory);
info.size = fs::file_size(currentPath);
info.sha256 = CalculateSHA256(currentPath);
result.files.push_back(std::move(info));
}
catch (const std::exception& error)
{
result.errors.push_back({currentPath,error.what()});
}
}
ec.clear();
it.increment(ec);
if (ec)
{
result.errors.push_back({currentPath,"directory traversal: " + ec.message()});
ec.clear();
}
}
std::sort(result.files.begin(), result.files.end(), [](const FileInfo& a, const FileInfo& b)
{
return a.path.native() < b.path.native();
}
);
return result;
}
}