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
24[[nodiscard]] inline std::filesystem::path create_tmpdir()
25{
26 int max_tries = 1000;
27 auto tmp_dir = std::filesystem::temp_directory_path();
28 int i = 0;
29 std::random_device random_device;
30 std::mt19937 mersenne_prng(random_device());
31 std::uniform_int_distribution<uint64_t> uniform_int_distribution(0);
32 std::filesystem::path path;
33 while (true) {
34 std::stringstream string_stream;
35 string_stream << std::hex << uniform_int_distribution(mersenne_prng);
36 path = tmp_dir / ("porytiles_" + string_stream.str());
37 if (std::filesystem::create_directory(path)) {
38 break;
39 }
40 if (i == max_tries) {
41 panic("create_tmpdir: exceeded maximum retries");
42 }
43 i++;
44 }
45 return path;
46}
47
60[[nodiscard]] inline bool files_are_identical(const std::filesystem::path &file_a, const std::filesystem::path &file_b)
61{
62 if (!std::filesystem::exists(file_b)) {
63 return false;
64 }
65 if (std::filesystem::file_size(file_a) != std::filesystem::file_size(file_b)) {
66 return false;
67 }
68 StreamDigest digest;
69 std::ifstream stream_a{file_a, std::ios::binary};
70 std::ifstream stream_b{file_b, std::ios::binary};
71 if (!stream_a || !stream_b) {
72 return false;
73 }
74 return digest.digest(stream_a) == digest.digest(stream_b);
75}
76
96[[nodiscard]] inline std::filesystem::path strip_all_extensions(const std::filesystem::path &path)
97{
98 auto dir = path.parent_path();
99 auto filename = path.filename();
100 while (!filename.extension().empty()) {
101 filename = filename.stem();
102 }
103 if (dir.empty()) {
104 return filename;
105 }
106 return dir / filename;
107}
108
109} // 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.