Switch to using a filesystem class for better testing

This commit is contained in:
pmb
2025-06-25 11:59:07 -07:00
parent 3d35345eb9
commit e880f6ba1d
5 changed files with 200 additions and 39 deletions
+45 -6
View File
@@ -1,15 +1,54 @@
#pragma once
#include <string>
#include <exception>
#include <filesystem>
#include <fstream>
#include <stdexcept>
#include <string>
class InvalidInput : public std::runtime_error
{
class IFilesystemWrapper {
public:
InvalidInput(const std::string& what = "") : std::runtime_error(what) {}
virtual ~IFilesystemWrapper() = default;
virtual bool exists(const std::filesystem::path &path) const = 0;
virtual std::string read_file(const std::filesystem::path &path) const = 0;
};
class RealFilesystemWrapper : public IFilesystemWrapper {
public:
bool exists(const std::filesystem::path &path) const override {
return std::filesystem::exists(path);
}
std::string process(const std::string &username);
std::string read_file(const std::filesystem::path &path) const override {
std::ifstream file(path);
if (!file.is_open()) {
return "";
}
std::string content;
std::string line;
while (std::getline(file, line)) {
content += line + "\n";
}
// Return the content with proper line endings
if (!content.empty() && content.back() == '\n') {
content.pop_back(); // Remove the last newline
content += "\r\n";
return content;
} else if (!content.empty()) {
content += "\r\n";
return content;
}
return "";
}
};
class InvalidInput : public std::runtime_error {
public:
InvalidInput(const std::string &what = "") : std::runtime_error(what) {}
};
std::string process(const std::string &username);
std::string process(const std::string &username, const IFilesystemWrapper &fs);