Porytiles
Loading...
Searching...
No Matches
filesystem_utils.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <filesystem>
4#include <fstream>
5#include <random>
6#include <sstream>
7
10
11namespace porytiles {
12
22[[nodiscard]] inline std::filesystem::path create_tmpdir()
23{
24 int max_tries = 1000;
25 auto tmp_dir = std::filesystem::temp_directory_path();
26 int i = 0;
27 std::random_device random_device;
28 std::mt19937 mersenne_prng(random_device());
29 std::uniform_int_distribution<uint64_t> uniform_int_distribution(0);
30 std::filesystem::path path;
31 while (true) {
32 std::stringstream string_stream;
33 string_stream << std::hex << uniform_int_distribution(mersenne_prng);
34 path = tmp_dir / ("porytiles_" + string_stream.str());
35 if (std::filesystem::create_directory(path)) {
36 break;
37 }
38 if (i == max_tries) {
39 panic("create_tmpdir: exceeded maximum retries");
40 }
41 i++;
42 }
43 return path;
44}
45
56[[nodiscard]] inline bool files_are_identical(const std::filesystem::path &file_a, const std::filesystem::path &file_b)
57{
58 if (!std::filesystem::exists(file_b)) {
59 return false;
60 }
61 if (std::filesystem::file_size(file_a) != std::filesystem::file_size(file_b)) {
62 return false;
63 }
64 StreamDigest digest;
65 std::ifstream stream_a{file_a, std::ios::binary};
66 std::ifstream stream_b{file_b, std::ios::binary};
67 if (!stream_a || !stream_b) {
68 return false;
69 }
70 return digest.digest(stream_a) == digest.digest(stream_b);
71}
72
90[[nodiscard]] inline std::filesystem::path strip_all_extensions(const std::filesystem::path &path)
91{
92 auto dir = path.parent_path();
93 auto filename = path.filename();
94 while (!filename.extension().empty()) {
95 filename = filename.stem();
96 }
97 if (dir.empty()) {
98 return filename;
99 }
100 return dir / filename;
101}
102
103} // namespace porytiles
Computes the MD5 digest of an input stream.
std::string digest(std::istream &stream) const
Computes the MD5 digest of an input stream.
void panic(const StringViewSourceLoc &s)
Unconditionally terminates the program with a panic message.
Definition panic.cpp:43
std::filesystem::path create_tmpdir()
Creates a unique temporary directory.
bool files_are_identical(const std::filesystem::path &file_a, const std::filesystem::path &file_b)
Checks if two files have identical contents.
std::filesystem::path strip_all_extensions(const std::filesystem::path &path)
Strips all extensions from a path, returning the path with only the stem.