32#include <nlohmann/json.hpp>
38 constexpr std::string_view METADATA_PATH =
"metadata.json";
39 constexpr std::string_view PROJECT_PATH =
"project.json";
41 template <auto Fn>
struct ZipDeleter {
42 template <
typename T>
void operator()(T* ptr)
const noexcept
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>>;
53 [[nodiscard]] std::string readEntry(zip_t* archive,
const std::string& entryName)
55 const zip_int64_t entryIndex =
56 zip_name_locate(archive, entryName.c_str(), ZIP_FL_ENC_UTF_8);
58 throw std::runtime_error(std::format(
"Project archive is missing {}", entryName));
62 if (zip_stat_index(archive, entryIndex, 0, &stat) != 0)
63 throw std::runtime_error(
64 std::format(
"Cannot inspect project archive entry {}", entryName));
66 if ((stat.valid & ZIP_STAT_SIZE) == 0)
67 throw std::runtime_error(
68 std::format(
"Project archive entry {} has no size", entryName));
73 UniqueZipFile file(zip_fopen_index(archive, entryIndex, 0));
75 throw std::runtime_error(
76 std::format(
"Cannot read project archive entry {}", entryName));
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));
85 return static_cast<std::size_t
>(bytesRead);
91 void addEntry(zip_t* archive,
const std::string& entryName, std::string_view contents,
92 bool storeUncompressed =
false)
94 void* buffer = std::malloc(contents.size());
95 if (!buffer && !contents.empty())
96 throw std::bad_alloc();
98 if (!contents.empty())
99 std::memcpy(buffer, contents.data(), contents.size());
101 UniqueZipSource
source(zip_source_buffer(archive, buffer, contents.size(), 1));
104 throw std::runtime_error(std::format(
"Cannot create zip source for {}", entryName));
107 const zip_int64_t index = zip_file_add(archive, entryName.c_str(),
source.get(),
108 ZIP_FL_OVERWRITE | ZIP_FL_ENC_UTF_8);
110 throw std::runtime_error(
111 std::format(
"Cannot add {} to project archive", entryName));
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));
120 template <
typename F>
void enumerateZipEntries(zip_t* archive, F&& callback)
122 const zip_int64_t count = zip_get_num_entries(archive, 0);
124 throw std::runtime_error(
"Cannot inspect project archive entries");
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});
132 void validateUniqueArchiveEntries(zip_t* archive)
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");
142 template <
typename T>
143 [[nodiscard]] T requireField(
const nlohmann::json& obj, std::string_view key,
144 std::string_view entryName)
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));
154 [[nodiscard]]
bool isDocumentRoot(
const std::string_view path)
157 return path == info.root;
161 [[nodiscard]] std::vector<std::string> documentEntries(zip_t* archive)
163 std::vector<std::string> entries;
164 enumerateZipEntries(archive, [&](
const std::string_view name) {
165 if (name ==
"mimetype" || name == METADATA_PATH || name == PROJECT_PATH)
168 if (name.ends_with(
'/')) {
169 if (isDocumentRoot(name))
171 throw std::runtime_error(
172 std::format(
"Project archive contains invalid directory entry {}", name));
176 throw std::runtime_error(
177 std::format(
"Project archive contains invalid entry {}", name));
179 entries.emplace_back(name);
182 std::ranges::sort(entries, [](
const std::string& left,
const std::string& right) {
185 return leftType == rightType ? left < right : leftType < rightType;
190 void validateDocuments(
const std::vector<Document>& documents)
192 std::vector<std::string_view> paths;
193 paths.reserve(documents.size());
195 bool hasCircuit =
false;
197 for (
const auto& document : documents) {
198 paths.push_back(document.getPath());
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");
210 throw std::runtime_error(
"Project archive must contain at least one circuit entry");
216 nlohmann::json::parse(readEntry(archive, std::string(METADATA_PATH)));
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)};
224 throw std::runtime_error(std::format(
225 "Unsupported Silicon project format version {}", metadata.formatVersion));
230 [[nodiscard]]
ProjectInfo parseProjectInfo(zip_t* archive)
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),
238 requireField<std::string>(json,
"description", PROJECT_PATH)};
241 [[nodiscard]] nlohmann::ordered_json metadataToJson(
const ProjectMetadata& m)
243 return {{
"formatVersion", m.formatVersion},
244 {
"siliconVersion", m.siliconVersion},
245 {
"creationDate", m.creationDate},
246 {
"lastModify", m.lastModify}};
249 [[nodiscard]] nlohmann::ordered_json projectInfoToJson(
const ProjectInfo& p)
251 return {{
"name", p.name}, {
"description", p.description}};
259 std::chrono::floor<std::chrono::seconds>(std::chrono::system_clock::now());
260 return std::format(
"{:%Y-%m-%dT%H:%M:%SZ}", now);
267 .siliconVersion = SILICON_VERSION,
275 UniqueZip archive(zip_open(path.string().c_str(), ZIP_RDONLY, &errorCode));
277 throw std::runtime_error(
278 std::format(
"Cannot open Silicon project archive: ZIP error code {}", errorCode));
280 validateUniqueArchiveEntries(archive.get());
281 if (readEntry(archive.get(),
"mimetype") !=
MIME_TYPE)
282 throw std::runtime_error(
"Silicon project archive has an unexpected mimetype");
284 auto metadata = parseMetadata(archive.get());
285 auto project = parseProjectInfo(archive.get());
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));
293 validateDocuments(documents);
295 return ProjectFile{.metadata = std::move(metadata),
297 .documents = std::move(documents)};
302 validateDocuments(projectFile.
documents);
306 zip_open(path.string().c_str(), ZIP_CREATE | ZIP_TRUNCATE, &errorCode));
308 throw std::runtime_error(std::format(
309 "Cannot create Silicon project archive, ZIP error code: {}", errorCode));
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));
318 for (
const auto& document : projectFile.
documents)
319 addEntry(archive.get(), document.getPath(), document.getContents());
321 if (zip_close(archive.get()) != 0)
322 throw std::runtime_error(
"Cannot finalize Silicon project archive");
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.