#include "Project.hpp" #include #include #include #include #include #include #include namespace fs = std::filesystem; template void ReadItemList(ItemList& list, const fs::path& filePath) { std::ifstream ifs(filePath); if (ifs) { Json::Value root; ifs >> root; list = ItemList(root); } } Project Project::Load(const fs::path& projectFilePath) { // TODO better diagnostic const char* kInvalidFormatErr = "Failed to load project: invalid format."; std::ifstream ifs(projectFilePath); if (!ifs) { std::string message; message += "Failed to load project file at '"; message += projectFilePath.string(); message += "'."; throw std::runtime_error(message); } Project proj; proj.mRootPath = projectFilePath.parent_path(); proj.mRootPathString = proj.mRootPath.string(); { Json::Value root; ifs >> root; const auto& croot = root; // Use const reference so that accessors default to returning a null if not found, instead of silently creating new elements if (!croot.isObject()) { throw std::runtime_error(kInvalidFormatErr); } if (auto& name = croot["Name"]; name.isString()) { proj.mName = name.asString(); } else { throw std::runtime_error(kInvalidFormatErr); } } auto itemsDir = proj.mRootPath / "items"; ReadItemList(proj.Products, itemsDir / "products.json"); ReadItemList(proj.Factories, itemsDir / "factories.json"); ReadItemList(proj.Customers, itemsDir / "customers.json"); return proj; } Project Project::LoadDir(const std::filesystem::path& projectPath) { return Load(projectPath / "cplt_project.json"); } Project Project::Create(std::string name, const fs::path& path) { Project proj; proj.mRootPath = path; proj.mRootPathString = path.string(); proj.mName = std::move(name); return proj; } const fs::path& Project::GetPath() const { return mRootPath; } const std::string& Project::GetPathString() const { return mRootPathString; } const std::string& Project::GetName() const { return mName; } void Project::SetName(std::string name) { mName = std::move(name); } Json::Value Project::Serialize() { Json::Value root(Json::objectValue); root["Name"] = mName; return root; } template static void WriteItemList(ItemList& list, const fs::path& filePath) { std::ofstream ofs(filePath); ofs << list.Serialize(); } void Project::WriteToDisk() { std::ofstream ofs(mRootPath / "cplt_project.json"); ofs << this->Serialize(); auto itemsDir = mRootPath / "items"; fs::create_directories(itemsDir); WriteItemList(Products, itemsDir / "products.json"); WriteItemList(Factories, itemsDir / "factories.json"); WriteItemList(Customers, itemsDir / "customers.json"); }