#include "core/vfs.h" #include #include #include #include #include "core/pfp.h" namespace fs = std::filesystem; namespace playground { std::string normalizePath(const std::string& p) { std::string r = p; for (char& c : r) c = (c == '\\') ? '/' : char(std::tolower(static_cast(c))); while (r.rfind("./", 0) == 0) r.erase(0, 2); return r; } std::filesystem::path pathFromUtf8(const std::string& s) { return fs::path(std::u8string(s.begin(), s.end())); } std::string pathToUtf8(const fs::path& p) { auto u = p.u8string(); return std::string(u.begin(), u.end()); } bool Vfs::exists(const std::string& path) const { std::string k = normalizePath(path); for (auto& n : list()) if (normalizePath(n) == k) return true; return false; } bool readFile(const std::string& path, Bytes& out) { std::ifstream f(pathFromUtf8(path), std::ios::binary); if (!f) return false; f.seekg(0, std::ios::end); auto sz = f.tellg(); f.seekg(0); out.resize(size_t(sz)); if (sz > 0) f.read(reinterpret_cast(out.data()), sz); return bool(f) || sz == 0; } namespace { class DirVfs : public Vfs { public: fs::path root; std::vector names; const std::vector& list() const override { return names; } bool read(const std::string& path, Bytes& out) const override { std::string key = normalizePath(path); for (auto& n : names) if (normalizePath(n) == key) return readFile(pathToUtf8(root / pathFromUtf8(n)), out); return false; } }; } // namespace std::unique_ptr openDir(const std::string& dir, std::string* err) { std::error_code ec; if (!fs::is_directory(pathFromUtf8(dir), ec)) { if (err) *err = "not a directory: " + dir; return nullptr; } auto v = std::make_unique(); v->root = pathFromUtf8(dir); for (auto& e : fs::recursive_directory_iterator(v->root, ec)) if (e.is_regular_file()) v->names.push_back([&]{ auto u = fs::relative(e.path(), v->root).generic_u8string(); return std::string(u.begin(), u.end()); }()); std::sort(v->names.begin(), v->names.end()); return v; } std::unique_ptr openVfs(const std::string& path, std::string* err) { std::error_code ec; if (fs::is_directory(pathFromUtf8(path), ec)) return openDir(path, err); return openPfp(path, err); } } // namespace playground