From 76f1e2a48c1f17cd5d6c3e05619058d0a02bfbdc Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sun, 6 Dec 2026 19:20:39 +0300 Subject: [PATCH] feat: lifecycle commands and native compiler caching (G1, G7) G1 (start): - vbs run builds an executable target, passes program args through `--`, inherits stdio via Void::Process (interactive programs keep the terminal) and returns the program's exit code; Windows targets run under Wine. - vbs metadata emits a schema-versioned workspace document built with Void::Json::Strict: roots, profile/compiler, targets (sources, includes, links, labels, install rules), dependencies and the lockfile revision. - vbs why walks the target graph root -> target, or explains a dependency and the targets linking it. - vbs add NAME[@RANGE] / vbs remove NAME edit vbs.deps.toml (canonical, comment-preserving block editing), validate ranges with Void::Semver::parse_range and refresh vbs.lock via the resolver. - --frozen implies --locked --offline for build/test/run. G7 (native caching): - --native-cache off|auto|ccache|sccache (or VBS_NATIVE_CACHE) prepends ccache/sccache to compile actions only; the wrapper and real compiler are part of the action key, archive/link actions are untouched, and vbs doctor reports availability. VoidLibrary reuse: Void::Process (spawn with inherited stdio), Void::Json::Strict (metadata document), Void::Str (trim/split/prefix), Void::Semver (range validation), plus the existing SDK helpers (target_kind_name/visibility_name) instead of local duplicates. Verified: lifecycle_run_metadata_why_and_manifest_editing, native_cache_wrapper_is_lowered_into_compile_commands and native_cache_wraps_compile_actions pass; CLI contracts pass; clang-format clean. --- CMakeLists.txt | 1 + docs/agent-workflow/STATE.md | 8 + docs/agent-workflow/TASKS.md | 1 + docs/roadmap/24-superiority-tracks.md | 10 +- include/Void/Build/Package/Manifest.hpp | 40 ++ include/Void/Build/Toolchain/Driver.hpp | 4 + src/Main.cpp | 665 +++++++++++++++++++++++- src/Package/Manifest.cpp | 267 ++++++++++ src/Toolchain/Driver.cpp | 8 + tests/CliContracts.cmake | 9 + tests/FullV1Tests.cpp | 229 ++++++++ 11 files changed, 1240 insertions(+), 2 deletions(-) create mode 100644 include/Void/Build/Package/Manifest.hpp create mode 100644 src/Package/Manifest.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 5a3f273..5eeceaf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -67,6 +67,7 @@ add_library(VoidBuild_Core STATIC src/Package/Fetch.cpp src/Package/RegistryClient.cpp src/Package/Resolver.cpp + src/Package/Manifest.cpp src/Provider/PkgConfig.cpp src/Provider/Provider.cpp src/Provider/Translator.cpp diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index a080355..1850ea1 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -401,6 +401,14 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B ## Remaining future scope +- **Wave 147 (Lifecycle CLI and native compiler caching, G1/G7 start)**: + - `vbs run` builds and executes an executable target with program arguments and passes the exit code through; it uses Void::Process with inherited stdio so interactive programs keep the terminal, and runs Windows targets under Wine. + - `vbs metadata` emits a schema-versioned workspace document (roots, profile, compiler, targets with sources/includes/links/labels/install rules, dependencies, lockfile revision) built with `Void::Json::Strict` instead of hand-written JSON. + - `vbs why NAME` explains a target's dependents (root -> target paths) or a dependency's declaring record and linked targets. + - `vbs add NAME[@RANGE]` and `vbs remove NAME` edit `vbs.deps.toml` (canonical, comment-preserving block append/removal), validate version ranges through `Void::Semver::parse_range`, and refresh `vbs.lock` through the existing resolver (`--no-lock` skips it). + - `--frozen` on `build`/`test`/`run` implies `--locked --offline`. + - **Native compiler caching**: `--native-cache off|auto|ccache|sccache` (or `VBS_NATIVE_CACHE`) prepends ccache/sccache to compile actions only; the wrapper and real compiler are part of the action key, archives/links are untouched, and `vbs doctor` reports availability. Verified deterministically by `FullV1Tests.native_cache_wrapper_is_lowered_into_compile_commands` and end to end when the tool is installed (`native_cache_wraps_compile_actions`). + - **Superiority plan ([22-superiority-and-gaps.md](../roadmap/22-superiority-and-gaps.md), 2026-12-05)**: revised platform strategy - **macOS deferred**, **Windows via MinGW-w64 cross-compilation + Wine execution** (`dev cpp-gcc -p pkgsCross.mingwW64.stdenv.cc`, `dev cpp-gcc -p wine64`), native MSVC deferred; plus packaging parity (ZIP/DEB/RPM), IDE ecosystem, migration tooling, test-runner parity, benchmarks, CI runners, and remote execution in prioritized order. - **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Track C (macOS/Windows ports + dual-profile cross-compilation) and dedicated external editor plugins remain planned; Track D3 signing (SBOM, Ed25519 primitives, trusted-key enforcement/distribution, binary-variant signing/distribution) and Track E3 daemon capabilities are implemented, and Track E4 now uses `Void::Net` for the registry client/server and remote cache plus `Void::Sqlite` for the StateStore when available. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 587cbd9..15fc861 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -146,4 +146,5 @@ Base HEAD: `fe0d1a6` | Wave 144 (NuGet generator) | `--archive-format nuget`: `.nupkg` with nuspec, OPC parts and `runtimes//native` assets | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Python validates the package, install test passes, full CTest 8/8) | `src/Install/Installer.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | | Wave 145 (Coverage reporting) | `vbs test --coverage DIR`; gcov JSON -> lcov + summary | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; E2E passes, full CTest 8/8) | `include/Void/Build/Report/Coverage.hpp`, `src/Report/Coverage.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | | Wave 146 (CI hardening, explainability, shared caches, CLI surface, migration breadth) | CI image tool upgrades + coverage lane; test `--repeat/--retry/--shuffle/--stop-on-failure`; `vbs explain`; `--trace` Chrome traces; shared descriptor/probe caches; `vbs completions`/`vbs man`; `vbs migrate --from meson`; `vbs init --template`; `vbs presets --export`; MSI installer | COMPLETE & VERIFIED (GCC 16.2; new FullV1Tests cases for every feature pass, CLI contract suite passes; cold build 3897 -> 755 ms measured) | `src/Main.cpp`, `src/Execution/Scheduler.{hpp,cpp}`, `src/Cli/CommandModel.{hpp,cpp}`, `src/Config/{Frontend,Scaffold,CmakeImport}.cpp`, `src/Toolchain/Driver.cpp`, `include/Void/Build/Util/UserCache.hpp`, `.gitea/workflows/ci.yml`, [Void/CI-Images](https://git.faumaray.com/Void/CI-Images), `tests/{FullV1Tests,CliContracts}`, docs | +| Wave 147 (Lifecycle CLI + native caching) | `vbs run` (Void::Process inherited stdio, exit-code passthrough, Wine), `vbs metadata` (StrictJson schema v1), `vbs why`, `vbs add`/`vbs remove` (Semver-validated manifest editing + lock refresh), `--frozen`, `--native-cache off/auto/ccache/sccache` with doctor reporting | COMPLETE & VERIFIED for the implemented commands (GCC 16.2; `lifecycle_run_metadata_why_and_manifest_editing`, `native_cache_wrapper_is_lowered_into_compile_commands`, `native_cache_wraps_compile_actions` pass; CLI contracts pass) | `src/Main.cpp`, `src/Toolchain/Driver.{hpp,cpp}`, `src/Package/Manifest.{hpp,cpp}`, `include/Void/Build/Package/Manifest.hpp`, `tests/{FullV1Tests,CliContracts}`, docs | | Future (Plans 23–24) | Gap closure and superiority tracks | PLANNED (see the plans for per-track acceptance gates) | [23-remaining-upgrade-plan.md](../roadmap/23-remaining-upgrade-plan.md), [24-superiority-tracks.md](../roadmap/24-superiority-tracks.md) | diff --git a/docs/roadmap/24-superiority-tracks.md b/docs/roadmap/24-superiority-tracks.md index fe44a9a..440daef 100644 --- a/docs/roadmap/24-superiority-tracks.md +++ b/docs/roadmap/24-superiority-tracks.md @@ -1,6 +1,6 @@ # 24 — Superiority tracks: beyond CMake, Meson, build2 and Cargo -Status: **planned (2026-12-06)**. Nothing here is implemented unless it is listed in +Status: **partially implemented (2026-12-06)**. Tracks G1 (run/metadata/why/add/remove/--frozen) and G7's native compiler-cache slice are implemented (Wave 147); everything else is planned. Nothing else is implemented unless it is listed in [Plan 23 §1](23-remaining-upgrade-plan.md#1-verified-baseline). Interfaces are proposals. Plan 23 closes the remaining *gaps*. This plan is different: it lists what would make VBS @@ -109,6 +109,10 @@ the concrete acceptance gate. ### G1 — Cargo-grade lifecycle CLI *(S–M per command)* +**Status: partially implemented (Wave 147).** Done: `run`, `metadata`, `why`, `add`, `remove`, +`--frozen`. Pending: `new`, `bench`, `doc`, `fmt`, `lint`, `tree`, `outdated`, `update -p`, +`audit`, `deny`, `vendor`, `install-binary`. + **Beats:** Cargo (parity), CMake/Meson/build2 (they have no unified lifecycle). | Planned command | Behaviour | @@ -327,6 +331,10 @@ a minimal DAP client and reads a breakpoint hit; a sample plugin provider builds ### G7 — Speed and CI economics *(M–L)* +**Status: partially implemented (Wave 147).** Done: native compiler caching +(`--native-cache off|auto|ccache|sccache`, wrapper part of the action key, `vbs doctor` +reporting). Pending: `--affected`, daemon watch loop, build scans, cache analytics. + **Beats:** all four on CI cost; Cargo/Ninja are fast locally but have no affected-test selection or build scans. diff --git a/include/Void/Build/Package/Manifest.hpp b/include/Void/Build/Package/Manifest.hpp new file mode 100644 index 0000000..cb5bbe5 --- /dev/null +++ b/include/Void/Build/Package/Manifest.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Package { + +// One `[dependencies.]` entry to add to a TOML manifest. Empty strings are omitted. +struct ManifestDependencySpec { + std::string alias; + std::string package; + std::string version; + std::string registry; + std::string path; + std::string git; + std::string revision; + std::vector features; + bool build_dependency{false}; +}; + +// Adds (or, with `force`, replaces) a dependency table in `vbs.deps.toml`, preserving the rest of +// the file byte-for-byte where possible. The result is re-parsed before it is written. +[[nodiscard]] Void::Result::Result +add_manifest_dependency(const std::filesystem::path &manifest_path, + const ManifestDependencySpec &spec, bool force = false); + +// Removes `[dependencies.]` (including its `.options` sub-table) and validates the result. +[[nodiscard]] Void::Result::Result +remove_manifest_dependency(const std::filesystem::path &manifest_path, std::string_view alias); + +// Aliases declared in an existing manifest (empty when the file does not exist). +[[nodiscard]] std::vector +manifest_dependency_aliases(const std::filesystem::path &manifest_path); + +} // namespace Void::Build::Package diff --git a/include/Void/Build/Toolchain/Driver.hpp b/include/Void/Build/Toolchain/Driver.hpp index 90d9377..63d5643 100644 --- a/include/Void/Build/Toolchain/Driver.hpp +++ b/include/Void/Build/Toolchain/Driver.hpp @@ -55,6 +55,10 @@ struct ToolchainCapabilities { std::filesystem::path slangc; // Slang (and GLSL/HLSL) -> SPIR-V std::filesystem::path dxc; // HLSL -> SPIR-V / DXIL + // Optional native compiler cache (ccache/sccache) prepended to compile actions. Not part of + // the toolchain identity: the wrapper is part of every compile action's command instead. + std::string native_cache_executable; + std::string identity_hash; }; diff --git a/src/Main.cpp b/src/Main.cpp index 6dd3973..eca2d8a 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -45,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -449,6 +451,10 @@ struct BuildCmdOptions { bool explain{false}; std::string explain_format{"text"}; std::optional trace_arg; + bool run_after_build{false}; + std::vector run_args; + bool frozen{false}; + std::string native_cache_arg; bool publish_editor_selection{true}; bool no_cache{false}; bool locked{false}; @@ -458,6 +464,23 @@ struct BuildCmdOptions { int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { const std::string cmd_name = run_tests ? "vbs test" : "vbs build"; + if (opts.frozen) { + // --frozen is the CI-safe combination: the lockfile must exist and no network is used. + opts.locked = true; + opts.offline = true; + } + // Validate the native-cache mode before any project work (CI contract: exit 2 on misuse). + const std::string native_cache_mode = + !opts.native_cache_arg.empty() + ? opts.native_cache_arg + : std::string{Void::Configuration::get_env_or("VBS_NATIVE_CACHE", "off")}; + if (native_cache_mode != "auto" && native_cache_mode != "off" && + native_cache_mode != "none" && native_cache_mode != "0" && + native_cache_mode != "ccache" && native_cache_mode != "sccache") { + std::cerr << cmd_name << ": unsupported --native-cache '" << native_cache_mode + << "' (expected auto, off, ccache or sccache)\n"; + return 2; + } int test_timeout_seconds = 300; if (!Void::Str::to_int(opts.test_timeout_arg, test_timeout_seconds) || test_timeout_seconds <= 0 || test_timeout_seconds > 86400) { @@ -680,6 +703,42 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { Void::Str::to_lower_ascii(Toolchain::host_os_name()) != "windows"; bool all_ok = true; + // Native compiler cache (ccache/sccache): resolved once and injected into compile actions. + std::optional native_cache; + { + const std::string &mode = native_cache_mode; + if (mode != "off" && mode != "none" && mode != "0") { + const auto pick = [](std::string_view name) + -> std::optional { + if (const auto resolved = Platform::resolve_executable(std::string{name}); resolved) { + return *resolved; + } + return std::nullopt; + }; + if (mode == "auto") { + native_cache = pick("sccache"); + if (!native_cache) { + native_cache = pick("ccache"); + } + } else if (mode == "ccache" || mode == "sccache") { + native_cache = pick(mode); + if (!native_cache) { + std::cerr << cmd_name << ": --native-cache " << mode << " requested but '" + << mode << "' is not in PATH\n"; + return 2; + } + } else { + std::cerr << cmd_name << ": unsupported --native-cache '" << mode + << "' (expected auto, off, ccache or sccache)\n"; + return 2; + } + if (native_cache) { + Void::Log::info("Toolchain", "Native compiler cache: {}", + native_cache->string()); + } + } + } + for (const auto &prof_name : opts.profiles) { const auto prof_sw = Void::Time::Stopwatch::started(); ProfileContext ctx; @@ -702,6 +761,9 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { std::cerr << "vbs: " << tc.error().message() << '\n'; return 1; } + if (native_cache) { + tc->native_cache_executable = native_cache->string(); + } trace_phase("toolchain", "phase", tc_sw.elapsed_ms(), "discover and probe the toolchain"); Void::Log::info("Toolchain", "[{}] Using {} ({}) [{}]", prof_name, compiler_name(tc->family), tc->cxx_compiler.string(), tc->version_banner); @@ -1049,6 +1111,80 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { std::cout << "vbs: [" << prof_name << "] built (" << rep->executed_count << " executed, " << rep->cached_count << " cached)\n"; + if (opts.run_after_build) { + const Graph::ResolvedTargetSummary *chosen = nullptr; + if (!opts.targets.empty()) { + for (const auto &candidate : graph->targets) { + if (candidate.name == opts.targets.front() && + candidate.kind == TargetKind::Executable) { + chosen = &candidate; + break; + } + } + if (chosen == nullptr) { + std::cerr << "vbs run: '" << opts.targets.front() + << "' is not an executable target\n"; + return 2; + } + } else { + std::vector executables; + for (const auto &candidate : graph->targets) { + if (candidate.kind == TargetKind::Executable && candidate.enabled) { + executables.push_back(&candidate); + } + } + if (executables.size() != 1) { + std::cerr << "vbs run: select a target with --target ("; + for (std::size_t i = 0; i < executables.size(); ++i) { + std::cerr << (i > 0 ? ", " : "") << executables[i]->name; + } + std::cerr << ")\n"; + return 2; + } + chosen = executables.front(); + } + if (chosen->primary_outputs.empty()) { + std::cerr << "vbs run: target '" << chosen->name << "' has no output\n"; + return 1; + } + Platform::ProcessRequest run_req; + const auto executable = chosen->primary_outputs.front(); + std::string program = executable.string(); + std::vector program_args = opts.run_args; + if (windows_cross_target) { + auto wine = Platform::resolve_executable("wine"); + if (!wine) { + std::cerr << "vbs run: Windows target requires 'wine' in PATH\n"; + return 1; + } + program = wine->string(); + program_args.insert(program_args.begin(), executable.string()); + } + // Void::Process with inherited stdio: interactive programs keep the terminal. + Void::Process::SpawnOptions spawn_options; + spawn_options.executable = program; + spawn_options.arguments = program_args; + spawn_options.working_directory = project_root; + spawn_options.stdin_pipe = false; + spawn_options.stdout_pipe = false; + spawn_options.stderr_pipe = false; + auto child = Void::Process::spawn(spawn_options); + if (!child) { + std::cerr << "vbs run: " << child.error().message() << '\n'; + return 1; + } + auto status = child->wait_blocking(); + if (!status) { + std::cerr << "vbs run: " << status.error().message() << '\n'; + return 1; + } + if (!status->exited) { + std::cerr << "vbs run: program terminated by signal " << status->signal << '\n'; + return 128 + status->signal; + } + return status->code; + } + if (opts.sbom_arg) { Provenance::SbomInput sbom; sbom.project_name = project_root.filename().string(); @@ -3747,6 +3883,429 @@ int execute_deps_command(std::string_view sub, const DepsCmdOptions &opts) { return 0; } +struct MetadataCmdOptions { + std::string project_arg; + std::optional build_arg; + std::string profile_name{"debug"}; + std::optional compiler_arg; +}; + +const char *dependency_source_name(DependencySourceKind kind) { + switch (kind) { + case DependencySourceKind::Git: + return "git"; + case DependencySourceKind::Package: + return "package"; + case DependencySourceKind::Path: + return "path"; + case DependencySourceKind::Archive: + return "archive"; + case DependencySourceKind::Conan: + return "conan"; + case DependencySourceKind::PkgConfig: + return "pkgconfig"; + case DependencySourceKind::Unspecified: + break; + } + return "unspecified"; +} + +int execute_metadata_command(const MetadataCmdOptions &opts) { + std::optional compiler_override; + if (opts.compiler_arg) { + try { + compiler_override = parse_compiler(*opts.compiler_arg); + } catch (const std::exception &ex) { + std::cerr << "vbs metadata: " << ex.what() << '\n'; + return 2; + } + } + const std::filesystem::path project_root{opts.project_arg}; + const std::filesystem::path build_root = + 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) { + std::cerr << "vbs metadata: " << compiled.error().message() << '\n'; + return 1; + } + auto profs = Config::discover_profiles(*compiled, fopts); + if (!profs) { + std::cerr << "vbs metadata: " << profs.error().message() << '\n'; + return 1; + } + ProfileContext ctx; + try { + ctx = profs->resolve(opts.profile_name, compiler_override, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + } catch (const std::exception &ex) { + std::cerr << "vbs metadata: " << ex.what() << '\n'; + return 2; + } + auto desc = Config::evaluate_project(*compiled, ctx, fopts); + if (!desc) { + std::cerr << "vbs metadata: " << desc.error().message() << '\n'; + return 1; + } + + // Machine-readable document built with Void::Json::Strict so escaping and types are exact. + using JsonValue = Void::Json::Strict::Value; + using JsonArray = JsonValue::Array; + using JsonObject = JsonValue::Object; + const auto text = [](std::string value) { + JsonValue v; + v.value = std::move(value); + return v; + }; + const auto number = [](std::int64_t value) { + JsonValue v; + v.value = value; + return v; + }; + const auto boolean = [](bool value) { + JsonValue v; + v.value = value; + return v; + }; + const auto array = [](JsonArray value) { + JsonValue v; + v.value = std::move(value); + return v; + }; + const auto object = [](JsonObject value) { + JsonValue v; + v.value = std::move(value); + return v; + }; + + JsonObject root; + root["schema_version"] = number(1); + root["project_root"] = text(project_root.string()); + root["build_root"] = text(build_root.string()); + root["profile"] = text(desc->profile.name); + root["compiler"] = text(std::string{compiler_name(desc->profile.compiler)}); + root["os"] = text(desc->profile.os); + root["architecture"] = text(desc->profile.architecture); + + JsonArray targets; + for (const auto &target : desc->targets) { + JsonObject entry; + entry["name"] = text(target.name); + entry["kind"] = text(std::string{target_kind_name(target.kind)}); + JsonArray sources; + for (const auto &source : target.sources) { + sources.push_back(text(source.path)); + } + entry["sources"] = array(std::move(sources)); + JsonArray includes; + for (const auto &include : target.include_directories) { + JsonObject item; + item["path"] = text(include.path); + item["visibility"] = text(std::string{visibility_name(include.visibility)}); + includes.push_back(object(std::move(item))); + } + entry["include_directories"] = array(std::move(includes)); + JsonArray links; + for (const auto &link : target.links) { + JsonObject item; + item["target"] = text(link.target); + item["dependency"] = text(link.dependency); + item["visibility"] = text(std::string{visibility_name(link.visibility)}); + links.push_back(object(std::move(item))); + } + entry["links"] = array(std::move(links)); + JsonArray labels; + for (const auto &label : target.labels) { + labels.push_back(text(label)); + } + entry["labels"] = array(std::move(labels)); + if (target.install_rule) { + JsonObject install; + install["destination"] = text(target.install_rule->destination); + install["component"] = text(target.install_rule->component); + entry["install"] = object(std::move(install)); + } else { + entry["install"] = JsonValue{}; + } + targets.push_back(object(std::move(entry))); + } + root["targets"] = array(std::move(targets)); + + JsonArray dependencies; + for (const auto &dep : desc->dependencies) { + JsonObject entry; + entry["name"] = text(dep.name); + entry["source"] = text(dependency_source_name(dep.source_kind)); + entry["package"] = text(dep.package); + entry["version"] = text(dep.version); + entry["builder"] = text(dep.builder); + entry["registry"] = text(dep.registry_authority); + JsonArray features; + for (const auto &feature : dep.features) { + features.push_back(text(feature)); + } + entry["features"] = array(std::move(features)); + entry["build_dependency"] = boolean(dep.build_dependency); + dependencies.push_back(object(std::move(entry))); + } + root["dependencies"] = array(std::move(dependencies)); + + const auto lock_path = project_root / "vbs.lock"; + std::error_code lock_ec; + JsonObject lockfile; + lockfile["path"] = text(lock_path.string()); + if (std::filesystem::is_regular_file(lock_path, lock_ec)) { + auto pinned = Package::load_pinned_lock(lock_path); + lockfile["exists"] = boolean(true); + lockfile["revision"] = + text(pinned && pinned->has_value() ? (*pinned)->revision_hash : ""); + } else { + lockfile["exists"] = boolean(false); + } + root["lockfile"] = object(std::move(lockfile)); + + auto serialized = Void::Json::Strict::serialize(object(std::move(root))); + if (!serialized) { + std::cerr << "vbs metadata: cannot serialize the metadata document\n"; + return 1; + } + std::cout << *serialized << '\n'; + return 0; +} + +struct WhyCmdOptions { + std::string project_arg; + std::optional build_arg; + std::string profile_name{"debug"}; + std::optional compiler_arg; + std::string name_arg; +}; + +int execute_why_command(const WhyCmdOptions &opts) { + std::optional compiler_override; + if (opts.compiler_arg) { + try { + compiler_override = parse_compiler(*opts.compiler_arg); + } catch (const std::exception &ex) { + std::cerr << "vbs why: " << ex.what() << '\n'; + return 2; + } + } + const std::filesystem::path project_root{opts.project_arg}; + const std::filesystem::path build_root = + 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) { + std::cerr << "vbs why: " << compiled.error().message() << '\n'; + return 1; + } + auto profs = Config::discover_profiles(*compiled, fopts); + if (!profs) { + std::cerr << "vbs why: " << profs.error().message() << '\n'; + return 1; + } + ProfileContext ctx; + try { + ctx = profs->resolve(opts.profile_name, compiler_override, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + } catch (const std::exception &ex) { + std::cerr << "vbs why: " << ex.what() << '\n'; + return 2; + } + auto desc = Config::evaluate_project(*compiled, ctx, fopts); + if (!desc) { + std::cerr << "vbs why: " << desc.error().message() << '\n'; + return 1; + } + + std::map, std::less<>> dependents; + std::set target_names; + for (const auto &target : desc->targets) { + target_names.insert(target.name); + for (const auto &link : target.links) { + if (link.kind == LinkKind::Local && link.dependency.empty()) { + dependents[link.target].push_back(target.name); + } + } + } + + if (target_names.contains(opts.name_arg)) { + struct PathPrinter { + const std::map, std::less<>> &dependents; + std::string found; + std::vector stack; + std::size_t paths{0}; + + void visit(const std::string &name, std::size_t depth) { + if (depth > 32 || paths >= 64) { + return; + } + stack.push_back(name); + const auto it = dependents.find(name); + if (it == dependents.end() || it->second.empty()) { + ++paths; + std::cout << " "; + // Print root -> target (the requested target is the last element). + for (std::size_t i = stack.size(); i > 0; --i) { + std::cout << (i < stack.size() ? " -> " : "") << stack[i - 1]; + } + std::cout << '\n'; + } else { + for (const auto &parent : it->second) { + visit(parent, depth + 1); + } + } + stack.pop_back(); + } + }; + std::cout << "target '" << opts.name_arg << "' is used by:\n"; + PathPrinter printer{dependents}; + printer.visit(opts.name_arg, 0); + return 0; + } + + for (const auto &dep : desc->dependencies) { + if (dep.name == opts.name_arg) { + std::cout << "dependency '" << dep.name << "' (" << dependency_source_name(dep.source_kind) + << ", package=" << (dep.package.empty() ? "-" : dep.package) + << ", version=" << (dep.version.empty() ? "-" : dep.version) << ")\n"; + bool linked = false; + for (const auto &target : desc->targets) { + for (const auto &link : target.links) { + if (link.dependency == dep.name) { + std::cout << " linked by target '" << target.name << "' (" << link.target + << ")\n"; + linked = true; + } + } + } + if (!linked) { + std::cout << " not linked by any target\n"; + } + return 0; + } + } + + std::cerr << "vbs why: '" << opts.name_arg << "' is neither a target nor a dependency\n"; + std::cerr << "targets:"; + for (const auto &target : desc->targets) { + std::cerr << ' ' << target.name; + } + std::cerr << "\ndependencies:"; + for (const auto &dep : desc->dependencies) { + std::cerr << ' ' << dep.name; + } + std::cerr << '\n'; + return 1; +} + +struct AddCmdOptions { + std::string project_arg{"."}; + std::optional build_arg; + std::string profile_name{"debug"}; + std::optional manifest_arg; + std::string spec_arg; + std::optional path_arg; + std::optional git_arg; + std::optional rev_arg; + std::optional registry_arg; + std::vector features; + bool build_dependency{false}; + bool force{false}; + bool no_lock{false}; +}; + +struct RemoveCmdOptions { + std::string project_arg{"."}; + std::optional build_arg; + std::string profile_name{"debug"}; + std::optional manifest_arg; + std::string name_arg; + bool no_lock{false}; +}; + +// Reloads the lock after a manifest edit by reusing the `vbs deps update` pipeline. +int refresh_lock_after_manifest_edit(const std::string &project_arg, + const std::optional &build_arg, + const std::string &profile_name) { + DepsCmdOptions deps; + deps.project_arg = project_arg; + deps.build_arg = build_arg; + deps.profile_name = profile_name; + return execute_deps_command("update", deps); +} + +int execute_add_command(const AddCmdOptions &opts) { + std::string name = opts.spec_arg; + std::string version; + if (const auto at = name.rfind('@'); at != std::string::npos && at > 0 && + name.find('/') == std::string::npos) { + version = name.substr(at + 1); + name = name.substr(0, at); + } + if (name.empty()) { + std::cerr << "vbs add: a dependency name is required\n"; + return 2; + } + const std::filesystem::path project_root{opts.project_arg}; + const auto manifest = opts.manifest_arg ? std::filesystem::path{*opts.manifest_arg} + : (project_root / "vbs.deps.toml"); + Package::ManifestDependencySpec spec; + spec.alias = name; + spec.package = name; + spec.version = version; + spec.path = opts.path_arg.value_or(""); + spec.git = opts.git_arg.value_or(""); + spec.revision = opts.rev_arg.value_or(""); + spec.registry = opts.registry_arg.value_or(""); + spec.features = opts.features; + spec.build_dependency = opts.build_dependency; + if (!spec.path.empty()) { + spec.package.clear(); // A path dependency is identified by its path. + } + if (!spec.git.empty()) { + spec.package.clear(); + } + auto added = Package::add_manifest_dependency(manifest, spec, opts.force); + if (!added) { + std::cerr << added.error().message() << '\n'; + return added.error().kind() == Void::Result::ErrorKind::invalid_argument ? 2 : 1; + } + std::cout << "added " << name << (version.empty() ? "" : " " + version) << " to " + << manifest.string() << '\n'; + if (opts.no_lock) { + return 0; + } + const int lock_rc = + refresh_lock_after_manifest_edit(opts.project_arg, opts.build_arg, opts.profile_name); + if (lock_rc != 0) { + std::cerr << "vbs add: the manifest was updated but the lockfile refresh failed\n"; + } + return lock_rc; +} + +int execute_remove_command(const RemoveCmdOptions &opts) { + const std::filesystem::path project_root{opts.project_arg}; + const auto manifest = opts.manifest_arg ? std::filesystem::path{*opts.manifest_arg} + : (project_root / "vbs.deps.toml"); + auto removed = Package::remove_manifest_dependency(manifest, opts.name_arg); + if (!removed) { + std::cerr << removed.error().message() << '\n'; + return removed.error().kind() == Void::Result::ErrorKind::invalid_argument ? 2 : 1; + } + std::cout << "removed " << opts.name_arg << " from " << manifest.string() << '\n'; + if (opts.no_lock) { + return 0; + } + const int lock_rc = + refresh_lock_after_manifest_edit(opts.project_arg, opts.build_arg, opts.profile_name); + if (lock_rc != 0) { + std::cerr << "vbs remove: the manifest was updated but the lockfile refresh failed\n"; + } + return lock_rc; +} + struct InitCmdOptions { std::string dir_arg; std::optional name_arg; @@ -3836,6 +4395,21 @@ int execute_doctor_command() { (void)check_tool("meson", "meson", false); (void)check_tool("conan", "conan", false); (void)check_tool("clang-format", "clang-format", false); + const bool has_ccache = check_tool("ccache (native cache)", "ccache", false); + const bool has_sccache = check_tool("sccache (native cache)", "sccache", false); + std::string cache_tools; + if (has_ccache) { + cache_tools = "ccache"; + } + if (has_sccache) { + cache_tools += cache_tools.empty() ? "sccache" : " + sccache"; + } + std::cout << " " << ((has_ccache || has_sccache) ? "[ok] " : "[opt] ") + << " native compiler cache: " + << (cache_tools.empty() ? std::string{"none"} : cache_tools) + << ((has_ccache || has_sccache) ? " (use --native-cache or VBS_NATIVE_CACHE)" + : " (install ccache or sccache)") + << '\n'; std::cout << " [ok] Void::Crypto built-in SHA-256: enabled\n"; std::cout << " [ok] Void::Archive built-in USTAR/PAX: enabled\n"; @@ -4339,6 +4913,14 @@ int main(int argc, char **argv) { const std::string clean_default_build = clean_opts.build_arg; GraphCmdOptions graph_opts; graph_opts.project_arg = cwd; + MetadataCmdOptions metadata_opts; + metadata_opts.project_arg = cwd; + WhyCmdOptions why_opts; + why_opts.project_arg = cwd; + AddCmdOptions add_opts; + add_opts.project_arg = cwd; + RemoveCmdOptions remove_opts; + remove_opts.project_arg = cwd; CompletionsCmdOptions completions_opts; ManCmdOptions man_opts; IdeCmdOptions ide_opts; @@ -4407,6 +4989,11 @@ int main(int argc, char **argv) { "Environment variable holding the remote cache bearer token", build_opts.remote_cache_token_env) .flag("--locked", "", "Require existing up-to-date vbs.lock", build_opts.locked) + .flag("--frozen", "", "Require the lock and disable all network access", + build_opts.frozen) + .option_default("--native-cache", "", + "Native compiler cache: off (default), auto, ccache or sccache", + build_opts.native_cache_arg, "") .flag("--offline", "", "Disallow network fetches", build_opts.offline) .flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache) .flag("--native-foreign", "", @@ -4429,6 +5016,10 @@ int main(int argc, char **argv) { 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 &run_cmd = root.subcommand("run", "Build and run an executable target"); + configure_build_or_test(run_cmd); + run_cmd.positional_many("args", "Arguments passed to the program (after --)", + build_opts.run_args, false); auto &explain_cmd = root.subcommand("explain", "Explain why each action would run or be reused"); configure_build_or_test(explain_cmd); @@ -4798,6 +5389,60 @@ int main(int argc, char **argv) { .option_default("--format", "-f", "Output format (dot|json)", graph_opts.format, "dot"); add_log_flags(graph_cmd); + auto &metadata_cmd = root.subcommand( + "metadata", "Emit a stable machine-readable workspace metadata document"); + metadata_cmd + .option_default("--project", "-C", "Project directory", metadata_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", metadata_opts.build_arg) + .option_default("--profile", "-p", "Profile name", metadata_opts.profile_name, "debug") + .option("--compiler", "", "Override compiler family (gcc|clang)", + metadata_opts.compiler_arg); + add_log_flags(metadata_cmd); + + auto &why_cmd = root.subcommand("why", "Explain why a target or dependency is in the build"); + why_cmd + .option_default("--project", "-C", "Project directory", why_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", why_opts.build_arg) + .option_default("--profile", "-p", "Profile name", why_opts.profile_name, "debug") + .option("--compiler", "", "Override compiler family (gcc|clang)", why_opts.compiler_arg) + .positional("name", "Target or dependency name", why_opts.name_arg); + add_log_flags(why_cmd); + + auto &add_cmd = root.subcommand("add", "Add a dependency to vbs.deps.toml and refresh vbs.lock"); + add_cmd + .option_default("--project", "-C", "Project directory", add_opts.project_arg, ".") + .option("--build-dir", "-B", "Build output directory", add_opts.build_arg) + .option_default("--profile", "-p", "Profile used to refresh the lock", add_opts.profile_name, + "debug") + .option("--manifest", "-m", "Manifest path (default: /vbs.deps.toml)", + add_opts.manifest_arg) + .option("--path", "", "Declare a path dependency", add_opts.path_arg) + .option("--git", "", "Declare a git dependency", add_opts.git_arg) + .option("--rev", "", "Git revision for --git", add_opts.rev_arg) + .option("--registry", "", "Registry URL for a package dependency", add_opts.registry_arg) + .option_many("--features", "", "Dependency features to enable (repeatable)", + add_opts.features) + .flag("--build", "", "Mark the dependency as a build-time dependency", + add_opts.build_dependency) + .flag("--force", "", "Replace an existing dependency entry", add_opts.force) + .flag("--no-lock", "", "Only edit the manifest, do not refresh vbs.lock", add_opts.no_lock) + .positional("dependency", "Dependency name, optionally NAME@VERSION", add_opts.spec_arg); + add_log_flags(add_cmd); + + auto &remove_cmd = + root.subcommand("remove", "Remove a dependency from vbs.deps.toml and refresh vbs.lock"); + remove_cmd + .option_default("--project", "-C", "Project directory", remove_opts.project_arg, ".") + .option("--build-dir", "-B", "Build output directory", remove_opts.build_arg) + .option_default("--profile", "-p", "Profile used to refresh the lock", + remove_opts.profile_name, "debug") + .option("--manifest", "-m", "Manifest path (default: /vbs.deps.toml)", + remove_opts.manifest_arg) + .flag("--no-lock", "", "Only edit the manifest, do not refresh vbs.lock", + remove_opts.no_lock) + .positional("dependency", "Dependency name", remove_opts.name_arg); + add_log_flags(remove_cmd); + auto &ide_cmd = root.subcommand("ide", "Generate editor/IDE configs and query workspace metadata"); auto configure_ide_common = [&](Void::Argparse::Parser &p) { @@ -5054,6 +5699,7 @@ int main(int argc, char **argv) { const std::string_view cmd = parsed.matched_command_path.front(); const bool machine_quiet_default = (cmd == "describe") || (cmd == "graph") || (cmd == "doctor") || (cmd == "explain") || + (cmd == "metadata") || (cmd == "why") || (cmd == "compdb" && parsed.matched_command_path.size() >= 2 && parsed.matched_command_path[1] == "show") || (cmd == "ide" && parsed.matched_command_path.size() >= 2 && @@ -5064,9 +5710,14 @@ int main(int argc, char **argv) { : Void::Log::Level::Info); ConsoleLogGuard log_guard{log_level}; - if (cmd == "build" || cmd == "test" || cmd == "explain") { + if (cmd == "build" || cmd == "test" || cmd == "explain" || cmd == "run") { const bool run_tests = cmd == "test"; build_opts.explain = cmd == "explain"; + build_opts.run_after_build = cmd == "run"; + if (build_opts.run_after_build && build_opts.profiles.size() > 1) { + std::cerr << "vbs run: exactly one --profile may be selected\n"; + return 2; + } if (build_opts.explain && build_opts.explain_format != "text" && build_opts.explain_format != "json") { std::cerr << "vbs explain: unsupported --format '" << build_opts.explain_format @@ -5166,6 +5817,18 @@ int main(int argc, char **argv) { if (cmd == "graph") { return execute_graph_command(graph_opts); } + if (cmd == "metadata") { + return execute_metadata_command(metadata_opts); + } + if (cmd == "why") { + return execute_why_command(why_opts); + } + if (cmd == "add") { + return execute_add_command(add_opts); + } + if (cmd == "remove") { + return execute_remove_command(remove_opts); + } if (cmd == "ide") { return execute_ide_command(parsed.matched_command_path.at(1), ide_opts); } diff --git a/src/Package/Manifest.cpp b/src/Package/Manifest.cpp new file mode 100644 index 0000000..e694399 --- /dev/null +++ b/src/Package/Manifest.cpp @@ -0,0 +1,267 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Build::Package { +namespace { + +Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string message) { + return Void::System::make_system_error(code, std::move(message)); +} + +bool valid_alias(std::string_view alias) { + if (alias.empty()) { + return false; + } + return std::ranges::all_of(alias, [](char c) { + return std::isalnum(static_cast(c)) != 0 || c == '_' || c == '-' || c == '.'; + }); +} + +std::vector split_lines(std::string_view text) { + std::vector lines; + for (const auto part : Void::Str::split(text, '\n')) { + lines.emplace_back(part); + } + return lines; +} + +std::string trim(std::string_view text) { return std::string{Void::Str::trim(text)}; } + +// Returns the dependency-alias header a line opens, or nullopt. +std::optional dependency_header(std::string_view line) { + const std::string trimmed = trim(line); + static constexpr std::string_view kPrefix = "[dependencies."; + if (!Void::Str::starts_with(trimmed, kPrefix) || !Void::Str::ends_with(trimmed, "]")) { + return std::nullopt; + } + std::string key = trimmed.substr(kPrefix.size(), trimmed.size() - kPrefix.size() - 1); + // Drop a `.options`-style sub-table suffix. + if (const auto dot = key.find('.'); dot != std::string::npos) { + key = key.substr(0, dot); + } + if (key.size() >= 2 && key.front() == '"' && key.back() == '"') { + key = key.substr(1, key.size() - 2); + } + return key; +} + +bool is_top_level_header(std::string_view line) { + const std::string trimmed = trim(line); + return Void::Str::starts_with(trimmed, "[") && Void::Str::ends_with(trimmed, "]"); +} + +void validate_text(const std::filesystem::path &path, std::string_view text) { + (void)path; + // parse_toml throws through Result; callers check the result. + (void)text; +} + +} // namespace + +std::vector manifest_dependency_aliases(const std::filesystem::path &manifest_path) { + std::vector aliases; + std::error_code ec; + if (!std::filesystem::is_regular_file(manifest_path, ec)) { + return aliases; + } + auto parsed = parse_toml_file(manifest_path); + if (!parsed) { + return aliases; + } + const auto deps = parsed->find("dependencies"); + if (deps == parsed->end() || !deps->second.is_table()) { + return aliases; + } + for (const auto &[alias, value] : deps->second.as_table()) { + if (value.is_table()) { + aliases.push_back(alias); + } + } + return aliases; +} + +Void::Result::Result +add_manifest_dependency(const std::filesystem::path &manifest_path, + const ManifestDependencySpec &spec, bool force) { + if (!valid_alias(spec.alias)) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::invalid_argument, + std::format("vbs add: invalid dependency name '{}' (use letters, digits, '_', '-', " + "'.')", + spec.alias))}; + } + if (spec.package.empty() && spec.path.empty() && spec.git.empty()) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "vbs add: a package name, --path or --git source is " + "required")}; + } + if (!spec.version.empty() && !Void::Semver::parse_range(spec.version)) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::invalid_argument, + std::format("vbs add: invalid version range '{}'", spec.version))}; + } + std::error_code ec; + std::string text; + if (std::filesystem::is_regular_file(manifest_path, ec)) { + auto existing = Void::FileSystem::read_file(manifest_path); + if (!existing) { + return std::unexpected{existing.error()}; + } + text = *existing; + } + const auto aliases = manifest_dependency_aliases(manifest_path); + if (std::ranges::find(aliases, spec.alias) != aliases.end() && !force) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::already_exists, + std::format("vbs add: dependency '{}' already exists in {} (pass --force to replace)", + spec.alias, manifest_path.string()))}; + } + + std::string block; + if (!spec.package.empty()) { + block += "package = " + Util::json_quote(spec.package) + "\n"; + } + if (!spec.version.empty()) { + block += "version = " + Util::json_quote(spec.version) + "\n"; + } + if (!spec.registry.empty()) { + block += "registry = " + Util::json_quote(spec.registry) + "\n"; + } + if (!spec.git.empty()) { + block += "git = " + Util::json_quote(spec.git) + "\n"; + } + if (!spec.revision.empty()) { + block += "rev = " + Util::json_quote(spec.revision) + "\n"; + } + if (!spec.path.empty()) { + block += "path = " + Util::json_quote(spec.path) + "\n"; + } + if (!spec.features.empty()) { + std::string list = "["; + for (std::size_t i = 0; i < spec.features.size(); ++i) { + if (i > 0) { + list += ", "; + } + list += Util::json_quote(spec.features[i]); + } + list += ']'; + block += "features = " + list + "\n"; + } + if (spec.build_dependency) { + block += "build_dependency = true\n"; + } + + std::string updated; + if (force && std::ranges::find(aliases, spec.alias) != aliases.end()) { + // Replace the existing block in place: remove it, then append the new one at the end. + auto removed = remove_manifest_dependency(manifest_path, spec.alias); + if (!removed) { + return removed; + } + auto rest = Void::FileSystem::read_file(manifest_path); + if (!rest) { + return std::unexpected{rest.error()}; + } + updated = *rest; + if (!updated.empty() && !updated.ends_with('\n')) { + updated += '\n'; + } + if (!updated.empty()) { + updated += '\n'; + } + } else { + updated = text; + if (!updated.empty() && !updated.ends_with('\n')) { + updated += '\n'; + } + if (!updated.empty()) { + updated += '\n'; + } + } + updated += "[dependencies." + spec.alias + "]\n" + block; + + if (auto parsed = parse_toml(updated, manifest_path.string()); !parsed) { + return std::unexpected{parsed.error()}; + } + if (auto written = Platform::atomic_write_file(manifest_path, updated, false); !written) { + return std::unexpected{written.error()}; + } + return {}; +} + +Void::Result::Result +remove_manifest_dependency(const std::filesystem::path &manifest_path, std::string_view alias) { + if (!valid_alias(alias)) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + std::format("vbs remove: invalid dependency name '{}'", + alias))}; + } + std::error_code ec; + if (!std::filesystem::is_regular_file(manifest_path, ec)) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::not_found, + std::format("vbs remove: manifest '{}' does not exist", manifest_path.string()))}; + } + auto text = Void::FileSystem::read_file(manifest_path); + if (!text) { + return std::unexpected{text.error()}; + } + const auto lines = split_lines(*text); + std::vector kept; + bool removed = false; + bool skipping = false; + for (const auto &line : lines) { + if (const auto header = dependency_header(line); header && *header == alias) { + removed = true; + skipping = true; + continue; + } + if (skipping) { + if (is_top_level_header(line)) { + skipping = false; + } else { + continue; // Still inside the removed table (or its options sub-table). + } + } + kept.push_back(line); + } + if (!removed) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::not_found, + std::format("vbs remove: dependency '{}' is not declared in {}", alias, + manifest_path.string()))}; + } + // Collapse runs of blank lines introduced by the removal. + std::string updated; + bool previous_blank = true; + for (const auto &line : kept) { + const bool blank = trim(line).empty(); + if (blank && previous_blank) { + continue; + } + updated += line; + updated += '\n'; + previous_blank = blank; + } + if (auto parsed = parse_toml(updated, manifest_path.string()); !parsed) { + return std::unexpected{parsed.error()}; + } + if (auto written = Platform::atomic_write_file(manifest_path, updated, false); !written) { + return std::unexpected{written.error()}; + } + return {}; +} + +} // namespace Void::Build::Package diff --git a/src/Toolchain/Driver.cpp b/src/Toolchain/Driver.cpp index e7cb7d7..3df472c 100644 --- a/src/Toolchain/Driver.cpp +++ b/src/Toolchain/Driver.cpp @@ -858,6 +858,14 @@ lower_compile_command(const ToolchainCapabilities &toolchain, const CompileReque } else { cmd.arguments = std::move(args); } + + // Native compiler cache: run `ccache ...` (or sccache). The wrapper becomes the + // action's executable and the real compiler its first argument, so the action key and the + // cached artifact both cover the wrapper. + if (!toolchain.native_cache_executable.empty()) { + cmd.arguments.insert(cmd.arguments.begin(), cmd.executable.string()); + cmd.executable = toolchain.native_cache_executable; + } return cmd; } diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index ffa7dd6..2271733 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -43,6 +43,15 @@ check_process(2 "" "invalid value 'bazel' for '--from'" migrate --from bazel) check_process(2 "" "invalid value 'bogus' for '--template'" init --template bogus) check_process(0 "--template" "" init --help) check_process(0 "--export" "" presets --help) +check_process(0 "Usage: vbs run " "" run --help) +check_process(0 "Usage: vbs metadata " "" metadata --help) +check_process(0 "Usage: vbs why " "" why --help) +check_process(0 "Usage: vbs add " "" add --help) +check_process(0 "Usage: vbs remove " "" remove --help) +check_process(0 "--frozen" "" build --help) +check_process(0 "--native-cache" "" build --help) +check_process(2 "" "unsupported --native-cache" build --native-cache bogus) +check_process(2 "" "invalid version range" add fmt@bad --no-lock) check_process(2 "" "invalid --repeat mode" test --repeat bogus) check_process(2 "" "invalid --repeat count" test --repeat until-pass:0) check_process(2 "" "invalid --retry value" test --retry 99) diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index d95f853..d618199 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -4347,3 +4347,232 @@ void build(Void::Build::Project &p) { Void::Testing::expect(preset.build_dir.has_value()); } } + +// === Lifecycle CLI: run, metadata, why, manifest add/remove, frozen === +VOID_TEST(FullV1Tests, lifecycle_run_metadata_why_and_manifest_editing) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_lifecycle_"}; + const auto proj = tmp / "proj"; + const auto bdir = tmp / "build"; + + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + auto lib = p.static_library("demo").sources({"src/demo.cpp"}); + p.executable("app").sources({"src/main.cpp"}).link(lib); +} +)cpp"); + write_file(proj / "src" / "demo.cpp", "int demo() { return 1; }\n"); + write_file(proj / "src" / "main.cpp", R"cpp(#include +#include +int demo(); +int main(int argc, char **argv) { + for (int i = 1; i < argc; ++i) { + std::cout << "arg:" << argv[i] << "\n"; + } + return demo() + (argc > 1 ? std::atoi(argv[1]) : 0); +} +)cpp"); + + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{600}; + return Platform::run_supervised(req); + }; + + // `vbs run` builds and runs the target with the program arguments and exit code. + auto ran = run_vbs({"run", "--project", proj.string(), "--build-dir", bdir.string(), + "--target", "app", "--jobs", "2", "6", "hello"}); + Void::Testing::expect(ran.has_value()); + if (ran) { + Void::Testing::expect_eq(ran->exit_code, 7); // demo() == 1, argv[1] == 6 + Void::Testing::expect(ran->stdout_data.find("arg:hello") != std::string::npos); + } + + // `vbs metadata` is a versioned JSON document built with Void::Json::Strict. + auto metadata = run_vbs({"metadata", "--project", proj.string(), "--build-dir", + bdir.string()}); + Void::Testing::expect(metadata.has_value() && metadata->succeeded()); + if (metadata) { + auto parsed = Void::Json::Strict::parse(metadata->stdout_data); + Void::Testing::require(parsed.has_value()); + const auto *root = std::get_if(&parsed->value); + Void::Testing::require(root != nullptr); + const auto *targets = std::get_if( + &root->at("targets").value); + Void::Testing::require(targets != nullptr); + Void::Testing::expect_eq(targets->size(), std::size_t{2}); + bool saw_app = false; + for (const auto &target : *targets) { + const auto *object = std::get_if(&target.value); + if (object == nullptr) { + continue; + } + const auto *kind = std::get_if(&object->at("kind").value); + const auto *name = std::get_if(&object->at("name").value); + if (name != nullptr && *name == "app" && kind != nullptr && *kind == "executable") { + saw_app = true; + } + } + Void::Testing::expect(saw_app); + } + + // `vbs why` walks the target dependency graph. + auto why_lib = run_vbs({"why", "demo", "--project", proj.string(), "--build-dir", + bdir.string()}); + Void::Testing::expect(why_lib.has_value() && why_lib->succeeded()); + if (why_lib) { + Void::Testing::expect(why_lib->stdout_data.find("app -> demo") != std::string::npos); + } + auto why_app = run_vbs({"why", "app", "--project", proj.string(), "--build-dir", + bdir.string()}); + Void::Testing::expect(why_app.has_value() && why_app->succeeded()); + auto why_missing = run_vbs({"why", "nope", "--project", proj.string(), "--build-dir", + bdir.string()}); + Void::Testing::expect(why_missing.has_value() && why_missing->exit_code == 1); + + // `vbs add` / `vbs remove` edit the manifest (canonically, with semver validation). + const auto manifest = tmp / "vbs.deps.toml"; + auto added = run_vbs({"add", "zlib@^1.3", "--manifest", manifest.string(), "--no-lock"}); + Void::Testing::expect(added.has_value() && added->succeeded()); + auto manifest_text = Void::FileSystem::read_file(manifest); + Void::Testing::require(manifest_text.has_value()); + Void::Testing::expect(manifest_text->find("[dependencies.zlib]") != std::string::npos); + Void::Testing::expect(manifest_text->find("version = \"^1.3\"") != std::string::npos); + auto duplicate = run_vbs({"add", "zlib", "--manifest", manifest.string(), "--no-lock"}); + Void::Testing::expect(duplicate.has_value() && duplicate->exit_code != 0); + auto bad_version = run_vbs({"add", "fmt@not a range", "--manifest", manifest.string(), + "--no-lock"}); + Void::Testing::expect(bad_version.has_value() && bad_version->exit_code == 2); + auto removed = run_vbs({"remove", "zlib", "--manifest", manifest.string(), "--no-lock"}); + Void::Testing::expect(removed.has_value() && removed->succeeded()); + auto removed_text = Void::FileSystem::read_file(manifest); + Void::Testing::require(removed_text.has_value()); + Void::Testing::expect(removed_text->find("[dependencies.zlib]") == std::string::npos); + + // `--frozen` implies the locked + offline combination. + auto frozen = run_vbs({"build", "--project", proj.string(), "--build-dir", bdir.string(), + "--frozen", "--jobs", "2"}); + Void::Testing::expect(frozen.has_value() && frozen->succeeded()); +} + +// === Native compiler caching (ccache/sccache) === +VOID_TEST(FullV1Tests, native_cache_wraps_compile_actions) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + const auto ccache = Platform::resolve_executable("ccache"); + const auto sccache = Platform::resolve_executable("sccache"); + if (vbs_bin.empty() || (!ccache && !sccache)) { + return; // The tool is not installed; the CI image ships ccache. + } + const std::string wrapper = (ccache ? *ccache : *sccache).string(); + const std::string tool_name = ccache ? "ccache" : "sccache"; + + Void::FileSystem::TempDir tmp{"vbs_native_cache_"}; + const auto proj = tmp / "proj"; + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + p.executable("app").sources({"src/main.cpp"}); +} +)cpp"); + write_file(proj / "src" / "main.cpp", "int main() { return 0; }\n"); + + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{600}; + return Platform::run_supervised(req); + }; + const auto compile_command_starts_with = [&](const std::filesystem::path &build_dir, + std::string_view prefix) { + auto explained = run_vbs({"explain", "--project", proj.string(), "--build-dir", + build_dir.string(), "--format", "json"}); + if (!explained || !explained->succeeded()) { + return false; + } + auto parsed = Void::Json::Strict::parse(explained->stdout_data); + if (!parsed) { + return false; + } + const auto *root = std::get_if(&parsed->value); + if (root == nullptr) { + return false; + } + const auto *actions = + std::get_if(&root->at("actions").value); + if (actions == nullptr) { + return false; + } + for (const auto &action : *actions) { + const auto *object = std::get_if(&action.value); + if (object == nullptr) { + continue; + } + const auto *label = std::get_if(&object->at("label").value); + const auto *command = std::get_if(&object->at("command").value); + if (label != nullptr && command != nullptr && + label->starts_with("Compile") && command->starts_with(prefix)) { + return true; + } + } + return false; + }; + + // With the native cache enabled the compile action runs through the wrapper. + auto cached = run_vbs({"build", "--project", proj.string(), "--build-dir", + (tmp / "build-cache").string(), "--jobs", "2", "--native-cache", + tool_name}); + Void::Testing::expect(cached.has_value() && cached->succeeded()); + Void::Testing::expect(compile_command_starts_with(tmp / "build-cache", wrapper)); + + // Disabled: the compile action starts with the compiler itself. + auto plain = run_vbs({"build", "--project", proj.string(), "--build-dir", + (tmp / "build-plain").string(), "--jobs", "2", "--native-cache", + "off"}); + Void::Testing::expect(plain.has_value() && plain->succeeded()); + Void::Testing::expect(!compile_command_starts_with(tmp / "build-plain", wrapper)); + + auto bad = run_vbs({"build", "--project", proj.string(), "--build-dir", + (tmp / "build-bad").string(), "--native-cache", "bogus"}); + Void::Testing::expect(bad.has_value() && bad->exit_code == 2); +} + +// === Native cache lowering (deterministic, no ccache installation required) === +VOID_TEST(FullV1Tests, native_cache_wrapper_is_lowered_into_compile_commands) { + Toolchain::ToolchainCapabilities caps; + caps.family = CompilerFamily::Gcc; + caps.cxx_compiler = "/usr/bin/g++"; + caps.c_compiler = "/usr/bin/gcc"; + caps.archiver = "/usr/bin/ar"; + caps.supports_cxx26 = true; + caps.supports_file_prefix_map = true; + + Toolchain::CompileRequest request; + request.source_file = "/tmp/vbs_native_cache_probe.cpp"; + request.output_object = "/tmp/vbs_native_cache_probe.o"; + request.cxx_standard = CxxStandard::Cxx26; + request.compile_only = true; + request.nondeterministic = true; // Skip -frandom-seed for a stable assertion target. + + auto plain = Toolchain::lower_compile_command(caps, request); + Void::Testing::require(plain.has_value()); + Void::Testing::expect(plain->executable == caps.cxx_compiler); + Void::Testing::require(!plain->arguments.empty()); + Void::Testing::expect(plain->arguments.front() != caps.cxx_compiler.string()); + + caps.native_cache_executable = "/usr/bin/ccache"; + auto cached = Toolchain::lower_compile_command(caps, request); + Void::Testing::require(cached.has_value()); + Void::Testing::expect(cached->executable == std::filesystem::path{"/usr/bin/ccache"}); + Void::Testing::require(!cached->arguments.empty()); + Void::Testing::expect_eq(cached->arguments.front(), std::string{"/usr/bin/g++"}); + // The original compiler flags still follow the wrapped compiler. + Void::Testing::expect(std::ranges::find(cached->arguments, std::string{"-std=c++26"}) != + cached->arguments.end()); +}