qswiki/cache/fscache.cpp

63 γραμμές
1.4 KiB
C++

2018-11-03 17:12:20 +01:00
#include <filesystem>
#include <fstream>
#include "fscache.h"
#include "../logger.h"
FsCache::FsCache(std::string path)
{
if(!std::filesystem::exists(path))
{
throw std::runtime_error{"Cache directory does not exist"};
2018-11-03 17:12:20 +01:00
}
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(std::string_view(entry.path().filename().c_str()).starts_with(prefix))
2018-11-03 17:12:20 +01:00
{
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);
}
}