Implement VoidBuildSystem v1 (Plans 01-19) with VoidLibrary integration
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s

This commit is contained in:
faumaray committed 2026-11-26 20:45:54 +03:00
1 parent 3cac890ce9
commit ab64147f9d
114 files changed
+23777 -1392

No files matched your search

+581
View File
@@ -0,0 +1,581 @@
#include <Void/Build/Package/Archive.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/System/Types.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <format>
#include <set>
#include <sys/stat.h>
#include <unistd.h>
namespace Void::Build::Package {
namespace {
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg, int err = 0) {
return Void::System::make_system_error(code, std::move(msg), err);
}
bool is_safe_archive_path(std::string_view raw) {
if (raw.empty() || raw.front() == '/' || raw.find('\\') != std::string_view::npos) {
return false;
}
for (const unsigned char c : raw) {
if (c < 0x20 || c == 0x7f) {
return false;
}
}
std::size_t pos = 0;
while (pos <= raw.size()) {
const auto slash = raw.find('/', pos);
const auto seg =
raw.substr(pos, slash == std::string_view::npos ? std::string_view::npos : slash - pos);
if (seg == "..") {
return false;
}
if (slash == std::string_view::npos) {
break;
}
pos = slash + 1;
}
return true;
}
void write_octal(char *dst, std::size_t width, std::uint64_t val) {
std::memset(dst, '0', width - 1);
dst[width - 1] = '\0';
for (std::size_t i = width - 1; i > 0; --i) {
dst[i - 1] = static_cast<char>('0' + (val & 7u));
val >>= 3;
}
}
std::optional<std::uint64_t> parse_octal(const char *src, std::size_t width) {
std::size_t i = 0;
while (i < width && (src[i] == ' ' || src[i] == '\0')) {
++i;
}
std::uint64_t val = 0;
bool any = false;
for (; i < width; ++i) {
if (src[i] == '\0' || src[i] == ' ') {
break;
}
if (src[i] < '0' || src[i] > '7') {
return std::nullopt;
}
any = true;
val = (val << 3) | static_cast<std::uint64_t>(src[i] - '0');
}
return any ? std::optional<std::uint64_t>{val} : std::optional<std::uint64_t>{0};
}
void finalize_tar_header(std::array<char, 512> &hdr, std::string_view name, std::uint32_t mode,
std::uint64_t size, std::int64_t mtime, char typeflag) {
hdr.fill('\0');
if (name.size() <= 100) {
std::memcpy(hdr.data(), name.data(), name.size());
} else {
// Split into USTAR prefix (155) + name (100) at a slash boundary.
const auto split = name.rfind('/', 154);
if (split != std::string_view::npos && name.size() - split - 1 <= 100) {
std::memcpy(hdr.data() + 345, name.data(), split);
std::memcpy(hdr.data(), name.data() + split + 1, name.size() - split - 1);
} else {
std::memcpy(hdr.data(), name.data(), std::min<std::size_t>(name.size(), 100));
}
}
write_octal(hdr.data() + 100, 8, mode & 0777u);
write_octal(hdr.data() + 108, 8, 0); // canonical uid=0
write_octal(hdr.data() + 116, 8, 0); // canonical gid=0
write_octal(hdr.data() + 124, 12, size);
write_octal(hdr.data() + 136, 12, mtime >= 0 ? static_cast<std::uint64_t>(mtime) : 0u);
std::memset(hdr.data() + 148, ' ', 8);
hdr[156] = typeflag;
std::memcpy(hdr.data() + 257, "ustar", 6);
hdr[263] = '0';
hdr[264] = '0';
std::uint64_t chksum = 0;
for (const char c : hdr) {
chksum += static_cast<unsigned char>(c);
}
write_octal(hdr.data() + 148, 7, chksum);
hdr[155] = ' ';
}
std::string build_pax_path_record(std::string_view path) {
// Format: "<len> path=<path>\n"
std::string body = " path=" + std::string{path} + "\n";
std::size_t total = body.size() + 1;
for (int i = 0; i < 6; ++i) {
const auto digits = std::to_string(total).size();
if (digits + body.size() == total) {
break;
}
total = digits + body.size();
}
return std::to_string(total) + body;
}
bool write_all(int fd, const void *data, std::size_t len) {
const auto *p = static_cast<const char *>(data);
std::size_t off = 0;
while (off < len) {
const ssize_t n = ::write(fd, p + off, len - off);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
off += static_cast<std::size_t>(n);
}
return true;
}
bool read_exact(int fd, void *data, std::size_t len, std::size_t &got_out) {
auto *p = static_cast<char *>(data);
got_out = 0;
while (got_out < len) {
const ssize_t n = ::read(fd, p + got_out, len - got_out);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
if (n == 0) {
return true;
}
got_out += static_cast<std::size_t>(n);
}
return true;
}
bool is_zero_block(const std::array<char, 512> &blk) {
return std::ranges::all_of(blk, [](char c) { return c == '\0'; });
}
bool is_excluded_source_pkg_part(std::string_view part) {
if (part == ".git" || part == ".vbs" || part == "build" || part == ".serena" ||
part == ".cache" || part == "keys" || part == "WG.conf") {
return true;
}
if (part == ".env" || (part.starts_with(".env.") && part != ".env.example")) {
return true;
}
if (part.ends_with(".pem") || part.ends_with(".key")) {
return true;
}
return false;
}
} // namespace
Void::Result::Result<std::string, Void::Result::Error>
create_deterministic_tar(const std::filesystem::path &output_tar,
std::vector<ArchiveEntrySpec> entries,
std::int64_t reproducibility_epoch) {
std::ranges::sort(entries, [](const ArchiveEntrySpec &a, const ArchiveEntrySpec &b) {
return a.archive_path < b.archive_path;
});
std::set<std::string> seen_names;
for (const auto &e : entries) {
if (!is_safe_archive_path(e.archive_path)) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("create_deterministic_tar: unsafe archive path '{}'", e.archive_path))};
}
if (!seen_names.insert(e.archive_path).second) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::invalid_argument,
std::format("create_deterministic_tar: duplicate archive path '{}'",
e.archive_path))};
}
}
std::error_code ec;
if (output_tar.has_parent_path()) {
std::filesystem::create_directories(output_tar.parent_path(), ec);
}
const auto temp_tar =
output_tar.parent_path() / (output_tar.filename().string() + ".stage_" +
std::to_string(static_cast<long long>(::getpid())));
const int fd = ::open(temp_tar.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd < 0) {
return std::unexpected{make_error(Void::System::map_errno_to_system_code(errno),
"create_deterministic_tar: cannot open temp file",
errno)};
}
Void::System::OwnedFd guard{fd};
auto fail_cleanup = [&] {
(void)guard.close();
std::filesystem::remove(temp_tar, ec);
};
Util::Sha256Hasher hasher;
auto write_hashed = [&](const void *buf, std::size_t n) -> bool {
hasher.update(std::span<const std::uint8_t>{static_cast<const std::uint8_t *>(buf), n});
return write_all(fd, buf, n);
};
std::array<char, 512> zero_pad{};
std::array<char, 512> hdr{};
std::array<char, 65536> copy_buf{};
for (const auto &entry : entries) {
auto meta = Platform::stat_lstat(entry.source_file);
if (!meta || !meta->exists || !meta->is_regular) {
fail_cleanup();
return std::unexpected{make_error(
Void::System::SystemErrorCode::not_found,
std::format("create_deterministic_tar: source '{}' is not a regular file",
entry.source_file.string()))};
}
// Use PAX extended header whenever path > 100 chars to guarantee lossless long paths.
if (entry.archive_path.size() > 100) {
const std::string pax = build_pax_path_record(entry.archive_path);
finalize_tar_header(hdr, "PaxHeader/" + entry.archive_path.substr(0, 60), 0644,
pax.size(), reproducibility_epoch, 'x');
if (!write_hashed(hdr.data(), hdr.size()) || !write_hashed(pax.data(), pax.size())) {
fail_cleanup();
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "tar write failed")};
}
const std::size_t rem = pax.size() % 512;
if (rem != 0 && !write_hashed(zero_pad.data(), 512 - rem)) {
fail_cleanup();
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "tar pad write failed")};
}
}
finalize_tar_header(hdr, entry.archive_path, entry.mode, meta->size, reproducibility_epoch,
'0');
if (!write_hashed(hdr.data(), hdr.size())) {
fail_cleanup();
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "tar header write failed")};
}
const int sfd = ::open(entry.source_file.c_str(), O_RDONLY | O_CLOEXEC);
if (sfd < 0) {
fail_cleanup();
return std::unexpected{make_error(Void::System::map_errno_to_system_code(errno),
"cannot open source file for tar", errno)};
}
Void::System::OwnedFd sguard{sfd};
std::uint64_t remaining = meta->size;
while (remaining > 0) {
const std::size_t chunk =
static_cast<std::size_t>(std::min<std::uint64_t>(remaining, copy_buf.size()));
std::size_t got = 0;
if (!read_exact(sfd, copy_buf.data(), chunk, got) || got != chunk) {
fail_cleanup();
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"short read while archiving file")};
}
if (!write_hashed(copy_buf.data(), got)) {
fail_cleanup();
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "tar body write failed")};
}
remaining -= got;
}
const std::size_t pad = static_cast<std::size_t>((512 - (meta->size % 512)) % 512);
if (pad > 0 && !write_hashed(zero_pad.data(), pad)) {
fail_cleanup();
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "tar padding write failed")};
}
}
// Two 512-byte zero blocks terminate a valid tar archive.
if (!write_hashed(zero_pad.data(), 512) || !write_hashed(zero_pad.data(), 512)) {
fail_cleanup();
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "tar trailer write failed")};
}
if (const auto closed = guard.close(); !closed) {
std::filesystem::remove(temp_tar, ec);
return std::unexpected{closed.error()};
}
std::filesystem::rename(temp_tar, output_tar, ec);
if (ec) {
std::filesystem::remove(temp_tar, ec);
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "tar atomic publish failed")};
}
return hasher.finalize_hex();
}
Void::Result::Result<std::string, Void::Result::Error>
create_source_package(const std::filesystem::path &project_root,
const std::filesystem::path &output_tar, std::int64_t reproducibility_epoch) {
std::error_code ec;
const auto canon = std::filesystem::weakly_canonical(project_root, ec);
if (ec || !std::filesystem::is_directory(canon)) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::not_found, "project root does not exist")};
}
std::vector<ArchiveEntrySpec> entries;
std::filesystem::recursive_directory_iterator it{
canon, std::filesystem::directory_options::skip_permission_denied, ec};
for (; !ec && it != std::filesystem::recursive_directory_iterator{}; it.increment(ec)) {
const auto rel = it->path().lexically_relative(canon);
bool skip = false;
for (const auto &part : rel) {
if (is_excluded_source_pkg_part(part.string())) {
skip = true;
break;
}
}
if (skip) {
if (it->is_directory(ec)) {
it.disable_recursion_pending();
}
continue;
}
if (it->is_regular_file(ec)) {
auto meta = Platform::stat_lstat(it->path());
const std::uint32_t mode = (meta && (meta->mode & 0111u)) ? 0755u : 0644u;
entries.push_back({rel.lexically_normal().generic_string(), it->path(), mode});
}
}
return create_deterministic_tar(output_tar, std::move(entries), reproducibility_epoch);
}
Void::Result::Result<ArchiveExtractionStats, Void::Result::Error>
extract_safe_tar(const std::filesystem::path &tar_path,
const std::filesystem::path &destination_dir, const ArchiveLimits &limits) {
const int fd = ::open(tar_path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return std::unexpected{make_error(
Void::System::map_errno_to_system_code(errno),
std::format("extract_safe_tar: cannot open '{}'", tar_path.string()), errno)};
}
Void::System::OwnedFd guard{fd};
std::error_code ec;
const auto parent = destination_dir.parent_path().empty() ? std::filesystem::path{"."}
: destination_dir.parent_path();
std::filesystem::create_directories(parent, ec);
const auto stage_dir = parent / (destination_dir.filename().string() + ".extract_" +
std::to_string(static_cast<long long>(::getpid())));
std::filesystem::remove_all(stage_dir, ec);
std::filesystem::create_directories(stage_dir, ec);
auto abort_extract = [&] { std::filesystem::remove_all(stage_dir, ec); };
ArchiveExtractionStats stats;
std::set<std::string> seen_paths;
std::optional<std::string> next_pax_path;
std::array<char, 512> hdr{};
std::array<char, 65536> buf{};
for (;;) {
std::size_t got = 0;
if (!read_exact(fd, hdr.data(), 512, got)) {
abort_extract();
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error, "tar read error")};
}
if (got == 0 || (got == 512 && is_zero_block(hdr))) {
break;
}
if (got != 512) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"truncated tar header")};
}
// Verify header checksum.
const auto expected_sum = parse_octal(hdr.data() + 148, 8);
if (!expected_sum) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"malformed tar checksum")};
}
std::uint64_t actual_sum = 0;
for (std::size_t i = 0; i < 512; ++i) {
actual_sum += (i >= 148 && i < 156) ? static_cast<unsigned char>(' ')
: static_cast<unsigned char>(hdr[i]);
}
if (actual_sum != *expected_sum) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"tar header checksum mismatch")};
}
const auto size_opt = parse_octal(hdr.data() + 124, 12);
const auto mode_opt = parse_octal(hdr.data() + 100, 8);
if (!size_opt || !mode_opt) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"malformed tar size or mode")};
}
const std::uint64_t entry_size = *size_opt;
const std::uint32_t entry_mode = static_cast<std::uint32_t>(*mode_opt & 0777u);
const char typeflag = hdr[156];
// Handle PAX extended header ('x') for long paths.
if (typeflag == 'x') {
if (entry_size > 65536) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::limit_exceeded,
"PAX header exceeds limit")};
}
std::string pax_data(static_cast<std::size_t>(entry_size), '\0');
if (!read_exact(fd, pax_data.data(), pax_data.size(), got) || got != pax_data.size()) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"truncated PAX body")};
}
const std::size_t pad = static_cast<std::size_t>((512 - (entry_size % 512)) % 512);
if (pad > 0 && (!read_exact(fd, buf.data(), pad, got) || got != pad)) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"truncated PAX padding")};
}
const auto path_pos = pax_data.find(" path=");
if (path_pos != std::string::npos) {
const auto val_start = path_pos + 6;
const auto nl = pax_data.find('\n', val_start);
next_pax_path = pax_data.substr(
val_start, nl == std::string::npos ? std::string::npos : nl - val_start);
}
continue;
}
// Reject symlinks ('2'), hardlinks ('1'), devices ('3'/'4'), FIFOs ('6'), etc.!
if (typeflag != '0' && typeflag != '\0' && typeflag != '5') {
abort_extract();
return std::unexpected{make_error(
Void::System::SystemErrorCode::permission_denied,
std::format("archive contains disallowed non-regular entry type '{}'", typeflag))};
}
std::string entry_name;
if (next_pax_path) {
entry_name = std::move(*next_pax_path);
next_pax_path.reset();
} else {
const std::string name_part(hdr.data(), ::strnlen(hdr.data(), 100));
const std::string prefix_part(hdr.data() + 345, ::strnlen(hdr.data() + 345, 155));
entry_name = prefix_part.empty() ? name_part : (prefix_part + "/" + name_part);
}
while (entry_name.starts_with("./")) {
entry_name.erase(0, 2);
}
while (!entry_name.empty() && entry_name.back() == '/') {
entry_name.pop_back();
}
if (entry_name.empty() && typeflag == '5') {
continue;
}
if (!is_safe_archive_path(entry_name)) {
abort_extract();
return std::unexpected{make_error(
Void::System::SystemErrorCode::permission_denied,
std::format("archive contains unsafe or traversal path '{}'", entry_name))};
}
if (++stats.entries > limits.max_entries) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::limit_exceeded,
"archive entry count exceeds limit")};
}
if (entry_size > limits.max_file_bytes ||
stats.total_bytes + entry_size > limits.max_total_bytes) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::limit_exceeded,
"archive extracted size exceeds limit")};
}
const auto rel_norm = std::filesystem::path{entry_name}.lexically_normal().generic_string();
if (!seen_paths.insert(rel_norm).second) {
abort_extract();
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("archive contains duplicate colliding path '{}'", rel_norm))};
}
const auto dst_path = stage_dir / rel_norm;
if (!Platform::path_is_within(stage_dir, dst_path)) {
abort_extract();
return std::unexpected{
make_error(Void::System::SystemErrorCode::permission_denied,
std::format("archive entry '{}' escapes destination", rel_norm))};
}
if (typeflag == '5') {
std::filesystem::create_directories(dst_path, ec);
continue;
}
if (dst_path.has_parent_path()) {
std::filesystem::create_directories(dst_path.parent_path(), ec);
}
const int out_fd = ::open(dst_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC,
static_cast<mode_t>(entry_mode ? entry_mode : 0644u));
if (out_fd < 0) {
abort_extract();
return std::unexpected{make_error(
Void::System::map_errno_to_system_code(errno),
std::format("extract_safe_tar: failed creating '{}'", dst_path.string()), errno)};
}
Void::System::OwnedFd out_guard{out_fd};
std::uint64_t remaining = entry_size;
while (remaining > 0) {
const std::size_t chunk =
static_cast<std::size_t>(std::min<std::uint64_t>(remaining, buf.size()));
if (!read_exact(fd, buf.data(), chunk, got) || got != chunk) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"truncated tar file body")};
}
if (!write_all(out_fd, buf.data(), got)) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"failed writing extracted file")};
}
remaining -= got;
}
stats.total_bytes += entry_size;
stats.extracted_files.push_back(std::filesystem::path{rel_norm});
const std::size_t pad = static_cast<std::size_t>((512 - (entry_size % 512)) % 512);
if (pad > 0 && (!read_exact(fd, buf.data(), pad, got) || got != pad)) {
abort_extract();
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"truncated tar file padding")};
}
}
// Atomic publication into destination_dir.
if (std::filesystem::exists(destination_dir, ec)) {
std::filesystem::remove_all(destination_dir, ec);
}
std::filesystem::rename(stage_dir, destination_dir, ec);
if (ec) {
abort_extract();
return std::unexpected{make_error(
Void::System::map_errno_to_system_code(ec.value()),
std::format("extract_safe_tar: atomic rename to '{}' failed", destination_dir.string()),
ec.value())};
}
return stats;
}
} // namespace Void::Build::Package
+365
View File
@@ -0,0 +1,365 @@
#include <Void/Build/Package/Fetch.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Build/Snapshot/Snapshot.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Core/Scope.hpp>
#include <Void/System/Types.hpp>
#include <Void/Text/Str.hpp>
#include <algorithm>
#include <format>
namespace Void::Build::Package {
namespace {
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
return Void::System::make_system_error(code, redact_secrets(msg));
}
std::string sanitize_key(std::string_view text) {
std::string out;
for (const char c : text) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '_' || c == '-') {
out.push_back(c);
} else {
out.push_back('_');
}
}
return out;
}
std::string trim(std::string_view s) { return std::string{Void::Str::trim_right_ascii(s)}; }
} // namespace
std::string redact_secrets(std::string_view text) {
std::string out{text};
// Redact scheme://user:pass@host -> scheme://<redacted>@host
std::size_t pos = 0;
while ((pos = out.find("://", pos)) != std::string::npos) {
const auto after = pos + 3;
const auto slash = out.find('/', after);
const auto space = out.find_first_of(" \t\r\n\"'", after);
const auto bound = std::min(slash, space);
const auto at = out.find('@', after);
if (at != std::string::npos && at < bound) {
out.replace(after, at - after, "<redacted>");
pos = after + 10;
} else {
pos = after;
}
}
// Redact Bearer tokens.
pos = 0;
while ((pos = out.find("Bearer ", pos)) != std::string::npos) {
const auto start = pos + 7;
const auto end = out.find_first_of(" \t\r\n\"',;}", start);
const auto len = (end == std::string::npos) ? (out.size() - start) : (end - start);
out.replace(start, len, "<redacted>");
pos = start + 10;
}
return out;
}
std::string BinaryCompatibilityKey::compute_key_hash() const {
Util::Sha256Hasher h;
h.update_length_prefixed("vbs-bin-abi-v1");
h.update_length_prefixed(os);
h.update_length_prefixed(architecture);
h.update_length_prefixed(compiler_family);
h.update_length_prefixed(compiler_abi);
h.update_length_prefixed(stdlib_abi);
h.update_length_prefixed(linkage);
h.update_length_prefixed(cpu_features);
h.update_length_prefixed(sanitizers_key);
h.update_length_prefixed(lto_mode);
h.update_length_prefixed(dependency_closure_hash);
return h.finalize_hex();
}
bool BinaryCompatibilityKey::matches(const BinaryVariantMeta &candidate) const noexcept {
return candidate.os == os && candidate.architecture == architecture &&
candidate.compiler_family == compiler_family && candidate.compiler_abi == compiler_abi &&
candidate.stdlib_abi == stdlib_abi && candidate.linkage == linkage &&
candidate.cpu_features == cpu_features && candidate.sanitizers_key == sanitizers_key &&
candidate.lto_mode == lto_mode &&
candidate.dependency_closure_hash == dependency_closure_hash;
}
BinaryCompatibilityKey
make_binary_compatibility_key(const ProfileContext &profile,
const Toolchain::ToolchainCapabilities &toolchain,
std::string_view linkage, std::string_view dependency_closure_hash) {
BinaryCompatibilityKey key;
key.os = profile.os;
key.architecture = profile.architecture;
key.compiler_family = std::string{compiler_name(profile.compiler)};
key.compiler_abi = toolchain.version_banner + "|" + toolchain.target_triple;
key.stdlib_abi = (profile.compiler == CompilerFamily::Gcc) ? "libstdc++" : "libstdc++/libc++";
for (const auto &opt : profile.compile_options) {
if (opt == "-stdlib=libc++") {
key.stdlib_abi = "libc++";
} else if (opt == "-stdlib=libstdc++") {
key.stdlib_abi = "libstdc++";
} else if (opt.starts_with("-march=") || opt.starts_with("-mcpu=")) {
if (!key.cpu_features.empty()) {
key.cpu_features += ",";
}
key.cpu_features += opt;
}
}
key.linkage = std::string{linkage};
key.lto_mode = std::string{lto_mode_name(profile.lto)};
std::vector<std::string> sans;
for (const auto s : profile.sanitizers) {
sans.emplace_back(sanitizer_name(s));
}
std::ranges::sort(sans);
for (std::size_t i = 0; i < sans.size(); ++i) {
if (i > 0) {
key.sanitizers_key += "+";
}
key.sanitizers_key += sans[i];
}
key.dependency_closure_hash = std::string{dependency_closure_hash};
return key;
}
std::optional<BinaryVariantMeta>
select_compatible_binary(const BinaryCompatibilityKey &key,
const std::vector<BinaryVariantMeta> &available) {
for (const auto &v : available) {
if (key.matches(v)) {
return v;
}
}
return std::nullopt;
}
Void::Result::Result<MaterializedSource, Void::Result::Error>
materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &options) {
std::error_code ec;
std::filesystem::create_directories(options.cache_dir, ec);
// 1. Local path source: compute content hash without mutating the external checkout.
if (dep.source_kind == DependencySourceKind::Path) {
const std::filesystem::path raw{dep.location};
const auto abs = raw.is_absolute() ? raw : (options.project_root / raw);
const auto canon = std::filesystem::weakly_canonical(abs, ec);
if (ec || !std::filesystem::is_directory(canon)) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::not_found,
std::format("local path dependency '{}' at '{}' does not exist",
dep.name, dep.location))};
}
Snapshot::SnapshotOptions sopts;
sopts.project_root = canon;
sopts.snapshot_store_dir = options.cache_dir / "path-snapshots";
sopts.materialize = false;
auto snap = Snapshot::capture_snapshot(sopts, {}, {canon});
if (!snap) {
return std::unexpected{snap.error()};
}
MaterializedSource out;
out.alias = dep.name;
out.source_dir = canon;
out.content_identity_hash = snap->snapshot_id;
out.from_cache = true;
return out;
}
// 2. Checksummed archive source (local file:// or verified cached tar).
if (dep.source_kind == DependencySourceKind::Archive) {
const auto extract_dir = options.cache_dir / "archives" / dep.sha256;
const auto marker = extract_dir / ".vbs_verified";
const auto lock_path = options.cache_dir / "locks" / (dep.sha256 + ".lock");
auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive);
if (!lock) {
return std::unexpected{lock.error()};
}
if (std::filesystem::is_regular_file(marker, ec)) {
MaterializedSource out;
out.alias = dep.name;
out.source_dir = extract_dir;
out.content_identity_hash = dep.sha256;
out.from_cache = true;
return out;
}
const auto downloaded_tar = options.cache_dir / "downloads" / (dep.sha256 + ".tar");
std::filesystem::create_directories(downloaded_tar.parent_path(), ec);
if (!std::filesystem::is_regular_file(downloaded_tar, ec)) {
if (dep.location.starts_with("file://")) {
const std::filesystem::path src_file{dep.location.substr(7)};
auto copied = Platform::copy_isolated(src_file, downloaded_tar);
if (!copied) {
return std::unexpected{copied.error()};
}
} else if (std::filesystem::is_regular_file(dep.location, ec)) {
auto copied = Platform::copy_isolated(dep.location, downloaded_tar);
if (!copied) {
return std::unexpected{copied.error()};
}
} else {
if (options.offline) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::not_found,
std::format("offline mode: archive '{}' (sha256={}) is not cached",
dep.location, dep.sha256))};
}
auto curl = Platform::resolve_executable("curl");
if (!curl) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::not_found,
"cannot fetch remote archive: neither curl nor Void::Net is available")};
}
const auto tmp_dl = downloaded_tar.string() + ".part";
Platform::ProcessRequest req;
req.executable = *curl;
req.arguments = {"--fail", "--silent", "--show-error", "--location", "--proto",
"=https,http", "--output", tmp_dl, dep.location};
req.timeout = std::chrono::seconds{120};
auto proc = Platform::run_supervised(req);
if (!proc || !proc->succeeded()) {
std::filesystem::remove(tmp_dl, ec);
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error,
std::format("failed fetching archive '{}': {}", dep.location,
proc ? proc->stderr_data : proc.error().message()))};
}
std::filesystem::rename(tmp_dl, downloaded_tar, ec);
}
}
// Verify SHA-256 BEFORE extracting!
auto actual_sha = Util::sha256_file_hex(downloaded_tar);
if (!actual_sha) {
return std::unexpected{actual_sha.error()};
}
if (*actual_sha != dep.sha256) {
std::filesystem::remove(downloaded_tar, ec);
return std::unexpected{
make_error(Void::System::SystemErrorCode::invalid_argument,
std::format("SHA-256 mismatch for archive '{}': expected {}, got {}",
dep.location, dep.sha256, *actual_sha))};
}
auto extracted = extract_safe_tar(downloaded_tar, extract_dir, options.archive_limits);
if (!extracted) {
return std::unexpected{extracted.error()};
}
(void)Platform::atomic_write_file(marker, dep.sha256 + "\n", true);
MaterializedSource out;
out.alias = dep.name;
out.source_dir = extract_dir;
out.content_identity_hash = dep.sha256;
out.from_cache = false;
return out;
}
// 3. Exact pinned Git revision source.
if (dep.source_kind == DependencySourceKind::Git) {
const auto git_dir =
options.cache_dir / "git" / (sanitize_key(dep.name) + "_" + dep.revision);
const auto marker = git_dir / ".vbs_verified_rev";
const auto lock_path = options.cache_dir / "locks" / ("git_" + dep.revision + ".lock");
auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive);
if (!lock) {
return std::unexpected{lock.error()};
}
if (std::filesystem::is_regular_file(marker, ec)) {
MaterializedSource out;
out.alias = dep.name;
out.source_dir = git_dir;
out.content_identity_hash = dep.revision;
out.from_cache = true;
return out;
}
const bool is_local_repo = dep.location.starts_with("file://") ||
dep.location.starts_with("/") ||
std::filesystem::is_directory(dep.location, ec);
if (options.offline && !is_local_repo) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::not_found,
std::format("offline mode: git dependency '{}' ({}@{}) is not cached",
dep.name, dep.location, dep.revision))};
}
auto git_bin = Platform::resolve_executable("git");
if (!git_bin) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::not_found, "'git' not found in PATH")};
}
const auto stage = git_dir.parent_path() / (git_dir.filename().string() + ".stage");
std::filesystem::remove_all(stage, ec);
std::filesystem::create_directories(stage.parent_path(), ec);
auto stage_cleanup = Void::Scope::on_exit([&] { std::filesystem::remove_all(stage, ec); });
auto run_git =
[&](std::vector<std::string> args,
std::optional<std::filesystem::path> cwd =
std::nullopt) -> Void::Result::Result<std::string, Void::Result::Error> {
Platform::ProcessRequest req;
req.executable = *git_bin;
req.arguments = std::move(args);
req.working_directory = cwd;
req.environment.set_vars["GIT_TERMINAL_PROMPT"] = "0";
req.timeout = std::chrono::seconds{180};
auto p = Platform::run_supervised(req);
if (!p || !p->succeeded()) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error,
std::format("git failed for '{}': {}", dep.location,
p ? p->stderr_data : p.error().message()))};
}
return p->stdout_data;
};
if (auto r = run_git({"clone", "--no-checkout", dep.location, stage.string()}); !r) {
return std::unexpected{r.error()};
}
if (auto r = run_git({"checkout", "--detach", dep.revision}, stage); !r) {
return std::unexpected{r.error()};
}
auto head = run_git({"rev-parse", "HEAD"}, stage);
if (!head || trim(*head) != dep.revision) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::invalid_argument,
std::format("git checkout HEAD mismatch for '{}': expected {}", dep.name,
dep.revision))};
}
(void)Platform::atomic_write_file(stage / ".vbs_verified_rev", dep.revision + "\n", true);
if (std::filesystem::exists(git_dir, ec)) {
std::filesystem::remove_all(git_dir, ec);
}
std::filesystem::rename(stage, git_dir, ec);
if (ec) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"failed publishing git checkout")};
}
stage_cleanup.dismiss();
MaterializedSource out;
out.alias = dep.name;
out.source_dir = git_dir;
out.content_identity_hash = dep.revision;
out.from_cache = false;
return out;
}
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("dependency '{}' requires package/registry resolution before source fetch",
dep.name))};
}
} // namespace Void::Build::Package
+389
View File
@@ -0,0 +1,389 @@
#include <Void/Build/Package/Lockfile.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Util/Json.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <algorithm>
#include <format>
#include <type_traits>
namespace Void::Build::Package {
namespace {
using JsonVal = Void::Json::Strict::Value;
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
return Void::System::make_system_error(code, std::move(msg));
}
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
const auto it = obj.find(k);
return it == obj.end() ? nullptr : &it->second;
}
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
const auto *v = find_key(obj, k);
if (!v) {
return {};
}
const auto *s = std::get_if<std::string>(&v->value);
return s ? *s : std::string{};
}
std::int64_t get_i64(const JsonVal::Object &obj, const std::string &k, std::int64_t def = 0) {
const auto *v = find_key(obj, k);
if (!v) {
return def;
}
const auto *i = std::get_if<std::int64_t>(&v->value);
return i ? *i : def;
}
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
const auto *v = find_key(obj, k);
if (!v) {
return def;
}
const auto *b = std::get_if<bool>(&v->value);
return b ? *b : def;
}
std::vector<std::string> get_str_array(const JsonVal::Object &obj, const std::string &k) {
std::vector<std::string> out;
const auto *v = find_key(obj, k);
if (!v) {
return out;
}
if (const auto *arr = std::get_if<JsonVal::Array>(&v->value)) {
for (const auto &item : *arr) {
if (const auto *s = std::get_if<std::string>(&item.value)) {
out.push_back(*s);
}
}
}
return out;
}
// Strips embedded URL credentials (user:pass@host) before persisting to vbs.lock!
std::string strip_url_credentials(std::string_view url) {
const auto scheme = url.find("://");
if (scheme == std::string_view::npos) {
return std::string{url};
}
const auto after_scheme = scheme + 3;
const auto slash = url.find('/', after_scheme);
const auto at = url.find('@', after_scheme);
if (at != std::string_view::npos && (slash == std::string_view::npos || at < slash)) {
return std::string{url.substr(0, after_scheme)} + std::string{url.substr(at + 1)};
}
return std::string{url};
}
std::string
serialize_contexts_body(const std::map<std::string, LockContextRecord, std::less<>> &ctxs) {
using Util::json_array;
using Util::json_quote;
std::string out{"{"};
bool first = true;
for (const auto &[key, ctx] : ctxs) {
if (!first) {
out += ',';
}
first = false;
out += json_quote(key) + ":{\"context_key\":" + json_quote(ctx.context_key) +
",\"profile_name\":" + json_quote(ctx.profile_name) +
",\"compiler\":" + json_quote(ctx.compiler) + ",\"os\":" + json_quote(ctx.os) +
",\"architecture\":" + json_quote(ctx.architecture) +
",\"machine_role\":" + json_quote(ctx.machine_role) +
",\"declaration_fingerprint\":" + json_quote(ctx.declaration_fingerprint) +
",\"entries\":";
out += json_array(ctx.entries, [](const LockedSourceEntry &e) {
return "{\"alias\":" + json_quote(e.alias) +
",\"source_kind\":" + json_quote(e.source_kind) + ",\"registry_authority\":" +
json_quote(strip_url_credentials(e.registry_authority)) +
",\"package_name\":" + json_quote(e.package_name) +
",\"version\":" + json_quote(e.version) +
",\"location\":" + json_quote(strip_url_credentials(e.location)) +
",\"revision\":" + json_quote(e.revision) +
",\"sha256\":" + json_quote(e.sha256) + ",\"builder\":" + json_quote(e.builder) +
",\"features\":" + json_array(e.features, json_quote) +
",\"build_dependency\":" + std::string{e.build_dependency ? "true" : "false"} +
'}';
});
out += '}';
}
out += '}';
return out;
}
} // namespace
std::string make_lock_context_key(const ProfileContext &profile, std::string_view machine_role) {
return std::format("{}:{}:{}:{}:{}", profile.name, compiler_name(profile.compiler), profile.os,
profile.architecture, machine_role);
}
std::string compute_declaration_fingerprint(const ProfileContext &profile,
std::string_view machine_role,
const std::vector<NormalizedDependency> &declarations) {
Util::Sha256Hasher h;
h.update_length_prefixed("vbs-lock-decl-v1");
h.update_length_prefixed(profile.name);
h.update_length_prefixed(compiler_name(profile.compiler));
h.update_length_prefixed(profile.os);
h.update_length_prefixed(profile.architecture);
h.update_length_prefixed(machine_role);
std::vector<const DependencyRecord *> sorted;
for (const auto &nd : declarations) {
const bool want_build = (machine_role == "build");
if (nd.record.build_dependency == want_build) {
sorted.push_back(&nd.record);
}
}
std::ranges::sort(sorted, [](const DependencyRecord *a, const DependencyRecord *b) {
return a->name < b->name;
});
h.update_u64(sorted.size());
for (const auto *d : sorted) {
h.update_length_prefixed(d->name);
h.update_u64(static_cast<std::uint64_t>(d->source_kind));
h.update_length_prefixed(strip_url_credentials(d->location));
h.update_length_prefixed(d->revision);
h.update_length_prefixed(d->package);
h.update_length_prefixed(d->version);
h.update_length_prefixed(d->builder);
h.update_length_prefixed(strip_url_credentials(d->registry_authority));
h.update_length_prefixed(d->sha256);
h.update_u64(d->features.size());
for (const auto &f : d->features) {
h.update_length_prefixed(f);
}
h.update_u64(d->options.size());
for (const auto &[k, opt] : d->options) {
h.update_length_prefixed(k);
std::visit(
[&](const auto &v) {
using T = std::remove_cvref_t<decltype(v)>;
if constexpr (std::same_as<T, std::string>) {
h.update_length_prefixed("s:" + v);
} else if constexpr (std::same_as<T, bool>) {
h.update_length_prefixed(v ? "b:1" : "b:0");
} else {
h.update_length_prefixed("i:" + std::to_string(v));
}
},
opt.value);
}
}
return h.finalize_hex();
}
std::string serialize_lockfile(const LockfileDocument &doc) {
const std::string body = serialize_contexts_body(doc.contexts);
const std::string rev = Util::sha256_hex(body);
return "{\"schema_version\":" + std::to_string(doc.schema_version) +
",\"revision_hash\":" + Util::json_quote(rev) + ",\"contexts\":" + body + "}\n";
}
Void::Result::Result<LockfileDocument, Void::Result::Error>
parse_lockfile(std::string_view json_text) {
if (!Util::is_valid_utf8(json_text)) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::invalid_argument, "lockfile invalid UTF-8")};
}
auto parsed = Void::Json::Strict::parse(json_text);
if (!parsed) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"malformed JSON in vbs.lock")};
}
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
if (!root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"vbs.lock root must be a JSON object")};
}
LockfileDocument doc;
doc.schema_version = static_cast<int>(get_i64(*root, "schema_version", 0));
if (doc.schema_version != kLockfileSchemaVersion) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::invalid_argument,
std::format("unsupported vbs.lock schema_version {}", doc.schema_version))};
}
doc.revision_hash = get_str(*root, "revision_hash");
if (const auto *ctxs_v = find_key(*root, "contexts")) {
const auto *cobj = std::get_if<JsonVal::Object>(&ctxs_v->value);
if (!cobj) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"vbs.lock contexts must be an object")};
}
for (const auto &[key, cv] : *cobj) {
const auto *co = std::get_if<JsonVal::Object>(&cv.value);
if (!co) {
continue;
}
LockContextRecord rec;
rec.context_key = get_str(*co, "context_key");
rec.profile_name = get_str(*co, "profile_name");
rec.compiler = get_str(*co, "compiler");
rec.os = get_str(*co, "os");
rec.architecture = get_str(*co, "architecture");
rec.machine_role = get_str(*co, "machine_role");
rec.declaration_fingerprint = get_str(*co, "declaration_fingerprint");
if (const auto *ev = find_key(*co, "entries")) {
if (const auto *earr = std::get_if<JsonVal::Array>(&ev->value)) {
for (const auto &item : *earr) {
if (const auto *eo = std::get_if<JsonVal::Object>(&item.value)) {
LockedSourceEntry e;
e.alias = get_str(*eo, "alias");
e.source_kind = get_str(*eo, "source_kind");
e.registry_authority = get_str(*eo, "registry_authority");
e.package_name = get_str(*eo, "package_name");
e.version = get_str(*eo, "version");
e.location = get_str(*eo, "location");
e.revision = get_str(*eo, "revision");
e.sha256 = get_str(*eo, "sha256");
e.builder = get_str(*eo, "builder");
e.features = get_str_array(*eo, "features");
e.build_dependency = get_bool(*eo, "build_dependency", false);
rec.entries.push_back(std::move(e));
}
}
}
}
doc.contexts[key] = std::move(rec);
}
}
// Verify revision hash integrity against canonical body!
const std::string expected_rev = Util::sha256_hex(serialize_contexts_body(doc.contexts));
if (!doc.revision_hash.empty() && doc.revision_hash != expected_rev) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
"vbs.lock revision_hash does not match contents (corrupted or hand-edited lockfile)")};
}
doc.revision_hash = expected_rev;
return doc;
}
Void::Result::Result<std::optional<PinnedLock>, Void::Result::Error>
load_pinned_lock(const std::filesystem::path &lock_path) {
auto meta = Platform::stat_lstat(lock_path);
if (!meta) {
return std::unexpected{meta.error()};
}
if (!meta->exists) {
return std::nullopt;
}
auto text = Void::FileSystem::read_file_bounded(lock_path, {64ULL * 1024ULL * 1024ULL});
if (!text) {
return std::unexpected{text.error()};
}
auto parsed = parse_lockfile(*text);
if (!parsed) {
return std::unexpected{parsed.error()};
}
PinnedLock pinned;
pinned.revision_hash = parsed->revision_hash;
pinned.raw_json = std::move(*text);
pinned.document = std::move(*parsed);
return pinned;
}
Void::Result::Result<const LockContextRecord *, Void::Result::Error>
validate_locked_context(const LockfileDocument &doc, std::string_view context_key,
std::string_view expected_declaration_fingerprint) {
const auto it = doc.contexts.find(context_key);
if (it == doc.contexts.end()) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("vbs.lock has no resolution for context '{}' (run 'vbs deps resolve')",
context_key))};
}
if (it->second.declaration_fingerprint != expected_declaration_fingerprint) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format(
"vbs.lock context '{}' is incompatible with current dependency declarations "
"(run 'vbs deps resolve' or 'vbs deps update')",
context_key))};
}
return &it->second;
}
Void::Result::Result<PinnedLock, Void::Result::Error>
publish_lock_context_cas(const std::filesystem::path &lock_path,
std::string_view expected_base_revision,
const LockContextRecord &updated_context, bool locked_mode) {
if (locked_mode) {
return std::unexpected{make_error(Void::System::SystemErrorCode::permission_denied,
"--locked forbids creating or modifying vbs.lock")};
}
const auto mutex_path = lock_path.parent_path() / ".vbs" / "lockfile.mutex";
auto mutex = Platform::FileLock::acquire(mutex_path, Platform::LockMode::Exclusive);
if (!mutex) {
return std::unexpected{mutex.error()};
}
LockfileDocument current;
std::string current_rev;
auto meta = Platform::stat_lstat(lock_path);
if (!meta) {
return std::unexpected{meta.error()};
}
if (meta->exists) {
auto text = Void::FileSystem::read_file_bounded(lock_path, {64ULL * 1024ULL * 1024ULL});
if (!text) {
return std::unexpected{text.error()};
}
auto parsed = parse_lockfile(*text);
if (!parsed) {
return std::unexpected{parsed.error()};
}
current = std::move(*parsed);
current_rev = current.revision_hash;
}
// Compare-and-swap revision check (D-025): if another profile updated the lock concurrently,
// allow merging ONLY if the other update did NOT touch our context_key; if it modified our
// context_key or base mismatch occurred, report busy conflict for caller re-resolution!
if (current_rev != expected_base_revision) {
const auto existing_ctx = current.contexts.find(updated_context.context_key);
if (existing_ctx != current.contexts.end() &&
existing_ctx->second.declaration_fingerprint !=
updated_context.declaration_fingerprint) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::busy,
std::format("concurrent vbs.lock revision conflict (expected '{}', found '{}'); "
"re-resolve and retry",
expected_base_revision, current_rev))};
}
}
current.contexts[updated_context.context_key] = updated_context;
const std::string serialized = serialize_lockfile(current);
auto reparsed = parse_lockfile(serialized);
if (!reparsed) {
return std::unexpected{reparsed.error()};
}
auto wrote = Platform::atomic_write_file(lock_path, serialized, true);
if (!wrote) {
return std::unexpected{wrote.error()};
}
PinnedLock pinned;
pinned.revision_hash = reparsed->revision_hash;
pinned.raw_json = serialized;
pinned.document = std::move(*reparsed);
return pinned;
}
} // namespace Void::Build::Package
+420
View File
@@ -0,0 +1,420 @@
#include <Void/Build/Package/RegistryClient.hpp>
#include <Void/Build/Package/Fetch.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Core/Scope.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <Void/Text/Semver.hpp>
#include <Void/Text/Str.hpp>
#include <Void/Text/Url.hpp>
#include <algorithm>
#include <arpa/inet.h>
#include <array>
#include <cerrno>
#include <cstring>
#include <format>
#include <map>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
namespace Void::Build::Package {
namespace {
using JsonVal = Void::Json::Strict::Value;
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
return Void::System::make_system_error(code, redact_secrets(msg));
}
struct ParsedHttpUrl {
std::string scheme;
std::string host;
std::uint16_t port{80};
std::string base_path;
};
Void::Result::Result<ParsedHttpUrl, Void::Result::Error> parse_registry_url(std::string_view url) {
url = Void::Str::trim_ascii(url);
const auto sep = url.find("://");
if (sep == std::string_view::npos) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"registry URL must include http:// or https:// scheme")};
}
ParsedHttpUrl out;
out.scheme = Void::Str::to_lower_ascii(url.substr(0, sep));
if (out.scheme != "http" && out.scheme != "https") {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"unsupported registry URL scheme (expected http/https)")};
}
const auto rest = url.substr(sep + 3);
const auto slash = rest.find('/');
const auto authority = slash == std::string_view::npos ? rest : rest.substr(0, slash);
out.base_path =
slash == std::string_view::npos ? std::string{} : std::string{rest.substr(slash)};
while (!out.base_path.empty() && out.base_path.back() == '/') {
out.base_path.pop_back();
}
const auto colon = authority.rfind(':');
if (colon != std::string_view::npos) {
out.host = std::string{authority.substr(0, colon)};
int p = 0;
if (!Void::Str::to_int(authority.substr(colon + 1), p) || p <= 0 || p > 65535) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"invalid port in registry URL")};
}
out.port = static_cast<std::uint16_t>(p);
} else {
out.host = std::string{authority};
out.port = (out.scheme == "https") ? 443 : 80;
}
if (out.host.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"empty host in registry URL")};
}
return out;
}
struct RawHttpReply {
std::uint16_t status{0};
std::map<std::string, std::string, std::less<>> headers;
std::string body;
};
bool send_all(int fd, std::string_view data) {
std::size_t off = 0;
while (off < data.size()) {
const ssize_t n = ::send(fd, data.data() + off, data.size() - off, MSG_NOSIGNAL);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
off += static_cast<std::size_t>(n);
}
return true;
}
Void::Result::Result<RawHttpReply, Void::Result::Error>
send_http_request(const ParsedHttpUrl &parsed, std::string_view method, std::string_view path,
const std::map<std::string, std::string, std::less<>> &headers,
std::string_view body) {
const std::string full_path = parsed.base_path + std::string{path};
// Plain TCP HTTP/1.1 client for http:// (loopback/local registry without external deps).
if (parsed.scheme == "http") {
struct addrinfo hints{};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo *res = nullptr;
const std::string port_s = std::to_string(parsed.port);
if (::getaddrinfo(parsed.host.c_str(), port_s.c_str(), &hints, &res) != 0 || !res) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("registry client: failed resolving host '{}'", parsed.host))};
}
auto free_ai = Void::Scope::on_exit([&] { ::freeaddrinfo(res); });
const int fd = ::socket(res->ai_family, res->ai_socktype | SOCK_CLOEXEC, res->ai_protocol);
if (fd < 0) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry client: socket() failed")};
}
Void::System::OwnedFd guard{fd};
struct timeval tv{30, 0};
(void)::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
(void)::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
if (::connect(fd, res->ai_addr, res->ai_addrlen) != 0) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("registry client: connect to {}:{} failed", parsed.host, parsed.port))};
}
std::string req = std::format("{} {} HTTP/1.1\r\nHost: {}:{}\r\nConnection: close\r\n"
"Content-Length: {}\r\n",
method, full_path, parsed.host, parsed.port, body.size());
for (const auto &[k, v] : headers) {
req += k + ": " + v + "\r\n";
}
req += "\r\n";
req += body;
if (!send_all(fd, req)) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry client: send() failed")};
}
std::string raw;
std::array<char, 16384> buf{};
for (;;) {
const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0);
if (n > 0) {
raw.append(buf.data(), static_cast<std::size_t>(n));
} else if (n == 0) {
break;
} else if (errno != EINTR) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry client: recv() failed")};
}
}
const auto hdr_end = raw.find("\r\n\r\n");
if (hdr_end == std::string::npos) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry client: malformed HTTP response")};
}
RawHttpReply reply;
const std::string_view hdr_block{raw.data(), hdr_end};
const auto first_crlf = hdr_block.find("\r\n");
const auto status_line = hdr_block.substr(0, first_crlf);
const auto sp1 = status_line.find(' ');
if (sp1 != std::string_view::npos) {
int code = 0;
if (Void::Str::to_int(status_line.substr(sp1 + 1, 3), code)) {
reply.status = static_cast<std::uint16_t>(code);
}
}
if (first_crlf != std::string_view::npos) {
std::size_t pos = first_crlf + 2;
while (pos < hdr_block.size()) {
const auto next = hdr_block.find("\r\n", pos);
const auto line = hdr_block.substr(
pos, next == std::string_view::npos ? std::string_view::npos : next - pos);
const auto colon = line.find(':');
if (colon != std::string_view::npos) {
reply.headers[Void::Str::to_lower_ascii(
Void::Str::trim_ascii(line.substr(0, colon)))] =
std::string{Void::Str::trim_ascii(line.substr(colon + 1))};
}
if (next == std::string_view::npos) {
break;
}
pos = next + 2;
}
}
reply.body = raw.substr(hdr_end + 4);
return reply;
}
// HTTPS fallback via curl (preserves TLS certificate verification; never disables TLS!).
auto curl = Platform::resolve_executable("curl");
if (!curl) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::not_found,
"HTTPS registry operations require curl (OpenSSL/Void::Net not linked)")};
}
const std::string full_url =
std::format("https://{}:{}{}", parsed.host, parsed.port, full_path);
Platform::ProcessRequest req;
req.executable = *curl;
req.arguments = {"--silent", "--show-error", "--proto", "=https",
"-X", std::string{method}, "-w", "\n%{http_code}"};
for (const auto &[k, v] : headers) {
req.arguments.push_back("-H");
req.arguments.push_back(k + ": " + v);
}
if (!body.empty()) {
req.arguments.push_back("--data-binary");
req.arguments.push_back("@-");
req.stdin_data = std::string{body};
}
req.arguments.push_back(full_url);
req.timeout = std::chrono::seconds{120};
auto proc = Platform::run_supervised(req);
if (!proc || !proc->succeeded()) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error,
std::format("HTTPS request failed: {}",
proc ? proc->stderr_data : proc.error().message()))};
}
const auto nl = proc->stdout_data.rfind('\n');
RawHttpReply reply;
if (nl != std::string::npos) {
int code = 0;
if (Void::Str::to_int(Void::Str::trim_ascii(proc->stdout_data.substr(nl + 1)), code)) {
reply.status = static_cast<std::uint16_t>(code);
}
reply.body = proc->stdout_data.substr(0, nl);
}
return reply;
}
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
const auto it = obj.find(k);
if (it == obj.end()) {
return {};
}
const auto *s = std::get_if<std::string>(&it->second.value);
return s ? *s : std::string{};
}
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
const auto it = obj.find(k);
if (it == obj.end()) {
return def;
}
const auto *b = std::get_if<bool>(&it->second.value);
return b ? *b : def;
}
} // namespace
Void::Result::Result<std::vector<ReleaseRecord>, Void::Result::Error>
fetch_package_releases(std::string_view registry_url, std::string_view package_name,
const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name);
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{make_error(reply->status == 404
? Void::System::SystemErrorCode::not_found
: Void::System::SystemErrorCode::permission_denied,
std::format("registry GET {} failed with HTTP {}: {}",
path, reply->status, reply->body))};
}
auto json = Void::Json::Strict::parse(reply->body);
if (!json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"invalid JSON returned by registry package endpoint")};
}
const auto *root = std::get_if<JsonVal::Object>(&json->value);
if (!root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"registry response root must be a JSON object")};
}
std::vector<ReleaseRecord> releases;
const auto rit = root->find("releases");
if (rit != root->end()) {
if (const auto *rarr = std::get_if<JsonVal::Array>(&rit->second.value)) {
for (const auto &rv : *rarr) {
const auto *ro = std::get_if<JsonVal::Object>(&rv.value);
if (!ro) {
continue;
}
const auto ver_str = get_str(*ro, "version");
auto ver = Void::Semver::parse_strict(ver_str);
if (!ver) {
continue;
}
ReleaseRecord rec;
rec.id = PackageId{std::string{registry_url}, std::string{package_name}};
rec.version = *ver;
rec.yanked = get_bool(*ro, "yanked", false);
rec.source_sha256 = get_str(*ro, "sha256");
rec.source_url = std::string{registry_url} + "/api/v1/packages/" +
Void::Encoding::Url::encode(package_name) + "/" +
Void::Encoding::Url::encode(ver_str) + "/download";
releases.push_back(std::move(rec));
}
}
}
return releases;
}
Void::Result::Result<std::filesystem::path, Void::Result::Error>
download_release_archive(std::string_view registry_url, std::string_view package_name,
std::string_view version, std::string_view expected_sha256,
const std::filesystem::path &dest_file, const RegistryAuth &auth) {
auto parsed_url = parse_registry_url(registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
std::map<std::string, std::string, std::less<>> headers;
if (!auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + auth.bearer_token;
}
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name) + "/" +
Void::Encoding::Url::encode(version) + "/download";
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
std::format("registry download {}@{} failed with HTTP {}",
package_name, version, reply->status))};
}
const std::string actual_sha = Util::sha256_hex(reply->body);
if (!expected_sha256.empty() && actual_sha != expected_sha256) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("registry archive SHA-256 mismatch for {}@{}: expected {}, got {}",
package_name, version, expected_sha256, actual_sha))};
}
auto wrote = Platform::atomic_write_file(dest_file, reply->body, true);
if (!wrote) {
return std::unexpected{wrote.error()};
}
return dest_file;
}
Void::Result::Result<PublishReceipt, Void::Result::Error>
publish_package_archive(const PublishOptions &options) {
if (!Void::Semver::parse_strict(options.version)) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"publish version must be strict SemVer (X.Y.Z)")};
}
auto parsed_url = parse_registry_url(options.registry_url);
if (!parsed_url) {
return std::unexpected{parsed_url.error()};
}
auto bytes = Void::FileSystem::read_file(options.archive_path);
if (!bytes) {
return std::unexpected{bytes.error()};
}
const std::string sha = Util::sha256_hex(*bytes);
std::map<std::string, std::string, std::less<>> headers;
headers["X-Content-SHA256"] = sha;
if (!options.auth.bearer_token.empty()) {
headers["Authorization"] = "Bearer " + options.auth.bearer_token;
}
if (options.is_private) {
headers["X-Package-Private"] = "true";
}
if (!options.description.empty()) {
headers["X-Package-Description"] = options.description;
}
const std::string path = "/api/v1/packages/" +
Void::Encoding::Url::encode(options.package_name) + "/" +
Void::Encoding::Url::encode(options.version);
auto reply = send_http_request(*parsed_url, "PUT", path, headers, *bytes);
if (!reply) {
return std::unexpected{reply.error()};
}
if (reply->status != 200 && reply->status != 201) {
return std::unexpected{make_error(
reply->status == 409 ? Void::System::SystemErrorCode::already_exists
: Void::System::SystemErrorCode::permission_denied,
std::format("registry publish {}@{} failed with HTTP {}: {}", options.package_name,
options.version, reply->status, reply->body))};
}
return PublishReceipt{sha, reply->status == 200};
}
} // namespace Void::Build::Package
+342
View File
@@ -0,0 +1,342 @@
#include <Void/Build/Package/Solver.hpp>
#include <Void/System/Types.hpp>
#include <Void/Text/Str.hpp>
#include <algorithm>
#include <format>
#include <optional>
#include <string>
namespace Void::Build::Package {
namespace {
Void::Result::Error solve_err(std::string msg) {
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
std::move(msg));
}
bool all_digits(std::string_view s) { return Void::Str::is_digit_ascii(s); }
std::string normalize_semver_token(std::string_view tok) {
if (tok.empty() || tok == "*") {
return std::string{tok};
}
std::string_view op;
if (tok.starts_with(">=") || tok.starts_with("<=")) {
op = tok.substr(0, 2);
tok.remove_prefix(2);
} else if (tok.starts_with('^') || tok.starts_with('~') || tok.starts_with('>') ||
tok.starts_with('<') || tok.starts_with('=')) {
op = tok.substr(0, 1);
tok.remove_prefix(1);
}
const auto meta_pos = tok.find_first_of("-+");
const auto core = meta_pos == std::string_view::npos ? tok : tok.substr(0, meta_pos);
const auto meta =
meta_pos == std::string_view::npos ? std::string_view{} : tok.substr(meta_pos);
if (core.find_first_of("xX*") != std::string_view::npos) {
return std::string{op} + std::string{tok};
}
const auto dot1 = core.find('.');
if (dot1 == std::string_view::npos) {
if (!all_digits(core)) {
return std::string{op} + std::string{tok};
}
if ((op == "~" || op == "^") && meta.empty()) {
const unsigned long maj = std::stoul(std::string{core});
if (op == "~" || maj == 0) {
return std::format(">={}.0.0 <{}.0.0", maj, maj + 1);
}
}
return std::string{op} + std::string{core} + ".0.0" + std::string{meta};
}
const auto dot2 = core.find('.', dot1 + 1);
if (dot2 == std::string_view::npos) {
const auto p1 = core.substr(0, dot1);
const auto p2 = core.substr(dot1 + 1);
if (!all_digits(p1) || !all_digits(p2)) {
return std::string{op} + std::string{tok};
}
return std::string{op} + std::string{p1} + "." + std::string{p2} + ".0" + std::string{meta};
}
return std::string{op} + std::string{tok};
}
// Adapter for shorthand SemVer comparator tokens (^1, ^1.0, ~1.2, <2) since
// pinned Void::Semver::parse_range requires full major.minor.patch triplets.
std::optional<Void::Semver::VersionRange> parse_semver_range_compat(std::string_view expr) {
if (auto direct = Void::Semver::parse_range(expr); direct) {
return direct;
}
std::string normalized;
std::size_t pos = 0;
bool first_clause = true;
while (pos <= expr.size()) {
const auto sep = expr.find("||", pos);
const auto clause = expr.substr(pos, sep == std::string_view::npos ? sep : sep - pos);
if (!first_clause) {
normalized += " || ";
}
first_clause = false;
bool first_tok = true;
std::size_t i = 0;
while (i < clause.size()) {
while (i < clause.size() && (clause[i] == ' ' || clause[i] == '\t')) {
++i;
}
if (i == clause.size()) {
break;
}
auto end = clause.find_first_of(" \t", i);
if (end == std::string_view::npos) {
end = clause.size();
}
if (!first_tok) {
normalized.push_back(' ');
}
first_tok = false;
normalized += normalize_semver_token(clause.substr(i, end - i));
i = end;
}
if (sep == std::string_view::npos) {
break;
}
pos = sep + 2;
}
return Void::Semver::parse_range(normalized);
}
struct ActiveConstraint {
Void::Semver::VersionRange range;
std::string range_expr;
std::string requirer;
std::vector<std::string> features;
};
// PubGrub-style conflict-driven backtracking solver with incompatibility explanation trace.
class PubGrubSolver {
public:
PubGrubSolver(const PackageIndex &index, const SolveOptions &options)
: index_{index}, options_{options} {}
Void::Result::Result<SolveResult, Void::Result::Error>
solve(const std::vector<DependencyConstraint> &roots) {
std::map<PackageId, std::vector<ActiveConstraint>> constraints;
for (const auto &rc : roots) {
auto parsed = parse_semver_range_compat(rc.range_expr);
if (!parsed) {
return std::unexpected{
solve_err(std::format("invalid version range '{}' for '{}' (from {})",
rc.range_expr, rc.target.format(), rc.origin_label))};
}
constraints[rc.target].push_back(ActiveConstraint{
*parsed, rc.range_expr, rc.origin_label.empty() ? "root" : rc.origin_label,
rc.required_features});
}
std::map<PackageId, ReleaseRecord> chosen;
if (backtrack(constraints, chosen)) {
SolveResult out;
for (const auto &[id, rel] : chosen) {
SolvedPackage sp;
sp.id = id;
sp.version = rel.version;
sp.source_sha256 = rel.source_sha256;
sp.source_url = rel.source_url;
sp.binaries = rel.binaries;
if (const auto cit = constraints.find(id); cit != constraints.end()) {
for (const auto &ac : cit->second) {
for (const auto &f : ac.features) {
sp.enabled_features.insert(f);
}
}
}
for (const auto &dep : rel.dependencies) {
sp.dependencies.push_back(dep.target);
}
std::ranges::sort(sp.dependencies);
sp.dependencies.erase(std::unique(sp.dependencies.begin(), sp.dependencies.end()),
sp.dependencies.end());
out.packages.emplace(id, std::move(sp));
}
return out;
}
std::string report = "dependency version resolution failed:\n";
if (conflicts_.empty()) {
report += " no satisfiable version assignment found within solver step budget";
} else {
const std::size_t shown = std::min<std::size_t>(conflicts_.size(), 8);
for (std::size_t i = 0; i < shown; ++i) {
report += " - " + conflicts_[i] + "\n";
}
}
return std::unexpected{solve_err(std::move(report))};
}
private:
bool matches_all(const Void::Semver::Version &v,
const std::vector<ActiveConstraint> &list) const {
for (const auto &c : list) {
if (!c.range.contains(v)) {
return false;
}
}
return true;
}
std::vector<ReleaseRecord> ordered_candidates(const PackageId &id,
const std::vector<ActiveConstraint> &list) const {
auto all = index_.releases_for(id);
std::vector<ReleaseRecord> matching;
const auto pin_it = options_.pinned_versions.find(id);
for (auto &rel : all) {
const bool is_pinned =
(pin_it != options_.pinned_versions.end() && rel.version == pin_it->second);
if (rel.yanked && !(is_pinned && options_.allow_yanked_if_pinned)) {
continue;
}
if (matches_all(rel.version, list)) {
matching.push_back(std::move(rel));
}
}
// Deterministic priority: pinned compatible version first, then highest SemVer descending.
std::ranges::sort(matching, [&](const ReleaseRecord &a, const ReleaseRecord &b) {
const bool a_pin =
(pin_it != options_.pinned_versions.end() && a.version == pin_it->second);
const bool b_pin =
(pin_it != options_.pinned_versions.end() && b.version == pin_it->second);
if (a_pin != b_pin) {
return a_pin;
}
return a.version > b.version;
});
return matching;
}
void record_incompatibility(const PackageId &id, const std::vector<ActiveConstraint> &list) {
std::string msg = "no version of " + id.format() + " satisfies: ";
for (std::size_t i = 0; i < list.size(); ++i) {
if (i > 0) {
msg += " AND ";
}
msg += list[i].range_expr + " (from " + list[i].requirer + ")";
}
if (conflicts_.size() < 32 && !std::ranges::contains(conflicts_, msg)) {
conflicts_.push_back(std::move(msg));
}
}
bool backtrack(std::map<PackageId, std::vector<ActiveConstraint>> &constraints,
std::map<PackageId, ReleaseRecord> &chosen) {
if (++steps_ > options_.max_steps) {
return false;
}
// Unit propagation / fail-fast check: choose undecided package with fewest candidates!
std::optional<PackageId> next_pkg;
std::vector<ReleaseRecord> best_candidates;
std::size_t min_count = std::numeric_limits<std::size_t>::max();
for (const auto &[id, clist] : constraints) {
if (const auto cit = chosen.find(id); cit != chosen.end()) {
if (!matches_all(cit->second.version, clist)) {
record_incompatibility(id, clist);
return false;
}
continue;
}
auto cands = ordered_candidates(id, clist);
if (cands.empty()) {
record_incompatibility(id, clist);
return false;
}
if (cands.size() < min_count) {
min_count = cands.size();
next_pkg = id;
best_candidates = std::move(cands);
if (min_count == 1) {
break;
}
}
}
if (!next_pkg) {
return true; // All constrained packages decided and mutually consistent!
}
const PackageId pkg = *next_pkg;
for (const auto &candidate : best_candidates) {
// Save constraints snapshot before descending.
auto next_constraints = constraints;
bool valid_ranges = true;
const std::string origin = pkg.format() + "@" + candidate.version.to_string();
for (const auto &dep : candidate.dependencies) {
auto parsed = parse_semver_range_compat(dep.range_expr);
if (!parsed) {
valid_ranges = false;
conflicts_.push_back(
std::format("package {} declares invalid range '{}' for {}", origin,
dep.range_expr, dep.target.format()));
break;
}
next_constraints[dep.target].push_back(
ActiveConstraint{*parsed, dep.range_expr, origin, dep.required_features});
}
if (!valid_ranges) {
continue;
}
chosen.insert_or_assign(pkg, candidate);
if (backtrack(next_constraints, chosen)) {
constraints = std::move(next_constraints);
return true;
}
chosen.erase(pkg);
}
return false;
}
const PackageIndex &index_;
const SolveOptions &options_;
std::size_t steps_{0};
std::vector<std::string> conflicts_;
};
} // namespace
std::string PackageId::format() const {
if (registry_authority.empty()) {
return name;
}
return registry_authority + "/" + name;
}
void PackageIndex::add_release(ReleaseRecord release) {
releases_[release.id].push_back(std::move(release));
}
std::vector<ReleaseRecord> PackageIndex::releases_for(const PackageId &id) const {
const auto it = releases_.find(id);
if (it == releases_.end()) {
return {};
}
return it->second;
}
Void::Result::Result<SolveResult, Void::Result::Error>
solve_dependencies(const std::vector<DependencyConstraint> &root_constraints,
const PackageIndex &index, const SolveOptions &options) {
PubGrubSolver solver{index, options};
return solver.solve(root_constraints);
}
} // namespace Void::Build::Package
+949
View File
@@ -0,0 +1,949 @@
#include <Void/Build/Package/Toml.hpp>
#include <Void/Build/Util/Json.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <algorithm>
#include <cctype>
#include <charconv>
#include <cmath>
#include <format>
#include <set>
namespace Void::Build::Package {
namespace {
Void::Result::Error parse_err(const SourceOrigin &orig, std::string msg) {
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
std::format("{}: {}", orig.format(), std::move(msg)));
}
class TomlParser {
public:
TomlParser(std::string_view text, std::string source_name)
: text_{text}, source_name_{std::move(source_name)} {}
Void::Result::Result<TomlTable, Void::Result::Error> parse() {
if (!Util::is_valid_utf8(text_)) {
return std::unexpected{parse_err({source_name_, 1, 1}, "invalid UTF-8 in TOML")};
}
TomlValue root = TomlValue::make_table({source_name_, 1, 1});
TomlTable *current_table = &root.as_table_mut();
while (!eof()) {
skip_ws_and_comments(true);
if (eof()) {
break;
}
if (peek() == '[') {
const auto hdr_origin = origin();
advance();
const bool is_array_table = (!eof() && peek() == '[');
if (is_array_table) {
advance();
}
skip_inline_ws();
auto keys = parse_key_path();
if (!keys) {
return std::unexpected{keys.error()};
}
skip_inline_ws();
if (eof() || peek() != ']') {
return std::unexpected{parse_err(origin(), "expected ']' in table header")};
}
advance();
if (is_array_table) {
if (eof() || peek() != ']') {
return std::unexpected{
parse_err(origin(), "expected ']]' in array-of-tables header")};
}
advance();
}
if (auto r = expect_line_end(); !r) {
return std::unexpected{r.error()};
}
auto tbl =
navigate_table_header(root.as_table_mut(), *keys, is_array_table, hdr_origin);
if (!tbl) {
return std::unexpected{tbl.error()};
}
current_table = *tbl;
} else {
const auto kv_origin = origin();
auto keys = parse_key_path();
if (!keys) {
return std::unexpected{keys.error()};
}
skip_inline_ws();
if (eof() || peek() != '=') {
return std::unexpected{parse_err(origin(), "expected '=' after key")};
}
advance();
skip_inline_ws();
auto val = parse_value();
if (!val) {
return std::unexpected{val.error()};
}
if (auto r = expect_line_end(); !r) {
return std::unexpected{r.error()};
}
if (auto r = insert_key_value(*current_table, *keys, std::move(*val), kv_origin);
!r) {
return std::unexpected{r.error()};
}
}
}
return std::move(root.as_table_mut());
}
private:
bool eof() const noexcept { return pos_ >= text_.size(); }
char peek(std::size_t off = 0) const noexcept {
return (pos_ + off < text_.size()) ? text_[pos_ + off] : '\0';
}
char advance() noexcept {
const char c = text_[pos_++];
if (c == '\n') {
++line_;
col_ = 1;
} else {
++col_;
}
return c;
}
SourceOrigin origin() const { return {source_name_, line_, col_}; }
void skip_inline_ws() noexcept {
while (!eof() && (peek() == ' ' || peek() == '\t')) {
advance();
}
}
void skip_ws_and_comments(bool allow_newlines) noexcept {
while (!eof()) {
const char c = peek();
if (c == ' ' || c == '\t' || (allow_newlines && (c == '\n' || c == '\r'))) {
advance();
} else if (c == '#') {
while (!eof() && peek() != '\n') {
advance();
}
} else {
break;
}
}
}
Void::Result::Result<void, Void::Result::Error> expect_line_end() {
skip_inline_ws();
if (!eof() && peek() == '#') {
while (!eof() && peek() != '\n') {
advance();
}
}
if (eof()) {
return {};
}
if (peek() == '\r') {
advance();
}
if (eof() || peek() == '\n') {
if (!eof()) {
advance();
}
return {};
}
return std::unexpected{parse_err(origin(), "unexpected trailing characters on line")};
}
Void::Result::Result<std::string, Void::Result::Error> parse_basic_string(bool multiline) {
const auto start = origin();
if (multiline && !eof() && (peek() == '\n' || (peek() == '\r' && peek(1) == '\n'))) {
if (peek() == '\r') {
advance();
}
advance();
}
std::string out;
while (!eof()) {
if (multiline && peek() == '"' && peek(1) == '"' && peek(2) == '"') {
advance();
advance();
advance();
return out;
}
if (!multiline && peek() == '"') {
advance();
return out;
}
const char c = advance();
if (!multiline && (c == '\n' || c == '\r')) {
return std::unexpected{parse_err(start, "unterminated basic string")};
}
if (c == '\\') {
if (eof()) {
return std::unexpected{parse_err(origin(), "unterminated escape sequence")};
}
const char esc = advance();
switch (esc) {
case 'b':
out.push_back('\b');
break;
case 't':
out.push_back('\t');
break;
case 'n':
out.push_back('\n');
break;
case 'f':
out.push_back('\f');
break;
case 'r':
out.push_back('\r');
break;
case '"':
out.push_back('"');
break;
case '\\':
out.push_back('\\');
break;
case '\n':
case '\r':
case ' ':
case '\t':
if (!multiline) {
return std::unexpected{parse_err(origin(), "invalid escape in string")};
}
while (!eof() &&
(peek() == ' ' || peek() == '\t' || peek() == '\n' || peek() == '\r')) {
advance();
}
break;
default:
return std::unexpected{
parse_err(origin(), std::format("unsupported escape '\\{}'", esc))};
}
} else {
out.push_back(c);
}
}
return std::unexpected{parse_err(start, "unterminated string literal")};
}
Void::Result::Result<std::string, Void::Result::Error> parse_literal_string(bool multiline) {
const auto start = origin();
if (multiline && !eof() && (peek() == '\n' || (peek() == '\r' && peek(1) == '\n'))) {
if (peek() == '\r') {
advance();
}
advance();
}
std::string out;
while (!eof()) {
if (multiline && peek() == '\'' && peek(1) == '\'' && peek(2) == '\'') {
advance();
advance();
advance();
return out;
}
if (!multiline && peek() == '\'') {
advance();
return out;
}
const char c = advance();
if (!multiline && (c == '\n' || c == '\r')) {
return std::unexpected{parse_err(start, "unterminated literal string")};
}
out.push_back(c);
}
return std::unexpected{parse_err(start, "unterminated literal string")};
}
Void::Result::Result<std::string, Void::Result::Error> parse_single_key() {
skip_inline_ws();
if (eof()) {
return std::unexpected{parse_err(origin(), "expected key")};
}
if (peek() == '"') {
advance();
return parse_basic_string(false);
}
if (peek() == '\'') {
advance();
return parse_literal_string(false);
}
std::string key;
while (!eof()) {
const char c = peek();
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '_' || c == '-') {
key.push_back(advance());
} else {
break;
}
}
if (key.empty()) {
return std::unexpected{parse_err(origin(), "empty or invalid bare key")};
}
return key;
}
Void::Result::Result<std::vector<std::string>, Void::Result::Error> parse_key_path() {
std::vector<std::string> parts;
auto first = parse_single_key();
if (!first) {
return std::unexpected{first.error()};
}
parts.push_back(std::move(*first));
for (;;) {
skip_inline_ws();
if (!eof() && peek() == '.') {
advance();
auto next = parse_single_key();
if (!next) {
return std::unexpected{next.error()};
}
parts.push_back(std::move(*next));
} else {
break;
}
}
return parts;
}
Void::Result::Result<TomlValue, Void::Result::Error> parse_value() {
skip_inline_ws();
const auto start = origin();
if (eof()) {
return std::unexpected{parse_err(start, "expected value")};
}
const char c = peek();
if (c == '"') {
if (peek(1) == '"' && peek(2) == '"') {
advance();
advance();
advance();
auto s = parse_basic_string(true);
if (!s) {
return std::unexpected{s.error()};
}
return TomlValue{std::move(*s), start};
}
advance();
auto s = parse_basic_string(false);
if (!s) {
return std::unexpected{s.error()};
}
return TomlValue{std::move(*s), start};
}
if (c == '\'') {
if (peek(1) == '\'' && peek(2) == '\'') {
advance();
advance();
advance();
auto s = parse_literal_string(true);
if (!s) {
return std::unexpected{s.error()};
}
return TomlValue{std::move(*s), start};
}
advance();
auto s = parse_literal_string(false);
if (!s) {
return std::unexpected{s.error()};
}
return TomlValue{std::move(*s), start};
}
if (c == '[') {
return parse_array();
}
if (c == '{') {
return parse_inline_table();
}
// Read scalar token (bool, int, float).
std::string token;
while (!eof()) {
const char ch = peek();
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '#' || ch == ',' ||
ch == ']' || ch == '}') {
break;
}
token.push_back(advance());
}
if (token == "true") {
return TomlValue{true, start};
}
if (token == "false") {
return TomlValue{false, start};
}
std::string clean;
for (const char ch : token) {
if (ch != '_') {
clean.push_back(ch);
}
}
if (clean.empty()) {
return std::unexpected{parse_err(start, "empty scalar value")};
}
// Integer (hex/oct/bin/dec).
const bool looks_float = clean.find('.') != std::string::npos ||
clean.find('e') != std::string::npos ||
clean.find('E') != std::string::npos;
if (!looks_float) {
int base = 10;
std::string_view digits{clean};
if (digits.starts_with("0x")) {
base = 16;
digits.remove_prefix(2);
} else if (digits.starts_with("0o")) {
base = 8;
digits.remove_prefix(2);
} else if (digits.starts_with("0b")) {
base = 2;
digits.remove_prefix(2);
} else if (digits.starts_with("+")) {
digits.remove_prefix(1);
}
std::int64_t iv = 0;
const auto [ptr, ec] =
std::from_chars(digits.data(), digits.data() + digits.size(), iv, base);
if (ec == std::errc{} && ptr == digits.data() + digits.size()) {
return TomlValue{iv, start};
}
}
double dv = 0.0;
const auto [ptr, ec] = std::from_chars(clean.data(), clean.data() + clean.size(), dv);
if (ec == std::errc{} && ptr == clean.data() + clean.size()) {
return TomlValue{dv, start};
}
return std::unexpected{parse_err(start, std::format("invalid TOML value '{}'", token))};
}
Void::Result::Result<TomlValue, Void::Result::Error> parse_array() {
const auto start = origin();
advance(); // '['
TomlValue arr = TomlValue::make_array(start);
for (;;) {
skip_ws_and_comments(true);
if (eof()) {
return std::unexpected{parse_err(start, "unterminated array")};
}
if (peek() == ']') {
advance();
return arr;
}
auto elem = parse_value();
if (!elem) {
return std::unexpected{elem.error()};
}
arr.as_array_mut().push_back(std::move(*elem));
skip_ws_and_comments(true);
if (!eof() && peek() == ',') {
advance();
continue;
}
if (!eof() && peek() == ']') {
advance();
return arr;
}
return std::unexpected{parse_err(origin(), "expected ',' or ']' in array")};
}
}
Void::Result::Result<TomlValue, Void::Result::Error> parse_inline_table() {
const auto start = origin();
advance(); // '{'
TomlValue tbl = TomlValue::make_table(start);
skip_inline_ws();
if (!eof() && peek() == '}') {
advance();
return tbl;
}
for (;;) {
skip_inline_ws();
const auto kv_origin = origin();
auto keys = parse_key_path();
if (!keys) {
return std::unexpected{keys.error()};
}
skip_inline_ws();
if (eof() || peek() != '=') {
return std::unexpected{parse_err(origin(), "expected '=' in inline table")};
}
advance();
auto val = parse_value();
if (!val) {
return std::unexpected{val.error()};
}
if (auto r = insert_key_value(tbl.as_table_mut(), *keys, std::move(*val), kv_origin);
!r) {
return std::unexpected{r.error()};
}
skip_inline_ws();
if (!eof() && peek() == ',') {
advance();
continue;
}
if (!eof() && peek() == '}') {
advance();
return tbl;
}
return std::unexpected{parse_err(origin(), "expected ',' or '}' in inline table")};
}
}
Void::Result::Result<TomlTable *, Void::Result::Error>
navigate_table_header(TomlTable &root, const std::vector<std::string> &keys,
bool is_array_table, const SourceOrigin &hdr_origin) {
TomlTable *cur = &root;
for (std::size_t i = 0; i + 1 < keys.size(); ++i) {
const auto &k = keys[i];
auto it = cur->find(k);
if (it == cur->end()) {
it = cur->emplace(k, TomlValue::make_table(hdr_origin)).first;
}
if (it->second.is_table()) {
cur = &it->second.as_table_mut();
} else if (it->second.is_array() && !it->second.as_array().empty() &&
it->second.as_array().back().is_table()) {
cur = &it->second.as_array_mut().back().as_table_mut();
} else {
return std::unexpected{
parse_err(hdr_origin, std::format("key '{}' is not a table", k))};
}
}
const auto &last = keys.back();
if (is_array_table) {
auto it = cur->find(last);
if (it == cur->end()) {
it = cur->emplace(last, TomlValue::make_array(hdr_origin)).first;
}
if (!it->second.is_array()) {
return std::unexpected{parse_err(
hdr_origin, std::format("key '{}' cannot be redefined as array table", last))};
}
it->second.as_array_mut().push_back(TomlValue::make_table(hdr_origin));
return &it->second.as_array_mut().back().as_table_mut();
}
auto it = cur->find(last);
if (it == cur->end()) {
it = cur->emplace(last, TomlValue::make_table(hdr_origin)).first;
}
if (!it->second.is_table()) {
return std::unexpected{
parse_err(hdr_origin, std::format("key '{}' already defined as non-table", last))};
}
std::string full_header;
for (std::size_t i = 0; i < keys.size(); ++i) {
if (i > 0) {
full_header += '.';
}
full_header += keys[i];
}
if (!explicit_tables_.insert(full_header).second) {
return std::unexpected{
parse_err(hdr_origin, std::format("duplicate table header [{}]", full_header))};
}
return &it->second.as_table_mut();
}
Void::Result::Result<void, Void::Result::Error>
insert_key_value(TomlTable &table, const std::vector<std::string> &keys, TomlValue val,
const SourceOrigin &kv_origin) {
TomlTable *cur = &table;
for (std::size_t i = 0; i + 1 < keys.size(); ++i) {
const auto &k = keys[i];
auto it = cur->find(k);
if (it == cur->end()) {
it = cur->emplace(k, TomlValue::make_table(kv_origin)).first;
}
if (!it->second.is_table()) {
return std::unexpected{
parse_err(kv_origin, std::format("cannot index into non-table key '{}'", k))};
}
cur = &it->second.as_table_mut();
}
const auto &leaf = keys.back();
if (cur->contains(leaf)) {
return std::unexpected{
parse_err(kv_origin, std::format("duplicate TOML key '{}'", leaf))};
}
cur->emplace(leaf, std::move(val));
return {};
}
std::string_view text_;
std::string source_name_;
std::size_t pos_{0};
std::size_t line_{1};
std::size_t col_{1};
std::set<std::string> explicit_tables_;
};
std::string toml_quote_key(std::string_view key) {
bool bare_ok = !key.empty();
for (const char c : key) {
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '_' || c == '-')) {
bare_ok = false;
break;
}
}
return bare_ok ? std::string{key} : Util::json_quote(key);
}
std::string serialize_scalar_or_inline(const TomlValue &v) {
if (v.is_string()) {
return Util::json_quote(v.as_string());
}
if (v.is_bool()) {
return v.as_bool() ? "true" : "false";
}
if (v.is_int()) {
return std::to_string(v.as_int());
}
if (v.is_double()) {
return std::format("{}", v.as_double());
}
if (v.is_array()) {
std::string out{"["};
const auto &arr = v.as_array();
for (std::size_t i = 0; i < arr.size(); ++i) {
if (i > 0) {
out += ", ";
}
out += serialize_scalar_or_inline(arr[i]);
}
out += "]";
return out;
}
std::string out{"{"};
bool first = true;
for (const auto &[k, val] : v.as_table()) {
if (!first) {
out += ", ";
}
first = false;
out += toml_quote_key(k) + " = " + serialize_scalar_or_inline(val);
}
out += "}";
return out;
}
void serialize_table_section(const TomlTable &tbl, const std::string &prefix, std::string &out) {
// Scalars & arrays first.
for (const auto &[k, v] : tbl) {
if (!v.is_table()) {
out += toml_quote_key(k) + " = " + serialize_scalar_or_inline(v) + "\n";
}
}
// Nested subtables next.
for (const auto &[k, v] : tbl) {
if (v.is_table()) {
const std::string header =
prefix.empty() ? toml_quote_key(k) : (prefix + "." + toml_quote_key(k));
out += "\n[" + header + "]\n";
serialize_table_section(v.as_table(), header, out);
}
}
}
bool option_value_equal(const OptionValue &a, const OptionValue &b) { return a.value == b.value; }
bool dependency_records_equal(const DependencyRecord &a, const DependencyRecord &b) {
if (a.source_kind != b.source_kind || a.location != b.location || a.revision != b.revision ||
a.package != b.package || a.version != b.version || a.builder != b.builder ||
a.registry_authority != b.registry_authority || a.sha256 != b.sha256 ||
a.features != b.features || a.build_dependency != b.build_dependency ||
a.options.size() != b.options.size()) {
return false;
}
for (const auto &[k, av] : a.options) {
const auto bit = b.options.find(k);
if (bit == b.options.end() || !option_value_equal(av, bit->second)) {
return false;
}
}
return true;
}
} // namespace
std::string SourceOrigin::format() const {
if (line == 0) {
return file.empty() ? "<unknown>" : file;
}
return std::format("{}:{}:{}", file, line, column);
}
TomlValue TomlValue::make_table(SourceOrigin origin) {
return TomlValue{std::make_shared<TomlTable>(), std::move(origin)};
}
TomlValue TomlValue::make_array(SourceOrigin origin) {
return TomlValue{std::make_shared<TomlArray>(), std::move(origin)};
}
Void::Result::Result<TomlTable, Void::Result::Error> parse_toml(std::string_view text,
std::string_view source_name) {
TomlParser parser{text, std::string{source_name}};
return parser.parse();
}
Void::Result::Result<TomlTable, Void::Result::Error>
parse_toml_file(const std::filesystem::path &path) {
auto content = Void::FileSystem::read_file(path);
if (!content) {
return std::unexpected{content.error()};
}
return parse_toml(*content, path.string());
}
std::string serialize_toml(const TomlTable &table) {
std::string out;
serialize_table_section(table, "", out);
return out;
}
Void::Result::Result<std::vector<NormalizedDependency>, Void::Result::Error>
load_dependencies_toml(const std::filesystem::path &toml_path) {
auto root_res = parse_toml_file(toml_path);
if (!root_res) {
return std::unexpected{root_res.error()};
}
const auto &root = *root_res;
// Validate top-level keys (reject unknown fields explicitly!).
for (const auto &[k, v] : root) {
if (k != "dependencies" && k != "build_dependencies" && k != "registries") {
return std::unexpected{parse_err(
v.origin, std::format("unknown top-level key '{}' in dependency manifest", k))};
}
}
std::vector<NormalizedDependency> out;
auto parse_dep_section =
[&](const std::string &section_key,
bool is_build_dep) -> Void::Result::Result<void, Void::Result::Error> {
const auto sec_it = root.find(section_key);
if (sec_it == root.end()) {
return {};
}
if (!sec_it->second.is_table()) {
return std::unexpected{
parse_err(sec_it->second.origin, std::format("'{}' must be a table", section_key))};
}
for (const auto &[alias, dep_val] : sec_it->second.as_table()) {
if (!dep_val.is_table()) {
return std::unexpected{parse_err(
dep_val.origin, std::format("dependency '{}' must be a table", alias))};
}
const auto &dtbl = dep_val.as_table();
DependencyRecord rec;
rec.name = alias;
rec.build_dependency = is_build_dep;
static const std::set<std::string_view> kAllowedFields{
"git", "rev", "path", "archive", "sha256", "package", "version",
"conan", "builder", "options", "registry", "features", "build_dependency"};
for (const auto &[fk, fv] : dtbl) {
if (!kAllowedFields.contains(fk)) {
return std::unexpected{
parse_err(fv.origin,
std::format("unknown field '{}' in dependency '{}'", fk, alias))};
}
}
int source_count = 0;
if (const auto it = dtbl.find("git"); it != dtbl.end()) {
++source_count;
if (!it->second.is_string()) {
return std::unexpected{parse_err(it->second.origin, "'git' must be a string")};
}
const auto rev_it = dtbl.find("rev");
if (rev_it == dtbl.end() || !rev_it->second.is_string()) {
return std::unexpected{
parse_err(dep_val.origin,
std::format("git dependency '{}' requires 40-hex 'rev'", alias))};
}
const auto &rev = rev_it->second.as_string();
if (rev.size() != 40 || !std::ranges::all_of(rev, [](char c) {
return std::isxdigit(static_cast<unsigned char>(c)) != 0;
})) {
return std::unexpected{parse_err(
rev_it->second.origin, "git 'rev' must be an exact 40-hex commit SHA")};
}
rec.source_kind = DependencySourceKind::Git;
rec.location = it->second.as_string();
rec.revision = rev;
}
if (const auto it = dtbl.find("package"); it != dtbl.end()) {
++source_count;
if (!it->second.is_string()) {
return std::unexpected{
parse_err(it->second.origin, "'package' must be a string")};
}
const auto ver_it = dtbl.find("version");
if (ver_it == dtbl.end() || !ver_it->second.is_string()) {
return std::unexpected{parse_err(
dep_val.origin,
std::format("package dependency '{}' requires 'version'", alias))};
}
rec.source_kind = DependencySourceKind::Package;
rec.package = it->second.as_string();
rec.version = ver_it->second.as_string();
}
if (const auto it = dtbl.find("path"); it != dtbl.end()) {
++source_count;
if (!it->second.is_string()) {
return std::unexpected{parse_err(it->second.origin, "'path' must be a string")};
}
rec.source_kind = DependencySourceKind::Path;
rec.location = it->second.as_string();
}
if (const auto it = dtbl.find("archive"); it != dtbl.end()) {
++source_count;
if (!it->second.is_string()) {
return std::unexpected{
parse_err(it->second.origin, "'archive' must be a string")};
}
const auto sha_it = dtbl.find("sha256");
if (sha_it == dtbl.end() || !sha_it->second.is_string() ||
sha_it->second.as_string().size() != 64) {
return std::unexpected{parse_err(
dep_val.origin,
std::format("archive dependency '{}' requires 64-hex 'sha256'", alias))};
}
rec.source_kind = DependencySourceKind::Archive;
rec.location = it->second.as_string();
rec.sha256 = sha_it->second.as_string();
}
if (const auto it = dtbl.find("conan"); it != dtbl.end()) {
++source_count;
if (!it->second.is_string()) {
return std::unexpected{
parse_err(it->second.origin, "'conan' must be a string")};
}
rec.source_kind = DependencySourceKind::Conan;
rec.package = it->second.as_string();
rec.builder = "conan";
}
if (source_count != 1) {
return std::unexpected{parse_err(
dep_val.origin, std::format("dependency '{}' must specify exactly one source "
"(git/package/path/archive/conan)",
alias))};
}
if (const auto it = dtbl.find("builder"); it != dtbl.end()) {
if (!it->second.is_string()) {
return std::unexpected{
parse_err(it->second.origin, "'builder' must be a string")};
}
const auto &b = it->second.as_string();
if (b != "cmake" && b != "meson" && b != "conan" && b != "native") {
return std::unexpected{
parse_err(it->second.origin, std::format("unsupported builder '{}'", b))};
}
if (rec.source_kind == DependencySourceKind::Package && b != "native") {
return std::unexpected{parse_err(
it->second.origin, "contradictory builder on native package dependency")};
}
rec.builder = b;
}
if (const auto it = dtbl.find("registry"); it != dtbl.end()) {
if (!it->second.is_string()) {
return std::unexpected{
parse_err(it->second.origin, "'registry' must be a string")};
}
rec.registry_authority = it->second.as_string();
}
if (const auto it = dtbl.find("build_dependency"); it != dtbl.end()) {
if (!it->second.is_bool()) {
return std::unexpected{
parse_err(it->second.origin, "'build_dependency' must be a bool")};
}
rec.build_dependency = it->second.as_bool();
}
if (const auto it = dtbl.find("features"); it != dtbl.end()) {
if (!it->second.is_array()) {
return std::unexpected{
parse_err(it->second.origin, "'features' must be an array of strings")};
}
for (const auto &fv : it->second.as_array()) {
if (!fv.is_string()) {
return std::unexpected{
parse_err(fv.origin, "feature entry must be a string")};
}
rec.features.push_back(fv.as_string());
}
}
if (const auto it = dtbl.find("options"); it != dtbl.end()) {
if (!it->second.is_table()) {
return std::unexpected{
parse_err(it->second.origin, "'options' must be a table")};
}
for (const auto &[ok, ov] : it->second.as_table()) {
if (ov.is_string()) {
rec.options.emplace(ok, OptionValue{ov.as_string()});
} else if (ov.is_bool()) {
rec.options.emplace(ok, OptionValue{ov.as_bool()});
} else if (ov.is_int()) {
rec.options.emplace(ok, OptionValue{ov.as_int()});
} else {
return std::unexpected{parse_err(
ov.origin,
std::format("option '{}' must be string, bool, or integer", ok))};
}
}
}
out.push_back(NormalizedDependency{std::move(rec), dep_val.origin});
}
return {};
};
if (auto r = parse_dep_section("dependencies", false); !r) {
return std::unexpected{r.error()};
}
if (auto r = parse_dep_section("build_dependencies", true); !r) {
return std::unexpected{r.error()};
}
return out;
}
Void::Result::Result<std::vector<NormalizedDependency>, Void::Result::Error>
merge_dependencies(const std::vector<DependencyRecord> &cpp_deps,
const std::vector<NormalizedDependency> &toml_deps) {
std::map<std::string, NormalizedDependency, std::less<>> merged;
for (const auto &d : cpp_deps) {
merged.emplace(d.name, NormalizedDependency{d, SourceOrigin{"build.cpp", 0, 0}});
}
for (const auto &td : toml_deps) {
const auto it = merged.find(td.record.name);
if (it == merged.end()) {
merged.emplace(td.record.name, td);
continue;
}
if (!dependency_records_equal(it->second.record, td.record)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("conflicting declaration for dependency '{}': first declared at {}, "
"conflicting declaration at {}",
td.record.name, it->second.origin.format(), td.origin.format()))};
}
}
std::vector<NormalizedDependency> out;
out.reserve(merged.size());
for (auto &[k, v] : merged) {
out.push_back(std::move(v));
}
return out;
}
} // namespace Void::Build::Package