2
0
mirror of https://github.com/Laupetin/OpenAssetTools.git synced 2025-07-01 16:51:56 +00:00

chore: add abstraction for opening output files to be able to mock it

This commit is contained in:
Jan
2025-01-07 00:02:38 +01:00
parent cacccf64e1
commit e0f8b3d3ca
25 changed files with 202 additions and 68 deletions

View File

@ -0,0 +1,18 @@
#pragma once
#include <memory>
#include <ostream>
#include <string>
class IOutputPath
{
public:
IOutputPath() = default;
virtual ~IOutputPath() = default;
IOutputPath(const IOutputPath& other) = default;
IOutputPath(IOutputPath&& other) noexcept = default;
IOutputPath& operator=(const IOutputPath& other) = default;
IOutputPath& operator=(IOutputPath&& other) noexcept = default;
virtual std::unique_ptr<std::ostream> Open(const std::string& fileName) = 0;
};

View File

@ -0,0 +1,27 @@
#include "OutputPathFilesystem.h"
#include <fstream>
namespace fs = std::filesystem;
OutputPathFilesystem::OutputPathFilesystem(const fs::path& path)
: m_path(fs::canonical(path))
{
}
std::unique_ptr<std::ostream> OutputPathFilesystem::Open(const std::string& fileName)
{
const auto fullNewPath = fs::canonical(m_path / fileName);
if (!fullNewPath.string().starts_with(m_path.string()))
return nullptr;
const auto containingDirectory = fullNewPath.parent_path();
fs::create_directories(containingDirectory);
std::ofstream stream(fullNewPath, std::ios::binary | std::ios::out);
if (!stream.is_open())
return nullptr;
return std::make_unique<std::ofstream>(std::move(stream));
}

View File

@ -0,0 +1,16 @@
#pragma once
#include "IOutputPath.h"
#include <filesystem>
class OutputPathFilesystem final : public IOutputPath
{
public:
explicit OutputPathFilesystem(const std::filesystem::path& path);
std::unique_ptr<std::ostream> Open(const std::string& fileName) override;
private:
std::filesystem::path m_path;
};