63 خطوط
1.4 KiB
C++
63 خطوط
1.4 KiB
C++
#include <filesystem>
|
|
#include <fstream>
|
|
#include "fscache.h"
|
|
#include "../logger.h"
|
|
|
|
FsCache::FsCache(std::string path)
|
|
{
|
|
if(!std::filesystem::exists(path))
|
|
{
|
|
throw std::runtime_error{"Directory does not exist"};
|
|
}
|
|
this->path = path;
|
|
}
|
|
|
|
std::string FsCache::getFilePath(std::string_view path) const
|
|
{
|
|
std::filesystem::path ps{path};
|
|
std::string name = ps.filename();
|
|
return std::filesystem::path{this->path} / name;
|
|
}
|
|
std::optional<std::string> FsCache::get(std::string_view key) const
|
|
{
|
|
std::string path = getFilePath(key);
|
|
if(std::filesystem::exists(path))
|
|
{
|
|
return utils::readCompleteFile(path);
|
|
}
|
|
return {};
|
|
}
|
|
|
|
void FsCache::put(std::string_view key, std::string val)
|
|
{
|
|
std::string path = std::filesystem::path{this->path} / key;
|
|
std::fstream f1;
|
|
f1.open(path, std::ios::out);
|
|
f1 << val;
|
|
}
|
|
|
|
void FsCache::remove(std::string_view key)
|
|
{
|
|
std::filesystem::remove_all(std::filesystem::path{this->path} / key);
|
|
}
|
|
|
|
void FsCache::removePrefix(std::string_view prefix)
|
|
{
|
|
// TODO: lock dir
|
|
for(auto &entry : std::filesystem::directory_iterator(std::filesystem::path{this->path}))
|
|
{
|
|
if(static_cast<std::string>(entry.path().filename()).find(prefix) == 0)
|
|
{
|
|
std::filesystem::remove_all(entry);
|
|
}
|
|
}
|
|
}
|
|
|
|
void FsCache::clear()
|
|
{
|
|
for(auto &entry : std::filesystem::directory_iterator(std::filesystem::path{this->path}))
|
|
{
|
|
std::filesystem::remove_all(entry);
|
|
}
|
|
}
|