diff --git a/AGENTS.md b/AGENTS.md index 40f8b5f..7fc2f7e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ The user's environment provides `dev cpp-gcc -c COMMAND...` (GCC 16.2, CMake 4.4.4, Ninja 1.13.2, Meson 1.12.1) and `dev cpp -c COMMAND...` (Clang 23.1.3). Use the GCC environment for this C++26 bootstrap. The bootstrap's source dependency is VoidLibrary at -9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5. +3e254055e081a104f08df68dde39711bc7813518. An explicit VBS_VOID_SOURCE_DIR override is development-only; never change that external checkout. It may contain untracked secrets. diff --git a/CMakeLists.txt b/CMakeLists.txt index 9235207..b7b4055 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -18,7 +18,7 @@ endif() option(VBS_BUILD_TESTS "Build declaration SDK and native engine test suites" ON) option(VBS_BUILD_BENCHMARKS "Build reproducible VBS benchmark harness" ON) set(VBS_VOID_SOURCE_DIR "" CACHE PATH "Development-only VoidLibrary source override (bypasses pin)") -set(VBS_VOID_REVISION "9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5") +set(VBS_VOID_REVISION "3e254055e081a104f08df68dde39711bc7813518") include(cmake/VoidDependency.cmake) vbs_add_void_dependency() @@ -69,19 +69,14 @@ target_link_libraries(VoidBuild_Core PUBLIC Void::Text Void::Unicode Void::Async - Void::Algorithms) + Void::Algorithms + Void::Crypto + Void::Archive) +target_compile_definitions(VoidBuild_Core PUBLIC VBS_HAS_VOID_CRYPTO=1 VBS_HAS_VOID_ARCHIVE=1) if(VBS_HAS_VOID_SQLITE) target_link_libraries(VoidBuild_Core PUBLIC Void::Sqlite) target_compile_definitions(VoidBuild_Core PUBLIC VBS_HAS_VOID_SQLITE=1) endif() -if(VBS_HAS_VOID_CRYPTO) - target_link_libraries(VoidBuild_Core PUBLIC Void::Crypto) - target_compile_definitions(VoidBuild_Core PUBLIC VBS_HAS_VOID_CRYPTO=1) -endif() -if(VBS_HAS_VOID_ARCHIVE) - target_link_libraries(VoidBuild_Core PUBLIC Void::Archive) - target_compile_definitions(VoidBuild_Core PUBLIC VBS_HAS_VOID_ARCHIVE=1) -endif() add_library(VoidBuild_Registry STATIC registry/service/HttpServer.cpp diff --git a/README.md b/README.md index 7118c07..64e46ca 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,12 @@ profile definitions live in ordinary `build.cpp`, `build.profiles.cpp`, and **Implemented scope (Plans 01–19):** - **Declaration SDK (`Void::Build`, ``)**: `VoidBuild_Sdk` / `Void::BuildSdk` with version-1 deterministic UTF-8 JSON schema, profile inheritance and cycle detection, all seven `TargetKind`s, scoped options/defines/links, modern C++ flags, install rules, and symbolic TOML manifest references. -- **Native Core Engine (`VoidBuild_Core` / `Void::BuildCore`)**: out-of-process host descriptor compilation, graph lowering and transitive visibility resolution, GCC 16 & Clang 23 toolchain discovery/capability probing, content-verified immutable snapshots (`FICLONE`/isolated copies, lookup guards), transactional CAS store (`StateStore`), and bounded-parallel DAG execution (`ProcessSupervisor` with `-pgid` `SIGTERM -> SIGKILL` cleanup). -- **Modern C++, Editor Metadata & Watchers**: Full graph-integrated P1689r5 named modules & module partitions (GCC `-fmodule-mapper` and Clang two-step `--precompile` `.pcm` -> `.o` + transitive `-fmodule-file=`), explicit `SourceKind::HeaderUnit` compilation, unity batches (excluding modules and per-file overrides), incompatible sanitizer rejection, per-profile `compile_commands.json` with monotonic selection tickets and user-file preservation, and Linux `inotify` build/metadata watching (`MetadataOnly` never triggers builds or foreign configures). -- **Native Package Manager, Foreign Providers, Bridge & Install**: TOML 1.0 parser/merger, PubGrub-style SemVer solver, context-aware CAS `vbs.lock`, live registry HTTP/1.1 client (`vbs publish`, `vbs deps resolve|update`, `vbs build --locked` against `vbs-registry`), deterministic PAX/USTAR `.tar` packaging with safe extraction, CMake File API & Meson introspection providers (plus explicit-error Conan2 adapter), `cmake/bridge/VbsDeps.cmake`, and staged relocatable install/export/uninstall. +- **Native Core Engine (`VoidBuild_Core` / `Void::BuildCore`)**: out-of-process host descriptor compilation, graph lowering and transitive visibility resolution, GCC 16 & Clang 23 toolchain discovery/capability probing, content-verified immutable snapshots (`FICLONE`/isolated copies, lookup guards), transactional CAS store (`StateStore`), bounded-parallel DAG execution (`ProcessSupervisor` with `-pgid` `SIGTERM -> SIGKILL` cleanup), and live `Void::Log` progress logging (`--verbose`/`-v`, `--quiet`/`-q`). +- **Self-Building `build.cpp`**: Root [build.cpp](build.cpp) declares the full `VoidBuildSystem` (`VoidBuildSdk`, `VoidBuildCore`, `GenerateBootstrapConfig`, `vbs`, `VoidBuildRegistry`, `vbs-registry`) so `vbs build` compiles and links `VoidBuildSystem` itself end-to-end. +- **Modern C++, Editor Metadata & Watchers**: Full graph-integrated P1689r5 named modules & module partitions (GCC `-fmodule-mapper` and Clang two-step `--precompile` `.pcm` -> `.o` + transitive `-fmodule-file=`), explicit `SourceKind::HeaderUnit` compilation, unity batches (excluding modules and per-file overrides), incompatible sanitizer rejection, per-profile `compile_commands.json` with monotonic selection tickets and user-file preservation, and Linux `inotify` build/metadata watching via `Void::FileSystem::DirectoryWatcher` (`MetadataOnly` never triggers builds or foreign configures). +- **Native Package Manager, Foreign Providers, Bridge & Install**: `Void::Data::Toml` 1.0 parser/merger, PubGrub-style SemVer solver (`Void::Semver::parse_range`), context-aware CAS `vbs.lock`, live registry HTTP/1.1 client (`vbs publish`, `vbs deps resolve|update`, `vbs build --locked` against `vbs-registry`), deterministic PAX/USTAR `.tar` packaging & staged safe extraction (`Void::Archive`), CMake File API & Meson introspection providers (plus explicit-error Conan2 adapter), `cmake/bridge/VbsDeps.cmake`, and staged relocatable install/export/uninstall. - **Registry Service, Web Admin UI & Native Self-Hosting**: `vbs-registry` HTTP/1.1 service (`VoidBuild_Registry` / `Void::BuildRegistry`) with RBAC, salted password hashes, CSRF/HttpOnly session auth, immutable releases, backup/restore, XSS-safe DOM-only web UI (`registry/web/`), native `VoidLibrary` & full `VbsSelfHostRecipe` recipes (`recipes/VoidLibrary/`, `recipes/SelfHost/`) compiling the full Stage 1 `vbs` binary without CMake to build & test Stage 2 projects, and non-CMake `Void::Testing` registration generator (`vbs gen-tests`). -- **VoidLibrary Reuse**: Built directly on VoidLibrary `Configuration` (`Void::Argparse::Parser` across `vbs`, `vbs-registry`, `vbs_describe`, and `vbs_benchmarks`; `Void::Configuration::get_env`/`get_env_or`), `Algorithms` (`Void::Algorithms::topological_order`), `Async` (`Void::Concurrency::ThreadPool`), `Unicode` (`Void::Unicode::validate_utf8`), `Text` (`Void::Str`, `Void::Encoding::Hex`, `Void::Encoding::Url`, `Void::Semver`), `Core` (`Void::Scope::on_exit`), `Time` (`Void::Time::Stopwatch`), `Data` (`Void::Json::Strict`), `System` (`Void::FileSystem`, `Void::Process::SignalWatcher`), and `Testing`. +- **Maximal VoidLibrary Reuse (`3e254055...`)**: Built directly on VoidLibrary `Configuration` (`Void::Argparse::Parser` with nested subcommands, `option_many`, and 100% auto-generated `--help` across `vbs`, `vbs-registry`, `vbs_describe`, and `vbs_benchmarks`; `Void::Configuration::get_env`/`get_env_or`), `Crypto` (`Void::Crypto::Hasher` zero-dep SHA-256), `Archive` (`Void::Archive::create` & `extract_staged`), `Data` (`Void::Data::Toml`, `Void::Json::Strict`), `System` (`Void::Process::spawn`/`communicate_blocking`/`enable_subreaper`, `Void::FileSystem::DirectoryWatcher`/`FileLock`/`reflink_copy_file`/`set_canonical_mtime`/`atomic_symlink_swap`, `Void::Process::SignalWatcher`), `Algorithms` (`Void::Algorithms::topological_order`), `Async` (`Void::Concurrency::ThreadPool`), `Unicode` (`Void::Unicode::validate_utf8`), `Text` (`Void::Str`, `Void::Encoding::Hex`, `Void::Encoding::Url`, `Void::Semver::parse_range`), `Log` (`Void::Log`), `Core` (`Void::Scope::on_exit`), `Time` (`Void::Time::Stopwatch`), and `Testing`. - **Remaining future design scope**: [Plan 20 — Later native foreign execution and platform ports](docs/roadmap/20-future-translation-platforms.md) (native foreign graph translation and Windows/macOS ports) remains planned architectural scope. Start with the [twenty roadmap plans](docs/roadmap/README.md), @@ -33,6 +34,8 @@ Start with the [twenty roadmap plans](docs/roadmap/README.md), Requirements: GCC 16+ with C++26 `-freflection`, CMake 4.0+, Git, and Ninja (verified on NixOS via `dev cpp-gcc` with GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2, Meson 1.12.1; Clang target matrix verified via `dev cpp` with Clang 23.1.3 and `clang-scan-deps`). +### Bootstrap build (CMake) + ```sh dev cpp-gcc -c cmake -S . -B build/dev -G Ninja \ -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON @@ -41,7 +44,7 @@ dev cpp-gcc -c ctest --test-dir build/dev --output-on-failure dev cpp-gcc -c build/dev/bin/vbs_benchmarks --files 15 ``` -CMake fetches VoidLibrary at pinned commit `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5`. +CMake fetches VoidLibrary at pinned commit `3e254055e081a104f08df68dde39711bc7813518`. For development against a local checkout without mutating the pin: ```sh @@ -49,11 +52,26 @@ dev cpp-gcc -c cmake -S . -B build/dev-local -G Ninja \ -DCMAKE_BUILD_TYPE=Debug -DVBS_VOID_SOURCE_DIR=../VoidLibrary ``` -Note on optional system dependencies: `dev cpp-gcc` provides pure-C++/Threads dependencies without external `SQLite3`, `OpenSSL`, `LibArchive`, or `conan`. `Void::BuildCore` links optional VoidLibrary modules when available and provides verified swappable local adapters in the meantime (tracked in [docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md](docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md)). Note that `conan` invocation requires `conan` in `PATH` and fails explicitly with a missing-prerequisite diagnostic when absent. +### Self-building VoidBuildSystem with `vbs` + +Once the bootstrap `vbs` binary is built, `VoidBuildSystem` builds itself directly from root [build.cpp](build.cpp) with live progress logs (`-v`/`--verbose` for debug detail, `-q`/`--quiet` for warnings/errors only): + +```sh +dev cpp-gcc -c build/dev/bin/vbs build --build-dir build/vbs-self +build/vbs-self/profiles/debug/out/bin/vbs --version +build/vbs-self/profiles/debug/out/bin/vbs --help +``` + +For offline/local VoidLibrary development during `vbs build`, set `VBS_VOID_SOURCE_DIR=/path/to/VoidLibrary`. + +Note on optional system dependencies: `Void::Crypto` (`VL-007`) and `Void::Archive` (`VL-006`) now build cleanly with zero external system dependencies in `dev cpp-gcc`. `SQLite3`, `Boost`/`OpenSSL` (for `Void::Net`), and `conan` remain optional; VBS links `Void::Sqlite` automatically when system `SQLite3` is installed and uses its verified pure-C++/POSIX adapters otherwise (tracked in [docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md](docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md)). `conan` invocation requires `conan` in `PATH` and fails explicitly with a missing-prerequisite diagnostic when absent. ## CLI Reference -- `vbs build [--project DIR] [--build-dir DIR] [--profile NAME]... [--target NAME]... [--compiler gcc|clang] [--editor-profile NAME] [--build-source FILE]... [--jobs N] [--locked] [--offline] [--no-cache]` +All CLI help text (`vbs --help`, `vbs --help`, `vbs compdb --help`, `vbs deps --help`, `vbs-registry --help`, etc.) is auto-generated directly by `Void::Argparse::Parser`: + +- `vbs [--version] [--verbose] [--quiet] ` +- `vbs build [--project DIR] [--build-dir DIR] [--profile NAME]... [--target NAME]... [--compiler gcc|clang] [--editor-profile NAME] [--build-source FILE]... [--jobs N] [--locked] [--offline] [--no-cache] [--verbose] [--quiet]` - `vbs test ...` (same flags as `vbs build`, then runs selected `TargetKind::Test` binaries) - `vbs describe [--project DIR] [--build-dir DIR] [--profile NAME] [--compiler gcc|clang]` - `vbs compdb use|show|export|watch ...` diff --git a/benchmarks/EngineBenchmarks.cpp b/benchmarks/EngineBenchmarks.cpp index e39c09d..8162745 100644 --- a/benchmarks/EngineBenchmarks.cpp +++ b/benchmarks/EngineBenchmarks.cpp @@ -11,48 +11,49 @@ #include #include -#include #include -#include +#include using namespace Void::Build; int main(int argc, char **argv) { std::string files_opt; std::string jobs_opt; + std::vector positional_files; Void::Argparse::Parser parser{ "vbs_benchmarks", "Run reproducible snapshot, cold build, and warm no-op timings for VoidBuildSystem."}; parser.option_default("--files", "-n", "number of generated source units", files_opt, "20") - .option_default("--jobs", "-j", "parallel worker count", jobs_opt, "4"); + .option_default("--jobs", "-j", "parallel worker count", jobs_opt, "4") + .positional_many("count", "optional positional file count override", positional_files, + false); - // Preserve positional shorthand `vbs_benchmarks 15` alongside `--files 15`. - if (argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h")) { - std::cout << parser.help(); + const auto parsed = parser.parse_detailed(argc, argv); + if (parsed.is_help()) { + std::cout << parsed.message; return 0; } + if (parsed.is_error()) { + std::cerr << "vbs_benchmarks: " << parsed.message << '\n'; + return 2; + } + if (positional_files.size() > 1) { + std::cerr << "vbs_benchmarks: expected at most one positional count argument\n"; + return 2; + } + if (!positional_files.empty()) { + files_opt = positional_files.front(); + } int parsed_files = 20; int parsed_jobs = 4; - if (argc == 2 && Void::Str::to_int(argv[1], parsed_files)) { - if (parsed_files <= 0) { - std::cerr << "vbs_benchmarks: file count must be positive\n"; - return 2; - } - } else { - auto parsed = parser.parse(argc, argv); - if (!parsed) { - std::cerr << "vbs_benchmarks: " << parsed.error() << '\n'; - return 2; - } - if (!Void::Str::to_int(files_opt, parsed_files) || parsed_files <= 0) { - std::cerr << "vbs_benchmarks: invalid --files value '" << files_opt << "'\n"; - return 2; - } - if (!Void::Str::to_int(jobs_opt, parsed_jobs) || parsed_jobs <= 0) { - std::cerr << "vbs_benchmarks: invalid --jobs value '" << jobs_opt << "'\n"; - return 2; - } + if (!Void::Str::to_int(files_opt, parsed_files) || parsed_files <= 0) { + std::cerr << "vbs_benchmarks: invalid --files value '" << files_opt << "'\n"; + return 2; + } + if (!Void::Str::to_int(jobs_opt, parsed_jobs) || parsed_jobs <= 0) { + std::cerr << "vbs_benchmarks: invalid --jobs value '" << jobs_opt << "'\n"; + return 2; } const auto file_count = static_cast(parsed_files); diff --git a/build.cpp b/build.cpp index 8b02c4e..c1ce4bb 100644 --- a/build.cpp +++ b/build.cpp @@ -1,20 +1,118 @@ #include "build-support/Defaults.hpp" void build(Void::Build::Project &project) { + const auto &ctx = project.context(); + auto library = project.dependency("VoidLibrary"); library .git("https://git.faumaray.com/Void/VoidLibrary.git", - Void::Build::Commit{"9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"}) - .cmake({{"VOID_ENABLED_MODULES", "Configuration;Testing"}, - {"VOID_ENABLE_TESTING", false}, - {"VOID_ENABLE_BENCHMARKS", false}, - {"BUILD_SHARED_LIBS", false}}); + Void::Build::Commit{"3e254055e081a104f08df68dde39711bc7813518"}) + .cmake( + {{"VOID_ENABLED_MODULES", "Configuration;Text;Unicode;Async;Algorithms;Crypto;Archive"}, + {"VOID_ENABLE_TESTING", false}, + {"VOID_ENABLE_BENCHMARKS", false}, + {"VOID_FETCH_SQLITE3", false}, + {"BUILD_SHARED_LIBS", false}}); auto sdk = project.static_library("VoidBuildSdk"); - sdk.sources({"src/Build.cpp"}).include_directory("include", Void::Build::Visibility::Public); - BuildSupport::compiler_warnings(sdk, project.context()); + sdk.cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"src/Build.cpp", "src/Util/Json.cpp"}) + .include_directory("include", Void::Build::Visibility::Public); + BuildSupport::compiler_warnings(sdk, ctx); + if (ctx.compiler == Void::Build::CompilerFamily::Gcc) { + sdk.compile_option("-freflection", Void::Build::Visibility::Public); + } + + auto core = project.static_library("VoidBuildCore"); + core.cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({ + "src/Util/Sha256.cpp", + "src/Platform/FileOps.cpp", + "src/Platform/ProcessSupervisor.cpp", + "src/Toolchain/Driver.cpp", + "src/Snapshot/Snapshot.cpp", + "src/State/StateStore.cpp", + "src/Graph/Graph.cpp", + "src/Execution/Scheduler.cpp", + "src/Config/Frontend.cpp", + "src/Editor/CompDb.cpp", + "src/Watch/Watcher.cpp", + "src/Package/Toml.cpp", + "src/Package/Solver.cpp", + "src/Package/Lockfile.cpp", + "src/Package/Archive.cpp", + "src/Package/Fetch.cpp", + "src/Package/RegistryClient.cpp", + "src/Provider/Provider.cpp", + "src/Install/Installer.cpp", + "src/Bridge/CMakeBridge.cpp", + "src/Modules/ModuleScanner.cpp", + "src/SelfHost/TestRegistryGen.cpp", + "recipes/VoidLibrary/VoidLibraryRecipe.cpp", + "recipes/SelfHost/VbsSelfHostRecipe.cpp", + }) + .include_directory("include", Void::Build::Visibility::Public) + .include_directory("recipes", Void::Build::Visibility::Public) + .define("VBS_HAS_VOID_CRYPTO=1", Void::Build::Visibility::Public) + .define("VBS_HAS_VOID_ARCHIVE=1", Void::Build::Visibility::Public) + .link(sdk, Void::Build::Visibility::Public) + .link(library.target("Void::Configuration"), Void::Build::Visibility::Public) + .link(library.target("Void::Text"), Void::Build::Visibility::Public) + .link(library.target("Void::Unicode"), Void::Build::Visibility::Public) + .link(library.target("Void::Async"), Void::Build::Visibility::Public) + .link(library.target("Void::Algorithms"), Void::Build::Visibility::Public) + .link(library.target("Void::Crypto"), Void::Build::Visibility::Public) + .link(library.target("Void::Archive"), Void::Build::Visibility::Public); + BuildSupport::compiler_warnings(core, ctx); + + // Generate profile-isolated BootstrapConfig.hpp inside $GEN/include/Void/Build/. + const std::string gen_script = + "mkdir -p \"$GEN/include/Void/Build\" && cat > " + "\"$GEN/include/Void/Build/BootstrapConfig.hpp\" " + "<<'EOF'\n" + "#pragma once\n" + "#include \n" + "namespace Void::Build::Bootstrap {\n" + "inline constexpr std::string_view version = \"0.1.0\";\n" + "inline constexpr std::string_view os = \"" + + ctx.os + + "\";\n" + "inline constexpr std::string_view architecture = \"" + + ctx.architecture + + "\";\n" + "inline constexpr std::string_view source_dir = \"$PROJECT_ROOT\";\n" + "inline constexpr std::string_view binary_dir = \"$BUILD_DIR\";\n" + "inline constexpr std::string_view sdk_include_dir = \"$PROJECT_ROOT/include\";\n" + "inline constexpr std::string_view sdk_source_dir = \"$PROJECT_ROOT/src\";\n" + "}\n" + "EOF\n"; + + auto bootstrap_cfg = project.custom_action("GenerateBootstrapConfig"); + bootstrap_cfg.command({"/bin/sh", "-c", gen_script}) + .outputs({"include/Void/Build/BootstrapConfig.hpp"}); auto cli = project.executable("vbs"); - cli.sources({"src/Main.cpp"}).link(sdk).link(library.target("Void::Configuration")); - BuildSupport::compiler_warnings(cli, project.context()); + cli.cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"src/Main.cpp"}) + .depends_on(bootstrap_cfg) + .include_directory("$GEN/include", Void::Build::Visibility::Private) + .link(core) + .install("bin"); + BuildSupport::compiler_warnings(cli, ctx); + + auto registry_lib = project.static_library("VoidBuildRegistry"); + registry_lib.cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"registry/service/HttpServer.cpp", "registry/service/RegistryService.cpp"}) + .include_directory("registry/include", Void::Build::Visibility::Public) + .link(core, Void::Build::Visibility::Public); + BuildSupport::compiler_warnings(registry_lib, ctx); + + auto registry_cli = project.executable("vbs-registry"); + registry_cli.cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"registry/service/Main.cpp"}) + .depends_on(bootstrap_cfg) + .include_directory("$GEN/include", Void::Build::Visibility::Private) + .link(registry_lib) + .install("bin"); + BuildSupport::compiler_warnings(registry_cli, ctx); } diff --git a/cmake/VoidDependency.cmake b/cmake/VoidDependency.cmake index 8e3442a..6e0a0c6 100644 --- a/cmake/VoidDependency.cmake +++ b/cmake/VoidDependency.cmake @@ -5,13 +5,14 @@ function(vbs_add_void_dependency) set(VOID_ENABLE_TESTING OFF) set(VOID_ENABLE_BENCHMARKS OFF) set(BUILD_SHARED_LIBS OFF) - set(VOID_ENABLED_MODULES Configuration Text Unicode Async Algorithms) + set(VOID_FETCH_SQLITE3 OFF) + set(VOID_ENABLED_MODULES Configuration Text Unicode Async Algorithms Crypto Archive) if(VBS_BUILD_TESTS) list(APPEND VOID_ENABLED_MODULES Testing) endif() - # Opportunistically enable VoidLibrary modules backed by optional system packages - # when those packages are present in the active toolchain environment. + # Crypto (VL-007) and Archive (VL-006) now work with zero external dependencies in VoidLibrary; + # Sqlite remains opportunistic when system SQLite3 is installed. find_package(SQLite3 QUIET) if(SQLite3_FOUND) list(APPEND VOID_ENABLED_MODULES Sqlite) @@ -20,22 +21,6 @@ function(vbs_add_void_dependency) set(VBS_HAS_VOID_SQLITE OFF PARENT_SCOPE) endif() - find_package(OpenSSL QUIET) - if(OpenSSL_FOUND) - list(APPEND VOID_ENABLED_MODULES Crypto) - set(VBS_HAS_VOID_CRYPTO ON PARENT_SCOPE) - else() - set(VBS_HAS_VOID_CRYPTO OFF PARENT_SCOPE) - endif() - - find_package(LibArchive QUIET) - if(LibArchive_FOUND) - list(APPEND VOID_ENABLED_MODULES Archive) - set(VBS_HAS_VOID_ARCHIVE ON PARENT_SCOPE) - else() - set(VBS_HAS_VOID_ARCHIVE OFF PARENT_SCOPE) - endif() - if(VBS_VOID_SOURCE_DIR) get_filename_component(_vbs_void_source "${VBS_VOID_SOURCE_DIR}" ABSOLUTE BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") diff --git a/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md b/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md index 106c5cd..7c1e8aa 100644 --- a/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md +++ b/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md @@ -1,259 +1,43 @@ # VoidLibrary Upstream Feature Requests -Pinned baseline inspected: `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5`. +Pinned VoidLibrary revision: `3e254055e081a104f08df68dde39711bc7813518` (merged `feat/upstream-vbs-requests` covering `VL-001`..`VL-013`; upgraded from `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5`). -This ledger tracks reusable, non-build-system-specific capabilities needed by -VoidBuildSystem that are absent, incomplete, or tightly bound to external -system libraries in the pinned VoidLibrary revision. Until a dedicated -VoidLibrary worker implements these items and the pin is updated, VBS keeps -swappable local adapters behind clean internal interfaces. +## Status Summary + +| ID | Capability | Upstream Status (`3e254055...`) | VBS Adoption Status | +| --- | --- | --- | --- | +| `VL-001` | Process group supervision (`Void::Process::spawn`, `communicate_blocking`, `enable_subreaper`) | Implemented | **Adopted** (`src/Platform/ProcessSupervisor.cpp`) | +| `VL-002` | TOML 1.0 parser & serializer (`Void::Data::Toml`) | Implemented | **Adopted** (`src/Package/Toml.cpp`) | +| `VL-003` | Kernel `inotify` recursive directory watcher (`Void::FileSystem::DirectoryWatcher`) | Implemented | **Adopted** (`src/Watch/Watcher.cpp`, `include/Void/Build/Watch/Watcher.hpp`) | +| `VL-004` | Concrete HTTP/1.1 server (`Void::Net::HttpServer`) | Implemented (requires Boost + OpenSSL) | Local loopback POSIX adapter retained for minimal `dev cpp-gcc` (no Boost/OpenSSL) | +| `VL-005` | Streaming HTTP client & TLS default (`Void::Net::HttpClient`) | Implemented (requires Boost + OpenSSL) | Local loopback POSIX + `curl` adapter retained for minimal `dev cpp-gcc` (no Boost/OpenSSL) | +| `VL-006` | Deterministic archive creation & safe staged extraction (`Void::Archive::create`, `extract_staged`) | Implemented (zero external deps for `.tar`) | **Adopted** (`src/Package/Archive.cpp`, always linked via `Void::Archive`) | +| `VL-007` | Zero-dependency built-in SHA-256 / BLAKE2b (`Void::Crypto::Hasher`) | Implemented (zero external deps when OpenSSL absent) | **Adopted** (`include/Void/Build/Util/Sha256.hpp`, `src/Util/Sha256.cpp`, always linked via `Void::Crypto`) | +| `VL-008` | Strict UTF-8 validation (`Void::Json::Strict`, `Void::Unicode::validate_utf8`) | Implemented | **Adopted** (`src/Util/Json.cpp`, `Void::Json::Strict` throughout) | +| `VL-009` | Native non-CMake `Void::Testing` registration API | Implemented | **Adopted** (supported alongside `vbs gen-tests` in `src/SelfHost/TestRegistryGen.cpp`) | +| `VL-010` | Advisory `FileLock`, `reflink_copy_file`, `set_canonical_mtime`, `atomic_symlink_swap` (`Void::FileSystem`) | Implemented | **Adopted** (`include/Void/Build/Platform/FileOps.hpp`, `src/Platform/FileOps.cpp`) | +| `VL-011a` | Subcommands, `option_many`, `positional_many`, `ParseOutcome::Help` (`Void::Argparse::Parser`) | Implemented | **Adopted** (`src/Main.cpp`, `src/Describe.cpp`, `registry/service/Main.cpp`, `benchmarks/EngineBenchmarks.cpp` — 100% auto-generated help) | +| `VL-011b` | Optional SQLite3 FetchContent (`Void::Sqlite`) | Implemented (`VOID_FETCH_SQLITE3`) | Opportunistic when system `SQLite3` is installed (`VOID_FETCH_SQLITE3=OFF` to keep offline configures fast); journaled atomic CAS store retained | +| `VL-012` | Naming consistency observation | Noted | VBS strictly uses `Void::Build`, `PascalCase` types/enums/paths, `snake_case` functions/methods | +| `VL-013` | Shorthand SemVer ranges (`^1.0`, `~1.2`, `>=1.2 <2`) in `Void::Semver::parse_range` | Implemented | **Adopted** (`src/Package/Solver.cpp` delegates directly to `Void::Semver::parse_range`) | --- -## VL-001: Robust Process Descendant Lifecycle Supervision (`Void::Process`) +## Detailed Notes -- **Target module**: `System` (`include/Void/System/Process.hpp`) -- **Priority**: High (Plan 06 — Execution & Cancellation) -- **Current gap**: `Void::Process::Child::terminate()` signals the process - group and waits for the direct leader PID, but returns immediately once the - leader exits even if grandchildren remain alive in the process group (e.g. - ignoring `SIGTERM`). -- **Requested API / behavior**: - - Track the entire owned process group (and optionally opt into Linux - `PR_SET_CHILD_SUBREAPER` or `pidfd` / `waitpid(-pgid, ...)` draining). - - `Child::terminate(grace)` must send `SIGTERM` to `-pgid`, poll/wait until - **all** members of the process group exit (not only the leader), escalate - to `SIGKILL` on `-pgid` when `grace` expires, and reap/confirm no members - remain (`kill(-pgid, 0) == -1 && errno == ESRCH`). -- **Acceptance test**: Leader spawns grandchild that ignores `SIGTERM`, leader - exits immediately; `terminate(100ms)` escalates to `SIGKILL` and verifies the - grandchild cannot write after `terminate()` returns. -- **VBS temporary adapter**: `Void::Build::Platform::SupervisedProcess` in - `src/Platform/ProcessSupervisor.cpp`. +### Adopted Upstream Capabilities (`VL-001`, `VL-002`, `VL-003`, `VL-006`, `VL-007`, `VL-008`, `VL-009`, `VL-010`, `VL-011a`, `VL-013`) -## VL-002: TOML 1.0 Parser and Serializer (`Void::Data::Toml`) +- **`VL-001` (`Void::Process`)**: `src/Platform/ProcessSupervisor.cpp` delegates process spawning, pipe multiplexing, timeouts, cancellation, `PR_SET_CHILD_SUBREAPER`, and `-pgid` `SIGTERM -> SIGKILL` termination to `Void::Process::spawn`, `Void::Process::communicate_blocking`, and `Void::Process::enable_subreaper`, adding post-leader process-group drain supervision for detached grandchildren with redirected stdio. +- **`VL-002` (`Void::Data::Toml`)**: `src/Package/Toml.cpp` delegates all TOML 1.0 parsing and canonical table serialization to `Void::Data::Toml::parse` and `Void::Data::Toml::serialize_table`. +- **`VL-003` (`Void::FileSystem::DirectoryWatcher`)**: `src/Watch/Watcher.cpp` wraps `Void::FileSystem::DirectoryWatcher` for recursive Linux `inotify` observation, ignore predicates, and `RescanRequired` overflow handling. +- **`VL-006` (`Void::Archive`)**: `CMakeLists.txt`, `cmake/VoidDependency.cmake`, `recipes/VoidLibrary/VoidLibraryRecipe.cpp`, and `recipes/SelfHost/VbsSelfHostRecipe.cpp` unconditionally enable `Void::Archive` (`VOID_ARCHIVE_HAS_LIBARCHIVE=0` built-in USTAR/PAX tar), and `src/Package/Archive.cpp` delegates archive creation and staged security-checked extraction to `Void::Archive::create` and `Void::Archive::extract_staged` + `StagedTree::publish`. +- **`VL-007` (`Void::Crypto`)**: `Void::Crypto` (`VOID_CRYPTO_HAS_OPENSSL=0` built-in FIPS 180-4 SHA-256) is unconditionally linked, and `src/Util/Sha256.cpp` delegates directly to `Void::Crypto::Hasher`, `Void::Crypto::sha256`, and `Void::Crypto::sha256_file`. +- **`VL-008` (`Void::Json::Strict` / `Void::Unicode`)**: Strict UTF-8 validation is active across `Void::Json::Strict` and `src/Util/Json.cpp`. +- **`VL-010` (`Void::FileSystem`)**: `src/Platform/FileOps.cpp` delegates `FileLock`, `copy_isolated`, `set_canonical_mtime`, and `atomic_swap_symlink` directly to `Void::FileSystem::FileLock`, `reflink_copy_file`, `set_canonical_mtime`, and `atomic_symlink_swap`. +- **`VL-011a` (`Void::Argparse::Parser`)**: Every VBS executable (`vbs`, `vbs-registry`, `vbs_describe`, `vbs_benchmarks`) uses `Void::Argparse::Parser::parse_detailed()` with native `subcommand()`, `option_many()`, `positional_many()`, and `require_subcommand()` — eliminating all custom help strings, manual `--help` checks, and manual repeatable-argument slicing. +- **`VL-013` (`Void::Semver::parse_range`)**: `src/Package/Solver.cpp` calls `Void::Semver::parse_range()` directly without local range normalization. -- **Target module**: `Data` (`include/Void/Data/Toml.hpp`) -- **Priority**: High (Plan 11 — Dependency Declarations & Lockfiles) -- **Current gap**: `Void::Data` provides `Json`, `StrictJson`, `Ini`, `Csv`, - and `Reflect`, with no TOML 1.0 parser/serializer. -- **Requested API / behavior**: - - Full TOML 1.0 parser returning `Void::Result::Result` - with line/column source locations (`Origin{line, column}`) on every node - and error. - - Typed values preserving string, boolean, signed 64-bit integer, double, - datetime, array, inline table, table, and array-of-tables, plus - deterministic canonical serializer. -- **Acceptance test**: Round-trip TOML 1.0 compliance fixtures including - multiline strings, dotted keys, inline tables, arrays of tables, comments, - and exact line/column error reporting on duplicate/malformed keys. -- **VBS temporary adapter**: `Void::Build::Package::Toml` in - `src/Package/Toml.cpp`. +### Remaining Optional External-Dependency Adapters (`VL-004`, `VL-005`, `VL-011b`) -## VL-003: Kernel-Event Recursive Directory Watcher (`Void::System` / `Void::SystemAsync`) - -- **Target module**: `System` / `SystemAsync` - (`include/Void/System/DirectoryWatcher.hpp` or extension to `AsyncWatcher.hpp`) -- **Priority**: High (Plan 10 — Build & Metadata Watchers) -- **Current gap**: `Void::FileSystem::FileWatcher` and - `Void::SystemAsync::WatcherService` are polling-only per explicit path. They - do not use Linux `inotify` for low-latency recursive tree observation or emit - kernel queue-overflow (`IN_Q_OVERFLOW`) rescan signals. -- **Requested API / behavior**: - - Linux `inotify`-backed recursive directory watcher with ignore predicates - (to skip `.git`, `build/`, etc.), automatic watch attachment on newly - created subdirectories, rename pairing (`IN_MOVED_FROM` / `IN_MOVED_TO`), - and explicit `RescanRequired` events on `IN_Q_OVERFLOW` or watch-limit - errors (`ENOSPC`). -- **Acceptance test**: Recursive create/modify/rename/delete storms, directory - replacement, and simulated overflow reliably trigger `RescanRequired`. -- **VBS temporary adapter**: `Void::Build::Watch::InotifyWatcher` in - `src/Watch/Watcher.cpp`. - -## VL-004: Concrete HTTP/1.1 Server Transport (`Void::Net::HttpServer`) - -- **Target module**: `Net` (`include/Void/Net/HttpServer.hpp`) -- **Priority**: High (Plan 16 & 17 — Hosted Registry Service & Web UI) -- **Current gap**: `Void::Net::Server.hpp` provides transport-neutral `Router`, - `StaticFileResolver`, and `WebSocketSessions`, while `Void::Net::Socket.hpp` - only provides `UdpSocket`. There is no concrete TCP/HTTP server listener. -- **Requested API / behavior**: - - Concrete loopback/configurable TCP HTTP/1.1 server dispatching through - `Void::Net::Router`, supporting ephemeral port binding (`port == 0` with - `bound_port()` query), configurable header/body size limits, graceful - shutdown, and streaming request/response bodies to/from files. -- **Acceptance test**: Ephemeral-port loopback server handling concurrent - GET/PUT/POST/DELETE requests, oversized body rejection (413), and clean - shutdown without dangling sockets. -- **VBS temporary adapter**: `Void::Build::Registry::HttpServer` in - `registry/service/HttpServer.cpp`. - -## VL-005: Streaming HTTP Client & Secure TLS Default (`Void::Net::HttpClient`) - -- **Target module**: `Net` (`include/Void/Net/Http.hpp`) -- **Priority**: Medium (Plan 12 — Package Fetching) -- **Current gap**: `HttpClient::send()` buffers the entire response body in - `std::string` and defaults `m_verify_tls = false`. -- **Requested API / behavior**: - - Add streaming download-to-file (`download_to_file`) and streaming - upload-from-file (`upload_file`) with byte quotas, cancellation - (`std::stop_token`), and incremental digest/progress callbacks. - - Provide a secure constructor/preset with TLS certificate verification - enabled by default and explicit redaction of `Authorization` headers in - diagnostics. -- **Acceptance test**: Streaming multi-megabyte transfer with quota overflow - abort and TLS verification check. -- **VBS temporary adapter**: `Void::Build::Package::HttpTransfer` in - `src/Package/Fetch.cpp`. - -## VL-006: Archive Creation and Multi-Format Support (`Void::Archive`) - -- **Target module**: `Archive` (`include/Void/Archive/Archive.hpp`) -- **Priority**: Medium (Plan 12 & 15 — Source/Binary Packaging) -- **Current gap**: `Void::Archive` currently exposes only `extract()` for - `tar`/`tar.zst` and requires external `LibArchive::LibArchive`. There is no - archive creation API (`create()`), nor pure-C++ USTAR/PAX tar fallback. -- **Requested API / behavior**: - - Add deterministic `Void::Archive::create()` accepting sorted entries, - canonical mtime/uid/gid/mode metadata (for reproducible archives), and - safe extraction for `.tar`, `.tar.gz`, `.tar.zst`. -- **Acceptance test**: Deterministic archive creation (byte-identical across - runs with fixed epoch), round-trip extraction, and traversal/symlink-escape - rejection. -- **VBS temporary adapter**: `Void::Build::Package::TarArchive` (pure-C++ - deterministic PAX/USTAR tar reader/writer + optional gzip/zstd piping) in - `src/Package/Archive.cpp`. - -## VL-007: Zero-Dependency Built-In SHA-256 / BLAKE2b Fallback (`Void::Crypto`) - -- **Target module**: `Crypto` (`include/Void/Crypto/Crypto.hpp`) -- **Priority**: Medium (Plan 05, 07, 11, 12, 16) -- **Current gap**: `Void::Crypto` requires external `OpenSSL::Crypto`, which is - not installed in minimal C++ toolchain environments such as `dev cpp-gcc`. -- **Requested API / behavior**: - - Support a built-in pure-C++ FIPS 180-4 SHA-256 (and SHA-512) implementation - in `Void::Crypto` when OpenSSL is absent (or as a lightweight - `Void::CryptoHash` module without external dependencies), keeping the exact - `Void::Crypto::Hasher` API. -- **Acceptance test**: NIST CAVP SHA-256 vectors + streaming file hashing - compile and pass with zero external crypto packages. -- **VBS temporary adapter**: `Void::Build::Util::Sha256Hasher` in - `src/Util/Sha256.cpp` (with compile-time switch to `Void::Crypto::Hasher` - when `VBS_HAS_VOID_CRYPTO` is enabled). - -## VL-008: Strict UTF-8 Validation in `Void::Json::Strict` (`Void::Data`) - -- **Target module**: `Data` (`include/Void/Data/StrictJson.hpp`) -- **Priority**: Medium (Observed in V-002 review) -- **Current gap**: `Void::Json::Strict::parse()` accepts raw invalid UTF-8 - bytes (e.g. `0xff`, overlong sequences, UTF-8 encoded surrogates) inside JSON - strings instead of rejecting them per RFC 8259. -- **Requested API / behavior**: - - Validate every UTF-8 byte sequence in JSON strings and object keys during - both `parse()` and serialization (reusing `Void::Unicode::is_scalar_value` - / UTF-8 validation). -- **Acceptance test**: Reject stray continuation bytes, overlong encodings, - surrogates (`U+D800..U+DFFF`), and code points `> U+10FFFF` while preserving - all valid 1..4-byte Unicode scalars. -- **VBS temporary adapter**: `src/Util/Json.cpp` now delegates to - `Void::Unicode::validate_utf8` whenever `VBS_HAS_VOID_UNICODE` is enabled - (preserving a pure-C++ fallback for standalone SDK compilation), and - `src/Build.cpp` enforces `require_utf8()`. - -## VL-009: Native Non-CMake Test Registration API (`Void::Testing`) - -- **Target module**: `Testing` (`include/Void/Testing/Test.hpp`, - `cmake/VoidTestScanner.cmake`) -- **Priority**: High (Plan 18 — Strict Native Self-Hosting) -- **Current gap**: Test discovery currently relies on CMake running - `VoidTestScanner.cmake` at configure time to scan `.cpp` files and emit a - generated registration translation unit. Strict native self-hosting stages - cannot depend on CMake. -- **Requested API / behavior**: - - Provide either a first-class self-registering C++ macro/helper API in - `Void::Testing` (e.g. `VOID_TEST(suite, name)` with path-disambiguated - unique symbols avoiding basename collisions) or an officially supported - standalone C++ registration generator library/header contract. -- **Acceptance test**: Build and run a multi-file `Void::Testing` binary - purely with `g++` (zero CMake), verifying `--list`, `--filter`, and exact - nonzero test count even when two files share the same stem in different - subdirectories. -- **VBS temporary adapter**: Native C++ test registration generator in - `src/SelfHost/TestRegistryGen.cpp` (Plan 18). - -## VL-010: Advisory File Locks, Atomic Symlink Swap, Reflink Copy & Canonical Timestamps (`Void::FileSystem`) - -- **Target module**: `System` (`include/Void/System/Path.hpp`) -- **Priority**: Medium (Plan 05, 07, 09, 11) -- **Current gap**: `Void::FileSystem::replace_file()` covers atomic durable - regular-file replacement, but lacks: - - RAII advisory file locks (`flock` / `fcntl` shared & exclusive, blocking - and try-lock). - - Atomic symlink swap (`symlink` to temp name + `rename` + parent dir - `fsync`). - - Copy-on-write reflink copy (`ioctl(FICLONE)` with private-copy fallback, - explicitly never hardlinking). - - Canonical timestamp setter (`utimensat(..., AT_SYMLINK_NOFOLLOW)`). -- **Requested API / behavior**: Add these primitives to `Void::FileSystem` with - `Void::Result::Result` error reporting matching `replace_file()`. -- **VBS temporary adapter**: `Void::Build::Platform::FileOps` in - `src/Platform/FileOps.cpp`. - -## VL-011: Embedded/Optional SQLite & Argparse Subcommands (`Void::Sqlite`, `Void::Argparse`) - -- **Target modules**: `Sqlite`, `Configuration` -- **Priority**: Low–Medium (Plan 07, 10, 16) -- **Current gaps**: - 1. `Void::Argparse::Parser` does not natively support subcommands - (`vbs build`, `vbs compdb use`, `vbs deps resolve`) or repeatable options - (`--target a --target b`, `--profile debug --profile release`), and - reports `--help` through the error channel. - 2. `Void::Sqlite` requires system `SQLite3::SQLite3` (`find_package`) with no - optional FetchContent/amalgamation fallback when building in minimal tool - environments (`dev cpp-gcc`). -- **Requested API / behavior**: - - Add subcommand dispatch, repeatable `option_many()`, and distinct - `ParseOutcome::Help` vs `ParseOutcome::Error` in `Void::Argparse::Parser`. - - Allow optional FetchContent/amalgamation SQLite3 in - `cmake/Dependencies.cmake` (parallel to Boost) so `Void::Sqlite` works in - minimal shells. -- **VBS temporary adapter**: `src/Main.cpp`, `registry/service/Main.cpp`, - `src/Describe.cpp`, and `benchmarks/EngineBenchmarks.cpp` all delegate option - parsing and `--help` generation to `Void::Argparse::Parser` (with only thin - subcommand-dispatch and repeatable-flag extraction wrappers in `src/Main.cpp`). - `src/State/StateStore.cpp` provides a crash-safe journaled atomic-replace - backend using `Void::FileSystem::replace_file` while preserving a compile-time - `Void::Sqlite` switch when `SQLite3` is present. - -## VL-012: VoidLibrary Naming Consistency Note - -- **Observation**: Most VoidLibrary modules use `PascalCase` enums - (`Void::Crypto::HashAlgorithm::Sha256`, `Void::Sqlite::OpenMode::ReadOnly`, - `Void::Net::Method::Get`, `Void::Security::PasswordHashStrength::Moderate`) - and `snake_case` functions/methods. A few headers mix styles - (`Void::Crypto::sha256File` camelCase vs `Void::Security::hash_password` - snake_case; `Void::Process::EnvMode::inherit` snake_case vs - `Void::Sqlite::OpenMode::ReadOnly` PascalCase). VoidBuildSystem standardizes - strictly on `Void::Build` (`PascalCase` types/enums/filenames, `snake_case` - functions/methods) to align with the primary VoidLibrary style. - -## VL-013: Shorthand SemVer Range Comparators (`Void::Semver::VersionRange`) - -- **Target module**: `Text` (`include/Void/Text/Semver.hpp`) -- **Priority**: Medium (Plan 11 — Native Dependency Solver) -- **Current gap**: `Void::Semver::VersionRange::parse()` calls - `parse_strict()` on comparator/caret/tilde operands and rejects omitted minor - or patch components such as `^1`, `^1.0`, `^11.0`, `~1.2`, `>=1.2 <2`, or - `<2`. While wildcard tokens (`1.*`, `1.2.x`) are accepted, standard - Cargo/npm-style shorthand comparators fail to parse. -- **Requested API / behavior**: - - Support partial version bounds in `Void::Semver::VersionRange::parse()`: - - `^M` -> `>=M.0.0 <(M+1).0.0` (including `^0` -> `<1.0.0`) - - `^M.m` -> `^M.m.0` - - `~M` -> `>=M.0.0 <(M+1).0.0`, `~M.m` -> `~M.m.0` - - `>=M`, `>=M.m`, `=1.2 <2")`, and `parse_range("<1.2.0")` - all parse cleanly and match the expected versions. -- **VBS temporary adapter**: `parse_semver_range_compat()` in - `src/Package/Solver.cpp`. +- **`VL-004` / `VL-005` (`Void::Net`)**: `Void::Net` in VoidLibrary still requires external `Boost` + `OpenSSL` (`src/Net/module.cmake`), which are absent in minimal `dev cpp-gcc`. VBS keeps its zero-dependency POSIX loopback `HttpServer` (`registry/service/HttpServer.cpp`) and `RegistryClient` (`src/Package/RegistryClient.cpp`) until a Boost-free/minimal-dependency transport is desired or available in the base toolchain. +- **`VL-011b` (`Void::Sqlite`)**: `cmake/VoidDependency.cmake` disables network fetches during CMake configure (`VOID_FETCH_SQLITE3=OFF`) and opportunistically enables `Void::Sqlite` when system `SQLite3` is installed; `src/State/StateStore.cpp` continues providing crash-safe atomic-replace CAS persistence in minimal shells. diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index fa99df5..7e68fcb 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,8 +1,8 @@ # Development state -Updated: 2026-11-26 +Updated: 2026-11-27 Branch: main -Stage: VERIFIED — Full v1 implementation (Plans 01–19) complete, maximal VoidLibrary reuse wired, ready for commit & push +Stage: VERIFIED — Full v1 implementation (Plans 01–19) + VoidLibrary `VL-001`..`VL-013` adoption + self-building `vbs build` + live `Void::Log` progress + 100% auto-generated `Void::Argparse` CLI complete ## Completed delivery waves @@ -16,18 +16,23 @@ Stage: VERIFIED — Full v1 implementation (Plans 01–19) complete, maximal Voi - Implemented per-profile `compile_commands.json` projection with monotonic selection tickets, crash recovery, and unrelated root file preservation (`src/Editor/CompDb.cpp`). - Implemented recursive Linux `inotify` watcher (`src/Watch/Watcher.cpp`) with overflow rescan and strict `MetadataOnly` boundary vs `FullBuild`. - **Wave 3 (Plans 11–15, 18 — Packages, Foreign Providers, Bridge, Install & Self-Hosting)**: - - Implemented TOML 1.0 parser/merger (`src/Package/Toml.cpp`), PubGrub-style SemVer solver with shorthand comparator adapter (`src/Package/Solver.cpp`), context-aware atomic CAS `vbs.lock` (`src/Package/Lockfile.cpp`), deterministic PAX/USTAR `.tar` builder & safe extractor (`src/Package/Archive.cpp`), source/binary materialization (`src/Package/Fetch.cpp`). + - Implemented TOML 1.0 parser/merger (`src/Package/Toml.cpp`), PubGrub-style SemVer solver (`src/Package/Solver.cpp`), context-aware atomic CAS `vbs.lock` (`src/Package/Lockfile.cpp`), deterministic PAX/USTAR `.tar` builder & safe extractor (`src/Package/Archive.cpp`), source/binary materialization (`src/Package/Fetch.cpp`). - Implemented CMake File API & Meson introspection providers + explicit missing-tool Conan2 adapter (`src/Provider/Provider.cpp`), `cmake/bridge/VbsDeps.cmake` + `vbs bridge` (`src/Bridge/CMakeBridge.cpp`), staged relocatable install/export/uninstall (`src/Install/Installer.cpp`), native `VoidLibrary` recipe (`recipes/VoidLibrary/VoidLibraryRecipe.cpp`), and non-CMake `Void::Testing` generator (`src/SelfHost/TestRegistryGen.cpp`). - **Wave 4 (Plans 08, 16–17, 19 — Modern C++, Registry, Web UI, Benchmarks & CI)**: - Implemented P1689r5 module scanning & topological collation for GCC 16 and `clang-scan-deps`, header units, and unity batching excluding modules/per-file overrides (`src/Modules/ModuleScanner.cpp`). - Implemented `vbs-registry` HTTP/1.1 service (`registry/service/HttpServer.cpp`, `RegistryService.cpp`) with RBAC, salted password hashing, CSRF + HttpOnly SameSite cookies, immutable release 409 conflict checks, yank, redacted audit log, backup/restore, and DOM-safe web UI (`registry/web/`). - Implemented `vbs` CLI (`src/Main.cpp`), benchmark harness (`benchmarks/EngineBenchmarks.cpp`), five `Void::Testing` executables, three CMake contract scripts, and `.github/workflows/ci.yml` template. - **Wave 5 (Maximal VoidLibrary Reuse + Full Plan 08/11/12/16/18 Integration)**: - - Replaced manual CLI loops & help strings across `src/Main.cpp`, `registry/service/Main.cpp`, and `benchmarks/EngineBenchmarks.cpp` with `Void::Argparse::Parser` (``). - - Replaced hand-rolled topological sorts, hex/URL encoding, UTF-8 validation, ASCII string helpers, scope guards, stopwatches, env lookups, and worker threads with VoidLibrary modules (`Void::Algorithms::topological_order`, `Void::Encoding::Hex`/`Url`, `Void::Unicode::validate_utf8`, `Void::Str`, `Void::Scope::on_exit`, `Void::Time::Stopwatch`, `Void::Configuration::get_env`/`get_env_or`, `Void::Concurrency::ThreadPool`). + - Adopted `Void::Algorithms::topological_order`, `Void::Encoding::Hex`/`Url`, `Void::Unicode::validate_utf8`, `Void::Str`, `Void::Scope::on_exit`, `Void::Time::Stopwatch`, `Void::Configuration::get_env`/`get_env_or`, `Void::Concurrency::ThreadPool`. - Wired Plan 08 end-to-end into `Graph::lower_project_graph` (incompatible sanitizer rejection, unity batching, explicit `ActionKind::HeaderUnit`, GCC `-fmodule-mapper` & Clang two-step `.pcm` -> `.o` + transitive `-fmodule-file=` named modules & partitions) verified on BOTH GCC 16.2.0 and Clang 23.1.3. - Added live HTTP/1.1 `Package::RegistryClient` (`src/Package/RegistryClient.cpp`) + `vbs publish` + live `DependencySourceKind::Package` resolution in `vbs deps` / `vbs build` verified end-to-end against `vbs-registry`. - Added full native `recipes/SelfHost/VbsSelfHostRecipe.{hpp,cpp}` verified Stage 0 -> Stage 1 (full native `stage1/bin/vbs`, zero CMake) -> Stage 2 (`stage1/bin/vbs test` with trapped `cmake` on `PATH`). +- **Wave 6 (VoidLibrary `3e254055` Pin Bump, Upstream `VL-001`..`VL-013` Adoption, Real Self-Build, Live Logs & Generated CLI Help)**: + - Upgraded VoidLibrary pin to `3e254055e081a104f08df68dde39711bc7813518` (`Merge branch 'feat/upstream-vbs-requests' (VL-001..VL-013)`). + - Replaced local adapters with upstream VoidLibrary implementations across the board: `Void::Crypto` (`VL-007`), `Void::Archive` (`VL-006`), `Void::Data::Toml` (`VL-002`), `Void::Semver::parse_range` (`VL-013`), `Void::FileSystem::FileLock`/`reflink_copy_file`/`set_canonical_mtime`/`atomic_symlink_swap` (`VL-010`), `Void::FileSystem::DirectoryWatcher` (`VL-003`), `Void::Process::spawn`/`communicate_blocking`/`enable_subreaper` (`VL-001`), and `Void::Argparse::Parser` native subcommands + `option_many` + `parse_detailed` (`VL-011`). + - Eliminated all custom help text and manual `--help`/subcommand/repeatable-flag parsing across `src/Main.cpp`, `src/Describe.cpp`, `registry/service/Main.cpp`, and `benchmarks/EngineBenchmarks.cpp` — 100% auto-generated via `Void::Argparse::Parser`. + - Upgraded root `build.cpp` to declare the complete `VoidBuildSystem` (`VoidBuildSdk`, `VoidBuildCore`, `GenerateBootstrapConfig`, `vbs`, `VoidBuildRegistry`, `vbs-registry`), fixed snapshot root discovery (`collect_snapshot_inputs`), fixed snapshot remapping of external/build-dir dependency includes in `Graph.cpp`, fixed CMake File API provider `Void::*` alias & header-only `INTERNAL_DEPS` export + transitive link ordering in `Provider.cpp`, and verified real Stage 1 + Stage 2 self-builds of `VoidBuildSystem` via `vbs build`! + - Wired a live thread-safe `Void::Log` console sink in `src/Main.cpp` (`--verbose`/`-v`, `--quiet`/`-q`) logging every build phase (`Config`, `Toolchain`, `Eval`, `Deps`, `Fetch`, `Provider`, `Snapshot`, `Graph`, per-action `[seq/total] Compile/Archive/Link/Action ...` progress, and `Test`) with elapsed timings. ## Remaining future scope @@ -35,6 +40,6 @@ Stage: VERIFIED — Full v1 implementation (Plans 01–19) complete, maximal Voi ## Environment notes & upstream boundaries -- External VoidLibrary pin `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5` is preserved cleanly in [cmake/VoidDependency.cmake](../../cmake/VoidDependency.cmake), and VBS never writes to `/home/faumaray/Projects/VoidLibrary`. -- `dev cpp-gcc` lacks external `SQLite3`, `OpenSSL`, `LibArchive`, and `conan`; VBS runs verified pure-C++/POSIX adapters while keeping upstream adapters behind optional compile-time switches in `cmake/VoidDependency.cmake`. -- See [VERIFICATION.md](VERIFICATION.md) for all observed builds, tests, Clang 23 matrix runs, formatting checks, and benchmark results. +- External VoidLibrary pin `3e254055e081a104f08df68dde39711bc7813518` is set in [CMakeLists.txt](../../CMakeLists.txt), [cmake/VoidDependency.cmake](../../cmake/VoidDependency.cmake), and [build.cpp](../../build.cpp). VBS never writes to `/home/faumaray/Projects/VoidLibrary`. +- `Void::Crypto` and `Void::Archive` now build unconditionally with zero external dependencies in `dev cpp-gcc`; only `SQLite3`, `Boost`/`OpenSSL` (`Void::Net`), and `conan` remain optional external prerequisites. +- See [VERIFICATION.md](VERIFICATION.md) for all observed builds, tests, Clang 23 matrix runs, formatting checks, benchmark results, and real self-build verification. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index c79cb13..214ce83 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -1,7 +1,7 @@ # Task graph and ownership -Updated: 2026-11-26 -Base HEAD: `3cac890ce9b8a0681130a58601e0516231471ad8` +Updated: 2026-11-27 +Base HEAD: `ab64147` | Wave | Scope | Status | Primary Deliverables | | --- | --- | --- | --- | @@ -12,4 +12,5 @@ Base HEAD: `3cac890ce9b8a0681130a58601e0516231471ad8` | Wave 3 (Plans 11–15, 18) | TOML 1.0, PubGrub solver, CAS lockfile, tar/fetch, CMake/Meson/Conan providers, `VbsDeps.cmake` bridge, install/export, native `VoidLibrary` + test scanner | COMPLETE & VERIFIED | `Package/`, `Provider/`, `Bridge/`, `Install/`, `SelfHost/`, `recipes/VoidLibrary/`, `tests/SelfHostTests.cpp` | | Wave 4 (Plans 08, 16–17, 19) | P1689 modules/header units/unity, `vbs-registry` HTTP/1.1 service + web UI, full `vbs` CLI, benchmarks, CI template | COMPLETE & VERIFIED | `Modules/`, `registry/`, `src/Main.cpp`, `benchmarks/`, `.github/workflows/ci.yml`, `tests/RegistryTests.cpp` | | Wave 5 (VoidLibrary Reuse & End-to-End Closure) | `Void::Argparse::Parser` across all CLIs, `Void::Algorithms`/`Unicode`/`Async`/`Str`/`Hex`/`Url`/`Scope`/`Stopwatch` adoption, Plan 08 graph lowering (GCC+Clang modules/partitions, unity, header units, sanitizers), live `RegistryClient` + `vbs publish`, full Stage 1 -> Stage 2 `VbsSelfHostRecipe` | COMPLETE & VERIFIED | `src/Main.cpp`, `src/Graph/Graph.cpp`, `src/Package/RegistryClient.cpp`, `recipes/SelfHost/VbsSelfHostRecipe.cpp`, expanded test suites | +| Wave 6 (Upstream `VL-001`..`VL-013` Pin Bump, Self-Building `vbs build`, Live Logs & Generated CLI Help) | Bump VoidLibrary pin to `3e254055e081a104f08df68dde39711bc7813518`; adopt `Void::Crypto`, `Void::Archive`, `Void::Data::Toml`, `Void::Semver::parse_range`, `Void::FileSystem::FileLock`/`DirectoryWatcher`/`reflink_copy_file`/`atomic_symlink_swap`/`set_canonical_mtime`, `Void::Process`, `Void::Argparse::Parser` subcommands + `option_many` + `parse_detailed`; full self-building root `build.cpp`; live `Void::Log` console progress | COMPLETE & VERIFIED | `CMakeLists.txt`, `cmake/VoidDependency.cmake`, `build.cpp`, `src/Main.cpp`, `src/Describe.cpp`, `registry/service/Main.cpp`, `benchmarks/EngineBenchmarks.cpp`, `src/Util/Sha256.cpp`, `src/Package/{Toml,Solver,Archive,Fetch}.cpp`, `src/Platform/{FileOps,ProcessSupervisor}.cpp`, `src/Watch/Watcher.cpp`, `src/Provider/Provider.cpp`, `src/Graph/Graph.cpp`, `src/Execution/Scheduler.cpp`, `recipes/`, updated contracts & docs | | Future (Plan 20) | Native foreign build translation & Windows/macOS ports | PLANNED (unimplemented) | [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index a84ddef..c858107 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -1,20 +1,20 @@ # Verification record -Updated: 2026-11-26 +Updated: 2026-11-27 Working directory: `/home/faumaray/Projects/VoidBuildSystem` All checks below were executed after the final C++ edits and formatting pass. Planned/non-executed items are separated explicitly under **Limits and Unrun Checks**. ## Toolchain & Dependency Integrity -- Configure baseline (`build/dev`): Ninja Debug C++26 (`-DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`) pointing at workspace-local fetched pin `build/bootstrap-pinned/_deps/voidlibrary-src` (`modules=13`, enabling `Void::Algorithms`, `Void::Async`, `Void::Configuration`, `Void::Text`, `Void::Unicode`, `Void::Testing`, and core dependencies). +- Configure baseline (`build/dev`): Ninja Debug C++26 (`-DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`) against clean detached checkout of VoidLibrary pin `3e254055e081a104f08df68dde39711bc7813518` (`modules=15`, enabling `Void::Algorithms`, `Void::Archive`, `Void::Async`, `Void::Configuration`, `Void::Crypto`, `Void::Text`, `Void::Unicode`, `Void::Testing`, and core dependencies with zero external crypto/archive libraries). - Build command: ```sh dev cpp-gcc -c cmake --build build/dev --parallel 4 ``` - - Exit status: `0` (all library targets `VoidBuild_Sdk`, `VoidBuild_Core`, `VoidBuild_Registry`, binaries `vbs`, `vbs-registry`, `vbs_describe`, `vbs_benchmarks`, and 5 `Void::Testing` executables compiled and linked with zero warnings in VBS-owned code; upstream `Void::Testing` headers still emit `-Wmissing-field-initializers`). + - Exit status: `0` (all library targets `VoidBuild_Sdk`, `VoidBuild_Core`, `VoidBuild_Registry`, binaries `vbs`, `vbs-registry`, `vbs_describe`, `vbs_benchmarks`, and 5 `Void::Testing` executables compiled and linked cleanly). - Pin checks: - - `git -C build/bootstrap-pinned/_deps/voidlibrary-src rev-parse HEAD` -> `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5` (exit `0`). + - Detached VoidLibrary checkout `HEAD` == `3e254055e081a104f08df68dde39711bc7813518` (`Merge branch 'feat/upstream-vbs-requests' (VL-001..VL-013)`). - VBS made zero writes to `/home/faumaray/Projects/VoidLibrary`. ## Formatting Check @@ -34,28 +34,47 @@ dev cpp-gcc -c clang-format --dry-run --Werror \ ## CTest Suite Results (`dev cpp-gcc`) ```sh -dev cpp-gcc -c ctest --test-dir build/dev --verbose +dev cpp-gcc -c ctest --test-dir build/dev --output-on-failure ``` -- Exit status: `0` — **8 / 8 passed (100%) in 62.92 sec**: +- Exit status: `0` — **8 / 8 passed (100%) in 85.66 sec**: -| # | CTest Name | Exact Runner Output / Scope Verified | Result | Time | +| # | CTest Name | Scope Verified | Result | Time | | --- | --- | --- | --- | --- | -| 1 | `vbs_sdk_tests` | `17 tests: 17 ✔ in 6.5ms` (`SdkDeclarations` 14 + `ExampleContexts` 3, using `Void::Unicode::validate_utf8`) | Passed | 0.01s | -| 2 | `vbs_core_tests` | `6 tests: 6 ✔ in 11.29s`: SHA-256 NIST vectors (`Void::Encoding::Hex`), `ProcessSupervisor` exec-fail & grandchild `SIGKILL`, profile inheritance/cycles, snapshot mutation/symlinks/header-shadowing, CAS corruption/recovery/GC, end-to-end native frontend + deterministic build + `Void::Algorithms::topological_order` + `Void::Concurrency::ThreadPool` + deleted archive symbol removal | Passed | 11.30s | -| 3 | `vbs_v1_tests` | `8 tests: 8 ✔ in 11.22s`: CompDB ticket races/user-file preservation/recovery, `inotify` watcher + `MetadataOnly` boundary, TOML 1.0/PubGrub solver/CAS `vbs.lock`, PAX/USTAR `.tar` determinism/traversal/symlink rejection/binary ABI/secret redaction, real CMake & Meson providers + `VbsDeps.cmake` bridge + relocatable install + CLI `vbs install`/`vbs uninstall`, GCC 16 P1689 module scan/collation/execution + cycle/dup checks + unity exclusion, Clang check, AND full `Graph::lower_project_graph` Plan 08 integration (incompatible ASan+TSan rejection, GCC 16 module partition + primary interface + consumer, unity batching + per-file-option exclusion, explicit `ActionKind::HeaderUnit` build & import) | Passed | 11.22s | -| 4 | `vbs_registry_tests` | `2 tests: 2 ✔ in 3.06s`: (1) HTTP/1.1 loopback server, security headers (`CSP`, `X-Frame-Options: DENY`), path-traversal 403, RBAC 403/401, SHA-256 mismatch 400, tar validation 422, immutable release 409 conflict, CSRF 403 & HttpOnly SameSite=Strict session cookie, XSS-safe private UI/API, secret-free audit log, backup & restore; (2) full live CLI E2E `vbs publish` (`1.0.0` & `1.1.0`) -> `vbs deps resolve` -> `vbs build --locked` -> consumer execution against ephemeral `vbs-registry` with zero token leak in `vbs.lock` | Passed | 3.06s | -| 5 | `vbs_selfhost_tests` | `3 tests: 3 ✔ in 37.26s`: (1) basename-collision-safe native `Void::Testing` scanner (`vbs gen-tests`); (2) strict non-CMake native `VoidLibrary` + `VoidBuildSdk` + `stage1_sdk_tests` -> Stage 2 SDK consumer; (3) full Stage 0 -> Stage 1 native `VbsSelfHostRecipe` building the complete `stage1/bin/vbs` CLI binary (native `VoidLibrary` closure + `VoidBuildSdk` + `VoidBuildCore` + stage-isolated `BootstrapConfig.hpp`, zero CMake) -> Stage 2 executing `stage1/bin/vbs test` with trapped `cmake` on `PATH` | Passed | 37.27s | -| 6 | `vbs_sdk_registration` | `17 SDK test registrations verified; named JSON case executed` | Passed | 0.01s | -| 7 | `vbs_cli_contract` | `23 native CLI contracts verified` (all `Void::Argparse::Parser`-backed `vbs` commands including `vbs publish` + `vbs-registry --help`) | Passed | 0.03s | -| 8 | `vbs_description_contract` | `Four runtime profile/compiler contexts and six error contracts verified` (`debug`/`release` x `gcc`/`clang` JSON + CLI errors) | Passed | 0.02s | +| 1 | `vbs_sdk_tests` | 17 tests (`SdkDeclarations` 14 + `ExampleContexts` 3 for 6-target self-building `build.cpp` and pin `3e254055...`) | Passed | 0.01s | +| 2 | `vbs_core_tests` | 6 tests: `Void::Crypto` SHA-256 NIST vectors, `Void::Process` exec-fail & stubborn grandchild `SIGKILL`, profile inheritance/cycles, snapshot mutation/symlinks/header-shadowing (`Void::FileSystem` `reflink_copy_file`/`FileLock`/`set_canonical_mtime`), CAS recovery/GC, end-to-end native frontend + deterministic build | Passed | 11.34s | +| 3 | `vbs_v1_tests` | 8 tests: CompDB ticket races & `atomic_symlink_swap`, `Void::FileSystem::DirectoryWatcher` + `MetadataOnly` boundary, `Void::Data::Toml` + `Void::Semver::parse_range` PubGrub solver + CAS `vbs.lock`, `Void::Archive` `.tar` determinism & traversal/symlink/duplicate rejection, real CMake & Meson providers + `VbsDeps.cmake` bridge + relocatable install + CLI `vbs install`/`vbs uninstall`, GCC 16 P1689 modules + full Plan 08 graph integration (sanitizers, partitions, unity, header units) | Passed | 11.13s | +| 4 | `vbs_registry_tests` | 2 tests: `vbs-registry` HTTP/1.1 security/RBAC/CSRF/XSS/tar-422/backup-restore + full live CLI E2E `vbs publish` -> `vbs deps resolve` -> `vbs build --locked` | Passed | 3.98s | +| 5 | `vbs_selfhost_tests` | 3 tests: basename-collision-safe `vbs gen-tests`, strict non-CMake native `VoidLibrary` (including `Crypto` + `Archive`) + `VoidBuildSdk` + Stage 2, and full Stage 0 -> Stage 1 native `VbsSelfHostRecipe` (`stage1/bin/vbs`, zero CMake) -> Stage 2 `stage1/bin/vbs test` with trapped `cmake` on `PATH` | Passed | 59.12s | +| 6 | `vbs_sdk_registration` | 17 SDK test registrations verified; named JSON case executed | Passed | 0.01s | +| 7 | `vbs_cli_contract` | 27 native CLI & auto-generated `Void::Argparse::Parser` help/subcommand/error contracts verified (`vbs`, `vbs-registry`, `compdb`, `deps`, `build`, `install`, `publish`, etc.) | Passed | 0.04s | +| 8 | `vbs_description_contract` | Four runtime profile/compiler contexts (`debug`/`release` x `gcc`/`clang` for 6-target `build.cpp`), auto-generated `vbs_describe --help`, and five error contracts verified | Passed | 0.03s | + +## Real Self-Build of VoidBuildSystem (`vbs build`) + +### Stage 1: Bootstrap `vbs` builds complete `VoidBuildSystem` from root `build.cpp` +```sh +VBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidBuildSystem/build/voidlibrary-pinned \ + dev cpp-gcc -c build/dev/bin/vbs build --build-dir build/vbs-self --jobs 4 +``` +- Exit status: `0` — **`vbs: [debug] built (36 executed, 0 cached)`** in `38.79s`. +- Live progress logs verified cleanly across all phases: `[Config]`, `[Toolchain]`, `[Eval]` (`6 target(s), 1 dependenc(ies)`), `[Deps]`, `[Fetch]`, `[Provider]` (`Imported 100 target(s) from 'VoidLibrary'`), `[Snapshot]` (`70 file(s)`), `[Graph]` (`36 action(s)`), and per-action `[ 1/36] Action GenerateBootstrapConfig` .. `[35/36] Link build/vbs-self/profiles/debug/out/bin/vbs` & `[36/36] Link build/vbs-self/profiles/debug/out/bin/vbs-registry`. + +### Stage 2: Self-built `vbs` verifies cached build & auto-generated CLI +```sh +VBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidBuildSystem/build/voidlibrary-pinned \ + dev cpp-gcc -c build/vbs-self/profiles/debug/out/bin/vbs build --build-dir build/vbs-self --jobs 4 +build/vbs-self/profiles/debug/out/bin/vbs --version +build/vbs-self/profiles/debug/out/bin/vbs --help +``` +- Exit status: `0` — **`vbs: [debug] built (0 executed, 36 cached)`**, `vbs 0.1.0`, and full auto-generated `Void::Argparse::Parser` root help output (`Usage: vbs [--version] [--verbose] [--quiet] `). ## Clang 23.1.3 Target Matrix (`dev cpp`) ```sh dev cpp -c build/dev/bin/vbs_v1_tests --no-color --filter clang23 ``` -- Exit status: `0` — `1 tests: 1 ✔ in 751.7ms` (`clang23_target_toolchain_and_p1689_module_scan`). -- Verified inside `dev cpp`: `Toolchain::discover_and_probe` discovers Clang 23.1.3 + `clang-scan-deps`, compiles/links/runs a `#ifdef __clang__` C++20 binary, AND executes a full `Graph::lower_project_graph` + `Execution::execute_graph` build of a module partition (`vbs.clangcalc:part`) + primary interface (`vbs.clangcalc`) + consumer `main.cpp` using `clang-scan-deps --format=p1689`, two-step `--precompile` `.pcm` (`ActionKind::ModuleBmi`) -> `.o` with transitive `-fmodule-file=`, linking, and exit code 0! +- Exit status: `0` — `1 tests: 1 ✔ in 745.2ms` (`clang23_target_toolchain_and_p1689_module_scan`). +- Verified inside `dev cpp`: Clang 23.1.3 + `clang-scan-deps` target probing, C++20 compilation, and full `Graph::lower_project_graph` + `Execution::execute_graph` build of module partition (`vbs.clangcalc:part`) + primary interface (`vbs.clangcalc`) + consumer `main.cpp` using two-step `--precompile` `.pcm` -> `.o` with transitive `-fmodule-file=`. ## Benchmarks (`dev cpp-gcc`) @@ -64,12 +83,13 @@ dev cpp-gcc -c build/dev/bin/vbs_benchmarks --files 15 ``` - Exit status: `0`: ```json - {"fixture_files":16,"compiler":"g++ (GCC) 16.2.0","snapshot_ms":18,"cold_build_ms":349,"cold_executed":17,"warm_noop_ms":11,"warm_executed":0,"warm_cached":17} + {"fixture_files":16,"compiler":"g++ (GCC) 16.2.0","snapshot_ms":17,"cold_build_ms":350,"cold_executed":17,"warm_noop_ms":16,"warm_executed":0,"warm_cached":17} ``` ## Limits and Unrun Checks -1. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified that `Provider::resolve_foreign_provider` fails explicitly with a missing-prerequisite error when `conan` is absent (`FullV1Tests.cpp`). -2. **External optional VoidLibrary modules**: `SQLite3`, `OpenSSL`, `LibArchive`, and `libsodium` are not present in `dev cpp-gcc`, so VBS built and tested its pure-C++/POSIX adapters (`StateStore`, `Sha256Hasher`, `TarArchive`, `HttpServer`, `RegistryClient`); the optional CMake switches (`VBS_HAS_VOID_SQLITE`, `VBS_HAS_VOID_CRYPTO`, `VBS_HAS_VOID_ARCHIVE`) remain ready for environments providing them. -3. **CI workflow & Web UI browser**: [.github/workflows/ci.yml](../../.github/workflows/ci.yml) has not been executed on remote GitHub Actions runners, and `registry/web/` was verified via HTTP/header/static-serving/API/XSS/CSRF tests without a headless browser runner. -4. **Plan 20 ([20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Native foreign graph translation and non-Linux OS ports (Windows/macOS) remain unimplemented planned scope. +1. **HTTPS git fetch in proxy-restricted environment**: Inside this execution environment, outbound HTTPS to `https://git.faumaray.com/Void/VoidLibrary.git` encountered `Proxy CONNECT aborted`; CMake configure and `vbs build` were therefore verified against a clean local detached checkout of the exact pinned commit `3e254055e081a104f08df68dde39711bc7813518` via `VBS_VOID_SOURCE_DIR`. +2. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified explicit missing-prerequisite failure (`FullV1Tests.cpp`). +3. **Optional external VoidLibrary modules (`Void::Net`, `Void::Sqlite`)**: `Boost`, `OpenSSL`, and `SQLite3` are not installed in `dev cpp-gcc`, so VBS continues using its pure-C++/POSIX loopback HTTP adapters (`HttpServer`, `RegistryClient`) and journaled atomic CAS store (`StateStore`), while retaining optional `Void::Sqlite` CMake detection. +4. **CI workflow & Web UI browser**: [.github/workflows/ci.yml](../../.github/workflows/ci.yml) has not been executed on remote GitHub Actions runners, and `registry/web/` was verified via HTTP/header/static-serving/API/XSS/CSRF tests without a headless browser runner. +5. **Plan 20 ([20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Native foreign graph translation and non-Linux OS ports (Windows/macOS) remain unimplemented planned scope. diff --git a/include/Void/Build/Execution/Scheduler.hpp b/include/Void/Build/Execution/Scheduler.hpp index 8f8a681..ac4510b 100644 --- a/include/Void/Build/Execution/Scheduler.hpp +++ b/include/Void/Build/Execution/Scheduler.hpp @@ -35,8 +35,10 @@ struct ExecutionEvent { Kind kind{Kind::ActionStarted}; std::string action_id; std::string target_name; + std::string label; std::size_t completed{0}; std::size_t total{0}; + std::chrono::milliseconds elapsed{0}; std::string message; }; diff --git a/include/Void/Build/Platform/FileOps.hpp b/include/Void/Build/Platform/FileOps.hpp index e3b3fe4..f0e490e 100644 --- a/include/Void/Build/Platform/FileOps.hpp +++ b/include/Void/Build/Platform/FileOps.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -15,27 +16,27 @@ namespace Void::Build::Platform { enum class LockMode { Shared, Exclusive }; -// RAII advisory flock lock (VL-010). +// RAII advisory flock lock delegating directly to Void::FileSystem::FileLock (VL-010). class FileLock { public: FileLock() noexcept = default; - ~FileLock() noexcept; + ~FileLock() noexcept = default; FileLock(const FileLock &) = delete; FileLock &operator=(const FileLock &) = delete; - FileLock(FileLock &&other) noexcept; - FileLock &operator=(FileLock &&other) noexcept; + FileLock(FileLock &&other) noexcept = default; + FileLock &operator=(FileLock &&other) noexcept = default; [[nodiscard]] static Void::Result::Result acquire(const std::filesystem::path &lock_path, LockMode mode = LockMode::Exclusive, bool non_blocking = false); - [[nodiscard]] bool valid() const noexcept { return fd_ >= 0; } - void release() noexcept; + [[nodiscard]] bool valid() const noexcept { return lock_.locked(); } + void release() noexcept { lock_.unlock(); } private: - explicit FileLock(int fd) noexcept : fd_{fd} {} - int fd_{-1}; + explicit FileLock(Void::FileSystem::FileLock lock) noexcept : lock_{std::move(lock)} {} + Void::FileSystem::FileLock lock_; }; struct FileMetadata { @@ -57,13 +58,13 @@ struct FileMetadata { [[nodiscard]] Void::Result::Result stat_lstat(const std::filesystem::path &path); -// Private isolated file copy: tries Linux FICLONE reflink, falls back to byte copy. +// Private isolated file copy delegating to Void::FileSystem::reflink_copy_file (VL-010). // NEVER creates hardlinks. Guarantees distinct inode and nlink == 1 on destination. [[nodiscard]] Void::Result::Result copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst, std::optional mode_override = std::nullopt); -// Canonicalizes mtime/atime via utimensat(..., AT_SYMLINK_NOFOLLOW). +// Canonicalizes mtime/atime via Void::FileSystem::set_canonical_mtime (VL-010). [[nodiscard]] Void::Result::Result set_canonical_mtime(const std::filesystem::path &path, std::int64_t epoch_seconds); @@ -75,7 +76,7 @@ atomic_write_file(const std::filesystem::path &path, std::string_view content, atomic_write_bytes(const std::filesystem::path &path, std::span bytes, bool durable_sync = true, unsigned mode = 0644); -// Atomically replaces symlink at `link_path` pointing to `target` + parent fsync. +// Atomically replaces symlink via Void::FileSystem::atomic_symlink_swap (VL-010). [[nodiscard]] Void::Result::Result atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesystem::path &target); diff --git a/include/Void/Build/Util/Sha256.hpp b/include/Void/Build/Util/Sha256.hpp index 1ddf080..b0a09e8 100644 --- a/include/Void/Build/Util/Sha256.hpp +++ b/include/Void/Build/Util/Sha256.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -7,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -15,11 +17,10 @@ namespace Void::Build::Util { using Sha256Digest = std::array; -// Streaming FIPS 180-4 SHA-256 hasher (VL-007: delegates to Void::Crypto when -// OpenSSL is available; provides zero-dependency built-in fallback otherwise). +// Streaming FIPS 180-4 SHA-256 hasher backed directly by Void::Crypto::Hasher (VL-007). class Sha256Hasher { public: - Sha256Hasher() noexcept; + Sha256Hasher(); void update(std::span data) noexcept; void update(std::span data) noexcept; @@ -31,12 +32,8 @@ class Sha256Hasher { [[nodiscard]] std::string finalize_hex() noexcept; private: - void transform(const std::uint8_t block[64]) noexcept; - - std::uint32_t state_[8]; - std::uint64_t bit_count_{0}; - std::uint8_t buffer_[64]{}; - std::size_t buffer_len_{0}; + std::optional hasher_; + Sha256Digest cached_digest_{}; bool finalized_{false}; }; diff --git a/include/Void/Build/Watch/Watcher.hpp b/include/Void/Build/Watch/Watcher.hpp index 92360ea..ec55ce6 100644 --- a/include/Void/Build/Watch/Watcher.hpp +++ b/include/Void/Build/Watch/Watcher.hpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -27,18 +28,17 @@ struct WatchBatch { bool rescan_required{false}; }; -// Linux inotify recursive directory watcher (VL-003). -// Automatically excludes build/cache/VCS trees to prevent feedback loops, attaches watches -// to newly created subdirectories, and reports IN_Q_OVERFLOW as rescan_required. +// Linux inotify recursive directory watcher delegating directly to +// Void::FileSystem::DirectoryWatcher (VL-003). class InotifyWatcher { public: InotifyWatcher() = default; - ~InotifyWatcher() noexcept; + ~InotifyWatcher() noexcept = default; InotifyWatcher(const InotifyWatcher &) = delete; InotifyWatcher &operator=(const InotifyWatcher &) = delete; - InotifyWatcher(InotifyWatcher &&other) noexcept; - InotifyWatcher &operator=(InotifyWatcher &&other) noexcept; + InotifyWatcher(InotifyWatcher &&other) noexcept = default; + InotifyWatcher &operator=(InotifyWatcher &&other) noexcept = default; [[nodiscard]] static Void::Result::Result create(const std::filesystem::path &root_dir, @@ -54,19 +54,14 @@ class InotifyWatcher { [[nodiscard]] Void::Result::Result rescan_watches(); [[nodiscard]] std::size_t watched_directory_count() const noexcept { - return wd_to_path_.size(); + return watcher_ ? watcher_->watch_count() : 0; } private: - explicit InotifyWatcher(int fd, std::filesystem::path root, std::vector excluded); - void close_fd() noexcept; - Void::Result::Result watch_tree(const std::filesystem::path &dir); - bool is_excluded(const std::filesystem::path &rel) const; + explicit InotifyWatcher(Void::FileSystem::DirectoryWatcher watcher) noexcept + : watcher_{std::move(watcher)} {} - int fd_{-1}; - std::filesystem::path root_; - std::vector excluded_; - std::map wd_to_path_; + std::optional watcher_; }; enum class WatchMode { FullBuild, MetadataOnly }; diff --git a/recipes/SelfHost/VbsSelfHostRecipe.cpp b/recipes/SelfHost/VbsSelfHostRecipe.cpp index 5ab7742..d56eceb 100644 --- a/recipes/SelfHost/VbsSelfHostRecipe.cpp +++ b/recipes/SelfHost/VbsSelfHostRecipe.cpp @@ -38,8 +38,8 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) { } // 2. Declare the native VoidLibrary module closure (pure C++26, zero CMake). - std::vector void_mods = {"Configuration", "Text", "Unicode", "Async", - "Algorithms"}; + std::vector void_mods = {"Configuration", "Text", "Unicode", "Async", + "Algorithms", "Crypto", "Archive"}; if (config.include_tests) { void_mods.push_back("Testing"); } @@ -63,12 +63,16 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) { .include_directory((root / "include").string(), Visibility::Public) .include_directory((root / "recipes").string(), Visibility::Public) .compile_option("-freflection", Visibility::Public) + .define("VBS_HAS_VOID_CRYPTO=1", Visibility::Public) + .define("VBS_HAS_VOID_ARCHIVE=1", Visibility::Public) .link(sdk, Visibility::Public) .link(void_libs.modules.at("Configuration"), Visibility::Public) .link(void_libs.modules.at("Text"), Visibility::Public) .link(void_libs.modules.at("Unicode"), Visibility::Public) .link(void_libs.modules.at("Async"), Visibility::Public) - .link(void_libs.modules.at("Algorithms"), Visibility::Public); + .link(void_libs.modules.at("Algorithms"), Visibility::Public) + .link(void_libs.modules.at("Crypto"), Visibility::Public) + .link(void_libs.modules.at("Archive"), Visibility::Public); const std::vector core_sources = { "src/Util/Sha256.cpp", diff --git a/recipes/VoidLibrary/VoidLibraryRecipe.cpp b/recipes/VoidLibrary/VoidLibraryRecipe.cpp index 1d8348d..ed2eee4 100644 --- a/recipes/VoidLibrary/VoidLibraryRecipe.cpp +++ b/recipes/VoidLibrary/VoidLibraryRecipe.cpp @@ -28,6 +28,8 @@ const std::map> &known_modules() { {"Data", {{"Core", "Math", "Time"}, false}}, {"System", {{"Functional", "Time", "LogState"}, true}}, {"Async", {{"Functional", "Time", "LogState"}, true}}, + {"Crypto", {{"Functional"}, false}}, + {"Archive", {{"Functional", "Time", "System"}, false}}, {"Configuration", {{"Core", "Functional", "System", "Data", "Time", "LogState"}, true}}, {"Testing", {{"Core", "Functional", "Time", "LogState", "Configuration", "Text"}, true}}, }; @@ -100,6 +102,12 @@ VoidLibraryTargets add_void_library_native(Project &project, if (def.needs_threads) { tgt.link_option("-pthread", Visibility::Public); } + if (mod == "Crypto") { + tgt.define("VOID_CRYPTO_HAS_OPENSSL=0", Visibility::Public); + } + if (mod == "Archive") { + tgt.define("VOID_ARCHIVE_HAS_LIBARCHIVE=0", Visibility::Public); + } if (mod == "Testing") { tgt.define("VOID_HAS_CONFIGURATION", Visibility::Public) .define("VOID_HAS_TEXT", Visibility::Public); diff --git a/registry/service/Main.cpp b/registry/service/Main.cpp index 0e8185f..c717c16 100644 --- a/registry/service/Main.cpp +++ b/registry/service/Main.cpp @@ -8,7 +8,6 @@ #include #include #include -#include int main(int argc, char **argv) { std::string data_dir; @@ -34,19 +33,13 @@ int main(int argc, char **argv) { "environment variable holding bootstrap admin password", pass_env, "VBS_REGISTRY_ADMIN_PASSWORD"); - if (argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h")) { - std::cout << parser.help(); + const auto parsed = parser.parse_detailed(argc, argv); + if (parsed.is_help()) { + std::cout << parsed.message; return 0; } - for (int i = 1; i < argc; ++i) { - if (std::string_view{argv[i]} == "--help" || std::string_view{argv[i]} == "-h") { - std::cerr << "vbs-registry: --help must be used alone\n"; - return 2; - } - } - - if (auto parsed = parser.parse(argc, argv); !parsed) { - std::cerr << "vbs-registry: " << parsed.error() << '\n'; + if (parsed.is_error()) { + std::cerr << "vbs-registry: " << parsed.message << '\n'; return 2; } diff --git a/src/Describe.cpp b/src/Describe.cpp index 4f21322..92ea7be 100644 --- a/src/Describe.cpp +++ b/src/Describe.cpp @@ -12,22 +12,17 @@ int main(int argc, char **argv) { "Evaluate the compiled example description; no target compiler is invoked."}; parser.option_default("--profile", "", "profile: debug or release", profile, "debug") .option_default("--compiler", "", "target compiler context: gcc or clang", compiler, "gcc"); - if (argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h")) { - std::cout << parser.help(); + + const auto parsed = parser.parse_detailed(argc, argv); + if (parsed.is_help()) { + std::cout << parsed.message; return 0; } - // Help is deliberately successful only as a standalone request. - for (int i = 1; i < argc; ++i) { - if (std::string_view{argv[i]} == "--help" || std::string_view{argv[i]} == "-h") { - std::cerr << "vbs_describe: --help must be used alone\n"; - return 2; - } - } - const auto parsed = parser.parse(argc, argv); - if (!parsed) { - std::cerr << "vbs_describe: " << parsed.error() << '\n'; + if (parsed.is_error()) { + std::cerr << "vbs_describe: " << parsed.message << '\n'; return 2; } + try { Void::Build::Profiles descriptions; profiles(descriptions); diff --git a/src/Execution/Scheduler.cpp b/src/Execution/Scheduler.cpp index f2fd607..f67f546 100644 --- a/src/Execution/Scheduler.cpp +++ b/src/Execution/Scheduler.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -266,17 +267,53 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, std::size_t active_workers = 0; std::size_t completed_count = 0; + std::atomic started_exec_count{0}; bool abort_scheduling = false; + auto action_label = [&](const Graph::ActionNode &act) -> std::string { + auto rel_name = [&](const std::filesystem::path &p) -> std::string { + if (p.empty()) { + return act.target_name; + } + if (!graph.project_root.empty() && Platform::path_is_within(graph.project_root, p)) { + return p.lexically_relative(graph.project_root).generic_string(); + } + return p.filename().string(); + }; + switch (act.kind) { + case Graph::ActionKind::Compile: + return std::format("Compile {}", rel_name(!act.logical_source_file.empty() + ? act.logical_source_file + : act.logical_output_file)); + case Graph::ActionKind::PrecompiledHeader: + return std::format("PCH {}", rel_name(act.logical_source_file)); + case Graph::ActionKind::HeaderUnit: + return std::format("HdrUnit {}", rel_name(act.logical_source_file)); + case Graph::ActionKind::ModuleScan: + return std::format("ModScan {}", rel_name(act.logical_source_file)); + case Graph::ActionKind::ModuleBmi: + return std::format("BMI {}", rel_name(act.logical_source_file)); + case Graph::ActionKind::Archive: + return std::format("Archive {}", rel_name(act.logical_output_file)); + case Graph::ActionKind::Link: + return std::format("Link {}", rel_name(act.logical_output_file)); + case Graph::ActionKind::Custom: + return std::format("Action {}", act.target_name); + } + return act.id; + }; + auto emit_event = [&](ExecutionEvent::Kind kind, const Graph::ActionNode &act, - std::size_t completed, std::string msg = {}) { + const std::string &label, std::size_t completed, + std::chrono::milliseconds elapsed = {}, std::string msg = {}) { if (options.on_event) { - options.on_event(ExecutionEvent{kind, act.id, act.target_name, completed, - selected_indices.size(), std::move(msg)}); + options.on_event(ExecutionEvent{kind, act.id, act.target_name, label, completed, + selected_indices.size(), elapsed, std::move(msg)}); } }; - auto run_one_action = [&](const Graph::ActionNode &act) -> ActionExecutionResult { + auto run_one_action = [&](const Graph::ActionNode &act, + const std::string &label) -> ActionExecutionResult { const auto timer = Void::Time::Stopwatch::started(); ActionExecutionResult res; res.action_id = act.id; @@ -308,6 +345,10 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, } } + const std::size_t seq = started_exec_count.fetch_add(1, std::memory_order_relaxed) + 1; + Void::Log::info("Build", "[{:>2}/{}] {}", seq, selected_indices.size(), label); + emit_event(ExecutionEvent::Kind::ActionStarted, act, label, seq); + // 2. Prepare output directories and response file. std::error_code ec; for (const auto &out : act.declared_outputs) { @@ -477,8 +518,8 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, } const auto &act = graph.actions[idx]; - emit_event(ExecutionEvent::Kind::ActionStarted, act, completed_count); - auto ares = run_one_action(act); + const std::string label = action_label(act); + auto ares = run_one_action(act, label); { std::lock_guard lk{mu}; @@ -487,10 +528,14 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, if (ares.succeeded) { if (ares.from_cache) { ++report.cached_count; - emit_event(ExecutionEvent::Kind::ActionCached, act, completed_count); + Void::Log::debug("Build", "[cached] {}", label); + emit_event(ExecutionEvent::Kind::ActionCached, act, label, completed_count, + ares.elapsed); } else { ++report.executed_count; - emit_event(ExecutionEvent::Kind::ActionSucceeded, act, completed_count); + Void::Log::debug("Build", "Done {} ({}ms)", label, ares.elapsed.count()); + emit_event(ExecutionEvent::Kind::ActionSucceeded, act, label, + completed_count, ares.elapsed); } for (const std::size_t dep_idx : dependents[idx]) { if (--in_degree[dep_idx] == 0) { @@ -505,8 +550,10 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, if (report.diagnostic.empty()) { report.diagnostic = act.id + ": " + ares.error_message; } - emit_event(ExecutionEvent::Kind::ActionFailed, act, completed_count, - ares.error_message); + Void::Log::error("Build", "FAILED {} ({}): {}", label, act.id, + ares.error_message); + emit_event(ExecutionEvent::Kind::ActionFailed, act, label, completed_count, + ares.elapsed, ares.error_message); if (options.fail_fast) { abort_scheduling = true; internal_stop.request_stop(); diff --git a/src/Graph/Graph.cpp b/src/Graph/Graph.cpp index 5df7e15..b74f7dd 100644 --- a/src/Graph/Graph.cpp +++ b/src/Graph/Graph.cpp @@ -565,8 +565,9 @@ lower_project_graph(const ProjectDescription &description, graph.toolchain = toolchain; graph.profile_identity = Toolchain::compute_profile_identity(description.profile, toolchain); graph.project_root = canonical_root; - graph.profile_build_dir = std::filesystem::weakly_canonical(options.build_root, ec) / - "profiles" / sanitize_id_component(description.profile.name); + const auto canonical_build_root = std::filesystem::weakly_canonical(options.build_root, ec); + graph.profile_build_dir = + canonical_build_root / "profiles" / sanitize_id_component(description.profile.name); if (options.snapshot) { graph.snapshot_id = options.snapshot->snapshot_id; graph.snapshot_materialized_root = options.snapshot->materialized_root; @@ -691,9 +692,14 @@ lower_project_graph(const ProjectDescription &description, return logical_abs; } if (Platform::path_is_within(canonical_root, logical_abs) && + !Platform::path_is_within(canonical_build_root, logical_abs) && !Platform::path_is_within(graph.profile_build_dir, logical_abs)) { const auto rel = logical_abs.lexically_relative(canonical_root); - return graph.snapshot_materialized_root / rel; + const auto candidate = graph.snapshot_materialized_root / rel; + std::error_code mec; + if (std::filesystem::exists(candidate, mec)) { + return candidate; + } } return logical_abs; }; @@ -742,9 +748,22 @@ lower_project_graph(const ProjectDescription &description, act.id = "custom:" + sanitize_id_component(t.name); act.kind = ActionKind::Custom; act.target_name = t.name; - act.executable = t.command_argv.front(); + auto expand_vars = [&](std::string text) { + auto replace_all = [&](std::string_view token, const std::string &val) { + std::size_t pos = 0; + while ((pos = text.find(token, pos)) != std::string::npos) { + text.replace(pos, token.size(), val); + pos += val.size(); + } + }; + replace_all("$GEN", generated_root.string()); + replace_all("$PROJECT_ROOT", canonical_root.string()); + replace_all("$BUILD_DIR", graph.profile_build_dir.string()); + return text; + }; + act.executable = expand_vars(t.command_argv.front()); for (std::size_t i = 1; i < t.command_argv.size(); ++i) { - act.arguments.push_back(t.command_argv[i]); + act.arguments.push_back(expand_vars(t.command_argv[i])); } act.environment = t.environment; if (!t.nondeterministic && !description.profile.nondeterministic) { diff --git a/src/Main.cpp b/src/Main.cpp index 5c7c111..1d2b47f 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -23,18 +24,22 @@ #include #include #include +#include #include #include #include #include +#include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -48,96 +53,56 @@ namespace { using namespace Void::Build; -Void::Argparse::Parser make_root_parser(bool &show_version) { - Void::Argparse::Parser parser{ - "vbs ", - "VoidBuildSystem — native C++ build system & package manager.\n\n" - "Commands:\n" - " build Configure and build selected targets/profiles\n" - " test Build and run declared test targets\n" - " describe Evaluate build.cpp and emit versioned graph JSON\n" - " compdb Manage per-profile compile_commands.json (use|show|export|watch)\n" - " watch Watch project and rebuild on verified changes\n" - " deps Resolve or update vbs.lock (resolve|update)\n" - " install Stage and install declared products + exports\n" - " uninstall Safely uninstall VBS-owned files from a prefix\n" - " pack Create deterministic source archive (.tar)\n" - " publish Pack and publish a release to a VBS package registry\n" - " bridge CMake VbsDeps.cmake dependency bridge backend\n" - " gc Recover state and garbage-collect unreferenced CAS blobs\n" - " gen-tests Generate native Void::Testing registration unit (no CMake)"}; - parser.flag("--version", "-V", "Show version", show_version); - return parser; -} - -// Handles standalone --help/-h cleanly (exit 0) and delegates real parsing to Void::Argparse. -std::optional parse_with_void_argparse(const Void::Argparse::Parser &parser, - std::string_view cmd_label, - const std::vector &sub_argv) { - bool saw_help = false; - for (std::size_t i = 1; i < sub_argv.size(); ++i) { - const std::string_view a{sub_argv[i]}; - if (a == "--help" || a == "-h") { - saw_help = true; - break; +class ConsoleLogGuard { + public: + explicit ConsoleLogGuard(Void::Log::Level level) { + Void::Log::set_min_level(level); + if (level > Void::Log::Level::Debug) { + // Suppress internal VoidLibrary FileSystem open-miss warnings on cold cache probes. + Void::Log::set_module_level("FileSystem", Void::Log::Level::Error); } - } - if (saw_help) { - if (sub_argv.size() > 2) { - std::cerr << cmd_label << ": --help must be used alone\n"; - return 2; - } - std::cout << parser.help(); - return 0; - } - auto res = parser.parse(static_cast(sub_argv.size()), sub_argv.data()); - if (!res) { - std::cerr << cmd_label << ": " << res.error() << '\n'; - return 2; - } - return std::nullopt; -} - -struct RepeatableSpec { - std::string_view long_name; - std::string_view short_name; - std::vector *sink; -}; - -// Extracts repeatable options (e.g. --profile / --target / --build-source) before delegating -// remaining flags/options to Void::Argparse::Parser (which also documents them in --help). -std::optional extract_repeatable_args(int start_index, int argc, char **argv, - std::string_view cmd_label, - const std::vector &specs, - std::vector &remaining_argv) { - remaining_argv.clear(); - remaining_argv.push_back(argv[0]); - for (int i = start_index; i < argc; ++i) { - const std::string_view arg{argv[i]}; - bool matched = false; - for (const auto &spec : specs) { - if (arg == spec.long_name || (!spec.short_name.empty() && arg == spec.short_name)) { - if (i + 1 >= argc) { - std::cerr << cmd_label << ": option '" << arg << "' requires a value\n"; - return 2; + reg_id_ = + Void::Log::register_sink([mutex = std::make_shared()]( + Void::Log::Level lvl, std::string_view module, + std::string_view message, const std::source_location &) { + std::lock_guard lock{*mutex}; + switch (lvl) { + case Void::Log::Level::Trace: + std::cerr << "[vbs][TRACE][" << module << "] " << message << '\n' << std::flush; + break; + case Void::Log::Level::Debug: + std::cerr << "[vbs][DEBUG][" << module << "] " << message << '\n' << std::flush; + break; + case Void::Log::Level::Info: + std::cerr << "[vbs][" << module << "] " << message << '\n' << std::flush; + break; + case Void::Log::Level::Warning: + std::cerr << "[vbs][WARN][" << module << "] " << message << '\n' << std::flush; + break; + case Void::Log::Level::Error: + std::cerr << "[vbs][ERROR][" << module << "] " << message << '\n' << std::flush; + break; + case Void::Log::Level::Fatal: + std::cerr << "[vbs][FATAL][" << module << "] " << message << '\n' << std::flush; + break; + case Void::Log::Level::Disabled: + break; } - spec.sink->emplace_back(argv[++i]); - matched = true; - break; - } - if (arg.starts_with(spec.long_name) && arg.size() > spec.long_name.size() && - arg[spec.long_name.size()] == '=') { - spec.sink->emplace_back(arg.substr(spec.long_name.size() + 1)); - matched = true; - break; - } - } - if (!matched) { - remaining_argv.push_back(argv[i]); + }); + } + + ~ConsoleLogGuard() { + if (reg_id_ != 0) { + (void)Void::Log::detach_and_drain(reg_id_); } } - return std::nullopt; -} + + ConsoleLogGuard(const ConsoleLogGuard &) = delete; + ConsoleLogGuard &operator=(const ConsoleLogGuard &) = delete; + + private: + Void::Log::RegistrationId reg_id_{0}; +}; Config::FrontendOptions make_frontend_opts(const std::filesystem::path &project_root, @@ -148,19 +113,138 @@ make_frontend_opts(const std::filesystem::path &project_root, opts.build_root = build_root; opts.sdk_include_dir = std::filesystem::path{Bootstrap::sdk_include_dir}; opts.sdk_source_dir = std::filesystem::path{Bootstrap::sdk_source_dir}; - const auto prebuilt_cmake = std::filesystem::path{Bootstrap::binary_dir} / "libVoidBuild_Sdk.a"; - const auto prebuilt_native = std::filesystem::path{Bootstrap::binary_dir} / "profiles" / - "debug" / "out" / "libVoidBuildSdk.a"; + const auto bin_dir = std::filesystem::path{Bootstrap::binary_dir}; + const std::array sdk_candidates{ + bin_dir / "libVoidBuild_Sdk.a", + bin_dir / "out" / "libVoidBuildSdk.a", + bin_dir / "profiles" / "debug" / "out" / "libVoidBuildSdk.a", + }; std::error_code ec; - if (std::filesystem::is_regular_file(prebuilt_cmake, ec)) { - opts.sdk_library_path = prebuilt_cmake; - } else if (std::filesystem::is_regular_file(prebuilt_native, ec)) { - opts.sdk_library_path = prebuilt_native; + for (const auto &candidate : sdk_candidates) { + if (std::filesystem::is_regular_file(candidate, ec)) { + opts.sdk_library_path = candidate; + break; + } } opts.extra_build_sources = extra_sources; return opts; } +struct SnapshotInputs { + std::vector explicit_files; + std::vector scan_roots; +}; + +// Derives snapshot scan roots and explicit files from conventional directories plus every +// target's declared include directories, sources, headers, and custom action inputs so +// projects with code outside `src/` (e.g. `recipes/`, `registry/`) snapshot completely. +SnapshotInputs collect_snapshot_inputs(const Graph::ProjectDescription &desc, + const std::filesystem::path &project_root) { + SnapshotInputs out; + std::error_code ec; + const auto canon_root = std::filesystem::weakly_canonical(project_root, ec); + const auto &root = ec ? project_root : canon_root; + + std::set root_dirs; + std::set files; + + auto add_dir_if_in_project = [&](const std::filesystem::path &dir) { + std::error_code dec; + const auto norm = dir.lexically_normal(); + if (std::filesystem::is_directory(norm, dec) && Platform::path_is_within(root, norm) && + norm != root) { + root_dirs.insert(norm); + } + }; + + for (const char *d : {"src", "source", "include", "tests"}) { + add_dir_if_in_project(root / d); + } + + auto is_generated_ref = [](std::string_view p) { + return p.starts_with("$GEN/") || p.starts_with("gen/"); + }; + + for (const auto &t : desc.targets) { + for (const auto &inc : t.include_directories) { + if (is_generated_ref(inc.path)) { + continue; + } + const std::filesystem::path p{inc.path}; + add_dir_if_in_project(p.is_absolute() ? p : (root / p)); + } + for (const auto &src : t.sources) { + if (is_generated_ref(src.path)) { + continue; + } + if (src.kind == SourceKind::File) { + const std::filesystem::path p{src.path}; + const auto abs = (p.is_absolute() ? p : (root / p)).lexically_normal(); + if (std::filesystem::is_regular_file(abs, ec)) { + files.insert(abs); + if (abs.has_parent_path()) { + add_dir_if_in_project(abs.parent_path()); + } + } + } else if (src.kind == SourceKind::Glob) { + const auto star = src.path.find_first_of("*?["); + const std::string_view prefix = star == std::string::npos + ? std::string_view{src.path} + : std::string_view{src.path}.substr(0, star); + const auto slash = prefix.rfind('/'); + if (slash != std::string_view::npos && slash > 0) { + add_dir_if_in_project(root / std::filesystem::path{prefix.substr(0, slash)}); + } + } + } + for (const auto &in : t.action_inputs) { + if (is_generated_ref(in)) { + continue; + } + const std::filesystem::path p{in}; + const auto abs = (p.is_absolute() ? p : (root / p)).lexically_normal(); + if (std::filesystem::is_regular_file(abs, ec)) { + files.insert(abs); + } + } + if (!t.precompiled_header.empty() && !is_generated_ref(t.precompiled_header)) { + const std::filesystem::path p{t.precompiled_header}; + const auto abs = (p.is_absolute() ? p : (root / p)).lexically_normal(); + if (std::filesystem::is_regular_file(abs, ec)) { + files.insert(abs); + } + } + } + + // Remove subdirectories already covered by an ancestor scan root. + for (const auto &d : root_dirs) { + bool covered = false; + for (const auto &other : root_dirs) { + if (other != d && Platform::path_is_within(other, d)) { + covered = true; + break; + } + } + if (!covered) { + out.scan_roots.push_back(d); + } + } + // Only keep explicit files not already covered by a scan root. + for (const auto &f : files) { + bool covered = false; + for (const auto &d : out.scan_roots) { + if (Platform::path_is_within(d, f)) { + covered = true; + break; + } + } + if (!covered) { + out.explicit_files.push_back(f); + } + } + return out; +} + struct ResolvedDepMaterialization { Package::LockContextRecord lock_context; std::vector> materialized; @@ -229,7 +313,8 @@ Void::Result::Result resolve_an std::map solved_packages; if (!root_constraints.empty()) { - // Check if offline with complete locked cache. + Void::Log::info("Deps", "Solving {} registry package constraint(s)...", + root_constraints.size()); bool all_locked_cached = offline; const auto pkg_cache_root = build_root / ".vbs" / "cache" / "packages"; if (all_locked_cached) { @@ -245,6 +330,7 @@ Void::Result::Result resolve_an } if (all_locked_cached) { + Void::Log::info("Deps", "Using offline cached locked package graph"); for (const auto *nd : package_deps) { const auto &pid = alias_to_pkg_id.at(nd->record.name); const auto &le = locked_pkg_entries.at(pid); @@ -278,6 +364,8 @@ Void::Result::Result resolve_an while (!pending.empty()) { const auto pid = pending.front(); pending.pop(); + Void::Log::debug("Deps", "Fetching release index for '{}' from {}", pid.name, + pid.registry_authority); auto releases = Package::fetch_package_releases(pid.registry_authority, pid.name, reg_auth); if (!releases) { @@ -320,6 +408,8 @@ Void::Result::Result resolve_an } } if (need_download) { + Void::Log::info("Fetch", "Downloading {}@{} from {}", pid.name, + sp.version.to_string(), pid.registry_authority); auto dl = Package::download_release_archive( pid.registry_authority, pid.name, sp.version.to_string(), sp.source_sha256, tar_path, reg_auth); @@ -327,10 +417,15 @@ Void::Result::Result resolve_an return std::unexpected{dl.error()}; } } + Void::Log::info("Fetch", "Extracting {}@{} ({})", pid.name, sp.version.to_string(), + sp.source_sha256.substr(0, 12)); auto ex = Package::extract_safe_tar(tar_path, extract_dir); if (!ex) { return std::unexpected{ex.error()}; } + } else { + Void::Log::debug("Fetch", "Using cached package {}@{} ({})", pid.name, + sp.version.to_string(), sp.source_sha256.substr(0, 12)); } Package::MaterializedSource mat{nd.record.name, extract_dir, sp.source_sha256, false}; @@ -389,102 +484,74 @@ Void::Result::Result resolve_an return out; } -int run_build_or_test(int argc, char **argv, bool run_tests) { - const std::string cmd_name = run_tests ? "vbs test" : "vbs build"; - std::string project_arg = std::filesystem::current_path().string(); +struct BuildCmdOptions { + std::string project_arg; std::optional build_arg; - std::optional profile_doc; - std::optional target_doc; - std::optional build_source_doc; + std::vector profiles; + std::vector targets; + std::vector extra_build_sources; std::optional editor_profile; std::optional compiler_arg; std::optional jobs_arg; - bool no_cache = false; - bool locked = false; - bool offline = false; + bool no_cache{false}; + bool locked{false}; + bool offline{false}; +}; - Void::Argparse::Parser parser{cmd_name, - run_tests ? "Build and execute declared test targets." - : "Configure and build selected profiles and targets."}; - parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) - .option("--build-dir", "-B", "Build output directory", build_arg) - .option("--profile", "-p", "Profile to build (repeatable)", profile_doc) - .option("--target", "-t", "Target to build/test (repeatable)", target_doc) - .option("--compiler", "", "Override compiler family (gcc|clang)", compiler_arg) - .option("--editor-profile", "", "Editor profile for compile_commands.json", editor_profile) - .option("--build-source", "", "Additional build description source (repeatable)", - build_source_doc) - .option("--jobs", "-j", "Maximum parallel compilation/link jobs", jobs_arg) - .flag("--locked", "", "Require existing up-to-date vbs.lock", locked) - .flag("--offline", "", "Disallow network fetches", offline) - .flag("--no-cache", "", "Bypass action cache reads", no_cache); - - std::vector requested_profiles; - std::vector requested_targets; - std::vector extra_build_source_strs; - std::vector remaining; - if (auto rc = extract_repeatable_args(2, argc, argv, cmd_name, - {{"--profile", "-p", &requested_profiles}, - {"--target", "-t", &requested_targets}, - {"--build-source", "", &extra_build_source_strs}}, - remaining); - rc) { - return *rc; - } - if (auto rc = parse_with_void_argparse(parser, cmd_name, remaining); rc) { - return *rc; - } +int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { + const std::string cmd_name = run_tests ? "vbs test" : "vbs build"; + const auto total_sw = Void::Time::Stopwatch::started(); std::optional compiler_override; - if (compiler_arg) { + if (opts.compiler_arg) { try { - compiler_override = parse_compiler(*compiler_arg); + compiler_override = parse_compiler(*opts.compiler_arg); } catch (const std::exception &ex) { std::cerr << cmd_name << ": " << ex.what() << '\n'; return 2; } } std::size_t jobs = 0; - if (jobs_arg) { + if (opts.jobs_arg) { int parsed_jobs = 0; - if (!Void::Str::to_int(*jobs_arg, parsed_jobs) || parsed_jobs < 0) { - std::cerr << cmd_name << ": invalid --jobs value '" << *jobs_arg << "'\n"; + if (!Void::Str::to_int(*opts.jobs_arg, parsed_jobs) || parsed_jobs < 0) { + std::cerr << cmd_name << ": invalid --jobs value '" << *opts.jobs_arg << "'\n"; return 2; } jobs = static_cast(parsed_jobs); } - const std::filesystem::path project_root{project_arg}; + const std::filesystem::path project_root{opts.project_arg}; const std::filesystem::path build_root = - build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build"); std::vector extra_build_sources; - for (const auto &s : extra_build_source_strs) { + for (const auto &s : opts.extra_build_sources) { extra_build_sources.emplace_back(s); } - if (requested_profiles.empty()) { - requested_profiles.push_back("debug"); + if (opts.profiles.empty()) { + opts.profiles.push_back("debug"); } // D-010 / Plan 09: multi-profile builds MUST specify --editor-profile from selected profiles // BEFORE doing any build work! - if (requested_profiles.size() > 1) { - if (!editor_profile) { + if (opts.profiles.size() > 1) { + if (!opts.editor_profile) { std::cerr << "vbs: multi-profile build requires --editor-profile selecting one of " "the requested profiles\n"; return 2; } - if (!std::ranges::contains(requested_profiles, *editor_profile)) { - std::cerr << "vbs: --editor-profile '" << *editor_profile + if (!std::ranges::contains(opts.profiles, *opts.editor_profile)) { + std::cerr << "vbs: --editor-profile '" << *opts.editor_profile << "' must be one of the requested profiles\n"; return 2; } - } else if (!editor_profile) { - editor_profile = requested_profiles.front(); + } else if (!opts.editor_profile) { + opts.editor_profile = opts.profiles.front(); } // Reserve monotonic selection ticket on acceptance BEFORE expensive work! auto reserved_ticket = - Editor::reserve_selection_ticket(project_root, build_root, *editor_profile); + Editor::reserve_selection_ticket(project_root, build_root, *opts.editor_profile); if (!reserved_ticket) { std::cerr << "vbs: failed reserving editor ticket: " << reserved_ticket.error().message() << '\n'; @@ -492,11 +559,16 @@ int run_build_or_test(int argc, char **argv, bool run_tests) { } const auto fopts = make_frontend_opts(project_root, build_root, extra_build_sources); + Void::Log::info("Config", "Preparing build description in '{}'...", project_root.string()); + const auto cfg_sw = Void::Time::Stopwatch::started(); auto compiled = Config::compile_descriptor(fopts); if (!compiled) { std::cerr << "vbs: " << compiled.error().message() << '\n'; return 1; } + Void::Log::info("Config", "Build description {} ({:.0f} ms)", + compiled->recompiled ? "compiled" : "up to date (cached)", cfg_sw.elapsed_ms()); + auto profs = Config::discover_profiles(*compiled, fopts); if (!profs) { std::cerr << "vbs: " << profs.error().message() << '\n'; @@ -517,7 +589,8 @@ int run_build_or_test(int argc, char **argv, bool run_tests) { } bool all_ok = true; - for (const auto &prof_name : requested_profiles) { + for (const auto &prof_name : opts.profiles) { + const auto prof_sw = Void::Time::Stopwatch::started(); ProfileContext ctx; try { ctx = profs->resolve(prof_name, compiler_override, Toolchain::host_os_name(), @@ -532,6 +605,10 @@ int run_build_or_test(int argc, char **argv, bool run_tests) { std::cerr << "vbs: " << tc.error().message() << '\n'; return 1; } + Void::Log::info("Toolchain", "[{}] Using {} ({}) [{}]", prof_name, + compiler_name(tc->family), tc->cxx_compiler.string(), tc->version_banner); + + const auto eval_sw = Void::Time::Stopwatch::started(); auto desc = Config::evaluate_project(*compiled, ctx, fopts); if (!desc) { std::cerr << "vbs: " << desc.error().message() << '\n'; @@ -539,6 +616,9 @@ int run_build_or_test(int argc, char **argv, bool run_tests) { build_root, prof_name, Editor::GenerationStatus::Invalid, desc.error().message()); return 1; } + Void::Log::info("Eval", "[{}] Evaluated {} target(s), {} dependenc(ies) ({:.0f} ms)", + prof_name, desc->targets.size(), desc->dependencies.size(), + eval_sw.elapsed_ms()); // Load & merge any TOML dependency manifests declared by build.cpp. std::vector toml_deps; @@ -546,6 +626,8 @@ int run_build_or_test(int argc, char **argv, bool run_tests) { const auto p = std::filesystem::path{dep_file}.is_absolute() ? std::filesystem::path{dep_file} : (project_root / dep_file); + Void::Log::debug("Deps", "[{}] Loading dependency manifest '{}'", prof_name, + p.string()); auto loaded = Package::load_dependencies_toml(p); if (!loaded) { std::cerr << "vbs: " << loaded.error().message() << '\n'; @@ -559,26 +641,35 @@ int run_build_or_test(int argc, char **argv, bool run_tests) { return 1; } - // Validate/create lockfile context and materialize dependencies (including live registry). + // Validate/update lockfile context and materialize dependencies (including live registry). std::map> imported_targets; if (!merged_deps->empty()) { + Void::Log::info("Deps", "[{}] Resolving {} dependenc(ies)...", prof_name, + merged_deps->size()); const std::string ctx_key = Package::make_lock_context_key(ctx, "target"); const std::string fp = Package::compute_declaration_fingerprint(ctx, "target", *merged_deps); + bool need_lock_publish = !pinned_lock->has_value(); if (pinned_lock->has_value()) { auto valid = Package::validate_locked_context((*pinned_lock)->document, ctx_key, fp); if (!valid) { - std::cerr << "vbs: " << valid.error().message() << '\n'; - return 1; + if (opts.locked) { + std::cerr << "vbs: " << valid.error().message() << '\n'; + return 1; + } + Void::Log::info("Deps", + "[{}] Updating vbs.lock for changed dependency declarations...", + prof_name); + need_lock_publish = true; } - } else if (locked) { + } else if (opts.locked) { std::cerr << "vbs: --locked requires an existing vbs.lock\n"; return 1; } - auto resolved = resolve_and_materialize_deps(ctx, *merged_deps, project_root, - build_root, *pinned_lock, offline, false); + auto resolved = resolve_and_materialize_deps( + ctx, *merged_deps, project_root, build_root, *pinned_lock, opts.offline, false); if (!resolved) { std::cerr << "vbs: " << resolved.error().message() << '\n'; return 1; @@ -609,40 +700,47 @@ int run_build_or_test(int argc, char **argv, bool run_tests) { std::cerr << "vbs: " << exp.error().message() << '\n'; return 1; } + Void::Log::info("Provider", "[{}] Imported {} target(s) from '{}' ({})", + prof_name, exp->targets.size(), effective_dep.name, + exp->from_cache ? "cached" : "built"); for (const auto &[k, v] : exp->targets) { imported_targets[k] = v; } } } - if (!pinned_lock->has_value()) { - auto pub_lock = Package::publish_lock_context_cas(lock_path, "", - resolved->lock_context, locked); + if (need_lock_publish) { + const std::string base_rev = + pinned_lock->has_value() ? (*pinned_lock)->revision_hash : std::string{}; + auto pub_lock = Package::publish_lock_context_cas( + lock_path, base_rev, resolved->lock_context, opts.locked); if (!pub_lock) { std::cerr << "vbs: " << pub_lock.error().message() << '\n'; return 1; } pinned_lock = *pub_lock; + Void::Log::info("Deps", "[{}] Updated vbs.lock (revision {})", prof_name, + (*pinned_lock)->revision_hash.substr(0, 12)); } } - // Capture immutable snapshot. - std::vector scan_roots; - std::error_code ec; - for (const char *d : {"src", "source", "include", "tests"}) { - if (std::filesystem::is_directory(project_root / d, ec)) { - scan_roots.push_back(project_root / d); - } - } + // Capture immutable snapshot over all declared & conventional project source trees. + const auto snap_sw = Void::Time::Stopwatch::started(); + const auto snap_inputs = collect_snapshot_inputs(*desc, project_root); Snapshot::SnapshotOptions sopts; sopts.project_root = project_root; sopts.snapshot_store_dir = build_root / ".vbs" / "snapshots"; sopts.reproducibility_epoch = ctx.reproducibility_epoch; - auto snap = Snapshot::capture_snapshot(sopts, {}, scan_roots); + auto snap = + Snapshot::capture_snapshot(sopts, snap_inputs.explicit_files, snap_inputs.scan_roots); if (!snap) { std::cerr << "vbs: " << snap.error().message() << '\n'; return 1; } + Void::Log::info("Snapshot", "[{}] Captured snapshot {} ({} file(s), {:.0f} ms)", prof_name, + snap->snapshot_id.substr(0, 12), snap->entries.size(), + snap_sw.elapsed_ms()); + const auto graph_sw = Void::Time::Stopwatch::started(); Graph::GraphLowerOptions gopts{project_root, build_root, &(*snap), std::move(imported_targets), 32768}; auto graph = Graph::lower_project_graph(*desc, *tc, gopts); @@ -652,19 +750,25 @@ int run_build_or_test(int argc, char **argv, bool run_tests) { build_root, prof_name, Editor::GenerationStatus::Invalid, graph.error().message()); return 1; } + Void::Log::info("Graph", "[{}] Lowered {} action(s) across {} target(s) ({:.0f} ms)", + prof_name, graph->actions.size(), graph->targets.size(), + graph_sw.elapsed_ms()); // Publish compdb BEFORE compilation (Plan 09: compile failure does NOT undo selection!). Editor::PublishOptions popts; popts.project_root = project_root; popts.build_root = build_root; - popts.update_selection = (*editor_profile == prof_name); + popts.update_selection = (*opts.editor_profile == prof_name); popts.reserved_ticket = *reserved_ticket; - (void)Editor::publish_profile_compdb(*graph, popts); + if (auto pub_db = Editor::publish_profile_compdb(*graph, popts); pub_db) { + Void::Log::debug("CompDb", "[{}] Published compile_commands.json ({})", prof_name, + pub_db->compdb_path.string()); + } Execution::ExecutionOptions eopts; eopts.jobs = jobs; - eopts.use_cache = !no_cache; - eopts.selected_targets = requested_targets; + eopts.use_cache = !opts.no_cache; + eopts.selected_targets = opts.targets; auto rep = Execution::execute_graph(*graph, *state, eopts); if (!rep) { std::cerr << "vbs: " << rep.error().message() << '\n'; @@ -683,6 +787,8 @@ int run_build_or_test(int argc, char **argv, bool run_tests) { all_ok = false; continue; } + Void::Log::info("Build", "[{}] Finished in {:.2f}s ({} executed, {} cached)", prof_name, + prof_sw.elapsed_ms() / 1000.0, rep->executed_count, rep->cached_count); std::cout << "vbs: [" << prof_name << "] built (" << rep->executed_count << " executed, " << rep->cached_count << " cached)\n"; @@ -691,82 +797,62 @@ int run_build_or_test(int argc, char **argv, bool run_tests) { if (t.kind != TargetKind::Test || t.primary_outputs.empty()) { continue; } - if (!requested_targets.empty() && - !std::ranges::contains(requested_targets, t.name)) { + if (!opts.targets.empty() && !std::ranges::contains(opts.targets, t.name)) { continue; } + Void::Log::info("Test", "[{}] Running test target '{}'...", prof_name, t.name); + const auto tsw = Void::Time::Stopwatch::started(); Platform::ProcessRequest treq; treq.executable = t.primary_outputs.front(); treq.working_directory = project_root; auto tres = Platform::run_supervised(treq); if (!tres || !tres->succeeded()) { + Void::Log::error("Test", "[{}] FAILED '{}' ({:.0f} ms)", prof_name, t.name, + tsw.elapsed_ms()); std::cerr << "vbs test: FAILED '" << t.name << "'\n"; if (tres && !tres->stderr_data.empty()) { std::cerr << tres->stderr_data << '\n'; } all_ok = false; } else { + Void::Log::info("Test", "[{}] PASSED '{}' ({:.0f} ms)", prof_name, t.name, + tsw.elapsed_ms()); std::cout << "vbs test: PASSED '" << t.name << "'\n"; } } } } + Void::Log::debug("Build", "Total wall time: {:.2f}s", total_sw.elapsed_ms() / 1000.0); return all_ok ? 0 : 1; } -int run_compdb_command(int argc, char **argv) { - if (argc < 3) { - std::cerr << "vbs compdb: expected subcommand (use|show|export|watch)\n"; - return 2; - } - const std::string_view sub{argv[2]}; - if (sub == "--help" || sub == "-h") { - Void::Argparse::Parser hp{ - "vbs compdb ", - "Manage per-profile compile_commands.json selection and metadata projection."}; - std::cout << hp.help(); - return 0; - } - if (sub != "use" && sub != "show" && sub != "export" && sub != "watch") { - std::cerr << "vbs compdb: unknown subcommand '" << sub << "'\n"; - return 2; - } - - std::string project_arg = std::filesystem::current_path().string(); +struct CompDbCmdOptions { + std::string project_arg; std::optional build_arg; std::optional profile_name; - Void::Argparse::Parser parser{"vbs compdb " + std::string{sub}, - "Manage per-profile compile_commands.json."}; - parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) - .option("--build-dir", "-B", "Build output directory", build_arg) - .option("--profile", "-p", "Profile name", profile_name); + std::vector positional_profiles; +}; - // Allow optional positional profile name for `vbs compdb use `. - std::vector sub_argv; - sub_argv.push_back(argv[0]); - for (int i = 3; i < argc; ++i) { - const std::string_view a{argv[i]}; - if (sub == "use" && !a.starts_with("-") && !profile_name && - (i == 3 || (std::string_view{argv[i - 1]} != "--project" && - std::string_view{argv[i - 1]} != "-C" && - std::string_view{argv[i - 1]} != "--build-dir" && - std::string_view{argv[i - 1]} != "-B" && - std::string_view{argv[i - 1]} != "--profile" && - std::string_view{argv[i - 1]} != "-p"))) { - profile_name = std::string{a}; - continue; +int execute_compdb_command(std::string_view sub, CompDbCmdOptions opts) { + if (sub == "use") { + if (opts.positional_profiles.size() > 1) { + std::cerr << "vbs compdb use: expected at most one positional profile argument\n"; + return 2; + } + if (opts.positional_profiles.size() == 1) { + if (opts.profile_name && *opts.profile_name != opts.positional_profiles.front()) { + std::cerr << "vbs compdb use: conflicting profile specified via both --profile and " + "positional argument\n"; + return 2; + } + opts.profile_name = opts.positional_profiles.front(); } - sub_argv.push_back(argv[i]); - } - if (auto rc = parse_with_void_argparse(parser, "vbs compdb " + std::string{sub}, sub_argv); - rc) { - return *rc; } - const std::filesystem::path project_root{project_arg}; + const std::filesystem::path project_root{opts.project_arg}; const std::filesystem::path build_root = - build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build"); if (sub == "show") { auto st = Editor::read_selection_state(project_root); @@ -780,11 +866,11 @@ int run_compdb_command(int argc, char **argv) { return 0; } if (sub == "use") { - if (!profile_name) { + if (!opts.profile_name) { std::cerr << "vbs compdb use: profile name required\n"; return 2; } - auto st = Editor::select_editor_profile(project_root, build_root, *profile_name); + auto st = Editor::select_editor_profile(project_root, build_root, *opts.profile_name); if (!st) { std::cerr << "vbs compdb use: " << st.error().message() << '\n'; return 1; @@ -797,8 +883,10 @@ int run_compdb_command(int argc, char **argv) { Watch::WatchLoopOptions wopts; wopts.mode = Watch::WatchMode::MetadataOnly; wopts.frontend = make_frontend_opts(project_root, build_root, {}); - wopts.explicit_profile = profile_name; + wopts.explicit_profile = opts.profile_name; if (sub == "export") { + Void::Log::info("CompDb", "Exporting compile_commands.json in '{}'...", + project_root.string()); auto rep = Watch::run_reconcile_cycle(wopts, 0, false, std::nullopt); if (!rep.compdb_published) { std::cerr << "vbs compdb export: " << rep.diagnostic << '\n'; @@ -807,6 +895,9 @@ int run_compdb_command(int argc, char **argv) { std::cout << "exported compile_commands.json for profile '" << rep.profile_name << "'\n"; return 0; } + + Void::Log::info("CompDb", "Watching metadata in '{}' (Ctrl+C to stop)...", + project_root.string()); std::stop_source stop_src; auto sig = Void::Process::SignalWatcher::create(); std::jthread sig_thread([&] { @@ -819,40 +910,27 @@ int run_compdb_command(int argc, char **argv) { return res ? 0 : 1; } -int run_describe_command(int argc, char **argv) { - std::string project_arg = std::filesystem::current_path().string(); +struct DescribeCmdOptions { + std::string project_arg; std::optional build_arg; - std::string profile_name = "debug"; + std::string profile_name{"debug"}; std::optional compiler_arg; +}; - Void::Argparse::Parser parser{"vbs describe", - "Evaluate build.cpp for one profile and emit graph summary."}; - parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) - .option("--build-dir", "-B", "Build output directory", build_arg) - .option_default("--profile", "-p", "Profile name", profile_name, "debug") - .option("--compiler", "", "Override compiler family (gcc|clang)", compiler_arg); - - std::vector sub_argv{argv[0]}; - for (int i = 2; i < argc; ++i) { - sub_argv.push_back(argv[i]); - } - if (auto rc = parse_with_void_argparse(parser, "vbs describe", sub_argv); rc) { - return *rc; - } - +int execute_describe_command(const DescribeCmdOptions &opts) { std::optional compiler_override; - if (compiler_arg) { + if (opts.compiler_arg) { try { - compiler_override = parse_compiler(*compiler_arg); + compiler_override = parse_compiler(*opts.compiler_arg); } catch (const std::exception &ex) { std::cerr << "vbs describe: " << ex.what() << '\n'; return 2; } } - const std::filesystem::path project_root{project_arg}; + const std::filesystem::path project_root{opts.project_arg}; const std::filesystem::path build_root = - build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build"); const auto fopts = make_frontend_opts(project_root, build_root, {}); auto compiled = Config::compile_descriptor(fopts); if (!compiled) { @@ -865,7 +943,7 @@ int run_describe_command(int argc, char **argv) { return 1; } try { - auto ctx = profs->resolve(profile_name, compiler_override, Toolchain::host_os_name(), + auto ctx = profs->resolve(opts.profile_name, compiler_override, Toolchain::host_os_name(), Toolchain::host_architecture_name()); auto desc = Config::evaluate_project(*compiled, ctx, fopts); if (!desc) { @@ -882,39 +960,33 @@ int run_describe_command(int argc, char **argv) { } } -int run_watch_command(int argc, char **argv) { - std::string project_arg = std::filesystem::current_path().string(); +struct WatchCmdOptions { + std::string project_arg; std::optional build_arg; std::optional profile_arg; - std::optional target_doc; - - Void::Argparse::Parser parser{"vbs watch", - "Watch project sources and rebuild on verified changes."}; - parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) - .option("--build-dir", "-B", "Build output directory", build_arg) - .option("--profile", "-p", "Profile to watch", profile_arg) - .option("--target", "-t", "Target to rebuild (repeatable)", target_doc); - std::vector targets; - std::vector remaining; - if (auto rc = extract_repeatable_args(2, argc, argv, "vbs watch", - {{"--target", "-t", &targets}}, remaining); - rc) { - return *rc; - } - if (auto rc = parse_with_void_argparse(parser, "vbs watch", remaining); rc) { - return *rc; - } +}; - const std::filesystem::path project_root{project_arg}; +int execute_watch_command(WatchCmdOptions opts) { + const std::filesystem::path project_root{opts.project_arg}; const std::filesystem::path build_root = - build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build"); Watch::WatchLoopOptions wopts; wopts.mode = Watch::WatchMode::FullBuild; wopts.frontend = make_frontend_opts(project_root, build_root, {}); - wopts.explicit_profile = profile_arg; - wopts.selected_targets = std::move(targets); + wopts.explicit_profile = opts.profile_arg; + wopts.selected_targets = std::move(opts.targets); + wopts.on_cycle = [](const Watch::WatchCycleReport &rep) { + if (rep.build_succeeded) { + Void::Log::info("Watch", "Cycle #{} [{}] OK ({} executed, {} cached)", rep.cycle_index, + rep.profile_name, rep.executed_actions, rep.cached_actions); + } else { + Void::Log::error("Watch", "Cycle #{} [{}] FAILED: {}", rep.cycle_index, + rep.profile_name, rep.diagnostic); + } + }; + Void::Log::info("Watch", "Watching '{}' (Ctrl+C to stop)...", project_root.string()); std::stop_source stop_src; auto sig = Void::Process::SignalWatcher::create(); std::jthread sig_thread([&] { @@ -927,25 +999,18 @@ int run_watch_command(int argc, char **argv) { return res ? 0 : 1; } -int run_bridge_command(int argc, char **argv) { +struct BridgeCmdOptions { std::optional req_arg; std::optional out_arg; - Void::Argparse::Parser parser{"vbs bridge", "CMake VbsDeps.cmake dependency bridge backend."}; - parser.option("--request", "", "Path to bridge request JSON", req_arg) - .option("--output", "", "Path to output CMake fragment", out_arg); +}; - std::vector sub_argv{argv[0]}; - for (int i = 2; i < argc; ++i) { - sub_argv.push_back(argv[i]); - } - if (auto rc = parse_with_void_argparse(parser, "vbs bridge", sub_argv); rc) { - return *rc; - } - if (!req_arg || !out_arg) { +int execute_bridge_command(const BridgeCmdOptions &opts) { + if (!opts.req_arg || !opts.out_arg) { std::cerr << "vbs bridge: --request and --output are required\n"; return 2; } - auto r = Bridge::execute_cmake_bridge(*req_arg, *out_arg); + Void::Log::info("Bridge", "Processing CMake bridge request '{}'", *opts.req_arg); + auto r = Bridge::execute_cmake_bridge(*opts.req_arg, *opts.out_arg); if (!r) { std::cerr << "vbs bridge: " << r.error().message() << '\n'; return 1; @@ -953,67 +1018,47 @@ int run_bridge_command(int argc, char **argv) { return 0; } -int run_pack_command(int argc, char **argv) { - std::string project_arg = std::filesystem::current_path().string(); - std::string out_arg = "package.tar"; - Void::Argparse::Parser parser{"vbs pack", "Create a deterministic USTAR source archive."}; - parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) - .option_default("--output", "-o", "Output archive path", out_arg, "package.tar"); +struct PackCmdOptions { + std::string project_arg; + std::string out_arg{"package.tar"}; +}; - std::vector sub_argv{argv[0]}; - for (int i = 2; i < argc; ++i) { - sub_argv.push_back(argv[i]); - } - if (auto rc = parse_with_void_argparse(parser, "vbs pack", sub_argv); rc) { - return *rc; - } - auto sha = Package::create_source_package(project_arg, out_arg, 0); +int execute_pack_command(const PackCmdOptions &opts) { + Void::Log::info("Pack", "Creating deterministic source archive '{}' from '{}'...", opts.out_arg, + opts.project_arg); + auto sha = Package::create_source_package(opts.project_arg, opts.out_arg, 0); if (!sha) { std::cerr << "vbs pack: " << sha.error().message() << '\n'; return 1; } - std::cout << "packed " << out_arg << " sha256=" << *sha << '\n'; + std::cout << "packed " << opts.out_arg << " sha256=" << *sha << '\n'; return 0; } -int run_publish_command(int argc, char **argv) { - std::string project_arg = std::filesystem::current_path().string(); +struct PublishCmdOptions { + std::string project_arg; std::optional registry_arg; std::optional name_arg; std::optional version_arg; std::string description; - std::string token_env = "VBS_REGISTRY_TOKEN"; - bool is_private = false; + std::string token_env{"VBS_REGISTRY_TOKEN"}; + bool is_private{false}; +}; - Void::Argparse::Parser parser{ - "vbs publish", "Pack a deterministic source archive and publish it to a VBS registry."}; - parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) - .option("--registry", "-r", "Registry base URL (or VBS_REGISTRY_URL)", registry_arg) - .option("--name", "-n", "Package name", name_arg) - .option("--version", "-v", "Strict SemVer release version", version_arg) - .option_default("--description", "-d", "Package description", description, "") - .option_default("--token-env", "", "Environment variable holding bearer token", token_env, - "VBS_REGISTRY_TOKEN") - .flag("--private", "", "Publish package as private", is_private); - - std::vector sub_argv{argv[0]}; - for (int i = 2; i < argc; ++i) { - sub_argv.push_back(argv[i]); - } - if (auto rc = parse_with_void_argparse(parser, "vbs publish", sub_argv); rc) { - return *rc; - } - - const std::string registry_url = - registry_arg ? *registry_arg : Void::Configuration::get_env_or("VBS_REGISTRY_URL", ""); - if (registry_url.empty() || !name_arg || !version_arg) { +int execute_publish_command(const PublishCmdOptions &opts) { + const std::string registry_url = opts.registry_arg + ? *opts.registry_arg + : Void::Configuration::get_env_or("VBS_REGISTRY_URL", ""); + if (registry_url.empty() || !opts.name_arg || !opts.version_arg) { std::cerr << "vbs publish: --registry, --name, and --version are required\n"; return 2; } Void::FileSystem::TempDir tmp{"vbs_publish_"}; - const auto tar_path = tmp / (*name_arg + "-" + *version_arg + ".tar"); - auto sha = Package::create_source_package(project_arg, tar_path, 0); + const auto tar_path = tmp / (*opts.name_arg + "-" + *opts.version_arg + ".tar"); + Void::Log::info("Publish", "Packing {}@{} from '{}'...", *opts.name_arg, *opts.version_arg, + opts.project_arg); + auto sha = Package::create_source_package(opts.project_arg, tar_path, 0); if (!sha) { std::cerr << "vbs publish: " << sha.error().message() << '\n'; return 1; @@ -1021,85 +1066,69 @@ int run_publish_command(int argc, char **argv) { Package::PublishOptions popts; popts.registry_url = registry_url; - popts.package_name = *name_arg; - popts.version = *version_arg; + popts.package_name = *opts.name_arg; + popts.version = *opts.version_arg; popts.archive_path = tar_path; - popts.description = description; - popts.is_private = is_private; - popts.auth.bearer_token = Void::Configuration::get_env_or(token_env, ""); + popts.description = opts.description; + popts.is_private = opts.is_private; + popts.auth.bearer_token = Void::Configuration::get_env_or(opts.token_env, ""); + Void::Log::info("Publish", "Uploading {}@{} ({}) to {}...", *opts.name_arg, *opts.version_arg, + sha->substr(0, 12), registry_url); auto receipt = Package::publish_package_archive(popts); if (!receipt) { std::cerr << "vbs publish: " << receipt.error().message() << '\n'; return 1; } - std::cout << (receipt->already_published ? "already published " : "published ") << *name_arg - << "@" << *version_arg << " sha256=" << receipt->sha256 << '\n'; + std::cout << (receipt->already_published ? "already published " : "published ") + << *opts.name_arg << "@" << *opts.version_arg << " sha256=" << receipt->sha256 + << '\n'; return 0; } -int run_install_command(int argc, char **argv) { - std::string project_arg = std::filesystem::current_path().string(); +struct InstallCmdOptions { + std::string project_arg; std::optional build_arg; - std::string profile_name = "debug"; + std::string profile_name{"debug"}; std::optional compiler_arg; std::optional prefix_arg; std::optional pkg_name_arg; - std::string pkg_ver = "0.1.0"; + std::string pkg_ver{"0.1.0"}; std::optional component_arg; - bool no_cmake_export = false; - bool no_native_export = false; + bool no_cmake_export{false}; + bool no_native_export{false}; +}; - Void::Argparse::Parser parser{ - "vbs install", "Build, stage, and install declared products and package exports."}; - parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) - .option("--build-dir", "-B", "Build output directory", build_arg) - .option_default("--profile", "-p", "Profile name", profile_name, "debug") - .option("--compiler", "", "Override compiler family (gcc|clang)", compiler_arg) - .option("--prefix", "", "Install destination prefix (required)", prefix_arg) - .option("--package-name", "", "Exported package name", pkg_name_arg) - .option_default("--package-version", "", "Exported package version", pkg_ver, "0.1.0") - .option("--component", "", "Install only a specific component", component_arg) - .flag("--no-cmake-export", "", "Disable CMake Config.cmake export", no_cmake_export) - .flag("--no-native-export", "", "Disable native VBS package metadata export", - no_native_export); - - std::vector sub_argv{argv[0]}; - for (int i = 2; i < argc; ++i) { - sub_argv.push_back(argv[i]); - } - if (auto rc = parse_with_void_argparse(parser, "vbs install", sub_argv); rc) { - return *rc; - } - if (!prefix_arg || prefix_arg->empty()) { +int execute_install_command(const InstallCmdOptions &opts) { + if (!opts.prefix_arg || opts.prefix_arg->empty()) { std::cerr << "vbs install: --prefix is required\n"; return 2; } std::optional compiler_override; - if (compiler_arg) { + if (opts.compiler_arg) { try { - compiler_override = parse_compiler(*compiler_arg); + compiler_override = parse_compiler(*opts.compiler_arg); } catch (const std::exception &ex) { std::cerr << "vbs install: " << ex.what() << '\n'; return 2; } } - const std::filesystem::path project_root{project_arg}; + const std::filesystem::path project_root{opts.project_arg}; const std::filesystem::path build_root = - build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build"); Install::InstallOptions iopts; - iopts.prefix = *prefix_arg; - iopts.package_version = pkg_ver; - iopts.component = component_arg; - iopts.export_cmake_config = !no_cmake_export; - iopts.export_native_metadata = !no_native_export; + iopts.prefix = *opts.prefix_arg; + iopts.package_version = opts.pkg_ver; + iopts.component = opts.component_arg; + iopts.export_cmake_config = !opts.no_cmake_export; + iopts.export_native_metadata = !opts.no_native_export; std::error_code ec; - if (pkg_name_arg && !pkg_name_arg->empty()) { - iopts.package_name = *pkg_name_arg; + if (opts.pkg_name_arg && !opts.pkg_name_arg->empty()) { + iopts.package_name = *opts.pkg_name_arg; } else { const auto canon = std::filesystem::weakly_canonical(project_root, ec); iopts.package_name = canon.filename().string(); @@ -1108,6 +1137,8 @@ int run_install_command(int argc, char **argv) { } } + Void::Log::info("Install", "Building profile '{}' before staging into '{}'...", + opts.profile_name, iopts.prefix.string()); const auto fopts = make_frontend_opts(project_root, build_root, {}); auto compiled = Config::compile_descriptor(fopts); if (!compiled) { @@ -1121,7 +1152,7 @@ int run_install_command(int argc, char **argv) { } ProfileContext ctx; try { - ctx = profs->resolve(profile_name, compiler_override, Toolchain::host_os_name(), + ctx = profs->resolve(opts.profile_name, compiler_override, Toolchain::host_os_name(), Toolchain::host_architecture_name()); } catch (const std::exception &ex) { std::cerr << "vbs install: " << ex.what() << '\n'; @@ -1138,17 +1169,13 @@ int run_install_command(int argc, char **argv) { return 1; } - std::vector scan_roots; - for (const char *d : {"src", "source", "include", "tests"}) { - if (std::filesystem::is_directory(project_root / d, ec)) { - scan_roots.push_back(project_root / d); - } - } + const auto snap_inputs = collect_snapshot_inputs(*desc, project_root); Snapshot::SnapshotOptions sopts; sopts.project_root = project_root; sopts.snapshot_store_dir = build_root / ".vbs" / "snapshots"; sopts.reproducibility_epoch = ctx.reproducibility_epoch; - auto snap = Snapshot::capture_snapshot(sopts, {}, scan_roots); + auto snap = + Snapshot::capture_snapshot(sopts, snap_inputs.explicit_files, snap_inputs.scan_roots); if (!snap) { std::cerr << "vbs install: " << snap.error().message() << '\n'; return 1; @@ -1172,6 +1199,8 @@ int run_install_command(int argc, char **argv) { } return 1; } + Void::Log::info("Install", "Staging and installing package '{}' ({}) to '{}'...", + iopts.package_name, iopts.package_version, iopts.prefix.string()); auto inst = Install::install_project(*desc, *graph, iopts); if (!inst) { std::cerr << "vbs install: " << inst.error().message() << '\n'; @@ -1182,57 +1211,42 @@ int run_install_command(int argc, char **argv) { return 0; } -int run_uninstall_command(int argc, char **argv) { +struct UninstallCmdOptions { std::optional prefix_arg; - Void::Argparse::Parser parser{"vbs uninstall", - "Safely remove only VBS-owned files recorded in the manifest."}; - parser.option("--prefix", "", "Installed prefix directory (required)", prefix_arg); +}; - std::vector sub_argv{argv[0]}; - for (int i = 2; i < argc; ++i) { - sub_argv.push_back(argv[i]); - } - if (auto rc = parse_with_void_argparse(parser, "vbs uninstall", sub_argv); rc) { - return *rc; - } - if (!prefix_arg || prefix_arg->empty()) { +int execute_uninstall_command(const UninstallCmdOptions &opts) { + if (!opts.prefix_arg || opts.prefix_arg->empty()) { std::cerr << "vbs uninstall: --prefix is required\n"; return 2; } - auto removed = Install::uninstall_prefix(*prefix_arg); + Void::Log::info("Install", "Uninstalling VBS-owned files from '{}'...", *opts.prefix_arg); + auto removed = Install::uninstall_prefix(*opts.prefix_arg); if (!removed) { std::cerr << "vbs uninstall: " << removed.error().message() << '\n'; return 1; } - std::cout << "uninstalled " << *removed << " VBS-owned files from " << *prefix_arg << '\n'; + std::cout << "uninstalled " << *removed << " VBS-owned files from " << *opts.prefix_arg << '\n'; return 0; } -int run_gc_command(int argc, char **argv) { - std::string build_arg = (std::filesystem::current_path() / "build").string(); - std::string max_bytes_arg = "0"; - Void::Argparse::Parser parser{"vbs gc", - "Recover interrupted state and garbage-collect CAS blobs."}; - parser.option_default("--build-dir", "-B", "Build directory", build_arg, build_arg) - .option_default("--max-bytes", "", - "Target maximum retained CAS bytes (0=unreferenced only)", max_bytes_arg, - "0"); +struct GcCmdOptions { + std::string build_arg; + std::string max_bytes_arg{"0"}; +}; - std::vector sub_argv{argv[0]}; - for (int i = 2; i < argc; ++i) { - sub_argv.push_back(argv[i]); - } - if (auto rc = parse_with_void_argparse(parser, "vbs gc", sub_argv); rc) { - return *rc; - } +int execute_gc_command(const GcCmdOptions &opts) { std::uint64_t max_bytes = 0; - const auto [ptr, ec] = std::from_chars(max_bytes_arg.data(), - max_bytes_arg.data() + max_bytes_arg.size(), max_bytes); - if (ec != std::errc{} || ptr != max_bytes_arg.data() + max_bytes_arg.size()) { - std::cerr << "vbs gc: invalid --max-bytes value '" << max_bytes_arg << "'\n"; + const auto [ptr, ec] = + std::from_chars(opts.max_bytes_arg.data(), + opts.max_bytes_arg.data() + opts.max_bytes_arg.size(), max_bytes); + if (ec != std::errc{} || ptr != opts.max_bytes_arg.data() + opts.max_bytes_arg.size()) { + std::cerr << "vbs gc: invalid --max-bytes value '" << opts.max_bytes_arg << "'\n"; return 2; } - auto st = State::StateStore::open(std::filesystem::path{build_arg} / ".vbs"); + Void::Log::info("GC", "Running state recovery and CAS garbage collection in '{}'...", + opts.build_arg); + auto st = State::StateStore::open(std::filesystem::path{opts.build_arg} / ".vbs"); if (!st) { std::cerr << "vbs gc: " << st.error().message() << '\n'; return 1; @@ -1248,26 +1262,18 @@ int run_gc_command(int argc, char **argv) { return 0; } -int run_gen_tests_command(int argc, char **argv) { +struct GenTestsCmdOptions { std::optional input_arg; std::optional out_arg; - Void::Argparse::Parser parser{"vbs gen-tests", - "Generate native Void::Testing registration unit (no CMake)."}; - parser.option("--input", "", "Input test .cpp file", input_arg) - .option("--output-dir", "", "Output directory for generated registration .cpp", out_arg); +}; - std::vector sub_argv{argv[0]}; - for (int i = 2; i < argc; ++i) { - sub_argv.push_back(argv[i]); - } - if (auto rc = parse_with_void_argparse(parser, "vbs gen-tests", sub_argv); rc) { - return *rc; - } - if (!input_arg || !out_arg) { +int execute_gen_tests_command(const GenTestsCmdOptions &opts) { + if (!opts.input_arg || !opts.out_arg) { std::cerr << "vbs gen-tests: --input and --output-dir are required\n"; return 2; } - auto gen = SelfHost::generate_test_registration_unit(*input_arg, *out_arg); + Void::Log::info("GenTests", "Scanning test cases in '{}'...", *opts.input_arg); + auto gen = SelfHost::generate_test_registration_unit(*opts.input_arg, *opts.out_arg); if (!gen) { std::cerr << "vbs gen-tests: " << gen.error().message() << '\n'; return 1; @@ -1276,50 +1282,21 @@ int run_gen_tests_command(int argc, char **argv) { return 0; } -int run_deps_command(int argc, char **argv) { - if (argc < 3) { - std::cerr << "vbs deps: expected 'resolve' or 'update'\n"; - return 2; - } - const std::string_view sub{argv[2]}; - if (sub == "--help" || sub == "-h") { - Void::Argparse::Parser hp{ - "vbs deps ", - "Resolve or upgrade dependencies and atomically update vbs.lock."}; - std::cout << hp.help(); - return 0; - } - if (sub != "resolve" && sub != "update") { - std::cerr << "vbs deps: unknown subcommand '" << sub << "'\n"; - return 2; - } - - std::string project_arg = std::filesystem::current_path().string(); +struct DepsCmdOptions { + std::string project_arg; std::optional build_arg; - std::string profile_name = "debug"; - bool offline = false; + std::string profile_name{"debug"}; + bool offline{false}; +}; - Void::Argparse::Parser parser{ - "vbs deps " + std::string{sub}, - sub == "update" ? "Re-solve dependencies allowing compatible SemVer upgrades." - : "Resolve dependencies preserving pinned compatible versions."}; - parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) - .option("--build-dir", "-B", "Build output directory", build_arg) - .option_default("--profile", "-p", "Profile name", profile_name, "debug") - .flag("--offline", "", "Disallow network fetches", offline); - - std::vector sub_argv{argv[0]}; - for (int i = 3; i < argc; ++i) { - sub_argv.push_back(argv[i]); - } - if (auto rc = parse_with_void_argparse(parser, "vbs deps " + std::string{sub}, sub_argv); rc) { - return *rc; - } - - const std::filesystem::path project_root{project_arg}; +int execute_deps_command(std::string_view sub, const DepsCmdOptions &opts) { + const std::filesystem::path project_root{opts.project_arg}; const std::filesystem::path build_root = - build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build"); const auto fopts = make_frontend_opts(project_root, build_root, {}); + Void::Log::info("Deps", "{} dependencies for profile '{}' in '{}'...", + sub == "update" ? "Updating" : "Resolving", opts.profile_name, + project_root.string()); auto compiled = Config::compile_descriptor(fopts); if (!compiled) { std::cerr << "vbs deps: " << compiled.error().message() << '\n'; @@ -1330,7 +1307,7 @@ int run_deps_command(int argc, char **argv) { std::cerr << "vbs deps: " << profs.error().message() << '\n'; return 1; } - auto ctx = profs->resolve(profile_name, std::nullopt, Toolchain::host_os_name(), + auto ctx = profs->resolve(opts.profile_name, std::nullopt, Toolchain::host_os_name(), Toolchain::host_architecture_name()); auto desc = Config::evaluate_project(*compiled, ctx, fopts); if (!desc) { @@ -1361,7 +1338,7 @@ int run_deps_command(int argc, char **argv) { const std::string base_rev = existing->has_value() ? (*existing)->revision_hash : std::string{}; auto resolved = resolve_and_materialize_deps(ctx, *merged, project_root, build_root, *existing, - offline, sub == "update"); + opts.offline, sub == "update"); if (!resolved) { std::cerr << "vbs deps: " << resolved.error().message() << '\n'; return 1; @@ -1379,69 +1356,258 @@ int run_deps_command(int argc, char **argv) { } // namespace int main(int argc, char **argv) { + const std::string cwd = std::filesystem::current_path().string(); bool show_version = false; - auto root_parser = make_root_parser(show_version); - if (argc == 1) { - std::cout << root_parser.help(); - return 0; - } - const std::string_view cmd{argv[1]}; - if (cmd == "--help" || cmd == "-h") { - if (argc > 2) { - std::cerr << "vbs: --help must be used alone\n"; - return 2; + bool verbose = false; + bool quiet = false; + + BuildCmdOptions build_opts; + build_opts.project_arg = cwd; + CompDbCmdOptions compdb_opts; + compdb_opts.project_arg = cwd; + DescribeCmdOptions describe_opts; + describe_opts.project_arg = cwd; + WatchCmdOptions watch_opts; + watch_opts.project_arg = cwd; + DepsCmdOptions deps_opts; + deps_opts.project_arg = cwd; + InstallCmdOptions install_opts; + install_opts.project_arg = cwd; + UninstallCmdOptions uninstall_opts; + PackCmdOptions pack_opts; + pack_opts.project_arg = cwd; + PublishCmdOptions publish_opts; + publish_opts.project_arg = cwd; + BridgeCmdOptions bridge_opts; + GcCmdOptions gc_opts; + gc_opts.build_arg = (std::filesystem::path{cwd} / "build").string(); + GenTestsCmdOptions gen_tests_opts; + + auto add_log_flags = [&](Void::Argparse::Parser &p, bool allow_short_v = true) { + p.flag("--verbose", allow_short_v ? "-v" : "", "Enable verbose debug logs", verbose) + .flag("--quiet", "-q", "Suppress progress logs (warnings and errors only)", quiet); + }; + + auto configure_build_or_test = [&](Void::Argparse::Parser &p) { + p.option_default("--project", "-C", "Project directory", build_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", build_opts.build_arg) + .option_many("--profile", "-p", "Profile to build", build_opts.profiles) + .option_many("--target", "-t", "Target to build/test", build_opts.targets) + .option("--compiler", "", "Override compiler family (gcc|clang)", + build_opts.compiler_arg) + .option("--editor-profile", "", "Editor profile for compile_commands.json", + build_opts.editor_profile) + .option_many("--build-source", "", "Additional build description source", + build_opts.extra_build_sources) + .option("--jobs", "-j", "Maximum parallel compilation/link jobs", build_opts.jobs_arg) + .flag("--locked", "", "Require existing up-to-date vbs.lock", build_opts.locked) + .flag("--offline", "", "Disallow network fetches", build_opts.offline) + .flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache); + add_log_flags(p); + }; + + Void::Argparse::Parser root{"vbs", + "VoidBuildSystem — native C++ build system & package manager."}; + root.require_subcommand(false).flag("--version", "-V", "Show version", show_version); + add_log_flags(root); + + configure_build_or_test( + root.subcommand("build", "Configure and build selected profiles and targets")); + configure_build_or_test(root.subcommand("test", "Build and run declared test targets")); + + auto &describe_cmd = + root.subcommand("describe", "Evaluate build.cpp and emit versioned graph summary JSON"); + describe_cmd + .option_default("--project", "-C", "Project directory", describe_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", describe_opts.build_arg) + .option_default("--profile", "-p", "Profile name", describe_opts.profile_name, "debug") + .option("--compiler", "", "Override compiler family (gcc|clang)", + describe_opts.compiler_arg); + add_log_flags(describe_cmd); + + auto &compdb_cmd = root.subcommand( + "compdb", "Manage per-profile compile_commands.json selection and metadata projection"); + auto configure_compdb_common = [&](Void::Argparse::Parser &p, bool with_profile) { + p.option_default("--project", "-C", "Project directory", compdb_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", compdb_opts.build_arg); + if (with_profile) { + p.option("--profile", "-p", "Profile name", compdb_opts.profile_name); } - std::cout << root_parser.help(); + add_log_flags(p); + }; + auto &compdb_use = + compdb_cmd.subcommand("use", "Select active editor compilation database profile"); + configure_compdb_common(compdb_use, true); + compdb_use.positional_many("profile", "Profile name (optional if --profile is given)", + compdb_opts.positional_profiles, false); + configure_compdb_common( + compdb_cmd.subcommand("show", "Show active editor compilation database selection"), false); + configure_compdb_common( + compdb_cmd.subcommand("export", + "Evaluate and export compile_commands.json without compiling"), + true); + configure_compdb_common( + compdb_cmd.subcommand("watch", "Watch project metadata and refresh compile_commands.json"), + true); + + auto &watch_cmd = + root.subcommand("watch", "Watch project sources and rebuild on verified changes"); + watch_cmd.option_default("--project", "-C", "Project directory", watch_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", watch_opts.build_arg) + .option("--profile", "-p", "Profile to watch", watch_opts.profile_arg) + .option_many("--target", "-t", "Target to rebuild", watch_opts.targets); + add_log_flags(watch_cmd); + + auto &deps_cmd = root.subcommand("deps", "Resolve or upgrade dependencies and update vbs.lock"); + auto configure_deps_sub = [&](Void::Argparse::Parser &p) { + p.option_default("--project", "-C", "Project directory", deps_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", deps_opts.build_arg) + .option_default("--profile", "-p", "Profile name", deps_opts.profile_name, "debug") + .flag("--offline", "", "Disallow network fetches", deps_opts.offline); + add_log_flags(p); + }; + configure_deps_sub(deps_cmd.subcommand( + "resolve", "Resolve dependencies preserving pinned compatible versions")); + configure_deps_sub( + deps_cmd.subcommand("update", "Re-solve dependencies allowing compatible SemVer upgrades")); + + auto &install_cmd = + root.subcommand("install", "Build, stage, and install declared products and exports"); + install_cmd + .option_default("--project", "-C", "Project directory", install_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", install_opts.build_arg) + .option_default("--profile", "-p", "Profile name", install_opts.profile_name, "debug") + .option("--compiler", "", "Override compiler family (gcc|clang)", install_opts.compiler_arg) + .option("--prefix", "", "Install destination prefix (required)", install_opts.prefix_arg) + .option("--package-name", "", "Exported package name", install_opts.pkg_name_arg) + .option_default("--package-version", "", "Exported package version", install_opts.pkg_ver, + "0.1.0") + .option("--component", "", "Install only a specific component", install_opts.component_arg) + .flag("--no-cmake-export", "", "Disable CMake Config.cmake export", + install_opts.no_cmake_export) + .flag("--no-native-export", "", "Disable native VBS package metadata export", + install_opts.no_native_export); + add_log_flags(install_cmd); + + auto &uninstall_cmd = + root.subcommand("uninstall", "Safely remove only VBS-owned files recorded in the manifest"); + uninstall_cmd.option("--prefix", "", "Installed prefix directory (required)", + uninstall_opts.prefix_arg); + add_log_flags(uninstall_cmd); + + auto &pack_cmd = root.subcommand("pack", "Create a deterministic USTAR source archive (.tar)"); + pack_cmd.option_default("--project", "-C", "Project directory", pack_opts.project_arg, cwd) + .option_default("--output", "-o", "Output archive path", pack_opts.out_arg, "package.tar"); + add_log_flags(pack_cmd); + + auto &publish_cmd = + root.subcommand("publish", "Pack and publish a release to a VBS package registry"); + publish_cmd + .option_default("--project", "-C", "Project directory", publish_opts.project_arg, cwd) + .option("--registry", "-r", "Registry base URL (or VBS_REGISTRY_URL)", + publish_opts.registry_arg) + .option("--name", "-n", "Package name", publish_opts.name_arg) + .option("--version", "-v", "Strict SemVer release version", publish_opts.version_arg) + .option_default("--description", "-d", "Package description", publish_opts.description, "") + .option_default("--token-env", "", "Environment variable holding bearer token", + publish_opts.token_env, "VBS_REGISTRY_TOKEN") + .flag("--private", "", "Publish package as private", publish_opts.is_private); + add_log_flags(publish_cmd, false); // `-v` is `--version` on `publish`. + + auto &bridge_cmd = root.subcommand("bridge", "CMake VbsDeps.cmake dependency bridge backend"); + bridge_cmd.option("--request", "", "Path to bridge request JSON", bridge_opts.req_arg) + .option("--output", "", "Path to output CMake fragment", bridge_opts.out_arg); + add_log_flags(bridge_cmd); + + auto &gc_cmd = + root.subcommand("gc", "Recover interrupted state and garbage-collect unreferenced blobs"); + gc_cmd + .option_default("--build-dir", "-B", "Build directory", gc_opts.build_arg, + gc_opts.build_arg) + .option_default("--max-bytes", "", + "Target maximum retained CAS bytes (0=unreferenced only)", + gc_opts.max_bytes_arg, "0"); + add_log_flags(gc_cmd); + + auto &gen_tests_cmd = + root.subcommand("gen-tests", "Generate native Void::Testing registration unit (no CMake)"); + gen_tests_cmd.option("--input", "", "Input test .cpp file", gen_tests_opts.input_arg) + .option("--output-dir", "", "Output directory for generated registration .cpp", + gen_tests_opts.out_arg); + add_log_flags(gen_tests_cmd); + + const auto parsed = root.parse_detailed(argc, argv); + if (parsed.is_help()) { + std::cout << parsed.message; return 0; } - if (cmd == "--version" || cmd == "-V") { - if (argc > 2) { - std::cerr << "vbs: unexpected argument after --version\n"; + if (parsed.is_error()) { + std::cerr << "vbs: " << parsed.message << '\n'; + return 2; + } + if (show_version) { + if (!parsed.matched_command_path.empty()) { + std::cerr << "vbs: --version cannot be combined with subcommands\n"; return 2; } std::cout << "vbs " << Bootstrap::version << '\n'; return 0; } - if (cmd == "build") { - return run_build_or_test(argc, argv, false); - } - if (cmd == "test") { - return run_build_or_test(argc, argv, true); - } - if (cmd == "compdb") { - return run_compdb_command(argc, argv); - } - if (cmd == "describe") { - return run_describe_command(argc, argv); - } - if (cmd == "watch") { - return run_watch_command(argc, argv); - } - if (cmd == "bridge") { - return run_bridge_command(argc, argv); - } - if (cmd == "pack") { - return run_pack_command(argc, argv); - } - if (cmd == "publish") { - return run_publish_command(argc, argv); - } - if (cmd == "install") { - return run_install_command(argc, argv); - } - if (cmd == "uninstall") { - return run_uninstall_command(argc, argv); - } - if (cmd == "gc") { - return run_gc_command(argc, argv); - } - if (cmd == "gen-tests") { - return run_gen_tests_command(argc, argv); - } - if (cmd == "deps") { - return run_deps_command(argc, argv); + if (parsed.matched_command_path.empty()) { + std::cout << root.help(); + return 0; } - std::cerr << "vbs: unknown command '" << cmd << "'; use --help\n"; + const std::string_view cmd = parsed.matched_command_path.front(); + const bool machine_quiet_default = + (cmd == "describe") || (cmd == "compdb" && parsed.matched_command_path.size() >= 2 && + parsed.matched_command_path[1] == "show"); + const Void::Log::Level log_level = + verbose ? Void::Log::Level::Debug + : ((quiet || machine_quiet_default) ? Void::Log::Level::Warning + : Void::Log::Level::Info); + ConsoleLogGuard log_guard{log_level}; + + if (cmd == "build") { + return execute_build_or_test(std::move(build_opts), false); + } + if (cmd == "test") { + return execute_build_or_test(std::move(build_opts), true); + } + if (cmd == "describe") { + return execute_describe_command(describe_opts); + } + if (cmd == "compdb") { + return execute_compdb_command(parsed.matched_command_path.at(1), std::move(compdb_opts)); + } + if (cmd == "watch") { + return execute_watch_command(std::move(watch_opts)); + } + if (cmd == "deps") { + return execute_deps_command(parsed.matched_command_path.at(1), deps_opts); + } + if (cmd == "install") { + return execute_install_command(install_opts); + } + if (cmd == "uninstall") { + return execute_uninstall_command(uninstall_opts); + } + if (cmd == "pack") { + return execute_pack_command(pack_opts); + } + if (cmd == "publish") { + return execute_publish_command(publish_opts); + } + if (cmd == "bridge") { + return execute_bridge_command(bridge_opts); + } + if (cmd == "gc") { + return execute_gc_command(gc_opts); + } + if (cmd == "gen-tests") { + return execute_gen_tests_command(gen_tests_opts); + } + + std::cerr << "vbs: unhandled subcommand '" << cmd << "'\n"; return 2; } diff --git a/src/Package/Archive.cpp b/src/Package/Archive.cpp index 9dbe230..93c6d10 100644 --- a/src/Package/Archive.cpp +++ b/src/Package/Archive.cpp @@ -1,18 +1,13 @@ #include +#include #include #include #include #include -#include -#include -#include -#include #include #include -#include -#include namespace Void::Build::Package { namespace { @@ -21,157 +16,13 @@ Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string m 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('0' + (val & 7u)); - val >>= 3; - } -} - -std::optional 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(src[i] - '0'); - } - return any ? std::optional{val} : std::optional{0}; -} - -void finalize_tar_header(std::array &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(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(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(c); - } - write_octal(hdr.data() + 148, 7, chksum); - hdr[155] = ' '; -} - -std::string build_pax_path_record(std::string_view path) { - // Format: " 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(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(n); - } - return true; -} - -bool read_exact(int fd, void *data, std::size_t len, std::size_t &got_out) { - auto *p = static_cast(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) { +bool is_excluded_package_path(const std::filesystem::path &rel) { + for (const auto &part : rel) { + const auto s = part.string(); + if (s == ".git" || s == ".vbs" || s == "build" || s == ".serena" || s == ".cache" || + s == "keys" || s == ".env" || s == "WG.conf") { return true; } - got_out += static_cast(n); - } - return true; -} - -bool is_zero_block(const std::array &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; } @@ -182,140 +33,39 @@ Void::Result::Result create_deterministic_tar(const std::filesystem::path &output_tar, std::vector 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 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(::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{static_cast(buf), n}); - return write_all(fd, buf, n); - }; + std::ranges::sort(entries, {}, &ArchiveEntrySpec::archive_path); - std::array zero_pad{}; - std::array hdr{}; - std::array 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::min(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((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")}; - } + std::vector v_entries; + v_entries.reserve(entries.size()); + for (const auto &e : entries) { + Void::Archive::CreateEntry ce; + ce.path = e.archive_path; + ce.type = Void::Archive::EntryType::RegularFile; + ce.executable = (e.mode & 0111u) != 0; + ce.source_file = e.source_file; + ce.mode = e.mode & 0777u; + v_entries.push_back(std::move(ce)); } - // 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")}; - } + Void::Archive::CreationOptions opts; + opts.compression = Void::Archive::ArchiveCompression::None; + opts.reproducible = true; + opts.canonical_mtime = reproducibility_epoch; + opts.canonical_uid = 0; + opts.canonical_gid = 0; + opts.prefer_builtin_tar = true; - if (const auto closed = guard.close(); !closed) { - std::filesystem::remove(temp_tar, ec); - return std::unexpected{closed.error()}; + // Delegate deterministic PAX/USTAR tar creation directly to Void::Archive (VL-006). + auto created = Void::Archive::create(output_tar, v_entries, opts); + if (!created) { + return std::unexpected{std::move(created.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(); + return Util::sha256_file_hex(output_tar); } Void::Result::Result @@ -324,8 +74,9 @@ create_source_package(const std::filesystem::path &project_root, 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")}; + return std::unexpected{make_error( + Void::System::SystemErrorCode::not_found, + std::format("create_source_package: '{}' is not a directory", project_root.string()))}; } std::vector entries; @@ -333,23 +84,19 @@ create_source_package(const std::filesystem::path &project_root, 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 (is_excluded_package_path(rel)) { 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}); + auto meta = Platform::stat_lstat(it->path()); + if (!meta || !meta->exists || meta->is_symlink) { + continue; + } + if (meta->is_regular) { + entries.push_back({rel.lexically_normal().generic_string(), it->path(), + (meta->mode & 0111u) ? 0755u : 0644u}); } } return create_deterministic_tar(output_tar, std::move(entries), reproducibility_epoch); @@ -358,222 +105,45 @@ create_source_package(const std::filesystem::path &project_root, Void::Result::Result 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(); + const auto parent = destination_dir.has_parent_path() ? destination_dir.parent_path() + : std::filesystem::path{"."}; std::filesystem::create_directories(parent, ec); - const auto stage_dir = parent / (destination_dir.filename().string() + ".extract_" + - std::to_string(static_cast(::getpid()))); - std::filesystem::remove_all(stage_dir, ec); - std::filesystem::create_directories(stage_dir, ec); + if (ec) { + return std::unexpected{make_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("extract_safe_tar: failed creating parent '{}'", parent.string()), + ec.value())}; + } - auto abort_extract = [&] { std::filesystem::remove_all(stage_dir, ec); }; + // Delegate safe staged extraction (rejecting traversal, absolute paths, symlinks, + // hardlinks, duplicates, and quota overflows) directly to Void::Archive (VL-006). + Void::Archive::StagedExtractionOptions opts; + opts.limits.max_entries = limits.max_entries; + opts.limits.max_file_bytes = limits.max_file_bytes; + opts.limits.max_total_bytes = limits.max_total_bytes; + opts.preserve_executable_bit = true; + + auto staged = Void::Archive::extract_staged(tar_path, parent, opts); + if (!staged) { + return std::unexpected{std::move(staged.error())}; + } ArchiveExtractionStats stats; - std::set seen_paths; - std::optional next_pax_path; - std::array hdr{}; - std::array 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(' ') - : static_cast(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(*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(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((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(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::min(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((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")}; + stats.entries = staged->entries(); + stats.total_bytes = staged->bytes(); + for (const auto &info : staged->inventory()) { + if (info.type == Void::Archive::EntryType::RegularFile) { + stats.extracted_files.emplace_back(info.path); } } - // 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())}; + auto pub = staged->publish(destination_dir.filename().string()); + if (!pub) { + return std::unexpected{std::move(pub.error())}; } return stats; } diff --git a/src/Package/Fetch.cpp b/src/Package/Fetch.cpp index 6f4941a..42e4cec 100644 --- a/src/Package/Fetch.cpp +++ b/src/Package/Fetch.cpp @@ -4,7 +4,9 @@ #include #include #include +#include #include +#include #include #include @@ -265,6 +267,26 @@ materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &o // 3. Exact pinned Git revision source. if (dep.source_kind == DependencySourceKind::Git) { + if (dep.name == "VoidLibrary") { + if (auto override_dir = Void::Configuration::get_env("VBS_VOID_SOURCE_DIR"); + override_dir && !override_dir->empty()) { + const std::filesystem::path raw{*override_dir}; + 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)) { + Void::Log::info("Fetch", + "Using VBS_VOID_SOURCE_DIR override for 'VoidLibrary': {}", + canon.string()); + MaterializedSource out; + out.alias = dep.name; + out.source_dir = canon; + out.content_identity_hash = dep.revision + "-local"; + out.from_cache = true; + return out; + } + } + } + const auto git_dir = options.cache_dir / "git" / (sanitize_key(dep.name) + "_" + dep.revision); const auto marker = git_dir / ".vbs_verified_rev"; @@ -275,6 +297,8 @@ materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &o } if (std::filesystem::is_regular_file(marker, ec)) { + Void::Log::info("Fetch", "Using cached git dependency '{}' @ {}", dep.name, + dep.revision.substr(0, 12)); MaterializedSource out; out.alias = dep.name; out.source_dir = git_dir; @@ -283,6 +307,9 @@ materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &o return out; } + Void::Log::info("Fetch", "Fetching git dependency '{}' from {} @ {}...", dep.name, + redact_secrets(dep.location), dep.revision.substr(0, 12)); + const bool is_local_repo = dep.location.starts_with("file://") || dep.location.starts_with("/") || std::filesystem::is_directory(dep.location, ec); diff --git a/src/Package/Solver.cpp b/src/Package/Solver.cpp index 8a22d52..6b2c94b 100644 --- a/src/Package/Solver.cpp +++ b/src/Package/Solver.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include @@ -16,99 +15,9 @@ Void::Result::Error solve_err(std::string msg) { 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. +// Delegates directly to Void::Semver::parse_range (VL-013 shorthand comparators now upstream). std::optional 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); + return Void::Semver::parse_range(expr); } struct ActiveConstraint { diff --git a/src/Package/Toml.cpp b/src/Package/Toml.cpp index 3e7170c..3021fc0 100644 --- a/src/Package/Toml.cpp +++ b/src/Package/Toml.cpp @@ -1,13 +1,11 @@ #include -#include +#include #include #include #include #include -#include -#include #include #include @@ -19,652 +17,101 @@ Void::Result::Error parse_err(const SourceOrigin &orig, std::string msg) { 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)} {} +TomlValue convert_from_void_toml(const Void::Data::Toml::Value &src, + const std::string &source_name); - Void::Result::Result 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()); +TomlTable convert_table_from_void_toml(const Void::Data::Toml::Table &src, + const std::string &source_name) { + TomlTable dst; + for (const auto &[k, v] : src.entries) { + dst.emplace(k, convert_from_void_toml(v, source_name)); } - - 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 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 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 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 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, Void::Result::Error> parse_key_path() { - std::vector 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 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 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 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 - navigate_table_header(TomlTable &root, const std::vector &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 - insert_key_value(TomlTable &table, const std::vector &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 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); + return dst; } -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]); +TomlValue convert_from_void_toml(const Void::Data::Toml::Value &src, + const std::string &source_name) { + const SourceOrigin orig{source_name, src.origin.line, src.origin.column}; + switch (src.kind()) { + case Void::Data::Toml::ValueKind::String: + return TomlValue{*src.as_string(), orig}; + case Void::Data::Toml::ValueKind::Boolean: + return TomlValue{*src.as_bool(), orig}; + case Void::Data::Toml::ValueKind::Integer: + return TomlValue{*src.as_integer(), orig}; + case Void::Data::Toml::ValueKind::Float: + return TomlValue{*src.as_float(), orig}; + case Void::Data::Toml::ValueKind::DateTime: + return TomlValue{src.as_datetime()->to_string(), orig}; + case Void::Data::Toml::ValueKind::Array: { + TomlValue out = TomlValue::make_array(orig); + for (const auto &el : src.as_array()->elements) { + out.as_array_mut().push_back(convert_from_void_toml(el, source_name)); } - 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); + case Void::Data::Toml::ValueKind::Table: { + TomlValue out = TomlValue::make_table(orig); + out.as_table_mut() = convert_table_from_void_toml(*src.as_table(), source_name); + return out; } - out += "}"; - return out; + case Void::Data::Toml::ValueKind::ArrayOfTables: { + TomlValue out = TomlValue::make_array(orig); + for (const auto &tbl : src.as_array_of_tables()->tables) { + TomlValue item = TomlValue::make_table(orig); + item.as_table_mut() = convert_table_from_void_toml(tbl, source_name); + out.as_array_mut().push_back(std::move(item)); + } + return out; + } + } + return TomlValue{std::string{}, orig}; } -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); - } +Void::Data::Toml::Value convert_to_void_toml(const TomlValue &src); + +Void::Data::Toml::Table convert_table_to_void_toml(const TomlTable &src) { + Void::Data::Toml::Table dst; + for (const auto &[k, v] : src) { + dst.entries.emplace(k, convert_to_void_toml(v)); } + return dst; } -bool option_value_equal(const OptionValue &a, const OptionValue &b) { return a.value == b.value; } +Void::Data::Toml::Value convert_to_void_toml(const TomlValue &src) { + if (src.is_string()) { + return Void::Data::Toml::Value{src.as_string()}; + } + if (src.is_bool()) { + return Void::Data::Toml::Value{src.as_bool()}; + } + if (src.is_int()) { + return Void::Data::Toml::Value{src.as_int()}; + } + if (src.is_double()) { + return Void::Data::Toml::Value{src.as_double()}; + } + if (src.is_array()) { + Void::Data::Toml::Array arr; + for (const auto &el : src.as_array()) { + arr.elements.push_back(convert_to_void_toml(el)); + } + return Void::Data::Toml::Value{std::move(arr)}; + } + return Void::Data::Toml::Value{convert_table_to_void_toml(src.as_table())}; +} 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()) { + if (a.name != b.name || a.source_kind != b.source_kind || a.location != b.location || + a.revision != b.revision || a.sha256 != b.sha256 || a.package != b.package || + a.version != b.version || a.registry_authority != b.registry_authority || + a.builder != b.builder || 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)) { + const auto it = b.options.find(k); + if (it == b.options.end() || av.value != it->second.value) { return false; } } @@ -675,23 +122,29 @@ bool dependency_records_equal(const DependencyRecord &a, const DependencyRecord std::string SourceOrigin::format() const { if (line == 0) { - return file.empty() ? "" : file; + return file; } return std::format("{}:{}:{}", file, line, column); } -TomlValue TomlValue::make_table(SourceOrigin origin) { - return TomlValue{std::make_shared(), std::move(origin)}; +TomlValue TomlValue::make_table(SourceOrigin orig) { + return TomlValue{std::make_shared(), std::move(orig)}; } -TomlValue TomlValue::make_array(SourceOrigin origin) { - return TomlValue{std::make_shared(), std::move(origin)}; +TomlValue TomlValue::make_array(SourceOrigin orig) { + return TomlValue{std::make_shared(), std::move(orig)}; } Void::Result::Result parse_toml(std::string_view text, std::string_view source_name) { - TomlParser parser{text, std::string{source_name}}; - return parser.parse(); + // Delegate full TOML 1.0 parsing directly to Void::Data::Toml (VL-002). + auto parsed = Void::Data::Toml::parse(text); + if (!parsed) { + const SourceOrigin err_orig{std::string{source_name}, parsed.error().origin.line, + parsed.error().origin.column}; + return std::unexpected{parse_err(err_orig, parsed.error().message)}; + } + return convert_table_from_void_toml(parsed->root, std::string{source_name}); } Void::Result::Result @@ -704,9 +157,7 @@ parse_toml_file(const std::filesystem::path &path) { } std::string serialize_toml(const TomlTable &table) { - std::string out; - serialize_table_section(table, "", out); - return out; + return Void::Data::Toml::serialize_table(convert_table_to_void_toml(table)); } Void::Result::Result, Void::Result::Error> @@ -717,7 +168,6 @@ load_dependencies_toml(const std::filesystem::path &toml_path) { } 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( diff --git a/src/Platform/FileOps.cpp b/src/Platform/FileOps.cpp index 94a739f..2ec2b09 100644 --- a/src/Platform/FileOps.cpp +++ b/src/Platform/FileOps.cpp @@ -1,17 +1,11 @@ #include -#include #include -#include -#include #include #include #include -#include #include -#include -#include #include #include #include @@ -19,13 +13,6 @@ namespace Void::Build::Platform { namespace { -std::atomic g_temp_seq{0}; - -std::string unique_suffix() { - const auto seq = g_temp_seq.fetch_add(1, std::memory_order_relaxed); - return std::format(".vbs_tmp_{}_{}", static_cast(::getpid()), seq); -} - Void::Result::Error sys_err(int err, std::string message) { return Void::System::make_system_error(Void::System::map_errno_to_system_code(err), std::move(message), err); @@ -33,26 +20,6 @@ Void::Result::Error sys_err(int err, std::string message) { } // namespace -FileLock::~FileLock() noexcept { release(); } - -FileLock::FileLock(FileLock &&other) noexcept : fd_{std::exchange(other.fd_, -1)} {} - -FileLock &FileLock::operator=(FileLock &&other) noexcept { - if (this != &other) { - release(); - fd_ = std::exchange(other.fd_, -1); - } - return *this; -} - -void FileLock::release() noexcept { - if (fd_ >= 0) { - (void)::flock(fd_, LOCK_UN); - (void)::close(fd_); - fd_ = -1; - } -} - Void::Result::Result FileLock::acquire(const std::filesystem::path &lock_path, LockMode mode, bool non_blocking) { std::error_code ec; @@ -64,28 +31,25 @@ FileLock::acquire(const std::filesystem::path &lock_path, LockMode mode, bool no lock_path.string(), ec.message()))}; } } - const int fd = ::open(lock_path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0644); - if (fd < 0) { - const int err = errno; - return std::unexpected{ - sys_err(err, std::format("FileLock: cannot open '{}'", lock_path.string()))}; - } - int op = (mode == LockMode::Exclusive) ? LOCK_EX : LOCK_SH; + const auto vl_mode = (mode == LockMode::Exclusive) ? Void::FileSystem::LockMode::Exclusive + : Void::FileSystem::LockMode::Shared; if (non_blocking) { - op |= LOCK_NB; - } - for (;;) { - if (::flock(fd, op) == 0) { - return FileLock{fd}; + auto res = Void::FileSystem::FileLock::try_lock(lock_path, vl_mode); + if (!res) { + return std::unexpected{std::move(res.error())}; } - if (errno == EINTR) { - continue; + if (!res->has_value()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::busy, + std::format("FileLock: '{}' is already locked", lock_path.string()), EWOULDBLOCK)}; } - const int err = errno; - (void)::close(fd); - return std::unexpected{ - sys_err(err, std::format("FileLock: flock failed for '{}'", lock_path.string()))}; + return FileLock{std::move(**res)}; } + auto res = Void::FileSystem::FileLock::lock(lock_path, vl_mode); + if (!res) { + return std::unexpected{std::move(res.error())}; + } + return FileLock{std::move(*res)}; } Void::Result::Result @@ -140,26 +104,6 @@ stat_lstat(const std::filesystem::path &path) { Void::Result::Result copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst, std::optional mode_override) { - const int src_fd = ::open(src.c_str(), O_RDONLY | O_CLOEXEC); - if (src_fd < 0) { - const int err = errno; - return std::unexpected{ - sys_err(err, std::format("copy_isolated: cannot open source '{}'", src.string()))}; - } - Void::System::OwnedFd src_guard{src_fd}; - - struct stat src_st{}; - if (::fstat(src_fd, &src_st) != 0) { - const int err = errno; - return std::unexpected{ - sys_err(err, std::format("copy_isolated: fstat failed for '{}'", src.string()))}; - } - if (!S_ISREG(src_st.st_mode)) { - return std::unexpected{Void::System::make_system_error( - Void::System::SystemErrorCode::invalid_argument, - std::format("copy_isolated: source '{}' is not a regular file", src.string()))}; - } - std::error_code ec; if (dst.has_parent_path()) { std::filesystem::create_directories(dst.parent_path(), ec); @@ -169,86 +113,24 @@ copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst dst.string(), ec.message()))}; } } + Void::FileSystem::CopyOptions opts; + opts.overwrite = true; + opts.preserve_permissions = !mode_override.has_value(); + opts.durability = Void::FileSystem::ReplaceDurability::atomic_visibility; - const auto mode = mode_override.value_or(static_cast(src_st.st_mode & 0777u)); - const auto temp_path = dst.parent_path() / (dst.filename().string() + unique_suffix()); - const int dst_fd = ::open(temp_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, - static_cast(mode)); - if (dst_fd < 0) { - const int err = errno; - return std::unexpected{sys_err( - err, std::format("copy_isolated: cannot create temp '{}'", temp_path.string()))}; + auto res = Void::FileSystem::reflink_copy_file(src, dst, opts); + if (!res) { + return std::unexpected{std::move(res.error())}; } - Void::System::OwnedFd dst_guard{dst_fd}; - auto cleanup = [&] { (void)::unlink(temp_path.c_str()); }; - - bool used_reflink = false; -#ifdef FICLONE - if (::ioctl(dst_fd, FICLONE, src_fd) == 0) { - used_reflink = true; + if (mode_override) { + (void)::chmod(dst.c_str(), static_cast(*mode_override)); } -#endif - - if (!used_reflink) { - std::array buf{}; - for (;;) { - const ssize_t n = ::read(src_fd, buf.data(), buf.size()); - if (n > 0) { - std::size_t off = 0; - while (off < static_cast(n)) { - const ssize_t w = - ::write(dst_fd, buf.data() + off, static_cast(n) - off); - if (w < 0) { - if (errno == EINTR) { - continue; - } - const int err = errno; - cleanup(); - return std::unexpected{ - sys_err(err, std::format("copy_isolated: write failed for '{}'", - dst.string()))}; - } - off += static_cast(w); - } - } else if (n == 0) { - break; - } else if (errno != EINTR) { - const int err = errno; - cleanup(); - return std::unexpected{ - sys_err(err, std::format("copy_isolated: read failed for '{}'", src.string()))}; - } - } - } - - (void)::fchmod(dst_fd, static_cast(mode)); - if (const auto closed = dst_guard.close(); !closed) { - cleanup(); - return std::unexpected{closed.error()}; - } - - if (::rename(temp_path.c_str(), dst.c_str()) != 0) { - const int err = errno; - cleanup(); - return std::unexpected{ - sys_err(err, std::format("copy_isolated: rename failed for '{}'", dst.string()))}; - } - return used_reflink; + return res->method == Void::FileSystem::CopyMethod::Reflink; } Void::Result::Result set_canonical_mtime(const std::filesystem::path &path, std::int64_t epoch_seconds) { - struct timespec times[2]; - times[0].tv_sec = static_cast(epoch_seconds); - times[0].tv_nsec = 0; - times[1].tv_sec = static_cast(epoch_seconds); - times[1].tv_nsec = 0; - if (::utimensat(AT_FDCWD, path.c_str(), times, AT_SYMLINK_NOFOLLOW) != 0) { - const int err = errno; - return std::unexpected{sys_err( - err, std::format("set_canonical_mtime: utimensat failed for '{}'", path.string()))}; - } - return {}; + return Void::FileSystem::set_canonical_mtime(path, epoch_seconds, 0); } Void::Result::Result @@ -319,19 +201,8 @@ atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesyste ec.value(), std::format("atomic_swap_symlink: create_directories failed for '{}'", parent.string()))}; } - const auto temp_link = parent / (link_path.filename().string() + unique_suffix()); - if (::symlink(target.c_str(), temp_link.c_str()) != 0) { - const int err = errno; - return std::unexpected{sys_err( - err, std::format("atomic_swap_symlink: symlink failed for '{}'", temp_link.string()))}; - } - if (::rename(temp_link.c_str(), link_path.c_str()) != 0) { - const int err = errno; - (void)::unlink(temp_link.c_str()); - return std::unexpected{sys_err( - err, std::format("atomic_swap_symlink: rename failed for '{}'", link_path.string()))}; - } - return fsync_directory(parent); + return Void::FileSystem::atomic_symlink_swap(link_path, target, + Void::FileSystem::ReplaceDurability::durable_sync); } bool path_is_within(const std::filesystem::path &root, const std::filesystem::path &path) { @@ -373,7 +244,6 @@ resolve_confined_path(const std::filesystem::path &root, const std::filesystem:: candidate.is_absolute() ? candidate : (canonical_root / candidate); current = current.lexically_normal(); - // Manually walk symlinks with a strict hop budget to detect loops explicitly. constexpr int kMaxSymlinkHops = 40; int hops = 0; std::set seen; @@ -396,7 +266,6 @@ resolve_confined_path(const std::filesystem::path &root, const std::filesystem:: return std::unexpected{meta.error()}; } if (!meta->exists) { - // Append remaining lexical components for non-existent path checks. ++it; for (; it != current.end(); ++it) { acc /= *it; diff --git a/src/Platform/ProcessSupervisor.cpp b/src/Platform/ProcessSupervisor.cpp index c8cde1d..bb82c35 100644 --- a/src/Platform/ProcessSupervisor.cpp +++ b/src/Platform/ProcessSupervisor.cpp @@ -1,31 +1,19 @@ #include +#include +#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include #include #include #include #include -extern char **environ; - namespace Void::Build::Platform { namespace { -struct ExecErrorPacket { - int err_no{0}; - int stage{0}; // 1 = chdir, 2 = execve -}; - bool is_executable_file(const std::filesystem::path &p) { struct stat st{}; if (::stat(p.c_str(), &st) != 0) { @@ -34,106 +22,9 @@ bool is_executable_file(const std::filesystem::path &p) { return S_ISREG(st.st_mode) && ::access(p.c_str(), X_OK) == 0; } -void set_nonblocking(int fd) noexcept { - const int flags = ::fcntl(fd, F_GETFL, 0); - if (flags >= 0) { - (void)::fcntl(fd, F_SETFL, flags | O_NONBLOCK); - } -} - -std::vector build_env_strings(const ProcessEnvironment &policy) { - std::map> env_map; - if (policy.mode != EnvPolicyMode::ExplicitOnly && environ != nullptr) { - for (char **ep = environ; *ep != nullptr; ++ep) { - const std::string_view entry{*ep}; - const auto eq = entry.find('='); - if (eq == std::string_view::npos) { - continue; - } - const auto key = std::string{entry.substr(0, eq)}; - if (policy.mode == EnvPolicyMode::Allowlist && - !std::ranges::contains(policy.allowlist, key)) { - continue; - } - env_map[key] = std::string{entry.substr(eq + 1)}; - } - } - for (const auto &k : policy.unset_keys) { - env_map.erase(k); - } - for (const auto &[k, v] : policy.set_vars) { - env_map[k] = v; - } - std::vector result; - result.reserve(env_map.size()); - for (const auto &[k, v] : env_map) { - result.push_back(k + "=" + v); - } - return result; -} - -bool process_group_alive(pid_t pgid) noexcept { - if (pgid <= 0) { - return false; - } - if (::kill(-pgid, 0) == 0) { - return true; - } - return errno != ESRCH; -} - -void reap_leader(pid_t pid, bool &reaped, int &raw_status, bool blocking) noexcept { - if (reaped || pid <= 0) { - return; - } - for (;;) { - const pid_t r = ::waitpid(pid, &raw_status, blocking ? 0 : WNOHANG); - if (r == pid) { - reaped = true; - return; - } - if (r == 0) { - return; - } - if (errno == EINTR) { - continue; - } - if (errno == ECHILD) { - reaped = true; - return; - } - return; - } -} - -// Terminates the entire process group (-pgid) and waits until every descendant -// (even grandchildren whose group leader already exited) is gone. -void terminate_process_group(pid_t leader_pid, pid_t pgid, bool &leader_reaped, int &raw_status, - std::chrono::milliseconds grace) noexcept { - if (pgid <= 0) { - return; - } - const auto effective_grace = grace.count() >= 0 ? grace : std::chrono::milliseconds{200}; - (void)::kill(-pgid, SIGTERM); - - const auto deadline = std::chrono::steady_clock::now() + effective_grace; - while (std::chrono::steady_clock::now() < deadline) { - reap_leader(leader_pid, leader_reaped, raw_status, false); - if (leader_reaped && !process_group_alive(pgid)) { - return; - } - std::this_thread::sleep_for(std::chrono::milliseconds{5}); - } - - // Escalate to SIGKILL on the entire process group and verify full disappearance. - (void)::kill(-pgid, SIGKILL); - reap_leader(leader_pid, leader_reaped, raw_status, true); - - const auto kill_deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5}; - while (process_group_alive(pgid) && std::chrono::steady_clock::now() < kill_deadline) { - (void)::kill(-pgid, SIGKILL); - std::this_thread::sleep_for(std::chrono::milliseconds{5}); - } +void ensure_subreaper() noexcept { + static std::once_flag once; + std::call_once(once, [] { (void)Void::Process::enable_subreaper(); }); } } // namespace @@ -152,11 +43,13 @@ resolve_executable(const std::filesystem::path &executable, } return std::nullopt; } + std::string owned_env; std::string_view path_env; if (path_override) { path_env = *path_override; - } else if (const char *env_val = std::getenv("PATH")) { - path_env = env_val; + } else if (auto env_val = Void::Configuration::get_env("PATH"); env_val) { + owned_env = std::move(*env_val); + path_env = owned_env; } std::size_t start = 0; while (start <= path_env.size()) { @@ -187,343 +80,119 @@ run_supervised(const ProcessRequest &request, std::stop_token stop) { "run_supervised: executable path must not be empty")}; } - auto env_strings = build_env_strings(request.environment); - std::optional child_path; - for (const auto &entry : env_strings) { - if (entry.starts_with("PATH=")) { - child_path = std::string_view{entry}.substr(5); - break; - } + ensure_subreaper(); + + // Delegate process spawning, streaming, timeout/cancellation, and robust -pgid + // descendant SIGTERM -> SIGKILL supervision directly to Void::Process (VL-001). + Void::Process::SpawnOptions opts; + opts.executable = request.executable; + opts.arguments = request.arguments; + opts.working_directory = request.working_directory; + opts.search_path = request.search_path; + opts.new_process_group = true; + opts.kill_grace = request.kill_grace; + opts.stdin_pipe = true; + opts.stdout_pipe = true; + opts.stderr_pipe = true; + + switch (request.environment.mode) { + case EnvPolicyMode::Inherit: + opts.environment.mode = Void::Process::EnvMode::inherit; + break; + case EnvPolicyMode::Allowlist: + opts.environment.mode = Void::Process::EnvMode::allowlist; + break; + case EnvPolicyMode::ExplicitOnly: + opts.environment.mode = Void::Process::EnvMode::explicit_only; + break; + } + opts.environment.allowlist = request.environment.allowlist; + opts.environment.unset_keys = request.environment.unset_keys; + for (const auto &[k, v] : request.environment.set_vars) { + opts.environment.set_vars.emplace_back(k, v); } - std::filesystem::path resolved_exec = request.executable; - if (request.search_path) { - if (auto found = resolve_executable(request.executable, child_path)) { - resolved_exec = std::move(*found); - } + auto child = Void::Process::spawn(opts); + if (!child) { + ProcessResult fail; + fail.exec_failed = true; + fail.exec_error_message = child.error().message(); + return fail; } - int stdin_pipe[2]{-1, -1}; - int stdout_pipe[2]{-1, -1}; - int stderr_pipe[2]{-1, -1}; - int err_pipe[2]{-1, -1}; - - auto close_pair = [](int p[2]) { - if (p[0] >= 0) { - (void)::close(p[0]); - p[0] = -1; - } - if (p[1] >= 0) { - (void)::close(p[1]); - p[1] = -1; - } - }; - - if (::pipe2(stdin_pipe, O_CLOEXEC) != 0 || ::pipe2(stdout_pipe, O_CLOEXEC) != 0 || - ::pipe2(stderr_pipe, O_CLOEXEC) != 0 || ::pipe2(err_pipe, O_CLOEXEC) != 0) { - const int err = errno; - close_pair(stdin_pipe); - close_pair(stdout_pipe); - close_pair(stderr_pipe); - close_pair(err_pipe); - return std::unexpected{Void::System::make_system_error( - Void::System::map_errno_to_system_code(err), "run_supervised: pipe2 failed", err)}; - } - - std::vector argv_storage; - argv_storage.reserve(request.arguments.size() + 1); - argv_storage.push_back(resolved_exec.string()); - for (const auto &arg : request.arguments) { - argv_storage.push_back(arg); - } - std::vector argv_ptrs; - argv_ptrs.reserve(argv_storage.size() + 1); - for (auto &s : argv_storage) { - argv_ptrs.push_back(s.data()); - } - argv_ptrs.push_back(nullptr); - - std::vector envp_ptrs; - envp_ptrs.reserve(env_strings.size() + 1); - for (auto &s : env_strings) { - envp_ptrs.push_back(s.data()); - } - envp_ptrs.push_back(nullptr); - - const std::string exec_str = resolved_exec.string(); - const std::string cwd_str = - request.working_directory ? request.working_directory->string() : std::string{}; - - const pid_t pid = ::fork(); - if (pid < 0) { - const int err = errno; - close_pair(stdin_pipe); - close_pair(stdout_pipe); - close_pair(stderr_pipe); - close_pair(err_pipe); - return std::unexpected{Void::System::make_system_error( - Void::System::map_errno_to_system_code(err), "run_supervised: fork failed", err)}; - } - - if (pid == 0) { - // Child: place into its own process group. - (void)::setpgid(0, 0); - // Reset signals to defaults. - ::signal(SIGINT, SIG_DFL); - ::signal(SIGTERM, SIG_DFL); - ::signal(SIGPIPE, SIG_DFL); - - (void)::dup2(stdin_pipe[0], STDIN_FILENO); - (void)::dup2(stdout_pipe[1], STDOUT_FILENO); - (void)::dup2(stderr_pipe[1], STDERR_FILENO); - - close_pair(stdin_pipe); - close_pair(stdout_pipe); - close_pair(stderr_pipe); - (void)::close(err_pipe[0]); - - if (!cwd_str.empty() && ::chdir(cwd_str.c_str()) != 0) { - ExecErrorPacket pkt{errno, 1}; - (void)::write(err_pipe[1], &pkt, sizeof(pkt)); - ::_exit(127); - } - - ::execve(exec_str.c_str(), argv_ptrs.data(), envp_ptrs.data()); - ExecErrorPacket pkt{errno, 2}; - (void)::write(err_pipe[1], &pkt, sizeof(pkt)); - ::_exit(127); - } - - // Parent: ensure pgid is established to avoid race with child setpgid. - (void)::setpgid(pid, pid); - const pid_t pgid = pid; - - (void)::close(stdin_pipe[0]); - (void)::close(stdout_pipe[1]); - (void)::close(stderr_pipe[1]); - (void)::close(err_pipe[1]); - - int in_fd = stdin_pipe[1]; - int out_fd = stdout_pipe[0]; - int err_fd = stderr_pipe[0]; - int exec_err_fd = err_pipe[0]; - - set_nonblocking(in_fd); - set_nonblocking(out_fd); - set_nonblocking(err_fd); - - if (request.stdin_data.empty()) { - (void)::close(in_fd); - in_fd = -1; - } - - // Read exec error pipe first (blocking is fine because child closes on exec or writes & exits). - ExecErrorPacket exec_pkt{}; - ssize_t exec_read = 0; - while (exec_read < static_cast(sizeof(exec_pkt))) { - const ssize_t n = ::read(exec_err_fd, reinterpret_cast(&exec_pkt) + exec_read, - sizeof(exec_pkt) - static_cast(exec_read)); - if (n > 0) { - exec_read += n; - } else if (n == 0) { - break; - } else if (errno != EINTR) { - break; - } - } - (void)::close(exec_err_fd); - - ProcessResult result; - bool leader_reaped = false; - int raw_status = 0; - - if (exec_read == static_cast(sizeof(exec_pkt)) && exec_pkt.err_no != 0) { - if (in_fd >= 0) { - (void)::close(in_fd); - } - (void)::close(out_fd); - (void)::close(err_fd); - reap_leader(pid, leader_reaped, raw_status, true); - result.exec_failed = true; - result.exec_errno = exec_pkt.err_no; - result.exec_error_message = - exec_pkt.stage == 1 - ? std::format("chdir('{}') failed: {}", cwd_str, std::strerror(exec_pkt.err_no)) - : std::format("execve('{}') failed: {}", exec_str, std::strerror(exec_pkt.err_no)); - return result; - } - - std::size_t stdin_offset = 0; const auto start_time = std::chrono::steady_clock::now(); const bool has_timeout = request.timeout.count() > 0; const auto deadline = start_time + request.timeout; - std::array buf{}; + Void::Process::CaptureLimits limits; + limits.max_stdout_bytes = request.max_stdout_bytes; + limits.max_stderr_bytes = request.max_stderr_bytes; + limits.max_line_bytes = 0; // Do not reject long compiler/linker diagnostic lines. + limits.max_stdin_bytes = std::max(limits.max_stdin_bytes, request.stdin_data.size() + 1); + limits.overflow_policy = request.fail_on_overflow + ? Void::Process::OverflowPolicy::fail_and_terminate + : Void::Process::OverflowPolicy::drain_and_truncate; - while (in_fd >= 0 || out_fd >= 0 || err_fd >= 0) { - if (stop.stop_requested()) { - result.cancelled = true; - terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace); - break; - } - if (has_timeout && std::chrono::steady_clock::now() >= deadline) { - result.timed_out = true; - terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace); - break; - } + Void::Process::StreamCallbacks callbacks; + const Void::Process::StreamCallbacks *cb_ptr = nullptr; + if (request.on_stdout_chunk || request.on_stderr_chunk) { + callbacks.on_stdout = request.on_stdout_chunk; + callbacks.on_stderr = request.on_stderr_chunk; + cb_ptr = &callbacks; + } - struct pollfd fds[3]; - int nfds = 0; - int in_idx = -1; - int out_idx = -1; - int err_idx = -1; - if (in_fd >= 0) { - in_idx = nfds; - fds[nfds++] = {in_fd, POLLOUT, 0}; - } - if (out_fd >= 0) { - out_idx = nfds; - fds[nfds++] = {out_fd, POLLIN, 0}; - } - if (err_fd >= 0) { - err_idx = nfds; - fds[nfds++] = {err_fd, POLLIN, 0}; - } + auto comm = Void::Process::communicate_blocking(*child, request.stdin_data, limits, + request.timeout, stop, cb_ptr); + if (!comm) { + (void)child->terminate(request.kill_grace); + return std::unexpected{std::move(comm.error())}; + } - int poll_ms = 25; - if (has_timeout) { - const auto rem = std::chrono::duration_cast( - deadline - std::chrono::steady_clock::now()); - poll_ms = static_cast(std::clamp(rem.count(), 1, 25)); - } - - const int ready = ::poll(fds, static_cast(nfds), poll_ms); - if (ready < 0) { - if (errno == EINTR) { - continue; + // If the leader exited cleanly while descendants in its process group are still alive + // (e.g. background child with redirected stdio), supervise the process group until it + // drains, times out, or is cancelled, then escalate via SIGTERM -> kill_grace -> SIGKILL. + bool group_timed_out = comm->timed_out; + bool group_cancelled = comm->cancelled; + const pid_t pgid = static_cast(child->pgid()); + if (!group_timed_out && !group_cancelled && !comm->overflowed) { + while (child->process_group_alive()) { + // Reap any adopted descendants in this process group (subreaper) so zombies clear. + int wstatus = 0; + while (pgid > 0 && ::waitpid(-pgid, &wstatus, WNOHANG) > 0) { } - break; - } - if (ready == 0) { - reap_leader(pid, leader_reaped, raw_status, false); - continue; - } - - if (in_idx >= 0 && (fds[in_idx].revents & (POLLOUT | POLLERR | POLLHUP))) { - const ssize_t w = ::write(in_fd, request.stdin_data.data() + stdin_offset, - request.stdin_data.size() - stdin_offset); - if (w > 0) { - stdin_offset += static_cast(w); - if (stdin_offset >= request.stdin_data.size()) { - (void)::close(in_fd); - in_fd = -1; - } - } else if (w < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) { - (void)::close(in_fd); - in_fd = -1; + if (!child->process_group_alive()) { + break; } - } - - auto drain_stream = [&](int &fd, std::string &target, std::size_t limit, bool &truncated, - const std::function &cb) { - for (;;) { - const ssize_t n = ::read(fd, buf.data(), buf.size()); - if (n > 0) { - const std::string_view chunk{buf.data(), static_cast(n)}; - if (cb) { - cb(chunk); - } - if (target.size() < limit) { - const std::size_t take = std::min(chunk.size(), limit - target.size()); - target.append(chunk.data(), take); - if (take < chunk.size()) { - truncated = true; - } - } else { - truncated = true; - } - if (truncated && request.fail_on_overflow) { - result.overflowed = true; - return; - } - } else if (n == 0) { - (void)::close(fd); - fd = -1; - return; - } else { - if (errno == EINTR) { - continue; - } - if (errno == EAGAIN || errno == EWOULDBLOCK) { - return; - } - (void)::close(fd); - fd = -1; - return; - } + if (stop.stop_requested()) { + group_cancelled = true; + break; } - }; - - if (out_idx >= 0 && (fds[out_idx].revents & (POLLIN | POLLHUP | POLLERR))) { - drain_stream(out_fd, result.stdout_data, request.max_stdout_bytes, - result.stdout_truncated, request.on_stdout_chunk); - } - if (err_idx >= 0 && (fds[err_idx].revents & (POLLIN | POLLHUP | POLLERR))) { - drain_stream(err_fd, result.stderr_data, request.max_stderr_bytes, - result.stderr_truncated, request.on_stderr_chunk); - } - if (result.overflowed) { - terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace); - break; + if (has_timeout && std::chrono::steady_clock::now() >= deadline) { + group_timed_out = true; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds{10}); } } - if (in_fd >= 0) { - (void)::close(in_fd); - } - if (out_fd >= 0) { - (void)::close(out_fd); - } - if (err_fd >= 0) { - (void)::close(err_fd); - } - - // Wait for leader AND any remaining process-group descendants, polling for stop/timeout. - while (!leader_reaped || process_group_alive(pgid)) { - reap_leader(pid, leader_reaped, raw_status, false); - if (leader_reaped && !process_group_alive(pgid)) { - break; - } - if (stop.stop_requested()) { - result.cancelled = true; - terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace); - break; - } - if (has_timeout && std::chrono::steady_clock::now() >= deadline) { - result.timed_out = true; - terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace); - break; - } - std::this_thread::sleep_for(std::chrono::milliseconds{5}); - } - - // Even if the leader exited cleanly or early, ensure no stray process-group - // descendants remain alive if we were cancelled/timed out/overflowed, or wait/clean them up. - if (result.cancelled || result.timed_out || result.overflowed) { - if (process_group_alive(pgid)) { - terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace); + if (group_cancelled || group_timed_out || comm->overflowed || child->process_group_alive()) { + (void)child->terminate(request.kill_grace); + int wstatus = 0; + while (pgid > 0 && ::waitpid(-pgid, &wstatus, WNOHANG) > 0) { } } - if (leader_reaped) { - if (WIFEXITED(raw_status)) { - result.exited = true; - result.exit_code = WEXITSTATUS(raw_status); - } else if (WIFSIGNALED(raw_status)) { - result.exited = false; - result.term_signal = WTERMSIG(raw_status); - } - } + ProcessResult result; + result.exited = comm->status.exited; + result.exit_code = comm->status.code; + result.term_signal = comm->status.signal; + result.stdout_data = std::move(comm->out); + result.stderr_data = std::move(comm->err); + result.stdout_truncated = comm->stdout_truncated; + result.stderr_truncated = comm->stderr_truncated; + result.timed_out = group_timed_out; + result.cancelled = group_cancelled; + result.overflowed = comm->overflowed; return result; } diff --git a/src/Provider/Provider.cpp b/src/Provider/Provider.cpp index 2b640ff..42a93b2 100644 --- a/src/Provider/Provider.cpp +++ b/src/Provider/Provider.cpp @@ -5,8 +5,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -237,6 +239,9 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path & build_dir / ".cmake" / "api" / "v1" / "query" / "codemodel-v2", "", false); // 1. Configure with isolated profile/toolchain context. + const auto sw = Void::Time::Stopwatch::started(); + Void::Log::info("Provider", "Configuring CMake dependency '{}' (profile='{}')...", + request.dependency.name, request.profile.name); { Platform::ProcessRequest req; req.executable = *cmake_bin; @@ -254,6 +259,14 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path & req.arguments.push_back("-D" + k + "=" + cmake_option_value(v)); } req.timeout = std::chrono::seconds{180}; + if (Void::Log::enabled(Void::Log::Level::Debug, "Provider")) { + req.on_stdout_chunk = [&](std::string_view line) { + Void::Log::debug("Provider", "[cmake:{}] {}", request.dependency.name, line); + }; + req.on_stderr_chunk = [&](std::string_view line) { + Void::Log::debug("Provider", "[cmake:{}] {}", request.dependency.name, line); + }; + } auto proc = Platform::run_supervised(req, stop); if (!proc || !proc->succeeded()) { return std::unexpected{make_error( @@ -265,11 +278,20 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path & } // 2. Build all targets in isolated build directory. + Void::Log::info("Provider", "Building CMake dependency '{}'...", request.dependency.name); { Platform::ProcessRequest req; req.executable = *cmake_bin; - req.arguments = {"--build", build_dir.string()}; + req.arguments = {"--build", build_dir.string(), "--parallel"}; req.timeout = std::chrono::seconds{300}; + if (Void::Log::enabled(Void::Log::Level::Debug, "Provider")) { + req.on_stdout_chunk = [&](std::string_view line) { + Void::Log::debug("Provider", "[build:{}] {}", request.dependency.name, line); + }; + req.on_stderr_chunk = [&](std::string_view line) { + Void::Log::debug("Provider", "[build:{}] {}", request.dependency.name, line); + }; + } auto proc = Platform::run_supervised(req, stop); if (!proc || !proc->succeeded()) { return std::unexpected{ @@ -435,6 +457,37 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path & } } + // Extract link command fragments (-pthread, -ldl, -lm, etc.). + if (const auto *lnk = find_key(*td, "link")) { + if (const auto *lobj = + std::get_if(&lnk->value)) { + if (const auto *frags = + find_key(*lobj, "commandFragments")) { + if (const auto *farr = + std::get_if(&frags->value)) { + for (const auto &fv : *farr) { + const auto *fo = + std::get_if(&fv.value); + if (!fo) { + continue; + } + const auto role = get_str(*fo, "role"); + const auto frag = get_str(*fo, "fragment"); + if ((role == "libraries" || role == "flags") && + (frag == "-pthread" || + frag == "-lpthread" || frag == "-ldl" || + frag == "-lm" || frag == "-lrt")) { + if (!std::ranges::contains( + rt.iface.link_options, frag)) { + rt.iface.link_options.push_back(frag); + } + } + } + } + } + } + } + // Extract dependencies for transitive static archive ordering. if (const auto *deps = find_key(*td, "dependencies")) { if (const auto *darr = @@ -457,7 +510,8 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path & } } - // Resolve transitive static library link order across CMake targets. + // Resolve transitive static library link order across CMake targets using post-order DFS + // reversed so every dependent library strictly precedes all of its dependencies on `ld`. ProviderExport exp; exp.dependency_name = request.dependency.name; exp.builder = "cmake"; @@ -465,36 +519,157 @@ run_cmake_provider(const ProviderRequest &request, const std::filesystem::path & for (const auto &[id, rt] : raw_by_id) { Graph::ImportedTargetInterface resolved = rt.iface; - std::set visited{id}; - std::vector queue = rt.dep_ids; - for (std::size_t qi = 0; qi < queue.size(); ++qi) { - const auto &dep_id = queue[qi]; - if (!visited.insert(dep_id).second) { - continue; + std::vector post_order; + std::set visited; + auto dfs = [&](auto &&self, const std::string &cur_id) -> void { + if (!visited.insert(cur_id).second) { + return; } - const auto dit = raw_by_id.find(dep_id); + const auto dit = raw_by_id.find(cur_id); if (dit == raw_by_id.end()) { - continue; + return; } - for (const auto &lib : dit->second.iface.static_libraries) { - resolved.static_libraries.push_back(lib); + for (const auto &sub : dit->second.dep_ids) { + self(self, sub); } - for (const auto &lib : dit->second.iface.shared_libraries) { - resolved.shared_libraries.push_back(lib); + post_order.push_back(cur_id); + }; + for (const auto &dep_id : rt.dep_ids) { + dfs(dfs, dep_id); + } + std::ranges::reverse(post_order); + for (const auto &dep_id : post_order) { + const auto &dep_rt = raw_by_id.at(dep_id); + for (const auto &lib : dep_rt.iface.static_libraries) { + if (!std::ranges::contains(resolved.static_libraries, lib)) { + resolved.static_libraries.push_back(lib); + } } - for (const auto &inc : dit->second.iface.include_dirs) { + for (const auto &lib : dep_rt.iface.shared_libraries) { + if (!std::ranges::contains(resolved.shared_libraries, lib)) { + resolved.shared_libraries.push_back(lib); + } + } + for (const auto &inc : dep_rt.iface.include_dirs) { if (!std::ranges::contains(resolved.include_dirs, inc)) { resolved.include_dirs.push_back(inc); } } - for (const auto &sub : dit->second.dep_ids) { - queue.push_back(sub); + for (const auto &def : dep_rt.iface.defines) { + if (!std::ranges::contains(resolved.defines, def)) { + resolved.defines.push_back(def); + } + } + for (const auto &lo : dep_rt.iface.link_options) { + if (!std::ranges::contains(resolved.link_options, lo)) { + resolved.link_options.push_back(lo); + } } } + // CMake targets linking Threads::Threads on GCC need -pthread at final link time. + if ((rt.name.starts_with("Void_") || request.dependency.name == "VoidLibrary") && + !std::ranges::contains(resolved.link_options, std::string{"-pthread"})) { + resolved.link_options.push_back("-pthread"); + } + exp.targets[rt.name] = resolved; exp.targets[request.dependency.name + "::" + rt.name] = resolved; + // Register CMake `Namespace::Component` alias convention (e.g. `Void_Configuration` -> + // `Void::Configuration`) because CMake File API codemodel-v2 omits ALIAS targets. + if (const auto us = rt.name.find('_'); us != std::string::npos && us > 0) { + const std::string alias = rt.name.substr(0, us) + "::" + rt.name.substr(us + 1); + exp.targets[alias] = resolved; + exp.targets[request.dependency.name + "::" + alias] = resolved; + } } + // CMake File API codemodel-v2 omits INTERFACE (header-only) libraries. For VoidLibrary, + // synthesize `Void::` interfaces for any module directory under `src/` that CMake + // configured as header-only (e.g. Text, Unicode, Async, Algorithms, Core, Data, Time, + // Functional), propagating compiled `INTERNAL_DEPS` (such as LogState) automatically. + if (request.dependency.name == "VoidLibrary" && + std::filesystem::is_directory(request.source.source_dir / "include", ec) && + std::filesystem::is_directory(request.source.source_dir / "src", ec)) { + std::vector hdr_mods; + for (const auto &entry : + std::filesystem::directory_iterator(request.source.source_dir / "src", ec)) { + if (!entry.is_directory(ec)) { + continue; + } + const std::string mod = entry.path().filename().string(); + const std::string alias = "Void::" + mod; + if (!exp.targets.contains(alias)) { + hdr_mods.push_back(mod); + Graph::ImportedTargetInterface hi; + hi.dependency_name = request.dependency.name; + hi.target_name = alias; + hi.include_dirs.emplace_back(request.source.source_dir / "include", false); + hi.link_options.push_back("-pthread"); + exp.targets[alias] = hi; + exp.targets[request.dependency.name + "::" + alias] = std::move(hi); + } + } + // Attach compiled INTERNAL_DEPS (e.g. Void_LogState for Async/Log) to synthesized + // header-only targets so linking any header-only Void module standalone works cleanly. + for (const auto &mod : hdr_mods) { + const auto mod_cmake = request.source.source_dir / "src" / mod / "module.cmake"; + if (!std::filesystem::is_regular_file(mod_cmake, ec)) { + continue; + } + auto text = Void::FileSystem::read_file(mod_cmake); + if (!text) { + continue; + } + const auto pos = text->find("INTERNAL_DEPS"); + if (pos == std::string::npos) { + continue; + } + const std::string alias = "Void::" + mod; + auto &hi = exp.targets[alias]; + const std::string_view rest = std::string_view{*text}.substr(pos + 13); + std::size_t idx = 0; + while (idx < rest.size()) { + while (idx < rest.size() && (rest[idx] == ' ' || rest[idx] == '\t' || + rest[idx] == '\r' || rest[idx] == '\n')) { + ++idx; + } + if (idx >= rest.size() || rest[idx] == ')') { + break; + } + const std::size_t start = idx; + while (idx < rest.size() && rest[idx] != ' ' && rest[idx] != '\t' && + rest[idx] != '\r' && rest[idx] != '\n' && rest[idx] != ')') { + ++idx; + } + const std::string dep_name{rest.substr(start, idx - start)}; + if (dep_name == "EXTERNAL_DEPS" || dep_name == "OPTIONAL_DEPS" || + dep_name == "DEPS_WIN32" || dep_name == "DEPS_UNIX" || + dep_name == "OPTIONS_WIN32" || dep_name == "OPTIONS_UNIX" || + dep_name == "EXTRA_HEADERS" || dep_name == "EXCLUDE_HEADERS") { + break; + } + const auto dit = exp.targets.find("Void::" + dep_name); + if (dit != exp.targets.end()) { + for (const auto &lib : dit->second.static_libraries) { + if (!std::ranges::contains(hi.static_libraries, lib)) { + hi.static_libraries.push_back(lib); + } + } + for (const auto &def : dit->second.defines) { + if (!std::ranges::contains(hi.defines, def)) { + hi.defines.push_back(def); + } + } + } + } + exp.targets[request.dependency.name + "::" + alias] = hi; + } + } + + Void::Log::info("Provider", "CMake dependency '{}' ready ({} targets in {}ms)", + request.dependency.name, exp.targets.size(), + sw.elapsed_as().count()); + // Apply explicit user overrides if supplied. for (const auto &[k, v] : request.explicit_overrides) { exp.targets[k] = v; diff --git a/src/Util/Sha256.cpp b/src/Util/Sha256.cpp index 72fae67..6d07bed 100644 --- a/src/Util/Sha256.cpp +++ b/src/Util/Sha256.cpp @@ -1,127 +1,45 @@ #include -#include #include +#include #include -#include -#include -#include namespace Void::Build::Util { namespace { -constexpr std::uint32_t kRoundConstants[64] = { - 0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu, 0x59f111f1u, 0x923f82a4u, - 0xab1c5ed5u, 0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu, - 0x9bdc06a7u, 0xc19bf174u, 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu, 0x2de92c6fu, - 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, 0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u, - 0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u, 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu, - 0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u, 0xa2bfe8a1u, 0xa81a664bu, - 0xc24b8b70u, 0xc76c51a3u, 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u, 0x19a4c116u, - 0x1e376c08u, 0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u, - 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u, 0x90befffau, 0xa4506cebu, 0xbef9a3f7u, - 0xc67178f2u}; - -constexpr std::uint32_t rotr(std::uint32_t x, unsigned n) noexcept { - return (x >> n) | (x << (32u - n)); +Sha256Digest copy_digest(const Void::Crypto::Digest &src) noexcept { + Sha256Digest out{}; + if (src.size() == out.size()) { + std::memcpy(out.data(), src.data(), out.size()); + } + return out; } } // namespace -Sha256Hasher::Sha256Hasher() noexcept - : state_{0x6a09e667u, 0xbb67ae85u, 0x3c6ef372u, 0xa54ff53au, - 0x510e527fu, 0x9b05688cu, 0x1f83d9abu, 0x5be0cd19u} {} - -void Sha256Hasher::transform(const std::uint8_t block[64]) noexcept { - std::uint32_t w[64]; - for (int i = 0; i < 16; ++i) { - w[i] = (static_cast(block[i * 4]) << 24) | - (static_cast(block[i * 4 + 1]) << 16) | - (static_cast(block[i * 4 + 2]) << 8) | - static_cast(block[i * 4 + 3]); - } - for (int i = 16; i < 64; ++i) { - const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); - const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); - w[i] = w[i - 16] + s0 + w[i - 7] + s1; - } - - std::uint32_t a = state_[0]; - std::uint32_t b = state_[1]; - std::uint32_t c = state_[2]; - std::uint32_t d = state_[3]; - std::uint32_t e = state_[4]; - std::uint32_t f = state_[5]; - std::uint32_t g = state_[6]; - std::uint32_t h = state_[7]; - - for (int i = 0; i < 64; ++i) { - const std::uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); - const std::uint32_t ch = (e & f) ^ ((~e) & g); - const std::uint32_t temp1 = h + S1 + ch + kRoundConstants[i] + w[i]; - const std::uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); - const std::uint32_t maj = (a & b) ^ (a & c) ^ (b & c); - const std::uint32_t temp2 = S0 + maj; - - h = g; - g = f; - f = e; - e = d + temp1; - d = c; - c = b; - b = a; - a = temp1 + temp2; - } - - state_[0] += a; - state_[1] += b; - state_[2] += c; - state_[3] += d; - state_[4] += e; - state_[5] += f; - state_[6] += g; - state_[7] += h; -} - -void Sha256Hasher::update(std::span data) noexcept { - if (finalized_ || data.empty()) { - return; - } - const std::uint8_t *ptr = data.data(); - std::size_t remaining = data.size(); - bit_count_ += static_cast(remaining) * 8u; - - if (buffer_len_ > 0) { - const std::size_t take = std::min(remaining, std::size_t{64} - buffer_len_); - std::memcpy(buffer_ + buffer_len_, ptr, take); - buffer_len_ += take; - ptr += take; - remaining -= take; - if (buffer_len_ == 64) { - transform(buffer_); - buffer_len_ = 0; - } - } - while (remaining >= 64) { - transform(ptr); - ptr += 64; - remaining -= 64; - } - if (remaining > 0) { - std::memcpy(buffer_, ptr, remaining); - buffer_len_ = remaining; +Sha256Hasher::Sha256Hasher() { + if (auto h = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256); h) { + hasher_.emplace(std::move(*h)); } } void Sha256Hasher::update(std::span data) noexcept { - update(std::span{reinterpret_cast(data.data()), - data.size()}); + if (finalized_ || !hasher_ || data.empty()) { + return; + } + (void)hasher_->update(data); +} + +void Sha256Hasher::update(std::span data) noexcept { + update(std::as_bytes(data)); } void Sha256Hasher::update(std::string_view text) noexcept { - update(std::span{reinterpret_cast(text.data()), - text.size()}); + if (finalized_ || !hasher_ || text.empty()) { + return; + } + (void)hasher_->update(text); } void Sha256Hasher::update_u64(std::uint64_t value) noexcept { @@ -141,31 +59,14 @@ void Sha256Hasher::update_length_prefixed(std::string_view text) noexcept { Sha256Digest Sha256Hasher::finalize() noexcept { if (!finalized_) { finalized_ = true; - buffer_[buffer_len_++] = 0x80u; - if (buffer_len_ > 56) { - std::memset(buffer_ + buffer_len_, 0, 64 - buffer_len_); - transform(buffer_); - buffer_len_ = 0; + if (hasher_) { + if (auto d = hasher_->finalize(); d) { + cached_digest_ = copy_digest(*d); + } + hasher_.reset(); } - std::memset(buffer_ + buffer_len_, 0, 56 - buffer_len_); - std::uint64_t bits = bit_count_; - for (int i = 7; i >= 0; --i) { - buffer_[56 + i] = static_cast(bits & 0xffu); - bits >>= 8; - } - transform(buffer_); } - - Sha256Digest out{}; - for (int i = 0; i < 8; ++i) { - out[static_cast(i * 4)] = static_cast((state_[i] >> 24) & 0xffu); - out[static_cast(i * 4 + 1)] = - static_cast((state_[i] >> 16) & 0xffu); - out[static_cast(i * 4 + 2)] = - static_cast((state_[i] >> 8) & 0xffu); - out[static_cast(i * 4 + 3)] = static_cast(state_[i] & 0xffu); - } - return out; + return cached_digest_; } std::string Sha256Hasher::finalize_hex() noexcept { return to_hex(finalize()); } @@ -175,45 +76,30 @@ std::string to_hex(const Sha256Digest &digest) { } Sha256Digest sha256_bytes(std::span data) noexcept { - Sha256Hasher hasher; - hasher.update(data); - return hasher.finalize(); + if (auto d = Void::Crypto::sha256(data); d) { + return copy_digest(*d); + } + return Sha256Digest{}; } std::string sha256_hex(std::string_view text) { - Sha256Hasher hasher; - hasher.update(text); - return hasher.finalize_hex(); + if (auto d = Void::Crypto::sha256(text); d) { + return Void::Encoding::Hex::encode(std::span{ + reinterpret_cast(d->data()), d->size()}); + } + return {}; } std::string sha256_hex(std::span data) { return to_hex(sha256_bytes(data)); } Void::Result::Result sha256_file_hex(const std::filesystem::path &path) { - const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); - if (fd < 0) { - const int err = errno; - return std::unexpected{Void::System::make_system_error( - Void::System::map_errno_to_system_code(err), - std::format("sha256_file_hex: cannot open '{}'", path.string()), err)}; + auto d = Void::Crypto::sha256_file(path); + if (!d) { + return std::unexpected{std::move(d.error())}; } - Void::System::OwnedFd guard{fd}; - Sha256Hasher hasher; - std::array buf{}; - for (;;) { - const ssize_t n = ::read(fd, buf.data(), buf.size()); - if (n > 0) { - hasher.update(std::span{buf.data(), static_cast(n)}); - } else if (n == 0) { - break; - } else if (errno != EINTR) { - const int err = errno; - return std::unexpected{Void::System::make_system_error( - Void::System::map_errno_to_system_code(err), - std::format("sha256_file_hex: read failed for '{}'", path.string()), err)}; - } - } - return hasher.finalize_hex(); + return Void::Encoding::Hex::encode(std::span{ + reinterpret_cast(d->data()), d->size()}); } bool constant_time_equal(std::string_view a, std::string_view b) noexcept { diff --git a/src/Watch/Watcher.cpp b/src/Watch/Watcher.cpp index b13dd9a..36705fe 100644 --- a/src/Watch/Watcher.cpp +++ b/src/Watch/Watcher.cpp @@ -4,113 +4,10 @@ #include #include -#include -#include #include -#include #include -#include -#include -#include namespace Void::Build::Watch { -namespace { - -Void::Result::Error sys_err(int err, std::string msg) { - return Void::System::make_system_error(Void::System::map_errno_to_system_code(err), - std::move(msg), err); -} - -constexpr std::uint32_t kWatchMask = IN_CREATE | IN_DELETE | IN_MODIFY | IN_CLOSE_WRITE | - IN_MOVED_FROM | IN_MOVED_TO | IN_ATTRIB | IN_DELETE_SELF | - IN_MOVE_SELF; - -} // namespace - -InotifyWatcher::InotifyWatcher(int fd, std::filesystem::path root, - std::vector excluded) - : fd_{fd}, root_{std::move(root)}, excluded_{std::move(excluded)} {} - -InotifyWatcher::~InotifyWatcher() noexcept { close_fd(); } - -InotifyWatcher::InotifyWatcher(InotifyWatcher &&other) noexcept - : fd_{std::exchange(other.fd_, -1)}, root_{std::move(other.root_)}, - excluded_{std::move(other.excluded_)}, wd_to_path_{std::move(other.wd_to_path_)} {} - -InotifyWatcher &InotifyWatcher::operator=(InotifyWatcher &&other) noexcept { - if (this != &other) { - close_fd(); - fd_ = std::exchange(other.fd_, -1); - root_ = std::move(other.root_); - excluded_ = std::move(other.excluded_); - wd_to_path_ = std::move(other.wd_to_path_); - } - return *this; -} - -void InotifyWatcher::close_fd() noexcept { - if (fd_ >= 0) { - (void)::close(fd_); - fd_ = -1; - } - wd_to_path_.clear(); -} - -bool InotifyWatcher::is_excluded(const std::filesystem::path &rel) const { - for (const auto &part : rel) { - const auto s = part.string(); - if (s.empty() || s == ".") { - continue; - } - if (std::ranges::contains(excluded_, s)) { - return true; - } - } - return false; -} - -Void::Result::Result -InotifyWatcher::watch_tree(const std::filesystem::path &dir) { - std::error_code ec; - if (!std::filesystem::is_directory(dir, ec)) { - return {}; - } - auto add_dir = - [&](const std::filesystem::path &p) -> Void::Result::Result { - const int wd = ::inotify_add_watch(fd_, p.c_str(), kWatchMask); - if (wd < 0) { - const int err = errno; - if (err == ENOENT || err == ENOTDIR) { - return {}; - } - return std::unexpected{sys_err( - err, std::format("InotifyWatcher: inotify_add_watch failed for '{}'", p.string()))}; - } - wd_to_path_[wd] = p; - return {}; - }; - - if (auto r = add_dir(dir); !r) { - return r; - } - std::filesystem::recursive_directory_iterator it{ - dir, 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(root_); - if (is_excluded(rel)) { - if (it->is_directory(ec)) { - it.disable_recursion_pending(); - } - continue; - } - if (it->is_directory(ec)) { - if (auto r = add_dir(it->path()); !r) { - return r; - } - } - } - return {}; -} Void::Result::Result InotifyWatcher::create(const std::filesystem::path &root_dir, @@ -122,99 +19,70 @@ InotifyWatcher::create(const std::filesystem::path &root_dir, Void::System::SystemErrorCode::not_found, std::format("InotifyWatcher: root '{}' is not a directory", root_dir.string()))}; } - const int fd = ::inotify_init1(IN_NONBLOCK | IN_CLOEXEC); - if (fd < 0) { - const int err = errno; - return std::unexpected{sys_err(err, "InotifyWatcher: inotify_init1 failed")}; + + Void::FileSystem::DirectoryWatcherOptions opts; + opts.ignore = [canon, excluded = std::move(excluded_names)](const std::filesystem::path &path, + bool /*is_directory*/) { + const auto rel = path.lexically_relative(canon); + for (const auto &part : rel) { + const auto s = part.string(); + if (s.empty() || s == ".") { + continue; + } + if (std::ranges::contains(excluded, s)) { + return true; + } + } + return false; + }; + + auto watcher = Void::FileSystem::DirectoryWatcher::create(canon, std::move(opts)); + if (!watcher) { + return std::unexpected{std::move(watcher.error())}; } - InotifyWatcher watcher{fd, canon, std::move(excluded_names)}; - if (auto r = watcher.watch_tree(canon); !r) { - return std::unexpected{r.error()}; - } - return watcher; + return InotifyWatcher{std::move(*watcher)}; } Void::Result::Result InotifyWatcher::rescan_watches() { - for (const auto &[wd, path] : wd_to_path_) { - (void)::inotify_rm_watch(fd_, wd); + if (!watcher_) { + return {}; } - wd_to_path_.clear(); - return watch_tree(root_); + return watcher_->rescan(); } Void::Result::Result InotifyWatcher::poll_events(std::chrono::milliseconds timeout, std::chrono::milliseconds debounce) { WatchBatch batch; - if (fd_ < 0) { + if (!watcher_) { batch.rescan_required = true; return batch; } - struct pollfd pfd{fd_, POLLIN, 0}; - const int ready = ::poll(&pfd, 1, static_cast(std::max(0, timeout.count()))); - if (ready < 0) { - if (errno == EINTR) { - return batch; - } - return std::unexpected{sys_err(errno, "InotifyWatcher: poll failed")}; + auto events = watcher_->poll(timeout); + if (!events) { + return std::unexpected{std::move(events.error())}; } - if (ready == 0) { + if (events->empty()) { return batch; } std::set unique_paths; - alignas(struct inotify_event) std::array buf{}; - - auto drain_now = [&]() { - for (;;) { - const ssize_t n = ::read(fd_, buf.data(), buf.size()); - if (n <= 0) { - break; + auto ingest = [&](const std::vector &evs) { + for (const auto &ev : evs) { + if (ev.kind == Void::FileSystem::DirectoryEventKind::RescanRequired) { + batch.overflowed = true; + batch.rescan_required = true; + continue; } - ssize_t off = 0; - while (off < n) { - const auto *ev = reinterpret_cast(buf.data() + off); - off += static_cast(sizeof(struct inotify_event) + ev->len); - - if (ev->mask & IN_Q_OVERFLOW) { - batch.overflowed = true; - batch.rescan_required = true; - continue; - } - if (ev->mask & IN_IGNORED) { - wd_to_path_.erase(ev->wd); - continue; - } - - const auto dir_it = wd_to_path_.find(ev->wd); - if (dir_it == wd_to_path_.end()) { - batch.rescan_required = true; - continue; - } - std::filesystem::path full = dir_it->second; - if (ev->len > 0 && ev->name[0] != '\0') { - full /= ev->name; - } - const auto rel = full.lexically_relative(root_); - if (is_excluded(rel)) { - continue; - } - unique_paths.insert(full); - - if ((ev->mask & (IN_CREATE | IN_MOVED_TO)) && (ev->mask & IN_ISDIR)) { - auto attached = watch_tree(full); - if (!attached) { - batch.rescan_required = true; - } - } - if (ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) { - batch.rescan_required = true; - } + if (!ev.path.empty()) { + unique_paths.insert(ev.path); + } + if (!ev.old_path.empty()) { + unique_paths.insert(ev.old_path); } } }; - - drain_now(); + ingest(*events); // Coalesce burst edits across the debounce window. if (debounce.count() > 0 && (!unique_paths.empty() || batch.rescan_required)) { @@ -225,13 +93,11 @@ InotifyWatcher::poll_events(std::chrono::milliseconds timeout, std::chrono::mill if (rem.count() <= 0) { break; } - struct pollfd spfd{fd_, POLLIN, 0}; - const int sr = ::poll(&spfd, 1, static_cast(rem.count())); - if (sr > 0) { - drain_now(); - } else { + auto more = watcher_->poll(rem); + if (!more || more->empty()) { break; } + ingest(*more); } } @@ -344,6 +210,19 @@ WatchCycleReport run_reconcile_cycle(const WatchLoopOptions &options, std::size_ } } } + for (const auto &src : t.sources) { + if (src.kind == SourceKind::File && !src.path.starts_with("$GEN/") && + !src.path.starts_with("gen/")) { + const auto p = std::filesystem::path{src.path}.is_absolute() + ? std::filesystem::path{src.path} + : (options.frontend.project_root / src.path); + const auto dir = p.parent_path(); + if (!dir.empty() && std::filesystem::is_directory(dir, ec) && + !std::ranges::contains(scan_roots, dir)) { + scan_roots.push_back(dir); + } + } + } } Snapshot::SnapshotOptions sopts; diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index a34cb07..577cf0a 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -14,27 +14,31 @@ function(check_process expected_code expected_out_regex expected_err_regex) endif() endfunction() -check_process(0 "Usage: vbs " "" ) -check_process(0 "Usage: vbs " "" --help) -check_process(0 "Usage: vbs " "" -h) +check_process(0 "Usage: vbs .*.*Commands:" "" ) +check_process(0 "Usage: vbs .*.*Commands:" "" --help) +check_process(0 "Usage: vbs .*.*Commands:" "" -h) check_process(0 "^vbs ${VBS_VERSION}\n$" "" --version) check_process(0 "^vbs ${VBS_VERSION}\n$" "" -V) -check_process(2 "" "--help must be used alone" --help --invalid) -check_process(2 "" "unexpected argument after --version" --version --invalid) -check_process(2 "" "unknown command 'invalid'" invalid) -check_process(0 "Usage: vbs build" "" build --help) -check_process(0 "Usage: vbs test" "" test --help) +check_process(2 "" "unknown option: --invalid" --version --invalid) +check_process(2 "" "--version cannot be combined with subcommands" --version build) +check_process(2 "" "unknown subcommand: invalid" invalid) +check_process(0 "Usage: vbs build .*--profile.*\\(repeatable\\)" "" build --help) +check_process(0 "Usage: vbs test " "" test --help) check_process(2 "" "multi-profile build requires --editor-profile" build --profile debug --profile release) check_process(2 "" "must be one of the requested profiles" build --profile debug --profile release --editor-profile custom) -check_process(2 "" "expected subcommand" compdb) -check_process(2 "" "unknown subcommand" compdb bogus) -check_process(2 "" "expected 'resolve' or 'update'" deps) +check_process(0 "Usage: vbs compdb .*Commands:.*use.*show.*export.*watch" "" compdb --help) +check_process(0 "Usage: vbs compdb use " "" compdb use --help) +check_process(2 "" "missing subcommand for 'vbs compdb'" compdb) +check_process(2 "" "unknown subcommand: bogus" compdb bogus) +check_process(0 "Usage: vbs deps .*Commands:.*resolve.*update" "" deps --help) +check_process(0 "Usage: vbs deps resolve " "" deps resolve --help) +check_process(2 "" "missing subcommand for 'vbs deps'" deps) check_process(2 "" "--request and --output are required" bridge) -check_process(0 "Usage: vbs install" "" install --help) +check_process(0 "Usage: vbs install " "" install --help) check_process(2 "" "--prefix is required" install) check_process(2 "" "--prefix is required" uninstall) check_process(2 "" "--input and --output-dir are required" gen-tests) -check_process(0 "Usage: vbs publish" "" publish --help) +check_process(0 "Usage: vbs publish " "" publish --help) check_process(2 "" "--registry, --name, and --version are required" publish) execute_process(COMMAND "${VBS_REGISTRY}" --help @@ -42,4 +46,4 @@ execute_process(COMMAND "${VBS_REGISTRY}" --help if(NOT "${reg_code}" STREQUAL "0" OR NOT reg_out MATCHES "Usage: vbs-registry") message(FATAL_ERROR "vbs-registry --help failed: code=${reg_code}\nstdout=[${reg_out}]\nstderr=[${reg_err}]") endif() -message(STATUS "23 native CLI contracts verified") +message(STATUS "27 native CLI and auto-generated Argparse help contracts verified") diff --git a/tests/DescribeContracts.cmake b/tests/DescribeContracts.cmake index f7700f9..323831a 100644 --- a/tests/DescribeContracts.cmake +++ b/tests/DescribeContracts.cmake @@ -35,13 +35,23 @@ foreach(profile IN ITEMS debug release) expect_json(file targets 0 sources 0 kind) expect_json(src/Build.cpp targets 0 sources 0 path) expect_json(public targets 0 include_directories 0 visibility) - expect_json(vbs targets 1 name) - expect_json(executable targets 1 kind) + expect_json(VoidBuildCore targets 1 name) + expect_json(static_library targets 1 kind) expect_json(VoidBuildSdk targets 1 links 0 target) - expect_json(private targets 1 links 0 visibility) + expect_json(public targets 1 links 0 visibility) expect_json(VoidLibrary targets 1 links 1 dependency) expect_json(Void::Configuration targets 1 links 1 target) - foreach(index IN ITEMS 0 1) + expect_json(GenerateBootstrapConfig targets 2 name) + expect_json(custom_action targets 2 kind) + expect_json(vbs targets 3 name) + expect_json(executable targets 3 kind) + expect_json(VoidBuildCore targets 3 links 0 target) + expect_json(private targets 3 links 0 visibility) + expect_json(VoidBuildRegistry targets 4 name) + expect_json(static_library targets 4 kind) + expect_json(vbs-registry targets 5 name) + expect_json(executable targets 5 kind) + foreach(index IN ITEMS 0 1 3 4 5) if(compiler STREQUAL "gcc") expect_json(-Wduplicated-cond targets "${index}" compile_options 2) else() @@ -49,7 +59,7 @@ foreach(profile IN ITEMS debug release) endif() endforeach() expect_json(git dependencies 0 source kind) - expect_json(9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5 dependencies 0 source revision) + expect_json(3e254055e081a104f08df68dde39711bc7813518 dependencies 0 source revision) expect_json(cmake dependencies 0 builder) string(JSON option_type TYPE "${graph}" dependencies 0 options BUILD_SHARED_LIBS) if(NOT option_type STREQUAL "BOOLEAN") @@ -58,6 +68,13 @@ foreach(profile IN ITEMS debug release) endforeach() endforeach() +execute_process(COMMAND "${DESCRIBE}" --help + RESULT_VARIABLE help_code OUTPUT_VARIABLE help_out ERROR_VARIABLE help_err TIMEOUT 10) +if(NOT "${help_code}" STREQUAL "0" OR NOT "${help_err}" STREQUAL "" OR + NOT help_out MATCHES "Usage: vbs_describe") + message(FATAL_ERROR "vbs_describe --help failed: code=${help_code}\nstdout=[${help_out}]\nstderr=[${help_err}]") +endif() + function(expect_error expected) execute_process(COMMAND "${DESCRIBE}" ${ARGN} RESULT_VARIABLE code OUTPUT_VARIABLE out ERROR_VARIABLE err TIMEOUT 10) @@ -71,5 +88,4 @@ expect_error("unknown compiler 'msvc' (expected gcc or clang)" --compiler msvc) expect_error("option '--profile' requires a value" --profile) expect_error("unknown option: --invalid" --invalid) expect_error("unexpected positional argument: invalid" invalid) -expect_error("--help must be used alone" --help --invalid) -message(STATUS "Four runtime profile/compiler contexts and six error contracts verified") +message(STATUS "Four runtime profile/compiler contexts, generated help, and five error contracts verified") diff --git a/tests/ExampleContexts.cpp b/tests/ExampleContexts.cpp index 40b178f..6866fe3 100644 --- a/tests/ExampleContexts.cpp +++ b/tests/ExampleContexts.cpp @@ -13,7 +13,11 @@ Void::Testing::Test example_uses_runtime_compiler() { definitions.resolve("debug", Void::Build::CompilerFamily::Clang, "linux", "x86_64")}; build(gcc); build(clang); + Void::Testing::expect_eq(gcc.targets().size(), clang.targets().size()); for (std::size_t index = 0; index < gcc.targets().size(); ++index) { + if (gcc.targets().at(index).kind == Void::Build::TargetKind::CustomAction) { + continue; + } Void::Testing::expect(std::ranges::contains(gcc.targets().at(index).compile_options, std::string{"-Wduplicated-cond"})); Void::Testing::expect(!std::ranges::contains(gcc.targets().at(index).compile_options, @@ -47,15 +51,22 @@ Void::Testing::Test example_records_sources_links_and_pin() { Void::Build::Project project{Void::Build::default_profiles().resolve( "debug", Void::Build::CompilerFamily::Gcc, "linux", "x86_64")}; build(project); - Void::Testing::expect_eq(project.targets().size(), std::size_t{2}); + Void::Testing::expect_eq(project.targets().size(), std::size_t{6}); Void::Testing::expect_eq(project.targets().at(0).name, std::string{"VoidBuildSdk"}); Void::Testing::expect_eq(project.targets().at(0).sources.at(0).path, std::string{"src/Build.cpp"}); + Void::Testing::expect_eq(project.targets().at(1).name, std::string{"VoidBuildCore"}); Void::Testing::expect_eq(project.targets().at(1).links.at(0).target, std::string{"VoidBuildSdk"}); Void::Testing::expect_eq(project.targets().at(1).links.at(1).target, std::string{"Void::Configuration"}); + Void::Testing::expect_eq(project.targets().at(2).name, std::string{"GenerateBootstrapConfig"}); + Void::Testing::expect_eq(project.targets().at(3).name, std::string{"vbs"}); + Void::Testing::expect_eq(project.targets().at(3).links.at(0).target, + std::string{"VoidBuildCore"}); + Void::Testing::expect_eq(project.targets().at(4).name, std::string{"VoidBuildRegistry"}); + Void::Testing::expect_eq(project.targets().at(5).name, std::string{"vbs-registry"}); Void::Testing::expect_eq(project.dependencies().at(0).revision, - std::string{"9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"}); + std::string{"3e254055e081a104f08df68dde39711bc7813518"}); Void::Testing::expect_eq(project.dependencies().at(0).builder, std::string{"cmake"}); }