102 {
104 if (!fs::exists(draftPath))
105 return nlohmann::json();
106
107 nlohmann::json j;
108
109
110 try {
111 std::ifstream f(draftPath);
112 f >> j;
113 f.close();
114
115 auto now = std::chrono::system_clock::now();
116 std::time_t now_c = std::chrono::system_clock::to_time_t(now);
117 std::stringstream ss;
118 ss << std::put_time(std::gmtime(&now_c), "%Y-%m-%dT%H:%M:%SZ");
119
120 if (!j.contains("meta"))
121 j["meta"] = nlohmann::json::object();
122 j["meta"]["created"] = ss.str();
123 j["meta"]["version"] = std::to_string(std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count());
124
125 std::ofstream out(draftPath, std::ios::trunc);
126 out << j.dump(2);
127 out.close();
128 } catch (const std::exception& e) {
129 VLOG(1) << "Failed to inject metadata into draft: " << e.what();
130 }
131
132
133 if (fs::exists(mapFilePath)) {
134 fs::path versionDir = fs::path(mapFilePath).parent_path() / "versions";
135 if (!fs::exists(versionDir)) {
136 fs::create_directories(versionDir);
137 }
138
139 auto now = std::chrono::system_clock::now();
140 auto timestamp = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
141 std::string filename = fs::path(mapFilePath).filename().string();
142 std::string backupPath = versionDir / (filename + "." + std::to_string(timestamp));
143
144 fs::copy_file(mapFilePath, backupPath, fs::copy_options::overwrite_existing);
145
146
147 try {
148 std::vector<fs::path> versions;
149 for (const auto& entry : fs::directory_iterator(versionDir)) {
150 if (entry.path().filename().string().starts_with(filename + ".")) {
151 versions.push_back(entry.path());
152 }
153 }
154 if (versions.size() > 50) {
155 std::sort(versions.begin(), versions.end(), [](const fs::path& a, const fs::path& b) {
156 return fs::last_write_time(a) < fs::last_write_time(b);
157 });
158 for (size_t i = 0; i < versions.size() - 50; ++i) {
159 fs::remove(versions[i]);
160 }
161 }
162 } catch (...) {
163 }
164 }
165
166
167 fs::remove(draftPath);
168
169 return j;
170 }
static std::string getDraftPath(const std::string &mapFilePath)