From c8706c452b2d7040dc7ee94953c460c206cde4b5 Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:07:50 +0530 Subject: [PATCH 1/6] feat: the cache collects the work directories of plans that describe `mcpp emit build-database`, `mcpp pack --list-formats` and the pin check of `mcpp publish` plan a project without writing into it, each in a directory of the home: `cache/build-database/`, `cache/pack-formats/` and `cache/publish-plan/`, one per project. Nothing removed one. `cache gc`, `prune` and `clean` read only the build cache, so the directory of a project that no longer exists stayed for ever: one home held 626 of them, 3.4 GB, and another 1.9 GB under pack-formats (mcpp#969). The three commands now take their directory from one function, mcpp::bmi_cache::plan_work_dir. It creates the directory and records each use on its `.mcpp-plan` record: the record is written with the project root when the directory is new, and otherwise its time is set by mcpp::home::mark_used, the same rule the build cache's entries follow. The cache's maintenance walks these directories as entries of kind `work`: - `mcpp cache list` shows each one, named by the command and the project its record names. - The collection after a build, `cache prune --older-than`, `cache gc --older-than` and `gc --max-size` collect a directory by its record's time. A directory written before the record is dated by its own time. - `mcpp cache clean --work` empties the three areas, and `--all` now includes them. A bare `cache clean` still drops package entries only. Removing a directory costs the next plan of that project only writing it again (SPEC-005 R2.1 already calls the directory a cache). e2e 1119 seeds the three areas in a fresh home and checks the listing, the collection by age and by size, and the clean flags. e2e 921 checks that `emit build-database` records the project in its work directory. docs/09 and docs/04 describe the store and the flag, in English and Chinese. Closes #969. --- docs/04-mcpp-toml.md | 2 +- docs/09-commands-by-scenario.md | 13 ++++ docs/zh/04-mcpp-toml.md | 2 +- docs/zh/09-commands-by-scenario.md | 9 +++ src/bmi_cache/maintenance.cppm | 107 +++++++++++++++++++++++++++-- src/cli.cppm | 2 + src/cli/cmd_build.cppm | 13 ++-- src/cli/cmd_cache.cppm | 1 + src/cli/cmd_publish.cppm | 12 ++-- tests/e2e/cache/entries.cpp | 63 +++++++++++++++++ tests/e2e/cdb/sets.cpp | 7 ++ 11 files changed, 215 insertions(+), 16 deletions(-) diff --git a/docs/04-mcpp-toml.md b/docs/04-mcpp-toml.md index 4d02a96cb..50d7fad5f 100644 --- a/docs/04-mcpp-toml.md +++ b/docs/04-mcpp-toml.md @@ -1920,7 +1920,7 @@ mcpp cache info @ # one entry, including the key inputs it was mcpp cache verify # every entry's file list against the disk mcpp cache gc --max-size 5GiB # LRU-collect package and host tool entries to a budget mcpp cache gc --older-than 30d # ...or by how long since they were last used -mcpp cache clean [--deps|--std|--tools|--all|--legacy] +mcpp cache clean [--deps|--std|--tools|--work|--all|--legacy] ``` The on-disk entry layout is versioned. An mcpp release that changes it retires diff --git a/docs/09-commands-by-scenario.md b/docs/09-commands-by-scenario.md index d0a26d8e5..f4f12c9c5 100644 --- a/docs/09-commands-by-scenario.md +++ b/docs/09-commands-by-scenario.md @@ -32,6 +32,7 @@ them. Confusing them costs a full rebuild. |---|---|---|---| | `target///`, `target/.build-mcpp/{out,host}/` | one project | a configuration fingerprint changes and opens a new directory; a build program's outputs and the build programs are kept per configuration | `mcpp clean`, `mcpp clean --stale` | | the build cache (`mcpp cache dir`) | the whole machine | any project compiles a dependency or a `std` module, or builds a host tool, or compiles the `mcpp` module its build program imports | collected after a build when unused for `[cache] unused_days`; `mcpp cache gc`, `mcpp cache prune`, `mcpp cache clean` | +| the work directories of plans (`/cache/{build-database,pack-formats,publish-plan}/`) | the whole machine, one per project | `mcpp emit build-database`, `mcpp pack --list-formats` or `mcpp publish` plans a project | collected with the build cache's entries; `mcpp cache clean --work` | `mcpp clean` removes `target/` entirely, and the next build recompiles everything. `mcpp clean --stale` removes only the fingerprint directories that @@ -111,6 +112,18 @@ warning states both (2026.11.8.1+). `mcpp cache prune` and `mcpp cache gc --older-than` collect `std` module entries by age as well; `gc --max-size` budgets packages and host tools, not `std` modules (2026.11.8.1+). +`mcpp emit build-database`, `mcpp pack --list-formats` and `mcpp publish`'s +check of a library's pins plan a project without writing into it, each in a work directory of the home, one +per project: `/cache/build-database/`, `cache/pack-formats/` and +`cache/publish-plan/`. A plan records its use in the directory's `.mcpp-plan`, +whose one line is the project root. `mcpp cache list` shows each directory as +an entry of kind `work`, named by the command and that project; the +collection after a build, `mcpp cache prune`, `mcpp cache gc --older-than` and +`gc --max-size` collect it by last use, as they collect a package entry; and +`mcpp cache clean --work` (or `--all`) empties all three areas. A directory +written before the record is dated by its own time. Removing one costs the +next plan of that project nothing but writing it again (mcpp#969). + ## The versions a package publishes `mcpp search` matches a substring and appends what each hit publishes, merged diff --git a/docs/zh/04-mcpp-toml.md b/docs/zh/04-mcpp-toml.md index 58efbbe38..c50084a0b 100644 --- a/docs/zh/04-mcpp-toml.md +++ b/docs/zh/04-mcpp-toml.md @@ -1708,7 +1708,7 @@ mcpp cache info @ # one entry, including the key inputs it was mcpp cache verify # every entry's file list against the disk mcpp cache gc --max-size 5GiB # LRU-collect package and host tool entries to a budget mcpp cache gc --older-than 30d # ...or by how long since they were last used -mcpp cache clean [--deps|--std|--tools|--all|--legacy] +mcpp cache clean [--deps|--std|--tools|--work|--all|--legacy] ``` 磁盘上的条目布局是版本化的。一个改变了它的 mcpp 发布版,会一次性 diff --git a/docs/zh/09-commands-by-scenario.md b/docs/zh/09-commands-by-scenario.md index 17bcbb758..cbfc673f4 100644 --- a/docs/zh/09-commands-by-scenario.md +++ b/docs/zh/09-commands-by-scenario.md @@ -29,6 +29,7 @@ |---|---|---|---| | `target/<三元组>/<指纹>/`、`target/.build-mcpp/{out,host}/` | 单个工程 | 一个配置指纹变化,开出一个新目录;构建程序的输出与构建程序按配置保存 | `mcpp clean`、`mcpp clean --stale` | | 构建缓存(`mcpp cache dir`) | 整台机器 | 任何工程编译一个依赖、一个 `std` 模块,或构建一个 host 工具,或编译其构建程序 import 的 `mcpp` 模块 | 构建后回收 `[cache] unused_days` 内未使用的条目;`mcpp cache gc`、`mcpp cache prune`、`mcpp cache clean` | +| 规划的工作目录(`/cache/{build-database,pack-formats,publish-plan}/`) | 整台机器,每个工程一个 | `mcpp emit build-database`、`mcpp pack --list-formats` 或 `mcpp publish` 规划一个工程 | 与构建缓存的条目一同回收;`mcpp cache clean --work` | `mcpp clean` 整个删掉 `target/`,下次构建重编一切。`mcpp clean --stale` 只删已无构建记录使用的指纹目录,在用的配置保留。每个配置目录在 `uses.list` 中 @@ -90,6 +91,14 @@ host 工具条目。一份 `std` BMI 被机器上每个工程共享,实现以" 与 `mcpp cache gc --older-than` 也按年龄收集 `std` 模块条目;`gc --max-size` 只对包与宿主工具做 预算(2026.11.8.1+)。 +`mcpp emit build-database`、`mcpp pack --list-formats` 与 `mcpp publish` 对库的版本钉的检查规划工程而不写入工程, +各自在 home 的一个工作目录中进行,每个工程一个:`/cache/build-database/`、`cache/pack-formats/` +与 `cache/publish-plan/`。规划把一次使用记在目录的 `.mcpp-plan` 上,该文件只有一行,即工程根。 +`mcpp cache list` 把每个目录列为 `work` 类条目,以命令与该工程命名;构建后的回收、`mcpp cache prune`、 +`mcpp cache gc --older-than` 与 `gc --max-size` 按最后使用时间回收它,与回收包条目相同; +`mcpp cache clean --work`(或 `--all`)清空这三处。早于该记录写出的目录以目录自身的时间计。 +移除一个目录,该工程的下一次规划只需重新写出它(mcpp#969)。 + ## 一个包已发布的版本 `mcpp search` 按子串匹配,并在每个命中行后附上该包发布的版本 —— 跨描述符 diff --git a/src/bmi_cache/maintenance.cppm b/src/bmi_cache/maintenance.cppm index 957c149e0..0b478a935 100644 --- a/src/bmi_cache/maintenance.cppm +++ b/src/bmi_cache/maintenance.cppm @@ -6,6 +6,8 @@ // $MCPP_HOME/build-cache/v1/std//std-module.json // $MCPP_HOME/build-cache/v1/tool//@//entry.json // (a host tool, mcpp.build.tool_store; last use = the record's time) +// $MCPP_HOME/cache/{build-database,pack-formats,publish-plan}//.mcpp-plan +// (the work directory of a plan that describes; last use = the record's time) // // Two things this file did wrong before the layout change and that the new // entry.json fixes: @@ -23,6 +25,7 @@ export module mcpp.bmi_cache.maintenance; import std; import mcpp.home; +import mcpp.home.files; // mark_used import nlohmann.json; import mcpp.libs.toml; import mcpp.ui; @@ -94,6 +97,58 @@ export std::optional parse_size(std::string_view v) { return std::nullopt; } +// THE WORK DIRECTORIES OF PLANS THAT DESCRIBE (mcpp#969). `mcpp emit +// build-database`, `mcpp pack --list-formats` and the pin check of `mcpp +// publish` plan a project without writing into it (PrepareIntent::Describe), +// each in a directory of the home, `cache//`, one per project. +// Nothing removed one: a home measured on 2026-11-19 held 626 of them, 3.4 GB, +// most of them for projects that no longer existed. A plan states its use on +// the directory's record, and `cache list`, `gc`, `prune` and the collection +// after a build treat each directory as an entry. Removing one costs nothing +// but the next plan's writing it again (SPEC-005 R2.1). +export enum class PlanArea { BuildDatabase, PackFormats, PublishPlan }; + +namespace { + +struct PlanAreaInfo { + PlanArea area; + std::string_view dir; // under `/cache/` + std::string_view command; // what plans there, as `cache list` names it +}; + +constexpr std::array kPlanAreas{{ + {PlanArea::BuildDatabase, "build-database", "emit build-database"}, + {PlanArea::PackFormats, "pack-formats", "pack --list-formats"}, + {PlanArea::PublishPlan, "publish-plan", "publish"}, +}}; + +// The record whose time is the directory's last use (mcpp::home::mark_used); +// its one line is the project root the directory plans. +constexpr std::string_view kPlanRecord = ".mcpp-plan"; + +std::filesystem::path plan_area_root(const PlanAreaInfo& area) { + return mcpp::home::root() / "cache" / area.dir; +} + +} // namespace + +// The work directory of a plan of `area` named `key`, created, with its use +// stated: the record is written when the directory is new and its time set to +// now otherwise. `project` is what `cache list` names the directory by. +export std::filesystem::path plan_work_dir(PlanArea area, std::string_view key, + const std::filesystem::path& project) { + const auto& info = *std::ranges::find(kPlanAreas, area, &PlanAreaInfo::area); + const auto dir = plan_area_root(info) / std::string(key); + std::error_code ec; + std::filesystem::create_directories(dir, ec); + const auto record = dir / kPlanRecord; + if (std::filesystem::exists(record, ec)) + mcpp::home::mark_used(record); + else + std::ofstream(record, std::ios::binary) << mcpplibs::os::fs::generic_utf8(project) << '\n'; + return dir; +} + namespace { std::filesystem::path pkg_root() { return mcpp::home::cache_root() / "pkg"; } @@ -353,10 +408,46 @@ std::vector walk_variant_entries() { return out; } +// The work directories of plans that describe (plan_work_dir): one per +// project and area, each last used when a plan last ran in it. Collected as +// the cache's entries are, and emptied by `cache clean --work`. +std::vector walk_plan_entries() { + std::vector out; + for (const auto& area : kPlanAreas) { + std::error_code ec; + const auto root = plan_area_root(area); + for (auto& d : std::filesystem::directory_iterator(root, ec)) { + if (!d.is_directory()) continue; + Entry e; + e.dir = d.path(); + e.kind = "work"; + e.key = mcpplibs::os::fs::generic_utf8(d.path().filename()); + const auto record = e.dir / kPlanRecord; + std::string project; + std::error_code fe; + if (std::filesystem::is_regular_file(record, fe)) { + e.accessed = dir_mtime_seconds(record); + if (std::ifstream is(record, std::ios::binary); is) std::getline(is, project); + } else { + // Written by an mcpp before the record: the directory's time is + // the last plan that wrote or removed a file directly in it. + e.accessed = dir_mtime_seconds(e.dir); + } + e.label = project.empty() + ? std::format("{} (work directory)", area.command) + : std::format("{} (work directory of {})", area.command, project); + measure(e); + out.push_back(std::move(e)); + } + } + return out; +} + std::vector walk_collectable() { auto out = walk_pkg_entries(); for (auto& e : walk_tool_entries()) out.push_back(std::move(e)); for (auto& e : walk_variant_entries()) out.push_back(std::move(e)); + for (auto& e : walk_plan_entries()) out.push_back(std::move(e)); return out; } @@ -674,10 +765,10 @@ export int cache_gc(const std::string& maxSizeArg, const std::string& olderThanA return 0; } -// `mcpp cache clean [--deps] [--std] [--all] [--legacy]`. -export int cache_clean(bool deps, bool stds, bool tools, bool all, bool legacy) { - if (all) { deps = true; stds = true; tools = true; } - if (!deps && !stds && !tools && !legacy) deps = true; // bare `clean` = dep entries +// `mcpp cache clean [--deps] [--std] [--tools] [--work] [--all] [--legacy]`. +export int cache_clean(bool deps, bool stds, bool tools, bool work, bool all, bool legacy) { + if (all) { deps = true; stds = true; tools = true; work = true; } + if (!deps && !stds && !tools && !work && !legacy) deps = true; // bare `clean` = dep entries std::error_code ec; if (deps) { @@ -695,6 +786,14 @@ export int cache_clean(bool deps, bool stds, bool tools, bool all, bool legacy) std::filesystem::remove_all(tool_root(), ec); std::println("Cleaned host tool entries ({})", human_bytes(n)); } + if (work) { + std::uintmax_t n = 0; + for (const auto& area : kPlanAreas) { + n += dir_size(plan_area_root(area)); + std::filesystem::remove_all(plan_area_root(area), ec); + } + std::println("Cleaned work directories of plans ({})", human_bytes(n)); + } if (legacy) { auto legacyRoot = mcpp::home::legacy_bmi_root(); if (std::filesystem::exists(legacyRoot, ec)) { diff --git a/src/cli.cppm b/src/cli.cppm index 95ce62904..de506101e 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -1257,6 +1257,8 @@ int run(int argc, char** argv) { .option(cl::Option("deps").help("Drop package entries (default)")) .option(cl::Option("std").help("Drop std module entries")) .option(cl::Option("tools").help("Drop host tool entries")) + .option(cl::Option("work").help( + "Drop the work directories of emit build-database, pack --list-formats and publish")) .option(cl::Option("all").help("Drop every kind of entry")) .option(cl::Option("legacy") .help("Remove the unused pre-v1 cache at $MCPP_HOME/bmi")) diff --git a/src/cli/cmd_build.cppm b/src/cli/cmd_build.cppm index 5c5b7d5b8..5665dd6eb 100644 --- a/src/cli/cmd_build.cppm +++ b/src/cli/cmd_build.cppm @@ -14,7 +14,7 @@ import mcpplibs.cmdline; import mcpp.build.prepare; import mcpp.build.execute; import mcpp.build.ninja; // write_module_maps -import mcpp.bmi_cache.maintenance; // parse_duration, for `clean --stale --older-than` +import mcpp.bmi_cache.maintenance; // parse_duration, for `clean --stale --older-than`; plan_work_dir import mcpp.build.directives; // the device-slot table import mcpp.build.configure; import mcpp.build.coff_exports; @@ -669,12 +669,15 @@ namespace { // One work directory per project root and member, under the mcpp home: the // planning pass writes its lock, its build programs' artifacts and its output -// directory there, never inside the project. +// directory there, never inside the project. The cache collects it once no +// plan has used it for a while (mcpp#969). std::filesystem::path build_database_work_dir(const std::filesystem::path& root, std::string_view member) { - return mcpp::home::root() / "cache" / "build-database" - / mcpp::toolchain::hash_string(root.lexically_normal().generic_string() - + "\x1f" + std::string(member)); + return mcpp::bmi_cache::plan_work_dir( + mcpp::bmi_cache::PlanArea::BuildDatabase, + mcpp::toolchain::hash_string(root.lexically_normal().generic_string() + + "\x1f" + std::string(member)), + root); } std::optional read_whole_file(const std::filesystem::path& p) { diff --git a/src/cli/cmd_cache.cppm b/src/cli/cmd_cache.cppm index 89f661505..9577acec3 100644 --- a/src/cli/cmd_cache.cppm +++ b/src/cli/cmd_cache.cppm @@ -63,6 +63,7 @@ export int cmd_cache_clean(const mcpplibs::cmdline::ParsedArgs& parsed) { return mcpp::bmi_cache::cache_clean(parsed.is_flag_set("deps"), parsed.is_flag_set("std"), parsed.is_flag_set("tools"), + parsed.is_flag_set("work"), parsed.is_flag_set("all"), parsed.is_flag_set("legacy")); } diff --git a/src/cli/cmd_publish.cppm b/src/cli/cmd_publish.cppm index 788f4feb3..2d3379bc1 100644 --- a/src/cli/cmd_publish.cppm +++ b/src/cli/cmd_publish.cppm @@ -22,7 +22,7 @@ import mcpp.manifest; import mcpp.publish.pipeline; import mcpp.ui; import mcpp.wire; -import mcpp.home; // --list-formats plans outside the project +import mcpp.bmi_cache.maintenance; // plan_work_dir: --list-formats and the pin check plan outside the project import mcpp.pack.stage_tree; // the built-in formats import mcpp.toolchain.fingerprint; // hash_string import mcpp.toolchain.platform; // host_arch: the static row of `--linkage static` @@ -107,8 +107,9 @@ static int refuse_shared_exact_pins() { if (!library) return 0; mcpp::build::BuildOverrides ov; ov.intent = mcpp::build::PrepareIntent::Describe; - ov.work_dir = mcpp::home::root() / "cache" / "publish-plan" - / mcpp::toolchain::hash_string(root->lexically_normal().generic_string()); + ov.work_dir = mcpp::bmi_cache::plan_work_dir( + mcpp::bmi_cache::PlanArea::PublishPlan, + mcpp::toolchain::hash_string(root->lexically_normal().generic_string()), *root); std::expected ctx = std::unexpected(std::string{}); { mcpp::ui::terminal::StdoutToStderr narration; @@ -370,8 +371,9 @@ int cmd_pack_list_formats(const mcpplibs::cmdline::ParsedArgs& parsed) { if (auto o = parsed.option("target"); o && !o->get().values.empty()) ov.target_triple = o->get().values.back(); ov.intent = mcpp::build::PrepareIntent::Describe; - ov.work_dir = mcpp::home::root() / "cache" / "pack-formats" - / mcpp::toolchain::hash_string(root->lexically_normal().generic_string()); + ov.work_dir = mcpp::bmi_cache::plan_work_dir( + mcpp::bmi_cache::PlanArea::PackFormats, + mcpp::toolchain::hash_string(root->lexically_normal().generic_string()), *root); std::expected ctx = std::unexpected(std::string{}); { mcpp::ui::terminal::StdoutToStderr narration; diff --git a/tests/e2e/cache/entries.cpp b/tests/e2e/cache/entries.cpp index 307c45bd9..53ba8d71b 100644 --- a/tests/e2e/cache/entries.cpp +++ b/tests/e2e/cache/entries.cpp @@ -421,4 +421,67 @@ E2E entries{"entries", [] { expect(fatal(e2e::succeeded(r))) << s::text(r); expect(fatal(fs::exists(std_dir / "old"))) << "a size budget evicted a std module\n" << s::text(r); }; + + "1119 the work directories of plans are cache entries"_test = [] { + // mcpp#969: the directories `emit build-database`, `pack --list-formats` and `publish` + // plan in are listed by `cache list` with the project their record names, collected by + // `cache prune --older-than`, `cache gc --older-than` and `gc --max-size` by their + // record's time (a directory from before the record by its own), and emptied by + // `cache clean --work` and `--all`, not by a bare `cache clean`. + const s::options home{.where = s::home::fresh}; + const auto cache = s::case_home(s::home::fresh) / "cache"; + const auto nowhere = s::case_dir(); + const auto old = cache / "build-database" / "old"; + const auto fresh = cache / "pack-formats" / "fresh"; + const auto legacy = cache / "publish-plan" / "legacy"; + const auto seed = [&](const fs::path& d, int days, bool record) { + fs::create_directories(d / "target"); + std::ofstream(d / "target" / "build.ninja") << "# planned\n"; + if (record) std::ofstream(d / ".mcpp-plan") << "/projects/" << d.filename().generic_string() << "\n"; + age(d, std::chrono::hours{24 * days}); + }; + const auto seed_all = [&] { + fs::remove_all(cache); + seed(old, 3, true); + seed(fresh, 0, true); + seed(legacy, 3, false); + }; + + seed_all(); + auto r = s::mcpp({"cache", "list", "--json"}, nowhere, home); + expect(fatal(e2e::succeeded(r))) << s::text(r); + std::map labels; + for (const auto& e : s::json(r.out)["entries"]) + if (e["kind"] == "work") labels[e["key"].get()] = e["label"].get(); + expect(fatal(labels.size() == 3u)) << "cache list does not list the three work directories\n" << r.out; + expect(fatal(labels["old"] == "emit build-database (work directory of /projects/old)")) << labels["old"]; + expect(fatal(labels["fresh"] == "pack --list-formats (work directory of /projects/fresh)")) << labels["fresh"]; + expect(fatal(labels["legacy"] == "publish (work directory)")) << labels["legacy"]; + + const std::vector> by_age{{"cache", "prune", "--older-than", "1d"}, {"cache", "gc", "--older-than", "1d"}}; + for (const auto& cmd : by_age) { + seed_all(); + r = s::mcpp(cmd, nowhere, home); + expect(fatal(e2e::succeeded(r))) << r.line << "\n" << s::text(r); + expect(fatal(!fs::exists(old))) << r.line << " kept a work directory unused for 3 days\n" << s::text(r); + expect(fatal(!fs::exists(legacy))) << r.line << " kept a work directory without a record, 3 days old\n" << s::text(r); + expect(fatal(fs::exists(fresh))) << r.line << " removed a work directory used now\n" << s::text(r); + } + r = s::mcpp({"cache", "gc", "--max-size", "1B"}, nowhere, home); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(fatal(!fs::exists(fresh))) << "a size budget kept a work directory\n" << s::text(r); + + seed_all(); + r = s::mcpp({"cache", "clean"}, nowhere, home); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(fatal(fs::exists(old) && fs::exists(fresh) && fs::exists(legacy))) << "a bare cache clean removed work directories\n" << s::text(r); + r = s::mcpp({"cache", "clean", "--work"}, nowhere, home); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(fatal(e2e::contains(s::text(r), "Cleaned work directories of plans"))) << s::text(r); + expect(fatal(!fs::exists(cache / "build-database") && !fs::exists(cache / "pack-formats") && !fs::exists(cache / "publish-plan"))) << "clean --work left a work directory\n" << s::text(r); + seed_all(); + r = s::mcpp({"cache", "clean", "--all"}, nowhere, home); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(fatal(!fs::exists(old) && !fs::exists(fresh) && !fs::exists(legacy))) << "clean --all left a work directory\n" << s::text(r); + }; }}; diff --git a/tests/e2e/cdb/sets.cpp b/tests/e2e/cdb/sets.cpp index c7c343a43..09ede112e 100644 --- a/tests/e2e/cdb/sets.cpp +++ b/tests/e2e/cdb/sets.cpp @@ -224,6 +224,13 @@ E2E sets{"sets", [] { expect(fatal(e2e::succeeded(first))) << "first emit: " << first.err; const auto locks = s::glob(home, "cache/build-database/*/target/.build-mcpp/host/*/mcpp.lock"); expect(fatal(!locks.empty())) << "host fixture must produce a nonempty lock"; + // mcpp#969: the work directory states the project it plans, which `cache list` names it by. + const auto records = s::glob(home, "cache/build-database/*/.mcpp-plan"); + expect(fatal(std::ranges::any_of(records, [&](const fs::path& f) { + auto line = s::read_file(f); + line.erase(std::min(line.find('\n'), line.size())); + return fs::weakly_canonical(fs::path(line)) == fs::weakly_canonical(app.dir()); + }))) << "no work directory records the project " << app.dir().generic_string(); std::map> snapshot; // os.utime(ns=10**18): a time far from now, which a rewrite would replace. const auto stamp = std::chrono::time_point_cast( From c6224106d15753438c2f8e742f71296a4bdf9dd2 Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:02:56 +0530 Subject: [PATCH 2/6] test: write the plan record in binary mode so Windows adds no carriage return The product writes and reads .mcpp-plan in binary; the e2e case seeded it in text mode, so on Windows the project label ended in a carriage return. --- tests/e2e/cache/entries.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/cache/entries.cpp b/tests/e2e/cache/entries.cpp index 53ba8d71b..86a507533 100644 --- a/tests/e2e/cache/entries.cpp +++ b/tests/e2e/cache/entries.cpp @@ -437,7 +437,7 @@ E2E entries{"entries", [] { const auto seed = [&](const fs::path& d, int days, bool record) { fs::create_directories(d / "target"); std::ofstream(d / "target" / "build.ninja") << "# planned\n"; - if (record) std::ofstream(d / ".mcpp-plan") << "/projects/" << d.filename().generic_string() << "\n"; + if (record) std::ofstream(d / ".mcpp-plan", std::ios::binary) << "/projects/" << d.filename().generic_string() << "\n"; age(d, std::chrono::hours{24 * days}); }; const auto seed_all = [&] { From 8adeb5840df12b73946da9208610854ab321afce Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 27 Nov 2026 00:51:52 +0900 Subject: [PATCH 3/6] cache: clean --all removes every kind of entry, the work directories of plans included A flag of their own was one more word for the surface while the outputs of build programs, the units and the patched variants had none: --all stated every kind and left all four. It now removes what cache list shows. Co-authored-by: speak-agent <248744407+speak-agent@users.noreply.github.com> --- docs/04-mcpp-toml.md | 2 +- docs/09-commands-by-scenario.md | 10 ++++++---- docs/zh/04-mcpp-toml.md | 2 +- docs/zh/09-commands-by-scenario.md | 8 +++++--- src/bmi_cache/maintenance.cppm | 24 +++++++++++++----------- src/cli.cppm | 2 -- src/cli/cmd_cache.cppm | 1 - tests/e2e/cache/entries.cpp | 9 ++------- 8 files changed, 28 insertions(+), 30 deletions(-) diff --git a/docs/04-mcpp-toml.md b/docs/04-mcpp-toml.md index 56237d017..f18f6b4e1 100644 --- a/docs/04-mcpp-toml.md +++ b/docs/04-mcpp-toml.md @@ -2000,7 +2000,7 @@ mcpp cache info @ # one entry, including the key inputs it was mcpp cache verify # every entry's file list against the disk mcpp cache gc --max-size 5GiB # LRU-collect package and host tool entries to a budget mcpp cache gc --older-than 30d # ...or by how long since they were last used -mcpp cache clean [--deps|--std|--tools|--work|--all|--legacy] +mcpp cache clean [--deps|--std|--tools|--all|--legacy] ``` The on-disk entry layout is versioned. An mcpp release that changes it retires diff --git a/docs/09-commands-by-scenario.md b/docs/09-commands-by-scenario.md index 05875d8ae..575313d72 100644 --- a/docs/09-commands-by-scenario.md +++ b/docs/09-commands-by-scenario.md @@ -32,7 +32,7 @@ them. Confusing them costs a full rebuild. |---|---|---|---| | `target///`, `target/.build-mcpp/{out,host}/` | one project | a configuration fingerprint changes and opens a new directory; a build program's outputs and the build programs are kept per configuration | `mcpp clean`, `mcpp clean --stale` | | the build cache (`mcpp cache dir`) | the whole machine | any project compiles a dependency or a `std` module, or builds a host tool, or compiles the `mcpp` module its build program imports | collected after a build when unused for `[cache] unused_days`; `mcpp cache gc`, `mcpp cache prune`, `mcpp cache clean` | -| the work directories of plans (`/cache/{build-database,pack-formats,publish-plan}/`) | the whole machine, one per project | `mcpp emit build-database`, `mcpp pack --list-formats` or `mcpp publish` plans a project | collected with the build cache's entries; `mcpp cache clean --work` | +| the work directories of plans (`/cache/{build-database,pack-formats,publish-plan}/`) | the whole machine, one per project | `mcpp emit build-database`, `mcpp pack --list-formats` or `mcpp publish` plans a project | collected with the build cache's entries, by last use; `mcpp cache clean --all` | `mcpp clean` removes `target/` entirely, and the next build recompiles everything. `mcpp clean --stale` removes only the fingerprint directories that @@ -137,9 +137,11 @@ per project: `/cache/build-database/`, `cache/pack-formats/` and whose one line is the project root. `mcpp cache list` shows each directory as an entry of kind `work`, named by the command and that project; the collection after a build, `mcpp cache prune`, `mcpp cache gc --older-than` and -`gc --max-size` collect it by last use, as they collect a package entry; and -`mcpp cache clean --work` (or `--all`) empties all three areas. A directory -written before the record is dated by its own time. Removing one costs the +`gc --max-size` collect it by last use, as they collect a package entry. +`mcpp cache clean --all` removes every entry of the cache, these and the +outputs of build programs, the units and the patched variants included; the +flags `--deps`, `--std` and `--tools` each remove one kind and leave them. A +directory written before the record is dated by its own time. Removing one costs the next plan of that project nothing but writing it again (mcpp#969). ## The versions a package publishes diff --git a/docs/zh/04-mcpp-toml.md b/docs/zh/04-mcpp-toml.md index c9f4598f2..e296fef08 100644 --- a/docs/zh/04-mcpp-toml.md +++ b/docs/zh/04-mcpp-toml.md @@ -1766,7 +1766,7 @@ mcpp cache info @ # one entry, including the key inputs it was mcpp cache verify # every entry's file list against the disk mcpp cache gc --max-size 5GiB # LRU-collect package and host tool entries to a budget mcpp cache gc --older-than 30d # ...or by how long since they were last used -mcpp cache clean [--deps|--std|--tools|--work|--all|--legacy] +mcpp cache clean [--deps|--std|--tools|--all|--legacy] ``` 磁盘上的条目布局是版本化的。一个改变了它的 mcpp 发布版,会一次性 diff --git a/docs/zh/09-commands-by-scenario.md b/docs/zh/09-commands-by-scenario.md index 46f10d4b5..339baa983 100644 --- a/docs/zh/09-commands-by-scenario.md +++ b/docs/zh/09-commands-by-scenario.md @@ -29,7 +29,7 @@ |---|---|---|---| | `target/<三元组>/<指纹>/`、`target/.build-mcpp/{out,host}/` | 单个工程 | 一个配置指纹变化,开出一个新目录;构建程序的输出与构建程序按配置保存 | `mcpp clean`、`mcpp clean --stale` | | 构建缓存(`mcpp cache dir`) | 整台机器 | 任何工程编译一个依赖、一个 `std` 模块,或构建一个 host 工具,或编译其构建程序 import 的 `mcpp` 模块 | 构建后回收 `[cache] unused_days` 内未使用的条目;`mcpp cache gc`、`mcpp cache prune`、`mcpp cache clean` | -| 规划的工作目录(`/cache/{build-database,pack-formats,publish-plan}/`) | 整台机器,每个工程一个 | `mcpp emit build-database`、`mcpp pack --list-formats` 或 `mcpp publish` 规划一个工程 | 与构建缓存的条目一同回收;`mcpp cache clean --work` | +| 规划的工作目录(`/cache/{build-database,pack-formats,publish-plan}/`) | 整台机器,每个工程一个 | `mcpp emit build-database`、`mcpp pack --list-formats` 或 `mcpp publish` 规划一个工程 | 与构建缓存的条目一同按最后使用时间回收;`mcpp cache clean --all` | `mcpp clean` 整个删掉 `target/`,下次构建重编一切。`mcpp clean --stale` 只删已无构建记录使用的指纹目录,在用的配置保留。每个配置目录在 `uses.list` 中 @@ -107,8 +107,10 @@ mcpp cache gc --older-than 60d 各自在 home 的一个工作目录中进行,每个工程一个:`/cache/build-database/`、`cache/pack-formats/` 与 `cache/publish-plan/`。规划把一次使用记在目录的 `.mcpp-plan` 上,该文件只有一行,即工程根。 `mcpp cache list` 把每个目录列为 `work` 类条目,以命令与该工程命名;构建后的回收、`mcpp cache prune`、 -`mcpp cache gc --older-than` 与 `gc --max-size` 按最后使用时间回收它,与回收包条目相同; -`mcpp cache clean --work`(或 `--all`)清空这三处。早于该记录写出的目录以目录自身的时间计。 +`mcpp cache gc --older-than` 与 `gc --max-size` 按最后使用时间回收它,与回收包条目相同。 +`mcpp cache clean --all` 移除缓存的全部条目,包括这些目录以及构建程序的输出、编译单元与打过补丁的变体; +`--deps`、`--std`、`--tools` 各移除一类条目,不触及它们。 +早于该记录写出的目录以目录自身的时间计。 移除一个目录,该工程的下一次规划只需重新写出它(mcpp#969)。 ## 一个包已发布的版本 diff --git a/src/bmi_cache/maintenance.cppm b/src/bmi_cache/maintenance.cppm index 7c5892eae..ff846cd1a 100644 --- a/src/bmi_cache/maintenance.cppm +++ b/src/bmi_cache/maintenance.cppm @@ -439,7 +439,8 @@ std::vector walk_program_out_entries() { // The work directories of plans that describe (plan_work_dir): one per // project and area, each last used when a plan last ran in it. Collected as -// the cache's entries are, and emptied by `cache clean --work`. +// the cache's entries are; like a build program's outputs and the units, the +// one flag of `cache clean` that removes them is `--all`. std::vector walk_plan_entries() { std::vector out; for (const auto& area : kPlanAreas) { @@ -829,10 +830,10 @@ export int cache_gc(const std::string& maxSizeArg, const std::string& olderThanA return 0; } -// `mcpp cache clean [--deps] [--std] [--tools] [--work] [--all] [--legacy]`. -export int cache_clean(bool deps, bool stds, bool tools, bool work, bool all, bool legacy) { - if (all) { deps = true; stds = true; tools = true; work = true; } - if (!deps && !stds && !tools && !work && !legacy) deps = true; // bare `clean` = dep entries +// `mcpp cache clean [--deps] [--std] [--all] [--legacy]`. +export int cache_clean(bool deps, bool stds, bool tools, bool all, bool legacy) { + if (all) { deps = true; stds = true; tools = true; } + if (!deps && !stds && !tools && !legacy) deps = true; // bare `clean` = dep entries std::error_code ec; if (deps) { @@ -850,13 +851,14 @@ export int cache_clean(bool deps, bool stds, bool tools, bool work, bool all, bo std::filesystem::remove_all(tool_root(), ec); std::println("Cleaned host tool entries ({})", human_bytes(n)); } - if (work) { + if (all) { + // `--all` is every kind `cache list` shows. The three roots above are + // gone; what is left are the kinds no flag names: patched variants, the + // outputs of build programs, the units and the work directories of + // plans (mcpp#969). Before, `--all` left them and stated nothing. std::uintmax_t n = 0; - for (const auto& area : kPlanAreas) { - n += dir_size(plan_area_root(area)); - std::filesystem::remove_all(plan_area_root(area), ec); - } - std::println("Cleaned work directories of plans ({})", human_bytes(n)); + for (const auto& e : walk_collectable()) n += remove_entry(e); + std::println("Cleaned the entries of every other kind ({})", human_bytes(n)); } if (legacy) { auto legacyRoot = mcpp::home::legacy_bmi_root(); diff --git a/src/cli.cppm b/src/cli.cppm index 891bbe5a4..9a4cba48d 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -1338,8 +1338,6 @@ int run(int argc, char** argv) { .option(cl::Option("deps").help("Drop package entries (default)")) .option(cl::Option("std").help("Drop std module entries")) .option(cl::Option("tools").help("Drop host tool entries")) - .option(cl::Option("work").help( - "Drop the work directories of emit build-database, pack --list-formats and publish")) .option(cl::Option("all").help("Drop every kind of entry")) .option(cl::Option("legacy") .help("Remove the unused pre-v1 cache at $MCPP_HOME/bmi")) diff --git a/src/cli/cmd_cache.cppm b/src/cli/cmd_cache.cppm index 6280be6ef..ac60235cf 100644 --- a/src/cli/cmd_cache.cppm +++ b/src/cli/cmd_cache.cppm @@ -91,7 +91,6 @@ export int cmd_cache_clean(const mcpplibs::cmdline::ParsedArgs& parsed) { return mcpp::bmi_cache::cache_clean(parsed.is_flag_set("deps"), parsed.is_flag_set("std"), parsed.is_flag_set("tools"), - parsed.is_flag_set("work"), parsed.is_flag_set("all"), parsed.is_flag_set("legacy")); } diff --git a/tests/e2e/cache/entries.cpp b/tests/e2e/cache/entries.cpp index f9858ed8d..b72a91721 100644 --- a/tests/e2e/cache/entries.cpp +++ b/tests/e2e/cache/entries.cpp @@ -552,8 +552,8 @@ E2E entries{"entries", s::home_fixture, [] { // mcpp#969: the directories `emit build-database`, `pack --list-formats` and `publish` // plan in are listed by `cache list` with the project their record names, collected by // `cache prune --older-than`, `cache gc --older-than` and `gc --max-size` by their - // record's time (a directory from before the record by its own), and emptied by - // `cache clean --work` and `--all`, not by a bare `cache clean`. + // record's time (a directory from before the record by its own). `cache clean --all` + // removes them with every other kind of entry; a bare `cache clean` leaves them. const s::options home{.where = s::home::fresh}; const auto cache = s::case_home(s::home::fresh) / "cache"; const auto nowhere = s::case_dir(); @@ -601,11 +601,6 @@ E2E entries{"entries", s::home_fixture, [] { r = s::mcpp({"cache", "clean"}, nowhere, home); expect(fatal(e2e::succeeded(r))) << s::text(r); expect(fatal(fs::exists(old) && fs::exists(fresh) && fs::exists(legacy))) << "a bare cache clean removed work directories\n" << s::text(r); - r = s::mcpp({"cache", "clean", "--work"}, nowhere, home); - expect(fatal(e2e::succeeded(r))) << s::text(r); - expect(fatal(e2e::contains(s::text(r), "Cleaned work directories of plans"))) << s::text(r); - expect(fatal(!fs::exists(cache / "build-database") && !fs::exists(cache / "pack-formats") && !fs::exists(cache / "publish-plan"))) << "clean --work left a work directory\n" << s::text(r); - seed_all(); r = s::mcpp({"cache", "clean", "--all"}, nowhere, home); expect(fatal(e2e::succeeded(r))) << s::text(r); expect(fatal(!fs::exists(old) && !fs::exists(fresh) && !fs::exists(legacy))) << "clean --all left a work directory\n" << s::text(r); From 16b2c7e335d79b429d54a1e625093c9c026afb5f Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 27 Nov 2026 01:10:37 +0900 Subject: [PATCH 4/6] fix: a missing mcpp.lock is named, and a component of emit sbom states the package The reader read a file that is not there as an empty lock, and the two commands that report or assert the record were written for a reader that fails: --locked named every package as one that is not in the lock, and emit sbom gave the root alone without its note. load_existing states the absence, and both read it. The refusal of --locked carries a help line and writes no lock. An entry's name is the lock's key: it may carry the namespace as a prefix, and marks a variant (+p) and a version only build programs hold (+b). emit sbom wrote the key as the package's name, so one package had the purl pkg:mcpp/compat/compat.zlib and a build program's version was a package of another name. short_name, moved from the lock's writer, and package_name state the package; a purl percent-encodes its segments; one identity under two spellings is one component; a version only build programs hold names them in mcpp:build-program properties. Closes #891, closes #892. Co-authored-by: speak-agent <248744407+speak-agent@users.noreply.github.com> --- docs/51-supported-versions.md | 16 +++++++- docs/zh/51-supported-versions.md | 11 +++++- src/build/prepare/records.cpp | 36 ++++++----------- src/cli/cmd_sbom.cppm | 56 ++++++++++++++++++++------ src/pm/lock_io.cppm | 52 ++++++++++++++++++++++-- tests/e2e/deps/lock.cpp | 68 ++++++++++++++++++++++++++++++++ tests/e2e/run/runners.cpp | 10 +++++ tests/unit/test_pm_lock_io.cpp | 55 ++++++++++++++++++++++++++ 8 files changed, 261 insertions(+), 43 deletions(-) diff --git a/docs/51-supported-versions.md b/docs/51-supported-versions.md index 5920856d7..2d5273fee 100644 --- a/docs/51-supported-versions.md +++ b/docs/51-supported-versions.md @@ -97,7 +97,9 @@ error: --locked was given and this resolution differs from mcpp.lock: ``` A release build, an audit or a CI job should pass `--locked`. It disables the -build fast path, so the assertion always runs. +build fast path, so the assertion always runs. With no `mcpp.lock` there is no +record to assert against: `--locked` then fails saying so, rather than naming +every package as one that moved, and writes none. The lock does not yet constrain resolution — it records and verifies it. Pinning a resolution to the lock as an input is a separate change to the @@ -112,10 +114,20 @@ resolution: mcpp emit sbom -o sbom.json ``` +A component's `name`, `group` and `purl` state the package, whichever way the +manifest that declared it spelled it: `cmdline` and `mcpplibs.cmdline` are both +`pkg:mcpp/mcpplibs/cmdline@`. A variant keeps its digest in the name, +and a version only build programs hold is the package at that version, with one +`mcpp:build-program` property for each program. A purl percent-encodes its +segments, so `+` is written `%2B`. + It reads `mcpp.lock` rather than resolving again, because a document describing a different graph from the one that was built is worse than no document. A component whose licence mcpp does not know is emitted as `NOASSERTION` rather -than omitted: an absent field reads as "not examined". +than omitted: an absent field reads as "not examined". With no `mcpp.lock` the +document names the root package alone, and a note on standard error says that +nothing is recorded: that is the whole truth for a project with no dependencies, +and not for one that has never been built. ## Default versions (2026.11.21.1+) diff --git a/docs/zh/51-supported-versions.md b/docs/zh/51-supported-versions.md index 53cc798e5..b5813e08a 100644 --- a/docs/zh/51-supported-versions.md +++ b/docs/zh/51-supported-versions.md @@ -84,7 +84,8 @@ error: --locked was given and this resolution differs from mcpp.lock: ``` 发布构建、审计或 CI 作业应当传入 `--locked`。它会关闭构建快路径,因此该断言 -总会执行。 +总会执行。没有 `mcpp.lock` 时没有可供断言的记录:此时 `--locked` 失败并说明这一点, +而不是把每个包都报成发生了变化,也不写出 lock。 锁尚不约束解析——它只记录并校验解析结果。把锁作为解析的输入来钉住结果,是对 解析器的另一项改动。 @@ -97,9 +98,15 @@ error: --locked was given and this resolution differs from mcpp.lock: mcpp emit sbom -o sbom.json ``` +组件的 `name`、`group` 与 `purl` 陈述的是包本身,与声明它的清单如何拼写无关:`cmdline` 与 +`mcpplibs.cmdline` 都是 `pkg:mcpp/mcpplibs/cmdline@<版本>`。变体在名字中保留其摘要;只被构建程序 +持有的版本就是该版本的这个包,并为每个构建程序带一条 `mcpp:build-program` 属性。purl 对各段做 +百分号编码,因此 `+` 写作 `%2B`。 + 它读取 `mcpp.lock` 而不是重新解析,因为一份描述了与实际构建不同的依赖图的 文档,比没有文档更糟。许可证 mcpp 无法识别的组件会被写成 `NOASSERTION` 而不是 -省略:缺失的字段读起来像「未检查」。 +省略:缺失的字段读起来像「未检查」。没有 `mcpp.lock` 时,文档只列出根包,并在标准 +错误上提示没有任何记录:这对没有依赖的工程是全部事实,对从未构建过的工程则不是。 ## 缺省版本(2026.11.21.1 起) diff --git a/src/build/prepare/records.cpp b/src/build/prepare/records.cpp index cd5910c79..954b68c4c 100644 --- a/src/build/prepare/records.cpp +++ b/src/build/prepare/records.cpp @@ -81,24 +81,9 @@ namespace mcpp::build { // runs, called from it in the same order, and are declared in the `:state` // partition (state.cppm) as the phases are. -// The short name of a lock entry. An index entry is written under the map key -// its declaring manifest used (`mcpplibs.cmdline` under `[dependencies.mcpplibs]`, -// `cmdline` under a bare key), so the spelled name may carry its namespace as a -// prefix; the identity is (namespace, short name) whichever way it was spelled. -// An entry without a namespace (a git entry, keyed by the root's map key) is its -// own short name. -static std::string lock_short_name(const mcpp::lockfile::LockedPackage& p) { - if (!p.namespace_.empty()) { - const std::string prefix = p.namespace_ + "."; - if (p.name.size() > prefix.size() && p.name.starts_with(prefix)) - return p.name.substr(prefix.size()); - } - return p.name; -} - // The identity two entries of one lock are compared by. static std::string lock_identity(const mcpp::lockfile::LockedPackage& p) { - return p.namespace_ + "\x1f" + lock_short_name(p); + return p.namespace_ + "\x1f" + mcpp::pm::short_name(p); } // THE IDENTITY THIS CONFIGURATION'S REQUEST WAS GIVEN (SPEC-016 §4.5), into @@ -506,16 +491,21 @@ std::expected step13_lockfile(PrepareState& state, BuildConte // true and useless; which package moved, from which version to // which, is what the reader does something about. if (mcpp::invocation::get("MCPP_LOCKED").value_or("") == "1") { - auto prior = mcpp::lockfile::load(lockPath); - if (!prior) { + // A lock that is not there is not one that differs: read as an + // empty lock it named every package as drift (mcpp#891). + auto read = mcpp::pm::load_existing(lockPath); + if (!read) return std::unexpected(std::format( - "--locked was given and there is no readable mcpp.lock at {}\n" - " Run the same command without --locked once to record " - "this resolution, then commit mcpp.lock.", + "--locked was given and mcpp.lock cannot be read: {}", read.error().message)); + if (!*read) + return std::unexpected(std::format( + "--locked was given and there is no mcpp.lock at {}\n" + " help: run the same command without --locked once to record " + "this resolution, then commit mcpp.lock", lockPath.string())); - } + const auto& prior = *read; auto key = [](const mcpp::lockfile::LockedPackage& p) { - const std::string sn = lock_short_name(p); + const std::string sn = mcpp::pm::short_name(p); return p.namespace_.empty() ? sn : p.namespace_ + "." + sn; }; diff --git a/src/cli/cmd_sbom.cppm b/src/cli/cmd_sbom.cppm index ad37d59df..a429f7a52 100644 --- a/src/cli/cmd_sbom.cppm +++ b/src/cli/cmd_sbom.cppm @@ -56,13 +56,35 @@ std::string esc(std::string_view s) { return o; } +// One segment of a package URL: the purl specification percent-encodes all but +// the unreserved characters and `:`. `+` is the one that occurs here, in a +// version's build metadata and in a variant's name. +std::string purl_segment(std::string_view s) { + std::string o; + o.reserve(s.size()); + for (char c : s) { + const auto u = static_cast(c); + if (std::isalnum(u) || c == '.' || c == '-' || c == '_' || c == '~' || c == ':') + o += c; + else + o += std::format("%{:02X}", static_cast(u)); + } + return o; +} + // A package URL for an mcpp package. `pkg:` URLs are how every SBOM consumer // correlates a component with an advisory feed, so emitting one is what makes // the document useful rather than merely well-formed. +std::string purl(std::string_view ns, std::string_view name, std::string_view version) { + return std::format("pkg:mcpp/{}/{}@{}", purl_segment(ns.empty() ? "mcpp" : ns), + purl_segment(name), purl_segment(version)); +} + +// It states the package, not the lock's key for it (mcpp#892): the key may +// spell one package `mcpplibs.cmdline` or `cmdline`, and marks a version only +// build programs hold, which the purl's version already tells apart. std::string purl(const mcpp::lockfile::LockedPackage& p) { - const std::string ns = p.namespace_.empty() ? std::string("mcpp") - : p.namespace_; - return std::format("pkg:mcpp/{}/{}@{}", ns, p.name, p.version); + return purl(p.namespace_, mcpp::pm::package_name(p), p.version); } // AN UNKNOWN LICENCE IS REPORTED AS UNKNOWN, NEVER OMITTED AND NEVER @@ -102,12 +124,14 @@ int cmd_sbom(const mcpplibs::cmdline::ParsedArgs& parsed) { const auto lockPath = *root / "mcpp.lock"; std::vector pkgs; - if (auto lock = mcpp::lockfile::load(lockPath)) { - pkgs = lock->packages; - } else if (std::filesystem::exists(lockPath)) { + auto lock = mcpp::pm::load_existing(lockPath); + if (!lock) { mcpp::ui::error(std::format( "mcpp.lock exists but could not be read: {}", lock.error().message)); return 2; + } + if (*lock) { + pkgs = std::move((*lock)->packages); } else { // NOT AN ERROR, AND NOT SILENCE EITHER. A project with no // dependencies has no lock and its bill of materials is one component, @@ -119,9 +143,13 @@ int cmd_sbom(const mcpplibs::cmdline::ParsedArgs& parsed) { "dependencies, build it once so the resolution is recorded."); } + // One component per package: a lock written by 2026.9.29.1 to .5 can hold + // one identity under two spellings, and a bom-ref is unique in a document. + std::set listed; + std::erase_if(pkgs, [&](const auto& d) { return !listed.insert(purl(d)).second; }); + const auto& p = man->package; - const std::string rootNs = p.namespace_.empty() ? std::string("mcpp") - : p.namespace_; + const std::string rootPurl = purl(p.namespace_, p.name, p.version); std::string out; out += "{\n"; @@ -133,13 +161,11 @@ int cmd_sbom(const mcpplibs::cmdline::ParsedArgs& parsed) { + esc(std::string(mcpp::MCPP_VERSION)) + "\" } ],\n"; out += " \"component\": {\n"; out += " \"type\": \"application\",\n"; - out += " \"bom-ref\": \"" + esc(std::format("pkg:mcpp/{}/{}@{}", - rootNs, p.name, p.version)) + "\",\n"; + out += " \"bom-ref\": \"" + esc(rootPurl) + "\",\n"; out += " \"name\": \"" + esc(p.name) + "\",\n"; out += " \"version\": \"" + esc(p.version) + "\",\n"; out += licence_block(p.license) + "\n"; - out += " \"purl\": \"" + esc(std::format("pkg:mcpp/{}/{}@{}", - rootNs, p.name, p.version)) + "\"\n"; + out += " \"purl\": \"" + esc(rootPurl) + "\"\n"; out += " }\n"; out += " },\n"; out += " \"components\": ["; @@ -151,7 +177,7 @@ int cmd_sbom(const mcpplibs::cmdline::ParsedArgs& parsed) { out += " {\n"; out += " \"type\": \"library\",\n"; out += " \"bom-ref\": \"" + esc(purl(d)) + "\",\n"; - out += " \"name\": \"" + esc(d.name) + "\",\n"; + out += " \"name\": \"" + esc(mcpp::pm::package_name(d)) + "\",\n"; out += " \"version\": \"" + esc(d.version) + "\",\n"; if (!d.namespace_.empty()) out += " \"group\": \"" + esc(d.namespace_) + "\",\n"; @@ -187,6 +213,10 @@ int cmd_sbom(const mcpplibs::cmdline::ParsedArgs& parsed) { out += " ] },\n"; properties.emplace_back("mcpp:variant", d.variant); } + // A version only build programs hold names them (design 2026-11-19 + // §21 A3): the lock's key said so with `+b`, which is not part + // of the package's name. + for (auto const& program : d.programs) properties.emplace_back("mcpp:build-program", program); if (!properties.empty()) { out += " \"properties\": ["; for (std::size_t i = 0; i < properties.size(); ++i) diff --git a/src/pm/lock_io.cppm b/src/pm/lock_io.cppm index 206a65fca..f4eb623c8 100644 --- a/src/pm/lock_io.cppm +++ b/src/pm/lock_io.cppm @@ -101,6 +101,23 @@ struct LockedToolchain { std::string version; }; +// THE NAME OF AN ENTRY IS A KEY OF THE LOCK, NOT THE PACKAGE'S NAME. An index +// entry is written under the map key its declaring manifest used +// (`mcpplibs.cmdline` under `[dependencies.mcpplibs]`, `cmdline` under a bare +// key), so the spelled name may carry its namespace as a prefix; a variant is +// `+p` and a version only build programs hold `+b`, +// which keep two entries of one package apart. +// +// The short name: the key without the namespace's prefix. Two entries of one +// lock are one identity when their namespace and short name are equal. An entry +// without a namespace (a git entry, keyed by the root's map key) is its own +// short name. +std::string short_name(const LockedPackage& p); +// The package's name, as a document outside the lock states it: the short name +// without `+b`, which the entry's version says there. A variant keeps +// `+p`: a patched library is another library, at the same version. +std::string package_name(const LockedPackage& p); + struct Lockfile { int schemaVersion = 2; std::vector indices; @@ -113,7 +130,14 @@ struct LockError { std::string message; }; +// A file that is not there reads as an empty lock: what a resolution wants, +// which starts from whatever was recorded. std::expected load(const std::filesystem::path& path); +// The lock, or nothing when there is no file: what a command that reports or +// asserts the record reads. An empty lock answered `--locked` and `emit sbom` +// for a file that was not there, as one that differs and as a project without +// dependencies (mcpp#891). +std::expected, LockError> load_existing(const std::filesystem::path& path); // Replaces the file atomically (a temporary name beside it, then a rename); // an unchanged lock is not rewritten. std::expected write(const Lockfile& lock, const std::filesystem::path& path); @@ -143,10 +167,32 @@ namespace mcpp::pm { namespace t = mcpp::libs::toml; -std::expected load(const std::filesystem::path& path) { - if (!std::filesystem::exists(path)) { - return Lockfile{}; // no lock yet +std::string short_name(const LockedPackage& p) { + if (!p.namespace_.empty()) { + const std::string prefix = p.namespace_ + "."; + if (p.name.size() > prefix.size() && p.name.starts_with(prefix)) + return p.name.substr(prefix.size()); } + return p.name; +} + +std::string package_name(const LockedPackage& p) { + auto name = short_name(p); + // Written last, after any `+p`, and a digest is hexadecimal: the + // last `+b` of an entry that lists its programs is the marker. + if (!p.programs.empty()) + if (const auto at = name.rfind("+b"); at != std::string::npos && at != 0) name.erase(at); + return name; +} + +std::expected load(const std::filesystem::path& path) { + return load_existing(path).transform([](std::optional&& lock) { + return std::move(lock).value_or(Lockfile{}); // no lock yet + }); +} + +std::expected, LockError> load_existing(const std::filesystem::path& path) { + if (!std::filesystem::exists(path)) return std::optional{}; auto doc = t::parse_file(path); if (!doc) return std::unexpected(LockError{ std::format("{}:{}:{}: {}", path.string(), doc.error().where.line, diff --git a/tests/e2e/deps/lock.cpp b/tests/e2e/deps/lock.cpp index 2c076b5b5..4ebf83882 100644 --- a/tests/e2e/deps/lock.cpp +++ b/tests/e2e/deps/lock.cpp @@ -352,6 +352,74 @@ int main() { expect(e2e::contains(targets, "x86_64-openkal")) << "the other configuration's target was dropped: " << targets; expect(e2e::contains(targets, ",")) << "this configuration's target is missing: " << targets; }; + + "1166 a component of emit sbom states the package"_test = [] { + // mcpp#892, mcpp#891: `mcpp emit sbom` reads the lock and nothing else, so the lock is + // written here: no toolchain, no index, no network. A component's name and purl state + // the package, not the lock's key for it -- a key may carry the namespace, and marks a + // version only build programs hold (`+b`); a variant stays another component; + // a purl percent-encodes `+`; one identity under two spellings is one component. With + // no lock the document is the root alone and the narration says nothing is recorded. + s::project p{{"mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0+7\"\n"}}; + const std::string cmdline = "[package.\"mcpplibs.cmdline\"]\nnamespace = \"mcpplibs\"\nversion = \"0.0.1\"\n" + "source = \"index+mcpplibs@0.0.1\"\nhash = \"fnv1a:0000000000000001\"\n"; + p.write("mcpp.lock", "version = 2\n\n" + cmdline + + "\n[package.\"compat.zlib\"]\nnamespace = \"compat\"\nversion = \"1.3.2\"\nsource = \"index+compat@1.3.2\"\nhash = \"fnv1a:0000000000000002\"\n" + "\n[package.\"compat.zlib+pabcdef012345\"]\nnamespace = \"compat\"\nversion = \"1.3.2\"\nsource = \"index+compat@1.3.2\"\nhash = \"fnv1a:0000000000000003\"\n" + "variant = \"abcdef0123456789\"\npatches = [\"patches/0001-fix.patch#sha256:00\"]\n" + "\n[package.\"compat.zlib+b0123456789ab\"]\nnamespace = \"compat\"\nversion = \"1.3.1\"\nsource = \"index+compat@1.3.1\"\nhash = \"fnv1a:0000000000000006\"\n" + "programs = [\"build:acme.gen@1.0.0\"]\n" + "\n[package.\"fmt\"]\nnamespace = \"mcpplibs\"\nversion = \"11.0.0+7\"\nsource = \"index+mcpplibs@11.0.0+7\"\nhash = \"fnv1a:0000000000000004\"\n" + "\n[package.\"acme.tool\"]\nversion = \"1.0.0\"\nsource = \"git+https://example.invalid/acme/tool#tag=v1.0.0\"\nhash = \"fnv1a:0000000000000005\"\n"); + auto r = p.mcpp({"emit", "sbom"}); + expect(fatal(e2e::succeeded(r))) << "mcpp emit sbom: " << s::text(r); + const auto d = s::json(r.out); + // (group, name, version) -> purl + std::map, std::string> got; + for (const auto& c : d["components"]) { + expect(fatal(c["bom-ref"] == c["purl"])) << c.dump(); + got[{c.value("group", std::string{}), c["name"].get(), c["version"].get()}] = c["purl"].get(); + } + const std::map, std::string> want{ + {{"mcpplibs", "cmdline", "0.0.1"}, "pkg:mcpp/mcpplibs/cmdline@0.0.1"}, + {{"compat", "zlib", "1.3.2"}, "pkg:mcpp/compat/zlib@1.3.2"}, + {{"compat", "zlib+pabcdef012345", "1.3.2"}, "pkg:mcpp/compat/zlib%2Bpabcdef012345@1.3.2"}, + {{"compat", "zlib", "1.3.1"}, "pkg:mcpp/compat/zlib@1.3.1"}, + {{"mcpplibs", "fmt", "11.0.0+7"}, "pkg:mcpp/mcpplibs/fmt@11.0.0%2B7"}, + {{"", "acme.tool", "1.0.0"}, "pkg:mcpp/mcpp/acme.tool@1.0.0"}, + }; + expect(fatal(got == want)) << "the components do not state the packages of the lock\n" << r.out; + for (const auto& c : d["components"]) { + if (c["name"] == "zlib+pabcdef012345") expect(fatal(c.contains("pedigree"))) << "a variant states no pedigree: " << c.dump(); + // What the key's marker said is said by a property. + if (c["version"] == "1.3.1") + expect(fatal(c["properties"].dump().find("build:acme.gen@1.0.0") != std::string::npos)) << "a version only build programs hold does not name them: " << c.dump(); + } + const auto& root = d["metadata"]["component"]; + expect(fatal(root["purl"] == "pkg:mcpp/mcpp/app@0.1.0%2B7")) << root.dump(); + expect(fatal(root["version"] == "0.1.0+7")) << root.dump(); + + // A lock from 2026.9.29.1 to .5 can hold one identity under both spellings. + p.write("mcpp.lock", "version = 2\n\n[package.\"cmdline\"]\nnamespace = \"mcpplibs\"\nversion = \"0.0.1\"\n" + "source = \"index+mcpplibs@0.0.1\"\nhash = \"fnv1a:0000000000000001\"\n\n" + cmdline); + r = p.mcpp({"emit", "sbom"}); + expect(fatal(e2e::succeeded(r))) << "mcpp emit sbom (two spellings): " << s::text(r); + std::vector refs; + for (const auto& c : s::json(r.out)["components"]) refs.push_back(c["bom-ref"]); + expect(fatal(refs == std::vector{"pkg:mcpp/mcpplibs/cmdline@0.0.1"})) << r.out; + + // No lock: nothing recorded is said on the narration stream, and the document is valid. + p.remove("mcpp.lock"); + r = p.mcpp({"emit", "sbom"}); + expect(fatal(e2e::succeeded(r))) << "mcpp emit sbom with no lock: " << s::text(r); + expect(fatal(e2e::contains(r.err, "no mcpp.lock"))) << "sbom did not say that nothing was recorded: " << r.err; + expect(fatal(s::json(r.out)["components"].empty())) << "sbom with no lock is not a root-only document: " << r.out; + // A lock that cannot be read is an error, not a root-only document. + p.write("mcpp.lock", "version = 2\n[package\n"); + r = p.mcpp({"emit", "sbom"}); + expect(fatal(failed(r))) << "sbom accepted a lock it cannot read: " << s::text(r); + expect(fatal(e2e::contains(s::text(r), "could not be read"))) << s::text(r); + }; }}; } // namespace diff --git a/tests/e2e/run/runners.cpp b/tests/e2e/run/runners.cpp index f4978bd66..4d66c4efd 100644 --- a/tests/e2e/run/runners.cpp +++ b/tests/e2e/run/runners.cpp @@ -190,6 +190,16 @@ E2E runners{"runners", s::home_fixture, [] { expect(fatal(e2e::contains(s::text(r), "differs from mcpp.lock"))) << "the refusal does not say what is wrong: " << s::text(r); expect(fatal(e2e::contains(s::text(r), "9.9.9 -> 0.0.1"))) << "the refusal does not name which package moved, and to what: " << s::text(r); q.write("mcpp.lock", lock); + // mcpp#891: a lock that is not there is not a lock that differs. The refusal says to + // record one, and a refused --locked writes none for the next run to pass against. + q.remove("mcpp.lock"); + r = q.mcpp({"build", "--locked"}); + expect(fatal(failed(r))) << "--locked accepted a project with no mcpp.lock"; + expect(fatal(e2e::contains(s::text(r), "there is no mcpp.lock"))) << "the refusal does not say the lock is missing: " << s::text(r); + expect(fatal(s::lacks(s::text(r), "not in the lock"))) << "the refusal reads a missing lock as one that differs: " << s::text(r); + expect(fatal(e2e::contains(s::text(r), "help: run the same command without --locked"))) << "the refusal names no next step: " << s::text(r); + expect(fatal(!q.exists("mcpp.lock"))) << "a refused --locked wrote mcpp.lock"; + q.write("mcpp.lock", lock); r = q.mcpp({"emit", "sbom", "-o", "sbom.json"}); expect(fatal(e2e::succeeded(r))) << "mcpp emit sbom: " << s::text(r); auto d = s::json_file(q.at("sbom.json")); diff --git a/tests/unit/test_pm_lock_io.cpp b/tests/unit/test_pm_lock_io.cpp index 63491e756..fdfb22376 100644 --- a/tests/unit/test_pm_lock_io.cpp +++ b/tests/unit/test_pm_lock_io.cpp @@ -295,3 +295,58 @@ UTest a_build_programs_version_names_its_programs{"PmLockIo/ABuildProgramsVersio expect(eq(back->packages[1].programs, second.programs)); expect(eq(back->packages[1].version, "0.4.1")); }}; + +// mcpp#892: an entry's name is the lock's key. The short name is the same whichever way +// the declaring manifest spelled the package, and the package's name drops the marker of +// a version only build programs hold, which the entry's version tells apart. +UTest an_entrys_key_is_not_the_packages_name{"PmLockIo/AnEntrysKeyIsNotThePackagesName", [] { + auto entry = [](std::string name, std::string ns, std::vector programs = {}) { + mcpp::pm::LockedPackage p; + p.name = std::move(name); + p.namespace_ = std::move(ns); + p.programs = std::move(programs); + return p; + }; + expect(eq(mcpp::pm::short_name(entry("mcpplibs.cmdline", "mcpplibs")), "cmdline")); + expect(eq(mcpp::pm::short_name(entry("cmdline", "mcpplibs")), "cmdline")); + expect(eq(mcpp::pm::short_name(entry("compat.zlib+pabcdef012345", "compat")), "zlib+pabcdef012345")); + // No namespace (a git entry): the name whole, dots included. + expect(eq(mcpp::pm::short_name(entry("acme.tool", "")), "acme.tool")); + // A name that is its namespace and nothing more is not a prefix to cut. + expect(eq(mcpp::pm::short_name(entry("compat.", "compat")), "compat.")); + + const std::vector programs{"build:acme.gen@1.0.0"}; + expect(eq(mcpp::pm::short_name(entry("compat.zlib+b0123456789ab", "compat", programs)), "zlib+b0123456789ab")); + expect(eq(mcpp::pm::package_name(entry("compat.zlib+b0123456789ab", "compat", programs)), "zlib")); + expect(eq(mcpp::pm::package_name(entry("compat.zlib+pabcdef012345+b0123456789ab", "compat", programs)), "zlib+pabcdef012345")); + // Without programs `+b` is the package's own spelling. + expect(eq(mcpp::pm::package_name(entry("a+b", "")), "a+b")); + expect(eq(mcpp::pm::package_name(entry("mcpplibs.cmdline", "mcpplibs")), "cmdline")); +}}; + +// mcpp#891: `load` reads a file that is not there as an empty lock; `load_existing` says +// that it is not there, and both report a file that cannot be read. +UTest a_lock_that_is_not_there_is_not_an_empty_lock{"PmLockIo/ALockThatIsNotThereIsNotAnEmptyLock", [] { + const auto dir = std::filesystem::temp_directory_path() / "mcpp-lock-io-existing"; + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + const auto path = dir / "mcpp.lock"; + + auto absent = mcpp::pm::load_existing(path); + expect(fatal(absent.has_value())); + expect(!absent->has_value()); + auto read_as_empty = mcpp::pm::load(path); + expect(fatal(read_as_empty.has_value())); + expect(read_as_empty->packages.empty()); + + std::ofstream(path) << "version = 2\n"; + auto empty = mcpp::pm::load_existing(path); + expect(fatal(empty.has_value())); + expect(fatal(empty->has_value())); + expect((*empty)->packages.empty()); + + std::ofstream(path) << "version = 2\n[package\n"; + expect(!mcpp::pm::load_existing(path).has_value()); + expect(!mcpp::pm::load(path).has_value()); + std::filesystem::remove_all(dir); +}}; From c159aeadec446f458cfbcc8263600e3fe23c2ffc Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 27 Nov 2026 01:10:38 +0900 Subject: [PATCH 5/6] fix: a range that reaches no key because of a pre-release names the pin A range matches a pre-release only when it names one of the same version, so no range reached a package whose one key is 0.0.0-651a425, and the refusal listed that key without the cause. For the highest pre-release whose release the range admits and which the range does not see, the refusal states the rule and its help line is the exact pin. A pre-release the range sees and excludes, or one outside the range, stays an ordinary miss. prerelease_visible is exported for the question. Closes #370. Co-authored-by: speak-agent <248744407+speak-agent@users.noreply.github.com> --- docs/05-dependencies.md | 6 ++ docs/zh/05-dependencies.md | 4 ++ modules/versioning/src/version_req.cppm | 9 ++- src/pm/resolver.cppm | 21 ++++++ tests/e2e/deps/lock.cpp | 13 ++++ tests/unit/test_pm_resolver.cpp | 85 +++++++++++++++++++++++++ 6 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 tests/unit/test_pm_resolver.cpp diff --git a/docs/05-dependencies.md b/docs/05-dependencies.md index 1bfe7d52a..5d61caa16 100644 --- a/docs/05-dependencies.md +++ b/docs/05-dependencies.md @@ -150,6 +150,12 @@ and `"0.0"` is `>= 0.0.0, < 0.1.0` (before 2026.10.31.1 both matched 0.0.0 alone). The dependency conflict check and the address check of `--locked` read requirements the same way. +A range matches a pre-release key (`1.0.0-rc.1`) only when it names a +pre-release of the same version, so `*` or `^0.0` reaches none of the keys of a +package that publishes only pre-releases (`compat.glad` publishes +`0.0.0-651a425`). The error states that cause for the highest pre-release whose +release the range admits, and its `help:` line is the exact pin to write. + ### `visibility` — whether a dependency's usage crosses this package's own boundary ```toml diff --git a/docs/zh/05-dependencies.md b/docs/zh/05-dependencies.md index f19efef0b..018fcfb58 100644 --- a/docs/zh/05-dependencies.md +++ b/docs/zh/05-dependencies.md @@ -132,6 +132,10 @@ qux = ">=1.0, <2.0" # Range combination 不带运算符的部分写法同样按 caret 的通配规则:`"0"` 为 `>= 0.0.0, < 1.0.0`,`"0.0"` 为 `>= 0.0.0, < 0.1.0`(2026.10.31.1 之前 两者都只匹配 0.0.0)。依赖冲突检查与 `--locked` 的地址核对以同样的方式读取要求。 +范围只在写出同一版本的预发布时才匹配预发布键(`1.0.0-rc.1`),因此对只发布预发布键的包 +(`compat.glad` 只发布 `0.0.0-651a425`),`*` 或 `^0.0` 一个键也够不着。这时的错误针对范围所容许的 +版本中最高的那个预发布键说明原因,并在 `help:` 行给出应写的精确版本。 + ### `visibility` —— 一个依赖的用法是否跨越本包自己的边界 ```toml diff --git a/modules/versioning/src/version_req.cppm b/modules/versioning/src/version_req.cppm index e887cee44..32a2a78c4 100644 --- a/modules/versioning/src/version_req.cppm +++ b/modules/versioning/src/version_req.cppm @@ -147,6 +147,11 @@ bool is_constraint(std::string_view s); bool matches(const Requirement& r, const Version& v); +// Whether `r` reaches the pre-release `v` at all: it names a pre-release of the +// same numbers. `matches` asks it first; a refusal asks it to tell a pre-release +// the range does not see from one it sees and excludes. +bool prerelease_visible(const Requirement& r, const Version& v); + // Indices of ALL versions in `available` that match `req` and tie for highest // precedence. Normally one element. More than one means distinct entries // compare EQUAL — only possible when they differ solely in build metadata @@ -319,6 +324,8 @@ std::expected parse_comparator(std::string_view s) { return Comparator{op, *v}; } +} // namespace + // SemVer/npm/Cargo pre-release visibility: a pre-release candidate is only // eligible when the requirement itself names a pre-release at the SAME numeric // tuple. Two bugs collapse into this one rule: @@ -334,8 +341,6 @@ bool prerelease_visible(const Requirement& r, const Version& v) { return false; } -} // namespace - bool is_constraint(std::string_view s) { if (s.empty()) return true; // "any version" if (s == "*") return true; diff --git a/src/pm/resolver.cppm b/src/pm/resolver.cppm index 712e24c2a..cbce04cac 100644 --- a/src/pm/resolver.cppm +++ b/src/pm/resolver.cppm @@ -245,6 +245,27 @@ resolve_semver(std::string_view ns, std::string_view shortName, if (!unorderable.empty()) msg += std::format("\n (also published, but not orderable: [{}]){}", join(unorderable), pin_hint(unorderable)); + // A PRE-RELEASE OF A VERSION THE RANGE ADMITS (mcpp#370). A range + // reaches a pre-release only when it names one of the same version + // (version_req), so no `*` and no `^0.0` reaches a package whose one + // key is `0.0.0-651a425`, and the list above then shows a key that + // reads as if it had to match. The cause is stated for the highest + // such key, with the pin that reaches it. A key the range sees and + // excludes, or one whose release it excludes as well, is an ordinary + // miss and gets no line. + std::optional held; + for (std::size_t i = 0; i < parsed.size(); ++i) { + if (!parsed[i].isPrerelease() || vr::prerelease_visible(*req, parsed[i])) continue; + auto release = parsed[i]; + release.prerelease.clear(); + if (vr::matches(*req, release) && (!held || parsed[*held] < parsed[i])) held = i; + } + if (held) + msg += std::format( + "\n {0} is a pre-release, which a range matches only when it names " + "a pre-release of the same version" + "\n help: pin it exactly: {1} = \"{0}\"", + literals[*held], qname); return std::unexpected(msg); } if (best.size() > 1) { diff --git a/tests/e2e/deps/lock.cpp b/tests/e2e/deps/lock.cpp index 4ebf83882..1d9e07470 100644 --- a/tests/e2e/deps/lock.cpp +++ b/tests/e2e/deps/lock.cpp @@ -77,6 +77,8 @@ E2E lock{"lock", s::home_fixture, [] { mk_pkg("im", "{ [\"1.92.8\"] = { url = \"u\", sha256 = \"0\" },\n [\"1.92.8-docking\"] = { url = \"u\", sha256 = \"0\" } }"); mk_pkg("jdk", "{ [\"latest\"] = { ref = \"25.0.4.7.1\" },\n [\"25.0.4\"] = { ref = \"25.0.4.7.1\" },\n [\"25.0.4.7.1\"] = { url = \"u\", sha256 = \"0\" } }"); mk_pkg("kh", "{ [\"latest\"] = { ref = \"pre-v0.0.5\" },\n [\"pre-v0.0.5\"] = { url = \"u\", sha256 = \"0\" } }"); + // compat.glad's shape: the only key is a pre-release (mcpp#370). + mk_pkg("pre", "{ [\"0.0.0-651a425\"] = { url = \"u\", sha256 = \"0\" } }"); mk_pkg("tie", "{ [\"1.0.0+a\"] = { url = \"u\", sha256 = \"0\" },\n [\"1.0.0+b\"] = { url = \"u\", sha256 = \"0\" } }"); mk_pkg("dv", "{ [\"1.0.0\"] = { url = \"u\", sha256 = \"0\" } }", "devkit"); // Payloads seeded so that only the right key can install. @@ -119,6 +121,17 @@ E2E lock{"lock", s::home_fixture, [] { auto b5b = build(); expect(failed(b5b)) << "expected the unseeded payload to fail"; expect(s::no_line(s::text(b5b), "invalid version constraint|not ordered versions")) << "'=' must resolve to that key"; + // mcpp#370: no range reaches a package whose one key is a pre-release; the refusal + // states that and its help line is the pin, which resolves. + use_dep("pre", "*"); + auto b5c = build(); + expect(failed(b5c)) << "'*' must not reach a pre-release"; + expect(e2e::contains(s::text(b5c), "0.0.0-651a425 is a pre-release")) << "the refusal does not say why '*' matches none: " << s::text(b5c); + expect(e2e::contains(s::text(b5c), "help: pin it exactly: acme.pre = \"0.0.0-651a425\"")) << "the refusal does not name the pin: " << s::text(b5c); + use_dep("pre", "0.0.0-651a425"); + auto b5d = build(); + expect(failed(b5d)) << "expected the unseeded payload to fail"; + expect(s::lacks(s::text(b5d), "matches none of")) << "the pin the refusal names must resolve: " << s::text(b5d); use_dep("tie", "^1.0"); auto b6 = build(); expect(failed(b6)) << "a tie must not silently pick one"; diff --git a/tests/unit/test_pm_resolver.cpp b/tests/unit/test_pm_resolver.cpp new file mode 100644 index 000000000..65a6afd55 --- /dev/null +++ b/tests/unit/test_pm_resolver.cpp @@ -0,0 +1,85 @@ +import std; +import mcpplibs.mtest; +import mcpp.pm.index_route; +import mcpp.pm.index_spec; +import mcpp.pm.resolver; +import mcpp.toolchain.platform; + +using namespace mcpplibs::mtest; + +namespace { + +// One package of a local index, `acme.`, publishing `keys` for every host. +struct OnePackage { + std::filesystem::path root; + mcpp::pm::IndexMap indices; + + OnePackage(std::string_view name, std::initializer_list keys) { + root = std::filesystem::temp_directory_path() / std::format("mcpp-resolver-{}", name); + std::filesystem::remove_all(root); + std::filesystem::create_directories(root / "pkgs" / "a"); + std::string table = "{\n"; + for (auto key : keys) table += std::format(" [\"{}\"] = {{ url = \"u\", sha256 = \"0\" }},\n", key); + table += " }"; + std::ofstream(root / "pkgs" / "a" / std::format("acme.{}.lua", name)) << std::format( + "package = {{\n spec = \"1\", namespace = \"acme\", name = \"{0}\", type = \"package\",\n" + " xpm = {{\n linux = {1},\n macosx = {1},\n windows = {1},\n }},\n}}\n", name, table); + indices["acme"] = mcpp::pm::IndexSpec{ .name = "acme", .path = root }; + } + ~OnePackage() { std::error_code ec; std::filesystem::remove_all(root, ec); } + + std::expected resolve(std::string_view name, std::string_view constraint) { + mcpp::pm::IndexRoute route{ &indices, "/nowhere", nullptr }; + return mcpp::pm::resolve_semver("acme", name, constraint, route, + mcpp::toolchain::platform::HostPlatform::current()); + } +}; + +bool has(std::string_view text, std::string_view part) { return text.find(part) != std::string_view::npos; } + +} // namespace + +// mcpp#370: compat.glad's shape. The one key is a pre-release, which no range that +// names a release reaches; the refusal says so and names the pin. +UTest a_range_over_a_pre_release_names_the_pin{"PmResolver/ARangeOverAPreReleaseNamesThePin", [] { + OnePackage idx("pre", {"0.0.0-651a425"}); + for (std::string_view constraint : {"*", "^0.0", ">=0"}) { + auto r = idx.resolve("pre", constraint); + expect(fatal(!r.has_value())) << constraint << " reached a pre-release"; + expect(has(r.error(), "matches none of: [0.0.0-651a425]")) << r.error(); + expect(has(r.error(), "0.0.0-651a425 is a pre-release")) << r.error(); + expect(has(r.error(), "\n help: pin it exactly: acme.pre = \"0.0.0-651a425\"")) << r.error(); + } + // The pin the refusal names is an answer. + auto pinned = idx.resolve("pre", "=0.0.0-651a425"); + expect(fatal(pinned.has_value())) << pinned.error(); + expect(eq(*pinned, "0.0.0-651a425")); +}}; + +UTest the_pin_named_is_the_highest_pre_release_the_range_admits{"PmResolver/ThePinNamedIsTheHighestPreReleaseTheRangeAdmits", [] { + OnePackage idx("rc", {"1.0.0-rc.1", "1.0.0-rc.2", "2.0.0-rc.1"}); + auto r = idx.resolve("rc", "^1.0"); + expect(fatal(!r.has_value())); + expect(has(r.error(), "acme.rc = \"1.0.0-rc.2\"")) << r.error(); + // A release among the keys does not hide the cause: `^2` admits 2.0.0. + OnePackage mixed("mixed", {"1.0.0", "2.0.0-rc.1"}); + r = mixed.resolve("mixed", "^2"); + expect(fatal(!r.has_value())); + expect(has(r.error(), "acme.mixed = \"2.0.0-rc.1\"")) << r.error(); +}}; + +// A pre-release whose release the range excludes as well is an ordinary miss: a pin of +// it would answer another question than the one the range asked. +UTest a_pre_release_outside_the_range_is_an_ordinary_miss{"PmResolver/APreReleaseOutsideTheRangeIsAnOrdinaryMiss", [] { + OnePackage idx("far", {"0.0.0-651a425", "1.2.0"}); + auto r = idx.resolve("far", "^3"); + expect(fatal(!r.has_value())); + expect(has(r.error(), "matches none of")) << r.error(); + expect(!has(r.error(), "pre-release")) << r.error(); + expect(!has(r.error(), "help:")) << r.error(); + // So is one the range names and excludes: `^1.0.0-rc.3` sees rc.2 and asks for more. + OnePackage seen("seen", {"1.0.0-rc.1", "1.0.0-rc.2"}); + r = seen.resolve("seen", "^1.0.0-rc.3"); + expect(fatal(!r.has_value())); + expect(!has(r.error(), "help:")) << r.error(); +}}; From 227e9595c8765efe63f5b8f7a25eb35243009e94 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 27 Nov 2026 01:10:38 +0900 Subject: [PATCH 6/6] ci(fresh-install): the tumbleweed leg refreshes before it installs zypper install continues on stale or empty metadata when its own refresh fails, and the leg failed with "No provider of 'binutils' found", naming a package instead of the repository that could not be read. The refresh is its own command, retried once, and the install runs only after it succeeds. Closes #523. Co-authored-by: speak-agent <248744407+speak-agent@users.noreply.github.com> --- .github/workflows/ci-fresh-install.yml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci-fresh-install.yml b/.github/workflows/ci-fresh-install.yml index 7405580d6..e88e4fedd 100644 --- a/.github/workflows/ci-fresh-install.yml +++ b/.github/workflows/ci-fresh-install.yml @@ -266,9 +266,19 @@ jobs: - distro: arch image: archlinux:latest setup: pacman -Syu --noconfirm curl bash tar gzip xz git findutils binutils file + # The refresh is its own command, retried once, and the install runs + # only after it succeeds (#523). `zypper install` refreshes too, but + # when that refresh fails it continues on stale or empty metadata, + # and the leg went red with `No provider of 'binutils' found` -- + # naming a package instead of the repository that could not be read. + # A rolling image can meet a repository's new signing key, which + # `-n` alone rejects; --gpg-auto-import-keys accepts it. - distro: tumbleweed image: opensuse/tumbleweed:latest - setup: zypper -n install curl bash tar gzip xz git findutils binutils file + setup: >- + { zypper -n --gpg-auto-import-keys refresh || + { sleep 15; zypper -n --gpg-auto-import-keys refresh; }; } && + zypper -n install curl bash tar gzip xz git findutils binutils file - distro: debian-testing image: debian:testing setup: apt-get update && apt-get -y install curl bash tar gzip xz-utils git ca-certificates binutils findutils file