SILICON
Loading...
Searching...
No Matches
projectFile.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "projectFile.hpp"
19
20#include <algorithm>
21#include <chrono>
22#include <cstdlib>
23#include <cstring>
24#include <format>
25#include <memory>
26#include <ranges>
27#include <stdexcept>
28#include <string_view>
29#include <utility>
30#include <vector>
31
32#include <nlohmann/json.hpp>
33#include <zip.h>
34
35namespace SILICON::project {
36namespace {
37
38 constexpr std::string_view METADATA_PATH = "metadata.json";
39 constexpr std::string_view PROJECT_PATH = "project.json";
40
41 template <auto Fn> struct ZipDeleter {
42 template <typename T> void operator()(T* ptr) const noexcept
43 {
44 if (ptr)
45 Fn(ptr);
46 }
47 };
48
49 using UniqueZip = std::unique_ptr<zip_t, ZipDeleter<zip_discard>>;
50 using UniqueZipFile = std::unique_ptr<zip_file_t, ZipDeleter<zip_fclose>>;
51 using UniqueZipSource = std::unique_ptr<zip_source_t, ZipDeleter<zip_source_free>>;
52
53 [[nodiscard]] std::string readEntry(zip_t* archive, const std::string& entryName)
54 {
55 const zip_int64_t entryIndex =
56 zip_name_locate(archive, entryName.c_str(), ZIP_FL_ENC_UTF_8);
57 if (entryIndex < 0)
58 throw std::runtime_error(std::format("Project archive is missing {}", entryName));
59
60 zip_stat_t stat;
61 zip_stat_init(&stat);
62 if (zip_stat_index(archive, entryIndex, 0, &stat) != 0)
63 throw std::runtime_error(
64 std::format("Cannot inspect project archive entry {}", entryName));
65
66 if ((stat.valid & ZIP_STAT_SIZE) == 0)
67 throw std::runtime_error(
68 std::format("Project archive entry {} has no size", entryName));
69
70 if (stat.size == 0)
71 return {};
72
73 UniqueZipFile file(zip_fopen_index(archive, entryIndex, 0));
74 if (!file)
75 throw std::runtime_error(
76 std::format("Cannot read project archive entry {}", entryName));
77
78 std::string contents;
79 contents.resize_and_overwrite(stat.size, [&](char* buf, std::size_t) {
80 const zip_int64_t bytesRead = zip_fread(file.get(), buf, stat.size);
81 if (bytesRead < 0 || static_cast<zip_uint64_t>(bytesRead) != stat.size) {
82 throw std::runtime_error(
83 std::format("Cannot read complete project archive entry {}", entryName));
84 }
85 return static_cast<std::size_t>(bytesRead);
86 });
87
88 return contents;
89 }
90
91 void addEntry(zip_t* archive, const std::string& entryName, std::string_view contents,
92 bool storeUncompressed = false)
93 {
94 void* buffer = std::malloc(contents.size());
95 if (!buffer && !contents.empty())
96 throw std::bad_alloc();
97
98 if (!contents.empty())
99 std::memcpy(buffer, contents.data(), contents.size());
100
101 UniqueZipSource source(zip_source_buffer(archive, buffer, contents.size(), 1));
102 if (!source) {
103 std::free(buffer);
104 throw std::runtime_error(std::format("Cannot create zip source for {}", entryName));
105 }
106
107 const zip_int64_t index = zip_file_add(archive, entryName.c_str(), source.get(),
108 ZIP_FL_OVERWRITE | ZIP_FL_ENC_UTF_8);
109 if (index < 0)
110 throw std::runtime_error(
111 std::format("Cannot add {} to project archive", entryName));
112
113 source.release(); // Ownership successfully transferred to libzip
114
115 if (storeUncompressed
116 && zip_set_file_compression(archive, index, ZIP_CM_STORE, 0) != 0)
117 throw std::runtime_error(std::format("Cannot store {} uncompressed", entryName));
118 }
119
120 template <typename F> void enumerateZipEntries(zip_t* archive, F&& callback)
121 {
122 const zip_int64_t count = zip_get_num_entries(archive, 0);
123 if (count < 0)
124 throw std::runtime_error("Cannot inspect project archive entries");
125
126 for (zip_uint64_t i = 0; i < static_cast<zip_uint64_t>(count); ++i) {
127 if (const char* name = zip_get_name(archive, i, ZIP_FL_ENC_UTF_8))
128 callback(std::string_view{name});
129 }
130 }
131
132 void validateUniqueArchiveEntries(zip_t* archive)
133 {
134 std::vector<std::string> names;
135 enumerateZipEntries(archive,
136 [&](const std::string_view name) { names.emplace_back(name); });
137 std::ranges::sort(names);
138 if (std::ranges::adjacent_find(names) != names.end())
139 throw std::runtime_error("Project archive contains duplicate entries");
140 }
141
142 template <typename T>
143 [[nodiscard]] T requireField(const nlohmann::json& obj, std::string_view key,
144 std::string_view entryName)
145 {
146 try {
147 return obj.at(key).get<T>();
148 } catch (const nlohmann::json::exception&) {
149 throw std::runtime_error(
150 std::format("{}.{} is missing or of the wrong type", entryName, key));
151 }
152 }
153
154 [[nodiscard]] bool isDocumentRoot(const std::string_view path)
155 {
156 return std::ranges::any_of(DOCUMENT_TYPE_INFO, [&](const DocumentTypeInfo& info) {
157 return path == info.root;
158 });
159 }
160
161 [[nodiscard]] std::vector<std::string> documentEntries(zip_t* archive)
162 {
163 std::vector<std::string> entries;
164 enumerateZipEntries(archive, [&](const std::string_view name) {
165 if (name == "mimetype" || name == METADATA_PATH || name == PROJECT_PATH)
166 return;
167
168 if (name.ends_with('/')) {
169 if (isDocumentRoot(name))
170 return;
171 throw std::runtime_error(
172 std::format("Project archive contains invalid directory entry {}", name));
173 }
174
175 if (!documentTypeForPath(name))
176 throw std::runtime_error(
177 std::format("Project archive contains invalid entry {}", name));
178
179 entries.emplace_back(name);
180 });
181
182 std::ranges::sort(entries, [](const std::string& left, const std::string& right) {
183 const auto leftType = *documentTypeForPath(left);
184 const auto rightType = *documentTypeForPath(right);
185 return leftType == rightType ? left < right : leftType < rightType;
186 });
187 return entries;
188 }
189
190 void validateDocuments(const std::vector<Document>& documents)
191 {
192 std::vector<std::string_view> paths;
193 paths.reserve(documents.size());
194
195 bool hasCircuit = false;
196
197 for (const auto& document : documents) {
198 paths.push_back(document.getPath());
199 if (document.getType() != DocumentType::Circuit)
200 continue;
201
202 hasCircuit = true;
203 }
204
205 std::ranges::sort(paths);
206 if (std::ranges::adjacent_find(paths) != paths.end())
207 throw std::runtime_error("Project archive contains duplicate document entries");
208
209 if (!hasCircuit)
210 throw std::runtime_error("Project archive must contain at least one circuit entry");
211 }
212
213 [[nodiscard]] ProjectMetadata parseMetadata(zip_t* archive)
214 {
215 const auto json =
216 nlohmann::json::parse(readEntry(archive, std::string(METADATA_PATH)));
217 ProjectMetadata metadata{
218 .formatVersion = requireField<int>(json, "formatVersion", METADATA_PATH),
219 .siliconVersion = requireField<std::string>(json, "siliconVersion", METADATA_PATH),
220 .creationDate = requireField<std::string>(json, "creationDate", METADATA_PATH),
221 .lastModify = requireField<std::string>(json, "lastModify", METADATA_PATH)};
222
223 if (metadata.formatVersion != FORMAT_VERSION)
224 throw std::runtime_error(std::format(
225 "Unsupported Silicon project format version {}", metadata.formatVersion));
226
227 return metadata;
228 }
229
230 [[nodiscard]] ProjectInfo parseProjectInfo(zip_t* archive)
231 {
232 const auto json = nlohmann::json::parse(readEntry(archive, std::string(PROJECT_PATH)));
233 if (!json.is_object() || json.size() != 2 || !json.contains("name")
234 || !json.contains("description"))
235 throw std::runtime_error("project.json must contain only name and description");
236 return ProjectInfo{.name = requireField<std::string>(json, "name", PROJECT_PATH),
237 .description =
238 requireField<std::string>(json, "description", PROJECT_PATH)};
239 }
240
241 [[nodiscard]] nlohmann::ordered_json metadataToJson(const ProjectMetadata& m)
242 {
243 return {{"formatVersion", m.formatVersion},
244 {"siliconVersion", m.siliconVersion},
245 {"creationDate", m.creationDate},
246 {"lastModify", m.lastModify}};
247 }
248
249 [[nodiscard]] nlohmann::ordered_json projectInfoToJson(const ProjectInfo& p)
250 {
251 return {{"name", p.name}, {"description", p.description}};
252 }
253
254} // namespace
255
257{
258 const auto now =
259 std::chrono::floor<std::chrono::seconds>(std::chrono::system_clock::now());
260 return std::format("{:%Y-%m-%dT%H:%M:%SZ}", now);
261}
262
264{
265 const auto now = currentUtcTimestamp();
266 return {.formatVersion = FORMAT_VERSION,
267 .siliconVersion = SILICON_VERSION,
268 .creationDate = now,
269 .lastModify = now};
270}
271
272ProjectFile readProjectFile(const std::filesystem::path& path)
273{
274 int errorCode = 0;
275 UniqueZip archive(zip_open(path.string().c_str(), ZIP_RDONLY, &errorCode));
276 if (!archive)
277 throw std::runtime_error(
278 std::format("Cannot open Silicon project archive: ZIP error code {}", errorCode));
279
280 validateUniqueArchiveEntries(archive.get());
281 if (readEntry(archive.get(), "mimetype") != MIME_TYPE)
282 throw std::runtime_error("Silicon project archive has an unexpected mimetype");
283
284 auto metadata = parseMetadata(archive.get());
285 auto project = parseProjectInfo(archive.get());
286
287 const auto documentPaths = documentEntries(archive.get());
288 std::vector<Document> documents;
289 documents.reserve(documentPaths.size());
290 for (const auto& documentPath : documentPaths)
291 documents.emplace_back(documentPath, readEntry(archive.get(), documentPath));
292
293 validateDocuments(documents);
294
295 return ProjectFile{.metadata = std::move(metadata),
296 .project = std::move(project),
297 .documents = std::move(documents)};
298}
299
300void writeProjectFile(const std::filesystem::path& path, const ProjectFile& projectFile)
301{
302 validateDocuments(projectFile.documents);
303
304 int errorCode = 0;
305 UniqueZip archive(
306 zip_open(path.string().c_str(), ZIP_CREATE | ZIP_TRUNCATE, &errorCode));
307 if (!archive) {
308 throw std::runtime_error(std::format(
309 "Cannot create Silicon project archive, ZIP error code: {}", errorCode));
310 }
311
312 addEntry(archive.get(), "mimetype", MIME_TYPE, true);
313 addEntry(archive.get(), std::string(METADATA_PATH),
314 metadataToJson(projectFile.metadata).dump(2));
315 addEntry(archive.get(), std::string(PROJECT_PATH),
316 projectInfoToJson(projectFile.project).dump(2));
317
318 for (const auto& document : projectFile.documents)
319 addEntry(archive.get(), document.getPath(), document.getContents());
320
321 if (zip_close(archive.get()) != 0)
322 throw std::runtime_error("Cannot finalize Silicon project archive");
323
324 archive.release();
325}
326
327} // namespace SILICON::project
std::string currentUtcTimestamp()
Returns the current UTC timestamp formatted as YYYY-MM-DDTHH\:MM\:SSZ.
constexpr std::array< DocumentTypeInfo, 4 > DOCUMENT_TYPE_INFO
constexpr int FORMAT_VERSION
Current version of the Silicon project archive schema.
constexpr std::string_view MIME_TYPE
MIME marker stored in Silicon project archives.
ProjectFile readProjectFile(const std::filesystem::path &path)
Reads and validates a Silicon .sil project archive.
void writeProjectFile(const std::filesystem::path &path, const ProjectFile &projectFile)
Writes a Silicon .sil project archive.
std::optional< DocumentType > documentTypeForPath(const std::string_view path)
ProjectMetadata metadataForNewFile()
Creates default metadata for a new project file.
In-memory representation of a .sil project archive.
std::vector< Document > documents
Authoritative ordered collection of project documents.
Project-level data stored in project.json.
Metadata stored in metadata.json.