feat: let a project file return several configurations
A project.cpp described one configuration: CrafterBuildProject returns a Configuration by value, and anything else the project wanted built had to be among that one's dependencies. There it was built as part of that configuration's graph: under the check that a graph builds each module once, with its libraries handed up to whatever links that configuration, and with its tests and scripts out of reach of `test` and `run`. Jorijn asked for a project.cpp that can return several unrelated configurations which all get built, and suggested a separate entry point, so that no existing project file breaks. A project file now defines one of two functions. CrafterBuildProject is as it was. CrafterBuildConfigurations returns std::vector<Configuration*>: pointers to configurations the file keeps alive itself, or that GitProject and LocalProject gave it. The two have different names because the loader finds the entry point by its C symbol, which carries no return type, so one name with two return types would be called as whichever the loader guessed. They are pointers because a project file takes pointers between its configurations, for `dependencies` and for a test's, before it returns them, and a vector of values would move them. LoadConfigurations loads a project file with either entry point and returns the list. A CrafterBuildProject's Configuration comes back as a list of one, constructed by the call where the loader keeps it for the rest of the process; LoadProjectFromRoot, which did that for a sibling's, leaves it to LoadConfigurations, and the project cache holds the lists without owning a Configuration. The Configuration of the project crafter-build is pointed at is kept that long as well, where it was a local of Run(). LoadConfigurations throws for a file that defines both functions or neither, and for a CrafterBuildConfigurations that returns nothing, a null pointer or one configuration twice. It also throws for one that returns a configuration a project loaded through GitProject or LocalProject keeps to itself, which the loader now takes down when it loads that project's file: what the configurations the file returned led to through `dependencies` or through their tests, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. Returned from here, such a configuration would count as this file's own to `test` and `run`, and only the configurations a project file returns are rebased onto its directory. LoadProject stays, for a caller that wants a CrafterBuildProject's Configuration by value, and throws for a file with the other entry point. GitProject and LocalProject keep, per spec and args, the list a sibling's file returned, and return the first one unless the spec's new `configuration` names another by Configuration::name. Every configuration of the list is rebased onto the sibling's directory, except one that another project's file had returned before, which was rebased onto that project's. Specs that differ only in the name they pick share one load. A name the sibling does not have throws, listing the names it has, and a name two of its configurations share throws too. A `#pragma crafter dependency` gets the first. BuildAll builds the returned configurations in one pass. Each is built by Build(), as a project's one configuration is, the first on the calling thread and each other one on a thread of its own, and its result then goes into the record of the pass under its PcmDir, where Build() looks for a dependency. One that another of them is built on is built before that other starts, which then finds it in the record: started beside it, the other would not find it there yet and would build it a second time. A configuration is not put into the record before it is built, because a dependency of its own that is built into the same directory would be handed its unfinished build and wait for it, while it waits for the dependency. All of them are built to the end, and the errors come back in the order given, each message once; an exception a build throws comes back as an error that names the configuration, where Run() printed the exception's own text for a project's one configuration. Refused before anything is built: two that would be built into one directory, which would be two builds writing the same files at once; several that are each built on something of another's directory, so that none could be built first; and one that is built on something of its own directory when another is built on that directory as well, since the record holds one result for a directory and the other could be given either. One shortcut is in it. A wasm executable that declares wasmVariants builds what it is built on once more per variant, and says which variant by rewriting those configurations in place, at the end of its Build(). A library that two returned configurations share would change under the one still building its baseline, so with such an executable anywhere in the graph BuildAll builds the configurations one after the other, on the calling thread. Keeping them side by side takes a variant driver that does not rewrite configurations other builds read, which this commit does not attempt. Run() works on the list. A build builds all of it. `test` runs the tests, and `run` offers the scripts, of the ones in it that the project file made itself. One that another project's file returned to GitProject or LocalProject, and that this file returns in turn, is built with the rest, but its tests and scripts stay that project's, so `run` still reaches only the scripts of the project crafter-build was pointed at. What the list itself rules out Run() refuses once the project file has loaded, before any of the list is built and before AGENTS.md is written: for a build, `-r`, `install` and `bundle` whatever BuildAll refuses a list for, and for `test`, which builds its tests with Build() and never comes to BuildAll, two returned configurations of one directory. BuildAll makes its refusals again for whoever calls it. A script is handed the configuration it is declared on. `lint` and `format` walk from every returned configuration and keep, as before, the configurations in the project's directory: the returned ones first, in the order the file returned them, then what they depend on, so that of two returned ones that register a rule under one name the earlier one's runs. `-r` runs the executable when exactly one of them is one, and `install` and `bundle` export the one that is packaged as a Flatpak; with more than one candidate each refuses and names them, `-r` once everything is built and `install` and `bundle` before anything is. AGENTS.md takes the notes that the dependencyNotes of each returned configuration the file made itself selects among what that one is built against, and the file's pragma tooling and a returned configuration of another project go by the widest of those settings. There, a configuration is another project's when GitProject or LocalProject loaded it from another project file than the one whose AGENTS.md is written, two files being one when they resolve to one path, so UpdateAgentsMd still reads the setting of a Configuration one of the two returned when it is given that Configuration's own project file. For that, RunTests, RunLint, RunScript and UpdateAgentsMd each gained an overload that takes the list, and the one that takes a single Configuration calls it with a list of one. SetParentProject gained one too, and ParentLib searches the graph of every configuration it was given. BuildAll, RunTests and RunScript count a configuration the list names twice once. The tests of several configurations share what one configuration's had to itself: AddTest names a test's sources, tests/<name>, and its build directory after the test and its compile state, not after the configuration that declares it. Two configurations that each declare a test of one name, compiled alike, would have RunTests build both in that one directory, each with the dependencies of its own declaration. RunTests fails both without building either, and each failure names the configurations. It compares tests of different configurations only, so a project of one configuration is treated as it was. The --help text names the second entry point, says what -r, install and bundle do with several configurations, and speaks of the project file's entry point as what gets the project args, where it named CrafterBuildProject. AGENTS.template.md says that a project.cpp returns one configuration or several, that Run() works on the list and what a new verb has to decide about it, which configurations have their path rebased, and that the scripts of a returned configuration of another project cannot be run. Two of its notes named LoadProject as what loads a project.cpp for crafter-build, which Run(), GitProject and LocalProject no longer call, and speak of the load now. Its rule for the link flags of a test that loads a project file names the ways a test loads one, where it named LoadProject, and its entry for `:Script` speaks of the `scripts` of the configurations the driver is given, where it named `cfg.scripts`. Its entry for `:Platform` names LoadConfigurations beside LoadProject. That entry also said that `:Platform` holds all OS-specific code, which it did not before this range either, :Agents, :Progress, :Lint and :Clang including POSIX headers of their own, and no longer says so. The bug-prover lens's section names BuildAll's threads and LoadConfigurations. Not in this commit: a way to say which executable -r runs or which app install and bundle export when there are several, and a keyword that lets a `#pragma crafter dependency` name a configuration.
This commit is contained in:
parent
a7aa22220b
commit
4283a3ecd2
16 changed files with 986 additions and 241 deletions
|
|
@ -345,18 +345,60 @@ namespace {
|
|||
return DependencyNote{ .name = name, .text = std::move(note.text) };
|
||||
}
|
||||
|
||||
// The loaded projects `configs` lead to without passing through another
|
||||
// loaded project, in the order the configurations name them: one ring
|
||||
// further out. `walked` spans the whole collection, so each
|
||||
// Configuration is looked at once however many paths reach it.
|
||||
std::vector<const Configuration*> NextRing(std::span<const Configuration* const> configs, std::unordered_set<const Configuration*>& walked) {
|
||||
// Tells a configuration of another project from one of the project
|
||||
// whose AGENTS.md is written, the one of the project file it is made
|
||||
// with. GitProject and LocalProject hold the configurations of a project
|
||||
// file they loaded, so held or not does not tell the two apart: the
|
||||
// project whose notes are written may itself have been loaded through
|
||||
// one of them, by a program that then writes its AGENTS.md for it. Two
|
||||
// files are one project file when they resolve to one path, which is
|
||||
// how the loader tells project files apart: a hard link to the project
|
||||
// file in another directory is another project's. Each loaded project's
|
||||
// file is compared with the project file once and the answer kept, so a
|
||||
// configuration is the same thing every time one collection asks,
|
||||
// whatever happens to the files meanwhile.
|
||||
class OtherProjects {
|
||||
public:
|
||||
explicit OtherProjects(const fs::path& projectFile) {
|
||||
// Left empty when the file cannot be resolved, and then no
|
||||
// loaded project's file is it.
|
||||
std::error_code ec;
|
||||
projectFile_ = fs::canonical(projectFile, ec);
|
||||
if (ec) projectFile_.clear();
|
||||
}
|
||||
// The project `cfg` was loaded from when that is another one;
|
||||
// nullopt for a configuration the project's own file made.
|
||||
std::optional<LoadedProject> Of(const Configuration& cfg) {
|
||||
std::optional<LoadedProject> loaded = LoadedProjectOf(cfg);
|
||||
if (!loaded) return loaded;
|
||||
const auto [known, added] = same_.try_emplace(loaded->projectFile, false);
|
||||
if (added && !projectFile_.empty()) {
|
||||
std::error_code ec;
|
||||
const fs::path file = fs::canonical(loaded->projectFile, ec);
|
||||
known->second = !ec && file == projectFile_;
|
||||
}
|
||||
if (known->second) loaded.reset();
|
||||
return loaded;
|
||||
}
|
||||
private:
|
||||
// The project file, resolved.
|
||||
fs::path projectFile_;
|
||||
// By a loaded project's file: whether it is projectFile_.
|
||||
std::unordered_map<fs::path, bool> same_;
|
||||
};
|
||||
|
||||
// The other projects `configs` lead to without passing through another
|
||||
// of them, in the order the configurations name them: one ring further
|
||||
// out. `walked` spans the whole collection, so each Configuration is
|
||||
// looked at once however many paths reach it.
|
||||
std::vector<const Configuration*> NextRing(std::span<const Configuration* const> configs, std::unordered_set<const Configuration*>& walked, OtherProjects& others) {
|
||||
std::vector<const Configuration*> ring;
|
||||
std::vector<const Configuration*> pending(configs.rbegin(), configs.rend());
|
||||
while (!pending.empty()) {
|
||||
const Configuration* cfg = pending.back();
|
||||
pending.pop_back();
|
||||
if (!cfg || !walked.insert(cfg).second) continue;
|
||||
if (LoadedProjectOf(*cfg)) {
|
||||
if (others.Of(*cfg)) {
|
||||
ring.push_back(cfg);
|
||||
continue;
|
||||
}
|
||||
|
|
@ -365,21 +407,72 @@ namespace {
|
|||
return ring;
|
||||
}
|
||||
|
||||
// The AGENTS.consumer.md of every project `project` depends on, as
|
||||
// project.dependencyNotes selects them, ring by ring: first the loaded
|
||||
// projects (the ones GitProject and LocalProject returned) that its
|
||||
// `#pragma crafter dependency` lines and its configurations name, in
|
||||
// that order, then the ones those depend on. Its own configurations, and
|
||||
// a dependency's internal ones, are only walked through. Direct stops
|
||||
// after the first ring.
|
||||
// The AGENTS.consumer.md of every project the project is built against,
|
||||
// as the dependencyNotes of `configurations`, the configurations its
|
||||
// project file returns, select them, ring by ring: first the other
|
||||
// projects (the ones GitProject and LocalProject loaded from another
|
||||
// project file) that its `#pragma crafter dependency` lines and its
|
||||
// configurations name, in that order, then the ones those depend on.
|
||||
// Its own configurations, and a dependency's internal ones, are only
|
||||
// walked through.
|
||||
//
|
||||
// Each configuration the file made itself selects for what it is built
|
||||
// against: None nothing, Direct the first ring from it, Transitive every
|
||||
// ring. Another project therefore has its own dependencies followed
|
||||
// when a Transitive configuration leads to it, at whatever depth, and
|
||||
// not when only Direct ones do. The pragma lines belong to the file and
|
||||
// not to one configuration, and a configuration the file loaded from
|
||||
// another project and returns is a project of the first ring itself,
|
||||
// with a setting that is that project's own: both go by the widest
|
||||
// setting among the configurations the file made, and by Transitive
|
||||
// when it made none.
|
||||
//
|
||||
// Never walked: the project's tests, since a plain build never touches
|
||||
// them and a test's dependency can point at the Configuration the project
|
||||
// file returned by value, which has since moved; and a dependency's own
|
||||
// pragma tooling, which is about how the dependency is built, not how it
|
||||
// is used, and is no `dependencies` edge to begin with.
|
||||
std::vector<DependencyNote> CollectNotes(const Configuration& project, const fs::path& projectFile, const fs::path& projectDir) {
|
||||
std::unordered_set<const Configuration*> walked = { &project };
|
||||
// them and a test's dependency can point at the Configuration a
|
||||
// CrafterBuildProject returned by value, which a caller of LoadProject
|
||||
// may have moved since; and a dependency's own pragma tooling, which is
|
||||
// about how the dependency is built, not how it is used, and is no
|
||||
// `dependencies` edge to begin with.
|
||||
std::vector<DependencyNote> CollectNotes(std::span<const Configuration* const> configurations, const fs::path& projectFile, const fs::path& projectDir) {
|
||||
OtherProjects others(projectFile);
|
||||
const auto made = [&](const Configuration* cfg) { return !others.Of(*cfg); };
|
||||
const auto asks = [&](DependencyNotes setting) {
|
||||
return std::ranges::any_of(configurations, [&](const Configuration* cfg) { return made(cfg) && cfg->dependencyNotes == setting; });
|
||||
};
|
||||
const bool transitive = asks(DependencyNotes::Transitive) || std::ranges::none_of(configurations, made);
|
||||
if (!transitive && !asks(DependencyNotes::Direct)) return {};
|
||||
|
||||
// Where the walk starts, and the starts that ask for every ring.
|
||||
std::vector<const Configuration*> start;
|
||||
std::vector<const Configuration*> deep;
|
||||
for (const Configuration* dep : PragmaDependencies(projectFile)) {
|
||||
start.push_back(dep);
|
||||
if (transitive) deep.push_back(dep);
|
||||
}
|
||||
for (const Configuration* cfg : configurations) {
|
||||
const DependencyNotes setting = made(cfg) ? cfg->dependencyNotes : transitive ? DependencyNotes::Transitive : DependencyNotes::Direct;
|
||||
if (setting == DependencyNotes::None) continue;
|
||||
start.push_back(cfg);
|
||||
if (setting == DependencyNotes::Transitive) deep.push_back(cfg);
|
||||
}
|
||||
// Every other project those lead to: the ones whose own
|
||||
// dependencies are followed. Worked out ahead of the walk below,
|
||||
// which meets each project once, at its nearest ring, and that can
|
||||
// be a ring a Direct configuration put it in.
|
||||
std::unordered_set<const Configuration*> followed;
|
||||
{
|
||||
std::unordered_set<const Configuration*> reached;
|
||||
for (std::vector<const Configuration*> ring = NextRing(deep, reached, others); !ring.empty();) {
|
||||
std::vector<const Configuration*> next;
|
||||
for (const Configuration* cfg : ring) {
|
||||
followed.insert(cfg);
|
||||
next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end());
|
||||
}
|
||||
ring = NextRing(next, reached, others);
|
||||
}
|
||||
}
|
||||
|
||||
std::unordered_set<const Configuration*> walked;
|
||||
// The project's own notes are for its consumers, so they never go
|
||||
// into its own AGENTS.md, whatever dependency they sit beside. Both
|
||||
// places count for a symlinked project file.
|
||||
|
|
@ -389,13 +482,11 @@ namespace {
|
|||
std::unordered_set<std::string> identities;
|
||||
std::vector<DependencyNote> notes;
|
||||
|
||||
std::vector<const Configuration*> start;
|
||||
for (const Configuration* dep : PragmaDependencies(projectFile)) start.push_back(dep);
|
||||
start.insert(start.end(), project.dependencies.begin(), project.dependencies.end());
|
||||
for (std::vector<const Configuration*> ring = NextRing(start, walked); !ring.empty();) {
|
||||
for (std::vector<const Configuration*> ring = NextRing(start, walked, others); !ring.empty();) {
|
||||
std::vector<const Configuration*> next;
|
||||
for (const Configuration* cfg : ring) {
|
||||
const std::optional<LoadedProject> loaded = LoadedProjectOf(*cfg);
|
||||
// Another project's, or NextRing had walked through it.
|
||||
const std::optional<LoadedProject> loaded = others.Of(*cfg);
|
||||
const fs::path file = loaded->projectFile.parent_path() / NotesFileName;
|
||||
// One library under two specs (a pin here, another revision
|
||||
// further down) is described once, as the ring nearest the
|
||||
|
|
@ -403,10 +494,9 @@ namespace {
|
|||
if (identities.insert(loaded->identity).second && files.insert(file).second) {
|
||||
if (std::optional<DependencyNote> note = ReadNote(file, loaded->name)) notes.push_back(std::move(*note));
|
||||
}
|
||||
next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end());
|
||||
if (followed.contains(cfg)) next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end());
|
||||
}
|
||||
if (project.dependencyNotes == DependencyNotes::Direct) break;
|
||||
ring = NextRing(next, walked);
|
||||
ring = NextRing(next, walked, others);
|
||||
}
|
||||
return notes;
|
||||
}
|
||||
|
|
@ -504,6 +594,11 @@ std::string Crafter::MergeDependencyNotes(std::string_view templateMd, std::span
|
|||
}
|
||||
|
||||
bool Crafter::UpdateAgentsMd(const Configuration& project, const fs::path& projectFile) {
|
||||
std::array<const Configuration*, 1> one = { &project };
|
||||
return UpdateAgentsMd(std::span<const Configuration* const>(one), projectFile);
|
||||
}
|
||||
|
||||
bool Crafter::UpdateAgentsMd(std::span<const Configuration* const> configurations, const fs::path& projectFile) {
|
||||
std::error_code ec;
|
||||
// Beside the project file as it was named, so a symlinked project.cpp
|
||||
// keeps the AGENTS.md beside the link.
|
||||
|
|
@ -527,7 +622,7 @@ bool Crafter::UpdateAgentsMd(const Configuration& project, const fs::path& proje
|
|||
return false;
|
||||
}
|
||||
|
||||
const std::vector<DependencyNote> notes = project.dependencyNotes == DependencyNotes::None ? std::vector<DependencyNote>() : CollectNotes(project, projectFile, projectDir);
|
||||
const std::vector<DependencyNote> notes = CollectNotes(configurations, projectFile, projectDir);
|
||||
std::string wanted;
|
||||
try {
|
||||
wanted = std::format("{}{}{}", GeneratedLine, LineEnd(templateMd), MergeDependencyNotes(templateMd, notes));
|
||||
|
|
|
|||
|
|
@ -479,6 +479,21 @@ CompileCommand Crafter::GetCompileCommand(const Configuration& config) {
|
|||
}
|
||||
|
||||
namespace {
|
||||
// Two of `configurations` that would be built into one directory, as
|
||||
// the error that names them; empty when no two would. Built side by
|
||||
// side they are two builds writing the same files, and a pass that has
|
||||
// built one of them hands it to whatever is built on the other.
|
||||
std::string SameDirectoryError(std::span<Configuration* const> configurations) {
|
||||
std::unordered_map<fs::path, const Configuration*> builtInto;
|
||||
for (const Configuration* cfg : configurations) {
|
||||
const auto [known, added] = builtInto.try_emplace(fs::absolute(cfg->PcmDir()).lexically_normal(), cfg);
|
||||
if (!added && known->second != cfg) {
|
||||
return std::format("two configurations named {} would both be built into {}: give each a name of its own", cfg->name, known->first.string());
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// The outcome of `work` for `key` in this build pass. The first caller
|
||||
// runs it; every other caller, whether at the same time or later, waits
|
||||
// for that run and gets its result or its exception. The keys are the
|
||||
|
|
@ -1667,6 +1682,175 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
|
|||
return buildResult;
|
||||
}
|
||||
|
||||
namespace {
|
||||
// How BuildAll builds the configurations of a list, or why it does not:
|
||||
// worked out from the list alone, before anything of it is built.
|
||||
struct BuildPlan {
|
||||
// Each of them once, however often the list names it.
|
||||
std::vector<Configuration*> roots;
|
||||
// For each of `roots`, the others it is built after, by their places
|
||||
// in `roots`.
|
||||
std::vector<std::vector<std::size_t>> waitsFor;
|
||||
// The places in `roots`, each after the ones it waits for.
|
||||
std::vector<std::size_t> order;
|
||||
// Whether a wasm executable that declares variants is among them or
|
||||
// among what they are built on, so that they are built one after the
|
||||
// other.
|
||||
bool rewrites = false;
|
||||
// Why the list is not built, as BuildAll returns it; empty when it
|
||||
// is.
|
||||
std::string refused;
|
||||
};
|
||||
|
||||
BuildPlan PlanBuild(std::span<Configuration* const> configurations) {
|
||||
BuildPlan plan;
|
||||
for (Configuration* cfg : configurations) {
|
||||
if (!std::ranges::contains(plan.roots, cfg)) plan.roots.push_back(cfg);
|
||||
}
|
||||
const std::span<Configuration* const> roots = plan.roots;
|
||||
const std::size_t count = roots.size();
|
||||
const auto directory = [](const Configuration& cfg) { return fs::absolute(cfg.PcmDir()).lexically_normal(); };
|
||||
|
||||
// The directory each of them is built into, and the directories of
|
||||
// everything it is built on. A wasm executable that declares
|
||||
// variants builds everything it is built on once more for each of
|
||||
// them, and says which variant by rewriting those configurations in
|
||||
// place (the end of Build()). A library that two of these share
|
||||
// would change under whichever is still building its baseline, so
|
||||
// with such a configuration anywhere among them they are built one
|
||||
// after the other.
|
||||
std::vector<fs::path> builtInto(count);
|
||||
std::vector<std::unordered_set<fs::path>> builtOn(count);
|
||||
for (std::size_t index = 0; index < count; ++index) {
|
||||
builtInto[index] = directory(*roots[index]);
|
||||
std::unordered_set<const Configuration*> seen = { roots[index] };
|
||||
std::vector<const Configuration*> pending = { roots[index] };
|
||||
while (!pending.empty()) {
|
||||
const Configuration& cfg = *pending.back();
|
||||
pending.pop_back();
|
||||
if (cfg.type == ConfigurationType::Executable && cfg.target.starts_with("wasm32") && !cfg.wasmVariants.empty()) plan.rewrites = true;
|
||||
for (const Configuration* dep : cfg.dependencies) {
|
||||
if (!seen.insert(dep).second) continue;
|
||||
builtOn[index].insert(directory(*dep));
|
||||
pending.push_back(dep);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
plan.refused = SameDirectoryError(roots);
|
||||
if (!plan.refused.empty()) return plan;
|
||||
|
||||
// One that another is built on, which is to say that something the
|
||||
// other is built on is built into its directory, is built before
|
||||
// the other starts: the other then finds it built, in the record of
|
||||
// the pass, instead of building it a second time beside this build
|
||||
// of it.
|
||||
plan.waitsFor.resize(count);
|
||||
for (std::size_t index = 0; index < count; ++index) {
|
||||
for (std::size_t other = 0; other < count; ++other) {
|
||||
if (other != index && builtOn[index].contains(builtInto[other])) plan.waitsFor[index].push_back(other);
|
||||
}
|
||||
}
|
||||
// One that is itself built on something of its own directory makes
|
||||
// two builds for that directory, its dependency's and its own, and
|
||||
// the record of the pass holds one result for a directory: another
|
||||
// of them that looks there for what it is built on would be given
|
||||
// one of the two, whichever it had asked for. By itself, or with no
|
||||
// other of them built on that directory, it builds as it does for
|
||||
// Build().
|
||||
for (std::size_t index = 0; index < count; ++index) {
|
||||
if (!builtOn[index].contains(builtInto[index])) continue;
|
||||
for (std::size_t other = 0; other < count; ++other) {
|
||||
if (other == index || !builtOn[other].contains(builtInto[index])) continue;
|
||||
plan.refused = std::format("{} and a configuration it is built on would both be built into {}, where {} looks for what it is built on: give each a name of its own", roots[index]->name, builtInto[index].string(), roots[other]->name);
|
||||
return plan;
|
||||
}
|
||||
}
|
||||
std::vector<bool> ordered(count, false);
|
||||
for (bool placed = true; placed;) {
|
||||
placed = false;
|
||||
for (std::size_t index = 0; index < count; ++index) {
|
||||
if (ordered[index] || !std::ranges::all_of(plan.waitsFor[index], [&](std::size_t other) { return ordered[other]; })) continue;
|
||||
ordered[index] = true;
|
||||
plan.order.push_back(index);
|
||||
placed = true;
|
||||
}
|
||||
}
|
||||
if (plan.order.size() != count) {
|
||||
std::string names;
|
||||
for (std::size_t index = 0; index < count; ++index) {
|
||||
if (ordered[index]) continue;
|
||||
if (!names.empty()) names += ", ";
|
||||
names += roots[index]->name;
|
||||
}
|
||||
plan.refused = std::format("{}: each of these is built on something that would be built into the directory of another of them, so none of them can be built first", names);
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
}
|
||||
|
||||
std::string Crafter::BuildAll(std::span<Configuration* const> configurations, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex) {
|
||||
const BuildPlan plan = PlanBuild(configurations);
|
||||
if (!plan.refused.empty()) return plan.refused;
|
||||
const std::size_t count = plan.roots.size();
|
||||
|
||||
std::vector<std::string> errors(count);
|
||||
const auto build = [&](std::size_t index) {
|
||||
Configuration& cfg = *plan.roots[index];
|
||||
// By Build() itself, as a project's one configuration always was,
|
||||
// and only then put into the record of the pass, where a
|
||||
// configuration that depends on this one looks for it, with what
|
||||
// the build returned or threw. Recorded while it is still being
|
||||
// built, it would be handed to a dependency of its own that is
|
||||
// built into the same directory, which would wait for the build
|
||||
// that is waiting for it. Such a dependency has left its own result
|
||||
// under that directory by now, and this one's takes its place: no
|
||||
// other of them is built on that directory, or the set was refused.
|
||||
std::promise<BuildResult> built;
|
||||
try {
|
||||
BuildResult result = Build(cfg, depResults, depMutex);
|
||||
errors[index] = result.result;
|
||||
built.set_value(std::move(result));
|
||||
} catch (const std::exception& e) {
|
||||
errors[index] = std::format("build of {} threw: {}", cfg.name, e.what());
|
||||
built.set_exception(std::current_exception());
|
||||
} catch (...) {
|
||||
errors[index] = std::format("build of {} threw something that is not a std::exception", cfg.name);
|
||||
built.set_exception(std::current_exception());
|
||||
}
|
||||
const std::lock_guard lock(depMutex);
|
||||
depResults.insert_or_assign(cfg.PcmDir(), built.get_future().share());
|
||||
};
|
||||
|
||||
if (plan.rewrites) {
|
||||
for (const std::size_t index : plan.order) build(index);
|
||||
} else {
|
||||
std::vector<std::promise<void>> finishes(count);
|
||||
std::vector<std::shared_future<void>> finished;
|
||||
finished.reserve(count);
|
||||
for (std::promise<void>& finish : finishes) finished.push_back(finish.get_future().share());
|
||||
const auto buildInTurn = [&](std::size_t index) {
|
||||
for (const std::size_t other : plan.waitsFor[index]) finished[other].wait();
|
||||
build(index);
|
||||
finishes[index].set_value();
|
||||
};
|
||||
// The first on this thread, so a project of one configuration is
|
||||
// built where it always was.
|
||||
std::vector<std::jthread> others;
|
||||
others.reserve(count);
|
||||
for (std::size_t index = 1; index < count; ++index) others.emplace_back(buildInTurn, index);
|
||||
if (count > 0) buildInTurn(0);
|
||||
}
|
||||
|
||||
std::string failed;
|
||||
for (auto error = errors.begin(); error != errors.end(); ++error) {
|
||||
if (error->empty() || std::ranges::contains(errors.begin(), error, *error)) continue;
|
||||
if (!failed.empty()) failed += '\n';
|
||||
failed += *error;
|
||||
}
|
||||
return failed;
|
||||
}
|
||||
|
||||
namespace {
|
||||
FlatpakExport ExportOf(const Configuration& config) {
|
||||
FlatpakExport app;
|
||||
|
|
@ -1700,6 +1884,41 @@ namespace {
|
|||
return "";
|
||||
}
|
||||
|
||||
// The names of `configurations`, as a message lists them.
|
||||
std::string NamesOf(std::span<const Configuration* const> configurations) {
|
||||
std::string names;
|
||||
for (const Configuration* cfg : configurations) {
|
||||
if (!names.empty()) names += ", ";
|
||||
names += cfg->name;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
// What install or bundle exports of the configurations a project file
|
||||
// returns: the only one, or of several the one packaged as a Flatpak.
|
||||
struct ExportChoice {
|
||||
// Null when none of several is packaged, or more than one is.
|
||||
const Configuration* config = nullptr;
|
||||
// Why `config` cannot be exported, or why there is none; empty when
|
||||
// it can be.
|
||||
std::string refused;
|
||||
};
|
||||
|
||||
ExportChoice ChooseExport(std::span<Configuration* const> configurations, std::string_view verb) {
|
||||
std::vector<const Configuration*> packaged;
|
||||
for (const Configuration* cfg : configurations) {
|
||||
if (cfg->ResolvedPackaging() == Packaging::Flatpak) packaged.push_back(cfg);
|
||||
}
|
||||
if (packaged.size() > 1) {
|
||||
return { nullptr, std::format("crafter-build {0}: {1} are each packaged as a Flatpak, and {0} exports one app", verb, NamesOf(packaged)) };
|
||||
}
|
||||
if (packaged.empty() && configurations.size() > 1) {
|
||||
return { nullptr, std::format("crafter-build {0}: none of {1} is packaged as a Flatpak; set cfg.packaging = Packaging::Flatpak in project.cpp on the one to {0}", verb, NamesOf(configurations)) };
|
||||
}
|
||||
const Configuration* const config = packaged.empty() ? configurations.front() : packaged.front();
|
||||
return { config, ExportRefusal(*config, verb) };
|
||||
}
|
||||
|
||||
// A repo's path as the file:// URL of a remote: percent-encoded, since
|
||||
// `remote-modify --url=` stores what it is given as it is.
|
||||
std::string FileUrl(const fs::path& path) {
|
||||
|
|
@ -2151,7 +2370,9 @@ R"(Usage:
|
|||
Loads ./project.cpp (override with --project=<path>), compiles it to a shared
|
||||
object, and invokes its CrafterBuildProject() to obtain a Configuration that
|
||||
drives the build. Outputs land at bin/<name>-<target>-<march>/, intermediates
|
||||
at build/<name>-<target>-<march>/.
|
||||
at build/<name>-<target>-<march>/. A project of several configurations
|
||||
defines CrafterBuildConfigurations() instead, which returns them all and gets
|
||||
the same args, and every one of them is built.
|
||||
|
||||
A build runs at most as many of its steps at once as the machine has hardware
|
||||
threads: the compiles of its sources, its shaders and assets, and its links
|
||||
|
|
@ -2165,7 +2386,8 @@ Build options:
|
|||
one for the host in its own directory, a wasm32 one
|
||||
under wasmtime or wasmer, or one built for the
|
||||
browser served over HTTP from its directory.
|
||||
Libraries cannot be run.
|
||||
Libraries cannot be run, and of several
|
||||
configurations one has to be the only executable.
|
||||
-v, --verbose Verbose progress output.
|
||||
-q, --quiet Suppress progress output.
|
||||
--project=<path> Path to the project file (default: ./project.cpp).
|
||||
|
|
@ -2244,7 +2466,9 @@ Install and bundle (after the `install` or `bundle` subcommand):
|
|||
run the host's flatpak, inside crafter-build's Flatpak through
|
||||
flatpak-spawn --host, and refuse a project whose bin/ and build/ the host
|
||||
does not see where crafter-build does, as in the sandbox's own /tmp, /var,
|
||||
/usr, /etc and /app, which they ask the host before building.
|
||||
/usr, /etc and /app, which they ask the host before building. Of several
|
||||
configurations they export the one that is packaged as a Flatpak, and
|
||||
refuse before building when none is, or more than one.
|
||||
|
||||
Clean (after the `clean` subcommand):
|
||||
Removes bin/ and build/ next to the project file. Does not load project.cpp,
|
||||
|
|
@ -2263,14 +2487,14 @@ AGENTS.md:
|
|||
Direct, or None.
|
||||
|
||||
Project args:
|
||||
Any flag not consumed above is forwarded verbatim to CrafterBuildProject as
|
||||
part of its `args` span. Project-specific flags (e.g. --target=, custom
|
||||
feature toggles) live there. ApplyStandardArgs reads --debug, --target=,
|
||||
--march=, --mtune=, --cuda-arch=, --sysroot=, --lib, --shared and
|
||||
--packaging=none|flatpak, the last for the project crafter-build was pointed
|
||||
at only. Flags it does not itself interpret are folded into the variant
|
||||
hash, so switching one lands in its own bin/ and build/ directory instead of
|
||||
overwriting the other setting's.
|
||||
Any flag not consumed above is forwarded verbatim to the project file's
|
||||
entry point as part of its `args` span. Project-specific flags (e.g.
|
||||
--target=, custom feature toggles) live there. ApplyStandardArgs reads
|
||||
--debug, --target=, --march=, --mtune=, --cuda-arch=, --sysroot=, --lib,
|
||||
--shared and --packaging=none|flatpak, the last for the project
|
||||
crafter-build was pointed at only. Flags it does not itself interpret are
|
||||
folded into the variant hash, so switching one lands in its own bin/ and
|
||||
build/ directory instead of overwriting the other setting's.
|
||||
|
||||
Environment:
|
||||
CRAFTER_BUILD_MARCH Override -march (default: native).
|
||||
|
|
@ -2436,7 +2660,7 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) {
|
|||
return 1;
|
||||
}
|
||||
|
||||
// Ahead of LoadProject on purpose — see CleanProject.
|
||||
// Ahead of the load on purpose — see CleanProject.
|
||||
if (verb == Verb::Clean) {
|
||||
std::vector<fs::path> removed = CleanProject(projectFile);
|
||||
if (removed.empty()) {
|
||||
|
|
@ -2447,19 +2671,31 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) {
|
|||
return 0;
|
||||
}
|
||||
|
||||
Configuration config = LoadProject(projectFile, projectArgs);
|
||||
SetParentProject(&config);
|
||||
// What the project file describes: one configuration, or several
|
||||
// that are all built.
|
||||
const std::vector<Configuration*> configurations = LoadConfigurations(projectFile, projectArgs);
|
||||
// The ones the file made itself: every one but those that another
|
||||
// project's file returned to GitProject or LocalProject. One of
|
||||
// those, returned here in turn, is built with the rest, and -r,
|
||||
// install and bundle count it among them, but its tests and its
|
||||
// scripts stay that project's: `run` still reaches no script but
|
||||
// those of the project crafter-build was pointed at.
|
||||
std::vector<Configuration*> own;
|
||||
for (Configuration* cfg : configurations) {
|
||||
if (!LoadedProjectOf(*cfg)) own.push_back(cfg);
|
||||
}
|
||||
SetParentProject(configurations);
|
||||
|
||||
if (verb == Verb::Run) {
|
||||
scriptOpts.projectFile = fs::absolute(projectFile).lexically_normal();
|
||||
return RunScript(config, scriptOpts);
|
||||
return RunScript(own, scriptOpts);
|
||||
}
|
||||
|
||||
if (verb == Verb::Lint || verb == Verb::Format) {
|
||||
// lexically_normal: fs::absolute keeps a "./" component, which
|
||||
// would leak into displayed paths and the project-root derivation.
|
||||
lintOpts.projectFile = fs::absolute(projectFile).lexically_normal();
|
||||
LintSummary lintSummary = RunLint(config, lintOpts);
|
||||
LintSummary lintSummary = RunLint(configurations, lintOpts);
|
||||
if (verb == Verb::Lint) return lintSummary.Clean() ? 0 : 1;
|
||||
if (lintSummary.noRulesDefined || lintSummary.errors > 0) return 1;
|
||||
// Apply: formatting files is success (gofmt convention).
|
||||
|
|
@ -2469,51 +2705,76 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) {
|
|||
|
||||
// What install and bundle cannot export they refuse here, before
|
||||
// anything is built: a project that is not packaged as a Flatpak, or
|
||||
// a host flatpak out of reach, is known from the loaded project.
|
||||
// a host flatpak out of reach, is known from the loaded project, and
|
||||
// so is which of several configurations is the app.
|
||||
ExportChoice exported;
|
||||
if (verb == Verb::Install || verb == Verb::Bundle) {
|
||||
if (const std::string refused = ExportRefusal(config, verb == Verb::Install ? "install" : "bundle"); !refused.empty()) {
|
||||
std::println(std::cerr, "{}", refused);
|
||||
exported = ChooseExport(configurations, verb == Verb::Install ? "install" : "bundle");
|
||||
if (!exported.refused.empty()) {
|
||||
std::println(std::cerr, "{}", exported.refused);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
// What the list itself rules out is refused here too, before any of
|
||||
// it is built and before AGENTS.md is written: two returned
|
||||
// configurations of one directory for every verb that builds, and
|
||||
// for the verbs that build the configurations themselves whatever
|
||||
// else BuildAll refuses a list for. `test` builds its tests with
|
||||
// Build() and never comes to BuildAll, which makes these refusals
|
||||
// again for whoever calls it.
|
||||
if (const std::string refused = verb == Verb::Test ? SameDirectoryError(configurations) : PlanBuild(configurations).refused; !refused.empty()) {
|
||||
Progress::Clear();
|
||||
std::println(std::cerr, "{}", refused);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Builds and test runs only: lint and `format --check` promise to
|
||||
// write nothing, `format` rewrites the project's sources and nothing
|
||||
// else, `run` is for chores and `test --list` only lists. Here,
|
||||
// before compiling, because loading has just fetched every
|
||||
// dependency, so the notes are current, and an agent fixing a build
|
||||
// that fails needs them.
|
||||
if (!testOpts.listOnly) UpdateAgentsMd(config, projectFile);
|
||||
if (!testOpts.listOnly) UpdateAgentsMd(configurations, projectFile);
|
||||
|
||||
if (verb == Verb::Test) {
|
||||
TestSummary summary = RunTests(config, testOpts, projectArgs);
|
||||
TestSummary summary = RunTests(own, testOpts, projectArgs);
|
||||
return summary.AllPassed() ? 0 : 1;
|
||||
}
|
||||
|
||||
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
|
||||
std::mutex depMutex;
|
||||
BuildResult result = Build(config, depResults, depMutex);
|
||||
|
||||
if (!result.result.empty()) {
|
||||
if (const std::string failed = BuildAll(configurations, depResults, depMutex); !failed.empty()) {
|
||||
Progress::Clear();
|
||||
std::println(std::cerr, "{}", result.result);
|
||||
std::println(std::cerr, "{}", failed);
|
||||
return 1;
|
||||
}
|
||||
|
||||
Progress::Finalize();
|
||||
|
||||
if (verb == Verb::Install || verb == Verb::Bundle) {
|
||||
const std::string failed = verb == Verb::Install ? InstallFlatpakApp(config) : BundleFlatpakApp(config);
|
||||
const std::string failed = verb == Verb::Install ? InstallFlatpakApp(*exported.config) : BundleFlatpakApp(*exported.config);
|
||||
if (failed.empty()) return 0;
|
||||
std::println(std::cerr, "{}", failed);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (runAfterBuild) {
|
||||
if (config.type != ConfigurationType::Executable) {
|
||||
std::vector<const Configuration*> executables;
|
||||
for (const Configuration* cfg : configurations) {
|
||||
if (cfg->type == ConfigurationType::Executable) executables.push_back(cfg);
|
||||
}
|
||||
if (executables.empty()) {
|
||||
std::println(std::cerr, "-r: cannot run a library");
|
||||
return 1;
|
||||
}
|
||||
// Everything is built by now, as without -r. Which one to run
|
||||
// would be a guess.
|
||||
if (executables.size() > 1) {
|
||||
std::println(std::cerr, "-r: {} are executables, and -r runs one", NamesOf(executables));
|
||||
return 1;
|
||||
}
|
||||
const Configuration& config = *executables.front();
|
||||
fs::path dir = config.ProgramDir();
|
||||
fs::path artifact = fs::absolute(ExpectedOutput(config));
|
||||
fs::path absDir = fs::absolute(dir);
|
||||
|
|
|
|||
|
|
@ -336,40 +336,33 @@ ExternalBuildResult Crafter::ExternalOutputs(const ExternalDependency& dep, std:
|
|||
|
||||
namespace {
|
||||
std::mutex ProjectCacheMutex;
|
||||
std::unordered_map<std::string, std::unique_ptr<Configuration>> ProjectCache;
|
||||
// Keyed by the Configurations ProjectCache owns, which live as long as
|
||||
// the process does, so the pointers never dangle. Guarded by
|
||||
// ProjectCacheMutex as well.
|
||||
// What each project file loaded here returned, in the file's order, by
|
||||
// spec and args. An entry is never changed or removed once it is in.
|
||||
std::unordered_map<std::string, std::vector<Configuration*>> ProjectCache;
|
||||
// Keyed by the Configurations ProjectCache holds, which live as long as
|
||||
// the process does (see LoadConfigurations), so the pointers never
|
||||
// dangle. Guarded by ProjectCacheMutex as well.
|
||||
std::unordered_map<const Configuration*, LoadedProject> LoadedProjects;
|
||||
// The configurations a loaded project keeps to itself, with the project:
|
||||
// what the configurations its file returned led to when the file was
|
||||
// loaded and the file did not return. A configuration leads to what it
|
||||
// is built on and to the configurations of its tests, and each of those
|
||||
// leads on in the same way. Taken down at that moment, since a consumer
|
||||
// may add to the `dependencies` of a configuration it was given, and
|
||||
// what it adds is its own. Guarded by ProjectCacheMutex as well.
|
||||
std::unordered_map<const Configuration*, LoadedProject> KeptConfigurations;
|
||||
|
||||
// Run the dep's project.cpp from its own directory so its relative paths
|
||||
// (cfg.path = "./", interfaces/, lib/, ...) resolve against the dep
|
||||
// root, then rebase cfg.path and all other relative path collections to
|
||||
// absolute so Build() can run from any cwd without misresolving them.
|
||||
// The mutex is NOT held across LoadProject — the dep may itself call
|
||||
// GitProject/LocalProject, and a non-recursive lock would deadlock.
|
||||
//
|
||||
// The Configuration is made on the heap with the call as its
|
||||
// initialiser, so it is constructed where the cache keeps it and is
|
||||
// never moved. A project file takes pointers to the Configuration it
|
||||
// returns, for a test that links the library it describes
|
||||
// (cfg.AddTest(...).Dependencies({ &cfg })), and they are pointers to
|
||||
// this object when the compiler constructed the local the file returns
|
||||
// in place of the return value, as clang does for a function that
|
||||
// returns one local. Assigned to a local here and moved into the cache
|
||||
// from there, the Configuration left every such pointer behind.
|
||||
std::unique_ptr<Configuration> LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span<const std::string_view> args) {
|
||||
fs::path savedCwd = fs::current_path();
|
||||
std::unique_ptr<Configuration> made;
|
||||
fs::current_path(depRoot);
|
||||
try {
|
||||
made.reset(new Configuration(LoadProject(projectPath, args)));
|
||||
} catch (...) {
|
||||
fs::current_path(savedCwd);
|
||||
throw;
|
||||
}
|
||||
fs::current_path(savedCwd);
|
||||
Configuration& cfg = *made;
|
||||
// What the cache holds under `fullHash`, or nullptr.
|
||||
const std::vector<Configuration*>* CachedProject(const std::string& fullHash) {
|
||||
const std::lock_guard lock(ProjectCacheMutex);
|
||||
const auto it = ProjectCache.find(fullHash);
|
||||
return it == ProjectCache.end() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
// cfg.path and every other relative path collection of `cfg`, made
|
||||
// absolute against `depRoot`, so Build() can run from any cwd without
|
||||
// misresolving them.
|
||||
void RebaseOnto(Configuration& cfg, const fs::path& depRoot) {
|
||||
cfg.path = fs::absolute(depRoot / cfg.path).lexically_normal();
|
||||
auto abs = [&](const fs::path& p) -> fs::path {
|
||||
return p.is_absolute() ? p : fs::absolute(depRoot / p).lexically_normal();
|
||||
|
|
@ -389,21 +382,81 @@ namespace {
|
|||
for (auto& entry : cfg.flatpak.share) {
|
||||
if (!entry.source.empty()) entry.source = abs(entry.source);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
// Into ProjectCache under `fullHash`, with `loaded` recorded beside it.
|
||||
// When another thread stored the same spec first, its Configuration
|
||||
// wins and `cfg` is dropped.
|
||||
Configuration* StoreProject(std::string fullHash, std::unique_ptr<Configuration> cfg, LoadedProject loaded) {
|
||||
std::lock_guard lock(ProjectCacheMutex);
|
||||
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) {
|
||||
return it->second.get();
|
||||
// Run the dep's project.cpp from its own directory so its relative paths
|
||||
// (cfg.path = "./", interfaces/, lib/, ...) resolve against the dep
|
||||
// root, then rebase every configuration it returns onto that root.
|
||||
// The mutex is NOT held across the load — the dep may itself call
|
||||
// GitProject/LocalProject, and a non-recursive lock would deadlock.
|
||||
std::vector<Configuration*> LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span<const std::string_view> args) {
|
||||
fs::path savedCwd = fs::current_path();
|
||||
std::vector<Configuration*> configurations;
|
||||
fs::current_path(depRoot);
|
||||
try {
|
||||
configurations = LoadConfigurations(projectPath, args);
|
||||
} catch (...) {
|
||||
fs::current_path(savedCwd);
|
||||
throw;
|
||||
}
|
||||
Configuration* ptr = cfg.get();
|
||||
ProjectCache.emplace(std::move(fullHash), std::move(cfg));
|
||||
LoadedProjects.emplace(ptr, std::move(loaded));
|
||||
return ptr;
|
||||
fs::current_path(savedCwd);
|
||||
for (Configuration* cfg : configurations) {
|
||||
// One the file loaded from another project file and returns
|
||||
// itself was rebased onto that project's root when it was
|
||||
// loaded, and other consumers may be reading it by now.
|
||||
if (!LoadedProjectOf(*cfg)) RebaseOnto(*cfg, depRoot);
|
||||
}
|
||||
return configurations;
|
||||
}
|
||||
|
||||
// Into ProjectCache under `fullHash`, with `loaded` recorded beside each
|
||||
// configuration that is not another project's already, and beside what
|
||||
// those are built on and the file kept to itself. When another thread
|
||||
// stored the same spec first, what it stored wins.
|
||||
const std::vector<Configuration*>& StoreProject(std::string fullHash, std::vector<Configuration*> configurations, const LoadedProject& loaded) {
|
||||
const std::lock_guard lock(ProjectCacheMutex);
|
||||
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) {
|
||||
return it->second;
|
||||
}
|
||||
// What this file returned, and then what each of those leads to:
|
||||
// what it is built on and the configurations of its tests. One that
|
||||
// another project's file returned is that project's, and so is what
|
||||
// is found from there.
|
||||
std::vector<const Configuration*> pending;
|
||||
const auto leadsTo = [&pending](const Configuration& cfg) {
|
||||
pending.insert(pending.end(), cfg.dependencies.begin(), cfg.dependencies.end());
|
||||
for (const Test& test : cfg.tests) pending.push_back(&test.config);
|
||||
};
|
||||
for (const Configuration* cfg : configurations) {
|
||||
if (LoadedProjects.try_emplace(cfg, loaded).second) leadsTo(*cfg);
|
||||
}
|
||||
while (!pending.empty()) {
|
||||
const Configuration* kept = pending.back();
|
||||
pending.pop_back();
|
||||
if (!kept || LoadedProjects.contains(kept) || !KeptConfigurations.try_emplace(kept, loaded).second) continue;
|
||||
leadsTo(*kept);
|
||||
}
|
||||
return ProjectCache.emplace(std::move(fullHash), std::move(configurations)).first->second;
|
||||
}
|
||||
|
||||
// The one of `configurations` a spec asks for by `name`: the first for
|
||||
// an empty name. `what` names the spec in the error for a name that none
|
||||
// has, or that two have.
|
||||
Configuration* PickConfiguration(std::span<Configuration* const> configurations, std::string_view name, std::string_view what) {
|
||||
if (name.empty()) return configurations.front();
|
||||
Configuration* picked = nullptr;
|
||||
for (Configuration* cfg : configurations) {
|
||||
if (cfg->name != name) continue;
|
||||
if (picked) throw std::runtime_error(std::format("{}: two of its configurations are named '{}', so the name picks neither", what, name));
|
||||
picked = cfg;
|
||||
}
|
||||
if (picked) return picked;
|
||||
std::string names;
|
||||
for (const Configuration* cfg : configurations) {
|
||||
if (!names.empty()) names += ", ";
|
||||
names += cfg->name;
|
||||
}
|
||||
throw std::runtime_error(std::format("{}: no configuration named '{}' (it has: {})", what, name, names));
|
||||
}
|
||||
|
||||
// `url` as it names a repository: without user info, which is where a
|
||||
|
|
@ -425,10 +478,11 @@ namespace {
|
|||
Configuration* Crafter::GitProject(const GitProjectSpec& spec) {
|
||||
// Two hashes: the clone is shared across specs that point at the same
|
||||
// source revision (forwarded args don't change what gets cloned, just
|
||||
// how the dep's project.cpp interprets them at runtime), while the
|
||||
// in-memory Configuration is keyed by the full spec so each (args)
|
||||
// permutation gets its own Configuration object, and host tooling one
|
||||
// apart from the target's even for the same args.
|
||||
// how the dep's project.cpp interprets them at runtime), while what the
|
||||
// file returned is keyed by the args as well, so each (args)
|
||||
// permutation gets its own Configuration objects, and host tooling ones
|
||||
// apart from the target's even for the same args. Which configuration
|
||||
// the spec picks is in neither: it chooses among what one load returned.
|
||||
std::string srcKey = std::format("git|{}|{}|{}|{}", spec.source.url, spec.source.branch, spec.source.commit, spec.projectFile.string());
|
||||
std::string srcHash = std::format("{:016x}", std::hash<std::string>{}(srcKey));
|
||||
|
||||
|
|
@ -438,12 +492,10 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) {
|
|||
fullKey += a;
|
||||
}
|
||||
std::string fullHash = std::format("{:016x}", std::hash<std::string>{}(fullKey));
|
||||
const std::string what = std::format("GitProject({})", spec.source.url);
|
||||
|
||||
{
|
||||
std::lock_guard lock(ProjectCacheMutex);
|
||||
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) {
|
||||
return it->second.get();
|
||||
}
|
||||
if (const std::vector<Configuration*>* cached = CachedProject(fullHash)) {
|
||||
return PickConfiguration(*cached, spec.configuration, what);
|
||||
}
|
||||
|
||||
std::string name = DeriveName(spec.source);
|
||||
|
|
@ -471,15 +523,15 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) {
|
|||
}
|
||||
|
||||
std::vector<std::string_view> argViews(spec.args.begin(), spec.args.end());
|
||||
std::unique_ptr<Configuration> cfg = LoadProjectFromRoot(projectPath, cloneDir, argViews);
|
||||
std::vector<Configuration*> configurations = LoadProjectFromRoot(projectPath, cloneDir, argViews);
|
||||
|
||||
const fs::path projectInRepo = spec.projectFile.lexically_normal();
|
||||
const fs::path below = projectInRepo.parent_path();
|
||||
return StoreProject(std::move(fullHash), std::move(cfg), {
|
||||
return PickConfiguration(StoreProject(std::move(fullHash), std::move(configurations), {
|
||||
.projectFile = projectPath.lexically_normal(),
|
||||
.name = below.empty() ? name : std::format("{}/{}", name, below.generic_string()),
|
||||
.identity = std::format("git|{}|{}", RepositoryKey(spec.source.url), projectInRepo.generic_string()),
|
||||
});
|
||||
}), spec.configuration, what);
|
||||
}
|
||||
|
||||
fs::path Crafter::GitFetch(const GitSource& source) {
|
||||
|
|
@ -522,23 +574,21 @@ Configuration* Crafter::LocalProject(const LocalProjectSpec& spec) {
|
|||
fullKey += a;
|
||||
}
|
||||
std::string fullHash = std::format("{:016x}", std::hash<std::string>{}(fullKey));
|
||||
const std::string what = std::format("LocalProject({})", canonical.string());
|
||||
|
||||
{
|
||||
std::lock_guard lock(ProjectCacheMutex);
|
||||
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) {
|
||||
return it->second.get();
|
||||
}
|
||||
if (const std::vector<Configuration*>* cached = CachedProject(fullHash)) {
|
||||
return PickConfiguration(*cached, spec.configuration, what);
|
||||
}
|
||||
|
||||
fs::path depRoot = canonical.parent_path();
|
||||
std::vector<std::string_view> argViews(spec.args.begin(), spec.args.end());
|
||||
std::unique_ptr<Configuration> cfg = LoadProjectFromRoot(canonical, depRoot, argViews);
|
||||
std::vector<Configuration*> configurations = LoadProjectFromRoot(canonical, depRoot, argViews);
|
||||
|
||||
return StoreProject(std::move(fullHash), std::move(cfg), {
|
||||
return PickConfiguration(StoreProject(std::move(fullHash), std::move(configurations), {
|
||||
.projectFile = canonical,
|
||||
.name = depRoot.filename().string(),
|
||||
.identity = std::format("local|{}", canonical.string()),
|
||||
});
|
||||
}), spec.configuration, what);
|
||||
}
|
||||
|
||||
std::optional<LoadedProject> Crafter::LoadedProjectOf(const Configuration& cfg) {
|
||||
|
|
@ -546,3 +596,9 @@ std::optional<LoadedProject> Crafter::LoadedProjectOf(const Configuration& cfg)
|
|||
if (auto it = LoadedProjects.find(&cfg); it != LoadedProjects.end()) return it->second;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<LoadedProject> Crafter::KeptBy(const Configuration& cfg) {
|
||||
const std::lock_guard lock(ProjectCacheMutex);
|
||||
if (const auto it = KeptConfigurations.find(&cfg); it != KeptConfigurations.end()) return it->second;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -866,18 +866,28 @@ namespace {
|
|||
// whose path lies inside the project root — GitProject / external deps
|
||||
// live under the global cache and are foreign code: they contribute
|
||||
// neither rules nor files. Root-first order so the root's rules win the
|
||||
// by-name dedup.
|
||||
std::vector<Configuration*> CollectLocalConfigs(Configuration& root, const fs::path& projectRoot) {
|
||||
// by-name dedup. Of several roots, the configurations a project file
|
||||
// returns, every root comes first, in the order given, and what they
|
||||
// depend on after them: walked one root's graph after another, a root
|
||||
// that an earlier one depends on would come before the roots between
|
||||
// the two, and its rule would win over theirs.
|
||||
std::vector<Configuration*> CollectLocalConfigs(std::span<Configuration* const> roots, const fs::path& projectRoot) {
|
||||
std::vector<Configuration*> local;
|
||||
std::unordered_set<Configuration*> seen;
|
||||
std::function<void(Configuration*)> walk = [&](Configuration* c) {
|
||||
if (!seen.insert(c).second) return;
|
||||
if (PathInsideRoot(fs::absolute(c->path), projectRoot)) {
|
||||
local.push_back(c);
|
||||
}
|
||||
for (Configuration* dep : c->dependencies) walk(dep);
|
||||
const auto keep = [&](Configuration* c) {
|
||||
if (PathInsideRoot(fs::absolute(c->path), projectRoot)) local.push_back(c);
|
||||
};
|
||||
walk(&root);
|
||||
std::function<void(Configuration*)> below = [&](Configuration* c) {
|
||||
for (Configuration* dep : c->dependencies) {
|
||||
if (!seen.insert(dep).second) continue;
|
||||
keep(dep);
|
||||
below(dep);
|
||||
}
|
||||
};
|
||||
for (Configuration* root : roots) {
|
||||
if (seen.insert(root).second) keep(root);
|
||||
}
|
||||
for (Configuration* root : roots) below(root);
|
||||
return local;
|
||||
}
|
||||
|
||||
|
|
@ -1069,6 +1079,11 @@ void Configuration::AddAstLintRule(std::string name, std::function<void(LintCont
|
|||
}
|
||||
|
||||
LintSummary Crafter::RunLint(Configuration& projectCfg, const RunLintOptions& opts) {
|
||||
std::array<Configuration*, 1> one = { &projectCfg };
|
||||
return RunLint(std::span<Configuration* const>(one), opts);
|
||||
}
|
||||
|
||||
LintSummary Crafter::RunLint(std::span<Configuration* const> configurations, const RunLintOptions& opts) {
|
||||
LintSummary summary;
|
||||
|
||||
// libclang backs the lexer every rule reads through, so a failed load is
|
||||
|
|
@ -1081,10 +1096,10 @@ LintSummary Crafter::RunLint(Configuration& projectCfg, const RunLintOptions& op
|
|||
}
|
||||
|
||||
fs::path projectRoot = opts.projectFile.empty()
|
||||
? fs::absolute(projectCfg.path)
|
||||
? fs::absolute(configurations.empty() ? fs::path() : configurations.front()->path)
|
||||
: opts.projectFile.parent_path();
|
||||
|
||||
std::vector<Configuration*> localConfigs = CollectLocalConfigs(projectCfg, projectRoot);
|
||||
std::vector<Configuration*> localConfigs = CollectLocalConfigs(configurations, projectRoot);
|
||||
// The tests' compile commands are worked out as RunTests builds them.
|
||||
for (Configuration* c : localConfigs) UnpackageTests(*c);
|
||||
|
||||
|
|
@ -1133,7 +1148,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
|
|||
CollectConfigSources(*c, files);
|
||||
for (const Test& t : c->tests) CollectConfigSources(t.config, files);
|
||||
}
|
||||
// project.cpp is not built by Build() at all — LoadProject compiles it
|
||||
// project.cpp is not built by Build() at all — its load compiles it
|
||||
// against the host PCM cache with its own flags, so it is owned by nothing
|
||||
// here and gets no compile command. Token rules still cover it.
|
||||
if (!opts.projectFile.empty()) files.emplace(opts.projectFile, nullptr);
|
||||
|
|
@ -1217,7 +1232,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
|
|||
continue;
|
||||
}
|
||||
// No compile command means this file is not a translation unit
|
||||
// of the build graph — project.cpp, which LoadProject compiles
|
||||
// of the build graph — project.cpp, which its load compiles
|
||||
// with its own flags, or a header. A semantic rule does not
|
||||
// apply there, the same way a rule self-filters by extension,
|
||||
// so skip it quietly. That is a different thing from a file we
|
||||
|
|
|
|||
|
|
@ -313,7 +313,7 @@ namespace {
|
|||
std::string Crafter::RunBuildCommand(std::string_view cmd) {
|
||||
// A job is on a worker already and runs the command where it is. A link,
|
||||
// or the precompile of the std module, comes from the thread of a Build()
|
||||
// or a LoadProject and waits here for its turn among the jobs.
|
||||
// or of a project file's load and waits here for its turn among the jobs.
|
||||
std::string result;
|
||||
JobPool::Process().Run([&result, cmd] { result = RunBuildStep(cmd); });
|
||||
return result;
|
||||
|
|
@ -328,7 +328,7 @@ std::string Crafter::RunBuildCommand(std::string_view cmd) {
|
|||
// file, so this is a directive next to the `import` it enables — where
|
||||
// `#include` lives. Each one is fetched, built for the host, and put on
|
||||
// project.so's module path and link line before project.cpp is compiled. The
|
||||
// dependency's own project.cpp goes through LoadProject, so its pragmas
|
||||
// dependency's own project.cpp is loaded the same way, so its pragmas
|
||||
// resolve recursively.
|
||||
namespace {
|
||||
struct PragmaDependency {
|
||||
|
|
@ -429,18 +429,18 @@ namespace {
|
|||
|
||||
struct ProjectFileFrame {
|
||||
fs::path project;
|
||||
// What LoadProject was given, for ProjectArgs(), and only once
|
||||
// CrafterBuildProject is about to be called (see LoadProject). A view
|
||||
// is enough: the caller's storage outlives LoadProject, and the frame
|
||||
// is popped before LoadProject returns.
|
||||
// What the load was given, for ProjectArgs(), and only once the
|
||||
// entry point is about to be called (see OpenProjectFile). A view
|
||||
// is enough: the caller's storage outlives the load, and the frame
|
||||
// is popped before the load returns.
|
||||
std::span<const std::string_view> args;
|
||||
std::vector<Configuration*> dependencies;
|
||||
};
|
||||
|
||||
// LoadProject nests: a dependency's project.cpp loads inside its
|
||||
// consumer's pre-pass, and GitProject inside CrafterBuildProject nests
|
||||
// again. Several threads may also load at once (ConcurrentCacheRace), so
|
||||
// the stack is per thread. ProjectDependency() reads the top frame.
|
||||
// Loads nest: a dependency's project.cpp loads inside its consumer's
|
||||
// pre-pass, and GitProject inside an entry point nests again. Several
|
||||
// threads may also load at once (ConcurrentCacheRace), so the stack is
|
||||
// per thread. ProjectDependency() reads the top frame.
|
||||
thread_local std::vector<ProjectFileFrame> LoadingFrames;
|
||||
|
||||
// A frame's dependencies, kept past the frame for PragmaDependencies().
|
||||
|
|
@ -450,7 +450,7 @@ namespace {
|
|||
std::mutex PragmaDependenciesMutex;
|
||||
std::unordered_map<fs::path, std::vector<Configuration*>> PragmaDependenciesByProject;
|
||||
|
||||
// Held for the whole of one LoadProject call. Pushing a file that is
|
||||
// Held for the whole of one load of a project file. Pushing one that is
|
||||
// already on the stack is a cycle, which used to recurse forever.
|
||||
class ProjectFileGuard {
|
||||
public:
|
||||
|
|
@ -491,7 +491,7 @@ namespace {
|
|||
|
||||
// A pre-dependency is host tooling: project.so is loaded into the running
|
||||
// crafter-build, so the dependency is built for the host and against the
|
||||
// same PCM cache LoadProject populates — the hostConfig LoadProject itself
|
||||
// same PCM cache a load populates — the hostConfig the load itself
|
||||
// compiles project.so with, so the dependency's std/Crafter.Build PCMs
|
||||
// land in the cache dir project.so is built against. Recursive, because
|
||||
// the dependency's project.cpp is loaded with no arguments and so passes
|
||||
|
|
@ -523,7 +523,7 @@ namespace {
|
|||
// Every dependency's BuildResult.libs, verbatim, then its runtimeLibs,
|
||||
// the CUDA runtime, then a run path per directory of its runPaths
|
||||
// (RunPathFlags), as Build() links a program: the shared libraries a
|
||||
// pragma dependency is built on are found there when LoadProject
|
||||
// pragma dependency is built on are found there when the load
|
||||
// dlopens project.so.
|
||||
std::string linkFlags;
|
||||
fs::file_time_type newestArtifact = fs::file_time_type::min();
|
||||
|
|
@ -548,7 +548,7 @@ namespace {
|
|||
|
||||
for (const PragmaDependency& pragma : pragmas) {
|
||||
// Neither spec sets args, and the tool still gets none of the
|
||||
// consumer's: this pre-pass runs before LoadProject hands the
|
||||
// consumer's: this pre-pass runs before the load hands the
|
||||
// frame its args, so ProjectArgs() is empty. Given the consumer's
|
||||
// --target=, the tool's project.cpp would pick sources and flags
|
||||
// for the wrong triple, and its flags would split the tool's
|
||||
|
|
@ -566,7 +566,7 @@ namespace {
|
|||
cfg = GitProject(spec);
|
||||
} else {
|
||||
if (!pragma.branch.empty() || !pragma.commit.empty()) PragmaError(absProject, pragma.line, "'branch' and 'commit' only apply to a git source");
|
||||
// Relative to the project file, not the cwd: LoadProject runs
|
||||
// Relative to the project file, not the cwd: the load runs
|
||||
// from wherever the consumer was invoked.
|
||||
fs::path local = (absProject.parent_path() / pragma.source).lexically_normal();
|
||||
if (fs::is_directory(local)) {
|
||||
|
|
@ -1067,10 +1067,32 @@ namespace {
|
|||
}
|
||||
}
|
||||
|
||||
Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const std::string_view> args) {
|
||||
RequireToolchain();
|
||||
fs::path absProject = fs::canonical(projectFile);
|
||||
ProjectFileGuard guard(absProject);
|
||||
namespace {
|
||||
using ProjectFn = Configuration (*)(std::span<const std::string_view>);
|
||||
using ConfigurationsFn = std::vector<Configuration*> (*)(std::span<const std::string_view>);
|
||||
|
||||
// The entry point of a loaded project file: one of the two is set.
|
||||
struct ProjectEntry {
|
||||
ProjectFn one = nullptr;
|
||||
ConfigurationsFn several = nullptr;
|
||||
};
|
||||
|
||||
// Every Configuration a CrafterBuildProject returned to
|
||||
// LoadConfigurations, kept for the rest of the process like the ones a
|
||||
// CrafterBuildConfigurations returns, which its project file keeps:
|
||||
// whoever holds a pointer LoadConfigurations gave out, the project cache
|
||||
// or a consumer's `dependencies`, holds it that long.
|
||||
std::mutex ReturnedConfigurationsMutex;
|
||||
std::vector<std::unique_ptr<Configuration>> ReturnedConfigurations;
|
||||
}
|
||||
|
||||
// Compiles the project file `guard` holds into project.so, unless the one
|
||||
// there is current, loads it and finds its entry point. The frame holds
|
||||
// `args` once this returns, for the call the caller makes next.
|
||||
static ProjectEntry OpenProjectFile(ProjectFileGuard& guard, std::span<const std::string_view> args) {
|
||||
// A copy: the loads of the file's dependencies push frames of their own,
|
||||
// which can move this one.
|
||||
const fs::path absProject = guard.Frame().project;
|
||||
fs::path buildDir = absProject.parent_path() / "build";
|
||||
if (!fs::exists(buildDir)) {
|
||||
fs::create_directories(buildDir);
|
||||
|
|
@ -1154,11 +1176,20 @@ Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const
|
|||
throw std::runtime_error(std::format("Failed to load project {}: {}", soPath.string(), dlerror()));
|
||||
}
|
||||
|
||||
using ProjectFn = Configuration (*)(std::span<const std::string_view>);
|
||||
dlerror();
|
||||
auto fn = reinterpret_cast<ProjectFn>(dlsym(handle, "CrafterBuildProject"));
|
||||
if (const char* err = dlerror()) {
|
||||
throw std::runtime_error(std::format("CrafterBuildProject not found in {}: {}", soPath.string(), err));
|
||||
// Looked up in project.so and the libraries it links, which is where
|
||||
// dlsym searches for a handle: every project file this process has
|
||||
// loaded exports an entry point under one of these two names, and none
|
||||
// of the others is found here.
|
||||
ProjectEntry entry;
|
||||
entry.one = reinterpret_cast<ProjectFn>(dlsym(handle, "CrafterBuildProject"));
|
||||
entry.several = reinterpret_cast<ConfigurationsFn>(dlsym(handle, "CrafterBuildConfigurations"));
|
||||
if (!entry.one && !entry.several) {
|
||||
throw std::runtime_error(std::format("{} defines neither CrafterBuildProject nor CrafterBuildConfigurations (looked in {})", absProject.string(), soPath.string()));
|
||||
}
|
||||
// Calling the first would leave what the second returns unbuilt, and
|
||||
// the other way around, without a word.
|
||||
if (entry.one && entry.several) {
|
||||
throw std::runtime_error(std::format("{} defines both CrafterBuildProject and CrafterBuildConfigurations; a project file has one entry point", absProject.string()));
|
||||
}
|
||||
|
||||
// The args only for the call itself, unlike the dependencies. A static
|
||||
|
|
@ -1168,5 +1199,67 @@ Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const
|
|||
// Now it gets none, whichever load ran it. The pragma pre-pass above
|
||||
// also ran on this frame and relies on the args not being there yet.
|
||||
guard.Frame().args = args;
|
||||
return fn(args);
|
||||
return entry;
|
||||
}
|
||||
|
||||
Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const std::string_view> args) {
|
||||
RequireToolchain();
|
||||
const fs::path absProject = fs::canonical(projectFile);
|
||||
ProjectFileGuard guard(absProject);
|
||||
const ProjectEntry entry = OpenProjectFile(guard, args);
|
||||
if (!entry.one) {
|
||||
throw std::runtime_error(std::format("{} defines CrafterBuildConfigurations, which LoadProject cannot return by value; load it with LoadConfigurations", absProject.string()));
|
||||
}
|
||||
return entry.one(args);
|
||||
}
|
||||
|
||||
std::vector<Configuration*> Crafter::LoadConfigurations(const fs::path& projectFile, std::span<const std::string_view> args) {
|
||||
RequireToolchain();
|
||||
const fs::path absProject = fs::canonical(projectFile);
|
||||
ProjectFileGuard guard(absProject);
|
||||
const ProjectEntry entry = OpenProjectFile(guard, args);
|
||||
if (entry.one) {
|
||||
// The call's return value is the initialiser of the new-expression,
|
||||
// so the Configuration is constructed where it stays and is never
|
||||
// moved; std::make_unique would move a temporary into place. A
|
||||
// project file takes pointers to the configuration it returns, for a
|
||||
// test that links the library it describes (cfg.AddTest(...)
|
||||
// .Dependencies({ &cfg })), and they are pointers to this object
|
||||
// when the compiler constructed the local the file returns in place
|
||||
// of the return value, as clang does for a function that returns one
|
||||
// local.
|
||||
std::unique_ptr<Configuration> returned(new Configuration(entry.one(args)));
|
||||
Configuration* const configuration = returned.get();
|
||||
const std::lock_guard lock(ReturnedConfigurationsMutex);
|
||||
ReturnedConfigurations.push_back(std::move(returned));
|
||||
return { configuration };
|
||||
}
|
||||
|
||||
std::vector<Configuration*> configurations = entry.several(args);
|
||||
if (configurations.empty()) {
|
||||
throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned no configuration", absProject.string()));
|
||||
}
|
||||
std::unordered_set<const Configuration*> seen;
|
||||
for (const Configuration* configuration : configurations) {
|
||||
if (!configuration) {
|
||||
throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned a null pointer", absProject.string()));
|
||||
}
|
||||
// Most often a pasted `&lib` where `&tool` was meant, which would
|
||||
// leave `tool` unbuilt without a word.
|
||||
if (!seen.insert(configuration).second) {
|
||||
throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned {} twice", absProject.string(), configuration->name));
|
||||
}
|
||||
// One that a project GitProject or LocalProject loaded keeps to
|
||||
// itself, taken out of the `dependencies` or the `tests` of what
|
||||
// that project's file returned. Returned from here it would count
|
||||
// as one this file
|
||||
// made: `test` would run its tests and `run` offer its scripts,
|
||||
// which are that project's. And only the configurations a project
|
||||
// file returns are rebased onto its directory, so this one would be
|
||||
// built wherever its relative `path` leads from here.
|
||||
if (const std::optional<LoadedProject> keeper = KeptBy(*configuration)) {
|
||||
throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned {}, which {} keeps to itself: a project file returns the configurations it makes and the ones GitProject or LocalProject returned", absProject.string(), configuration->name, keeper->name));
|
||||
}
|
||||
}
|
||||
return configurations;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,11 +11,18 @@ namespace fs = std::filesystem;
|
|||
using namespace Crafter;
|
||||
|
||||
namespace {
|
||||
std::string JoinNames(std::span<const Script> scripts) {
|
||||
// A script and the configuration it is declared on, which is the
|
||||
// project its callback is handed.
|
||||
struct Declared {
|
||||
const Script* script;
|
||||
Configuration* owner;
|
||||
};
|
||||
|
||||
std::string JoinNames(std::span<const Declared> scripts) {
|
||||
std::string out;
|
||||
for (const Script& script : scripts) {
|
||||
for (const Declared& declared : scripts) {
|
||||
if (!out.empty()) out += ", ";
|
||||
out += script.name;
|
||||
out += declared.script->name;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
@ -29,10 +36,22 @@ std::int32_t ScriptContext::Run(std::string_view command) const {
|
|||
}
|
||||
|
||||
std::int32_t Crafter::RunScript(Configuration& projectCfg, const RunScriptOptions& opts) {
|
||||
std::array<Configuration*, 1> one = { &projectCfg };
|
||||
return RunScript(std::span<Configuration* const>(one), opts);
|
||||
}
|
||||
|
||||
std::int32_t Crafter::RunScript(std::span<Configuration* const> configurations, const RunScriptOptions& opts) {
|
||||
// Loading the project may have left an in-place status line behind.
|
||||
Progress::Clear();
|
||||
|
||||
const std::span<const Script> scripts = projectCfg.scripts;
|
||||
std::vector<Declared> scripts;
|
||||
std::unordered_set<const Configuration*> listed;
|
||||
for (Configuration* cfg : configurations) {
|
||||
// Once, however often the list names it: its scripts are not names
|
||||
// declared twice.
|
||||
if (!listed.insert(cfg).second) continue;
|
||||
for (const Script& script : cfg->scripts) scripts.push_back({ &script, cfg });
|
||||
}
|
||||
if (scripts.empty()) {
|
||||
std::println(std::cerr,
|
||||
R"msg(No scripts defined.
|
||||
|
|
@ -51,7 +70,8 @@ returned; ctx.args holds the arguments.)msg");
|
|||
// declaration is reported the first time anyone uses `run` and not only
|
||||
// when that one name is asked for.
|
||||
std::unordered_set<std::string_view> seen;
|
||||
for (const Script& script : scripts) {
|
||||
for (const Declared& declared : scripts) {
|
||||
const Script& script = *declared.script;
|
||||
if (script.name.empty() || script.name.starts_with('-')) {
|
||||
std::println(std::cerr, "script name '{}' cannot be run: a name must not be empty or start with '-'", script.name);
|
||||
return 1;
|
||||
|
|
@ -69,36 +89,37 @@ returned; ctx.args holds the arguments.)msg");
|
|||
}
|
||||
|
||||
if (opts.listOnly || !opts.named) {
|
||||
for (const Script& script : scripts) std::println("{}", script.name);
|
||||
for (const Declared& declared : scripts) std::println("{}", declared.script->name);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const auto found = std::ranges::find(scripts, opts.name, &Script::name);
|
||||
const auto found = std::ranges::find_if(scripts, [&](const Declared& declared) { return declared.script->name == opts.name; });
|
||||
if (found == scripts.end()) {
|
||||
std::println(std::cerr, "No script named '{}'. Scripts: {}", opts.name, JoinNames(scripts));
|
||||
return 1;
|
||||
}
|
||||
const Script& script = *found->script;
|
||||
|
||||
ScriptContext ctx{
|
||||
.project = projectCfg,
|
||||
.project = *found->owner,
|
||||
// lexically_normal: fs::absolute keeps a "./" component.
|
||||
.projectDir = opts.projectFile.empty() ? fs::absolute(projectCfg.path).lexically_normal() : opts.projectFile.parent_path(),
|
||||
.projectDir = opts.projectFile.empty() ? fs::absolute(found->owner->path).lexically_normal() : opts.projectFile.parent_path(),
|
||||
.args = opts.args,
|
||||
};
|
||||
try {
|
||||
const std::int32_t code = found->run(ctx);
|
||||
const std::int32_t code = script.run(ctx);
|
||||
if (code >= 0 && code <= 255) return code;
|
||||
std::println(std::cerr, "script '{}' returned {}, which is not an exit status (0..255); exiting with 1", found->name, code);
|
||||
std::println(std::cerr, "script '{}' returned {}, which is not an exit status (0..255); exiting with 1", script.name, code);
|
||||
return 1;
|
||||
} catch (const std::exception& e) {
|
||||
// Never let a script's exception unwind across the project.so
|
||||
// boundary and out of Run: report it as this script's failure.
|
||||
Progress::Clear();
|
||||
std::println(std::cerr, "script '{}' failed: {}", found->name, e.what());
|
||||
std::println(std::cerr, "script '{}' failed: {}", script.name, e.what());
|
||||
return 1;
|
||||
} catch (...) {
|
||||
Progress::Clear();
|
||||
std::println(std::cerr, "script '{}' failed: it threw something that isn't a std::exception", found->name);
|
||||
std::println(std::cerr, "script '{}' failed: it threw something that isn't a std::exception", script.name);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -111,7 +111,8 @@ namespace {
|
|||
}
|
||||
|
||||
namespace {
|
||||
std::atomic<Configuration*> ParentProject{nullptr};
|
||||
std::mutex ParentProjectsMutex;
|
||||
std::vector<Configuration*> ParentProjects;
|
||||
|
||||
Configuration* FindLibInTree(Configuration* root, std::string_view name, std::unordered_set<Configuration*>& seen) {
|
||||
if (!seen.insert(root).second) return nullptr;
|
||||
|
|
@ -124,17 +125,31 @@ namespace {
|
|||
}
|
||||
|
||||
void Crafter::SetParentProject(Configuration* parent) {
|
||||
ParentProject.store(parent);
|
||||
SetParentProject(parent ? std::span<Configuration* const>(&parent, 1) : std::span<Configuration* const>());
|
||||
}
|
||||
|
||||
void Crafter::SetParentProject(std::span<Configuration* const> parents) {
|
||||
const std::lock_guard lock(ParentProjectsMutex);
|
||||
ParentProjects.assign(parents.begin(), parents.end());
|
||||
}
|
||||
|
||||
Configuration* Crafter::ParentLib(std::string_view name) {
|
||||
Configuration* root = ParentProject.load();
|
||||
if (!root) {
|
||||
std::vector<Configuration*> roots;
|
||||
{
|
||||
const std::lock_guard lock(ParentProjectsMutex);
|
||||
roots = ParentProjects;
|
||||
}
|
||||
if (roots.empty()) {
|
||||
throw std::runtime_error(std::format("Crafter::ParentLib('{}'): no parent project set", name));
|
||||
}
|
||||
std::unordered_set<Configuration*> seen;
|
||||
if (auto found = FindLibInTree(root, name, seen)) return found;
|
||||
throw std::runtime_error(std::format("Crafter::ParentLib('{}'): not found in parent project '{}'", name, root->name));
|
||||
std::string names;
|
||||
for (Configuration* root : roots) {
|
||||
if (auto found = FindLibInTree(root, name, seen)) return found;
|
||||
if (!names.empty()) names += ", ";
|
||||
names += root->name;
|
||||
}
|
||||
throw std::runtime_error(std::format("Crafter::ParentLib('{}'): not found in parent project '{}'", name, names));
|
||||
}
|
||||
|
||||
TestRunner TestRunner::Local() {
|
||||
|
|
@ -449,9 +464,22 @@ void Crafter::UnpackageTests(Configuration& cfg) {
|
|||
}
|
||||
|
||||
TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
|
||||
UnpackageTests(projectCfg);
|
||||
std::array<Configuration*, 1> one = { &projectCfg };
|
||||
return RunTests(std::span<Configuration* const>(one), opts, projectArgs);
|
||||
}
|
||||
|
||||
TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
|
||||
// Each of them once, however often the list names it: named twice, a
|
||||
// configuration would have each of its tests built twice at once.
|
||||
std::vector<Configuration*> distinct;
|
||||
for (Configuration* cfg : configurations) {
|
||||
if (!std::ranges::contains(distinct, cfg)) distinct.push_back(cfg);
|
||||
}
|
||||
if (distinct.size() != configurations.size()) return RunTests(distinct, opts, projectArgs);
|
||||
|
||||
for (Configuration* cfg : configurations) UnpackageTests(*cfg);
|
||||
// Multi-target sweep: when no --target= was given, the run covers every
|
||||
// distinct target declared across projectCfg.tests plus the host target.
|
||||
// distinct target declared across the tests plus the host target.
|
||||
// Lets a bare `crafter-build test` exercise cross-arch tests without the
|
||||
// user having to know which targets exist. An explicit --target=X
|
||||
// bypasses the sweep and runs that target only.
|
||||
|
|
@ -461,8 +489,10 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
|
|||
// the one shown and filtered on.
|
||||
std::map<std::string, std::string> sweep;
|
||||
sweep.emplace(NormalizeTarget(HostTarget()), HostTarget());
|
||||
for (const Test& t : projectCfg.tests) {
|
||||
if (!t.config.target.empty()) sweep.emplace(NormalizeTarget(t.config.target), t.config.target);
|
||||
for (const Configuration* cfg : configurations) {
|
||||
for (const Test& t : cfg->tests) {
|
||||
if (!t.config.target.empty()) sweep.emplace(NormalizeTarget(t.config.target), t.config.target);
|
||||
}
|
||||
}
|
||||
TestSummary aggregate;
|
||||
for (const auto& [normalized, target] : sweep) {
|
||||
|
|
@ -472,7 +502,7 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
|
|||
Progress::Clear();
|
||||
std::println("\n=== target: {} ===", target);
|
||||
}
|
||||
TestSummary s = RunTests(projectCfg, perTarget, projectArgs);
|
||||
TestSummary s = RunTests(configurations, perTarget, projectArgs);
|
||||
aggregate.passed += s.passed;
|
||||
aggregate.failed += s.failed;
|
||||
aggregate.crashed += s.crashed;
|
||||
|
|
@ -490,17 +520,22 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
|
|||
// time) because runnerOverride and FromEnv resolution depend on the
|
||||
// run's options, which the project.cpp doesn't know about.
|
||||
std::vector<Test*> filtered;
|
||||
filtered.reserve(projectCfg.tests.size());
|
||||
for (auto& test : projectCfg.tests) {
|
||||
if (!SameTarget(test.config.target, opts.targetFilter)) continue;
|
||||
if (!MatchAny(opts.globs, test.config.name)) continue;
|
||||
test.runner = TestRunner::FromEnv(test.config.target, TestRunner::ForTarget(test.config));
|
||||
if (opts.runnerOverride) {
|
||||
if (auto r = TestRunner::FromSpec(*opts.runnerOverride)) {
|
||||
test.runner = std::move(*r);
|
||||
// The configuration that declares each of them, whose path its log is
|
||||
// written under.
|
||||
std::vector<const Configuration*> owners;
|
||||
for (Configuration* cfg : configurations) {
|
||||
for (auto& test : cfg->tests) {
|
||||
if (!SameTarget(test.config.target, opts.targetFilter)) continue;
|
||||
if (!MatchAny(opts.globs, test.config.name)) continue;
|
||||
test.runner = TestRunner::FromEnv(test.config.target, TestRunner::ForTarget(test.config));
|
||||
if (opts.runnerOverride) {
|
||||
if (auto r = TestRunner::FromSpec(*opts.runnerOverride)) {
|
||||
test.runner = std::move(*r);
|
||||
}
|
||||
}
|
||||
filtered.push_back(&test);
|
||||
owners.push_back(cfg);
|
||||
}
|
||||
filtered.push_back(&test);
|
||||
}
|
||||
|
||||
if (opts.listOnly) {
|
||||
|
|
@ -515,6 +550,38 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
|
|||
return summary;
|
||||
}
|
||||
|
||||
// A test is built in a directory named after the test and what it is
|
||||
// compiled as, not after the configuration that declares it, and its
|
||||
// sources are tests/<name> whichever one does. Two configurations that
|
||||
// each declare a test of one name, compiled alike, would have the two
|
||||
// built in that one directory, at once when the run has the jobs for
|
||||
// it, each with the dependencies and link flags of its own declaration.
|
||||
// Neither is built: both fail, and say which configurations declare
|
||||
// them. Only tests of different configurations are looked at: a test
|
||||
// one configuration declares twice is as it was.
|
||||
std::vector<std::string> clashes(filtered.size());
|
||||
{
|
||||
std::unordered_map<fs::path, std::vector<std::size_t>> builtInto;
|
||||
for (std::size_t i = 0; i < filtered.size(); ++i) {
|
||||
builtInto[fs::absolute(filtered[i]->config.PcmDir()).lexically_normal()].push_back(i);
|
||||
}
|
||||
for (const auto& [directory, sharing] : builtInto) {
|
||||
std::vector<const Configuration*> declaring;
|
||||
for (const std::size_t i : sharing) {
|
||||
if (!std::ranges::contains(declaring, owners[i])) declaring.push_back(owners[i]);
|
||||
}
|
||||
if (declaring.size() < 2) continue;
|
||||
std::string names;
|
||||
for (const Configuration* cfg : declaring) {
|
||||
if (!names.empty()) names += ", ";
|
||||
names += cfg->name;
|
||||
}
|
||||
for (const std::size_t i : sharing) {
|
||||
clashes[i] = std::format("{} each declare a test named {}, which would be built for each of them in {}: give each test a name of its own", names, filtered[i]->config.name, directory.string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::int32_t jobs = opts.jobs > 0
|
||||
? opts.jobs
|
||||
: std::max(1u, std::thread::hardware_concurrency());
|
||||
|
|
@ -549,6 +616,18 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
|
|||
TestResult r;
|
||||
r.name = t.config.name;
|
||||
|
||||
if (!clashes[i].empty()) {
|
||||
r.outcome = TestOutcome::Fail;
|
||||
r.output = clashes[i];
|
||||
r.exitCode = -1;
|
||||
{
|
||||
std::lock_guard lk(printMutex);
|
||||
PrintResult(r, t.runner.name);
|
||||
}
|
||||
results[i] = std::move(r);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Declarative preconditions set via TestBuilder::Requires. Evaluated
|
||||
// before the build so a missing tool/file/env turns into a Skip without
|
||||
// paying the compile cost. Reports the first failure only — once one
|
||||
|
|
@ -632,7 +711,7 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
|
|||
}
|
||||
|
||||
if (r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped && !r.output.empty()) {
|
||||
WriteLog(projectCfg.path, r.name, r.output);
|
||||
WriteLog(owners[i]->path, r.name, r.output);
|
||||
}
|
||||
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue