Crafter.Build/tests/Script/main.cpp

296 lines
15 KiB
C++
Raw Normal View History

// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// `crafter-build run <name> [args...]` runs a script project.cpp put in
// cfg.scripts and exits with what the script returned.
//
// Two things are easy to get wrong and expensive when they are. The words
// after the script's name belong to the script: read by crafter-build
// instead, `run package clean` deletes the build tree, `run package --help`
// prints the wrong help, and anything else lands in the project's args,
// where it changes the variant hash and so the directory the project builds
// into. And the exit code is the script's whole result: collapsed to 0 or 1
// it loses what a caller branches on, and passed through unchecked a value
// such as 256 wraps to success.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
std::int32_t RunWith(std::vector<std::string> args) {
std::vector<char*> argv;
for (std::string& arg : args) argv.push_back(arg.data());
return Run(static_cast<std::int32_t>(argv.size()), argv.data());
}
std::vector<std::string> ReadLines(const fs::path& file) {
std::vector<std::string> lines;
std::ifstream in(file);
for (std::string line; std::getline(in, line);) lines.push_back(line);
return lines;
}
// One script that returns `code`, run by name.
std::int32_t RunReturning(std::int32_t code) {
Configuration cfg;
cfg.scripts.push_back({"it", [code](ScriptContext&) { return code; }});
return RunScript(cfg, {.name = "it", .named = true});
}
// LoadProject compiles a project file against the installed module
// sources; without them the command-line cases cannot run at all.
bool ModuleSourcesInstalled() {
try {
return fs::exists(GetCrafterBuildHome() / "Crafter.Build.cppm");
} catch (const std::exception&) {
return false;
}
}
}
int main() {
const fs::path fixture = fs::current_path() / "tests" / "Script" / "fixture";
const fs::path scratch = fs::temp_directory_path() / "crafter-build-script";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::create_directories(scratch);
fs::copy(fixture, scratch, fs::copy_options::recursive);
// The script gets the project, the project's directory and its
// arguments exactly as given, and its return value comes back.
{
Configuration cfg;
std::int32_t calls = 0;
std::vector<std::string> seen;
const Configuration* seenProject = nullptr;
fs::path seenDir;
cfg.scripts.push_back({"other", [&](ScriptContext&) {
++calls;
return 9;
}});
cfg.scripts.push_back({"pass", [&](ScriptContext& ctx) {
++calls;
seen.assign(ctx.args.begin(), ctx.args.end());
seenProject = &ctx.project;
seenDir = ctx.projectDir;
return 3;
}});
const std::vector<std::string> given = {"a", "--help", "", "two words", "it's"};
const std::int32_t code = RunScript(cfg, {.name = "pass", .named = true, .args = given, .projectFile = scratch / "project.cpp"});
Check(code == 3, std::format("the script's return value is the result (got {})", code));
Check(calls == 1, std::format("only the named script ran (ran {})", calls));
Check(seen == given, "the arguments arrive verbatim, empty ones and option-like ones included");
Check(seenProject == &cfg, "ctx.project is the configuration the script was declared on");
Check(seenDir == scratch, std::format("ctx.projectDir is the project file's directory (got '{}')", seenDir.string()));
// Asking for the list runs nothing, with or without a name.
calls = 0;
Check(RunScript(cfg, {}) == 0, "a run without a name lists and succeeds");
Check(RunScript(cfg, {.name = "pass", .named = true, .listOnly = true}) == 0, "--list succeeds");
Check(calls == 0, "listing runs no script");
// A name nobody declared. The empty string is one: it is a name
// that was given, not the absence of a name.
Check(RunScript(cfg, {.name = "nope", .named = true}) == 1, "an unknown name fails");
Check(RunScript(cfg, {.name = "", .named = true}) == 1, "an empty name is looked up and fails instead of listing");
Check(RunScript(cfg, {.name = "pas", .named = true}) == 1, "names match exactly, not by prefix");
Check(calls == 0, "an unknown name runs no script");
}
test: several configurations from one project file BuildAll builds configurations the test makes itself, on a fresh copy of its fixture outside the checkout. A library, a program built on it and an unrelated program all come out built, each in the record of the pass under its PcmDir, and a list that names one configuration twice builds it from nothing, what the build before left of it being removed first, and leaves it in the record of the pass once. A library built on another library of its own name, path and type, so that the two are built into one directory, builds, with both archives in that directory; returned beside a program that is built on it, the pair is refused, both by name, before the program is built or anything is recorded. Two libraries that are each built on a configuration of the other's directory are refused by name, and nothing of them is built or recorded. A wasm32 library that names no sysroot and a program for the host built on it leave the library in the record once, under the directory it has after the pass, and its refusal comes back once; it is refused for its -fno-exceptions, so the case needs no WASI sysroot. Of two programs built on a library that does not compile and a third that has nothing to do with it, the third is built, the two are not, and the library's error comes back once. Two configurations that would be built into one directory are refused, and neither is built. With a wasm executable that declares a variant among them, a program of one source is linked no earlier than the program and library given before it; the wasm one is refused for its -fno-exceptions before it builds anything, so the case needs no WASI sysroot. ProjectConfigurations loads fixture project files staged outside the checkout. A file with CrafterBuildConfigurations comes back as the three configurations it returns, with the pointer the file took from the second to the first intact, and as two when its args say so; LoadProject refuses it. A file with CrafterBuildProject comes back as a list of one whose test still depends on that Configuration, and that test builds and passes. A file with both entry points, one with neither, and ones whose CrafterBuildConfigurations returns nothing, a null pointer or one configuration twice are refused, each with a message that says which. Then crafter-build's verbs, through Run() and RunTests, on the file of three: a build builds all three; -r refuses to pick between its two executables, and runs the one executable there is when the file returns two configurations; RunTests runs the tests of the first and the third configuration in one run, and when the first declares the third's test as well, that test fails for both, naming the two, and is not built, while the first's own test passes, and a list that names the first configuration twice runs its test once; with a fourth configuration of the third's name and path, a test run and a build are each refused for the two that would be built into one directory, and neither writes the AGENTS.md that a build which is not refused writes from the template the test puts beside the project file; `run` reaches a script of the first and of the third configuration and hands each the configuration that declares it; install refuses the project while none of the three is packaged, bundle refuses it when two are, and with one packaged executable beside the library bundle does not take the library for the app. SiblingConfigurations loads such a file as another project's sibling. A spec without `configuration` gets the first, a spec that names one gets that one, and the three specs share one load: the dependency of the second is the first as LocalProject returned it. All three are rebased onto the sibling's directory. A name the sibling does not have throws with the names it has, and a name that two configurations of another fixture share throws too, while a spec without a name still gets the first of those two. Building the second builds the first with it and leaves the third unbuilt. A file that returns something a sibling keeps to itself is refused when it is loaded, the configuration and the sibling named: the library the sibling's program is built on, the configuration of that program's test, and a helper only that test is built on, none of which the sibling's file returns. A project that returns the sibling's third configuration beside one of its own builds both, cannot run the sibling's script and runs its own, and its test run leaves the sibling's test alone. DependencyNotes gains a project of two configurations and a fixture, outer, that builds against lib: two Direct configurations give what each of them names; a project a Direct one names is followed when a Transitive one leads to it; a configuration under None keeps out what only it is built against; with both under None, AGENTS.md is the template's text; and a returned configuration of another project is one of the projects the notes come from, followed further only under Transitive, which is also what a file that made no configuration gets. For outer's own AGENTS.md, written from the Configuration LocalProject returned and outer's project file, outer's own setting selects: lib under Direct, lib and base under Transitive, nothing under None. Script runs a script of each of two configurations, each handed the configuration that declares it, refuses a name both declare without running anything, and, given a list that names one configuration twice, runs the script asked for, which a name declared twice would have kept it from. Lint formats the sources of two configurations in one run, counts a rule both register as one, and runs a rule only one of them registers over the sources of both. Of two returned configurations that register a rule under one name the earlier one's runs, over the sources of all three, though the configuration returned ahead of both depends on the later one.
2026-11-15 02:16:07 +01:00
// The configurations a project file returns: their scripts are one list,
// each handed the configuration that declares it, and a name two of
// them declare is a name declared twice.
{
Configuration first;
Configuration second;
const Configuration* seenProject = nullptr;
first.scripts.push_back({"one", [&](ScriptContext& ctx) {
seenProject = &ctx.project;
return 1;
}});
second.scripts.push_back({"two", [&](ScriptContext& ctx) {
seenProject = &ctx.project;
return 2;
}});
std::array<Configuration*, 2> both = { &first, &second };
Check(RunScript(both, {.name = "two", .named = true}) == 2 && seenProject == &second, "a script of the second configuration runs, handed that configuration");
Check(RunScript(both, {.name = "one", .named = true}) == 1 && seenProject == &first, "and one of the first is handed the first");
// Named twice in the list, the first would declare "one" twice,
// which is refused with the status the script itself returns: only
// the script having run tells the two apart.
std::array<Configuration*, 2> same = { &first, &first };
seenProject = nullptr;
Check(RunScript(same, {.name = "one", .named = true}) == 1 && seenProject == &first, "a list that names one configuration twice declares its scripts once, and the script runs");
seenProject = nullptr;
second.scripts.push_back({"one", [&](ScriptContext& ctx) {
seenProject = &ctx.project;
return 0;
}});
Check(RunScript(both, {.name = "two", .named = true}) == 1 && seenProject == nullptr, "a name two configurations declare is refused, and nothing runs");
}
// The exit status passes through whole, and only an exit status does.
Check(RunReturning(0) == 0, "0 stays 0");
Check(RunReturning(1) == 1, "1 stays 1");
Check(RunReturning(77) == 77, "77 stays 77");
Check(RunReturning(255) == 255, "255 stays 255");
Check(RunReturning(256) == 1, "256 would wrap to success as an exit status and becomes 1");
Check(RunReturning(-1) == 1, "a negative value becomes 1");
// A script that throws is that script's failure, not a crash.
{
Configuration cfg;
cfg.scripts.push_back({"throws", [](ScriptContext&) -> std::int32_t { throw std::runtime_error("no such tool"); }});
Check(RunScript(cfg, {.name = "throws", .named = true}) == 1, "a throwing script exits 1");
cfg.scripts.push_back({"throwsInt", [](ScriptContext&) -> std::int32_t { throw 7; }});
Check(RunScript(cfg, {.name = "throwsInt", .named = true}) == 1, "and so does one throwing something that isn't a std::exception");
}
// Declarations that cannot work are refused before anything runs, also
// when a different, valid script was asked for.
{
Configuration none;
Check(RunScript(none, {.name = "it", .named = true}) == 1, "a project without scripts fails");
Check(RunScript(none, {}) == 1, "listing a project without scripts fails too");
std::int32_t calls = 0;
const auto count = [&](ScriptContext&) {
++calls;
return 0;
};
Configuration twice;
twice.scripts.push_back({"a", count});
twice.scripts.push_back({"b", count});
twice.scripts.push_back({"a", count});
Check(RunScript(twice, {.name = "b", .named = true}) == 1, "a name declared twice fails the run");
Check(RunScript(twice, {}) == 1, "a name declared twice fails the list");
Configuration dashed;
dashed.scripts.push_back({"ok", count});
dashed.scripts.push_back({"-x", count});
Check(RunScript(dashed, {.name = "ok", .named = true}) == 1, "a name starting with '-' could never be typed and is refused");
Configuration unnamed;
unnamed.scripts.push_back({"", count});
Check(RunScript(unnamed, {.name = "", .named = true}) == 1, "an empty name is refused");
Configuration hollow;
hollow.scripts.push_back({"hollow", nullptr});
Check(RunScript(hollow, {.name = "hollow", .named = true}) == 1, "a script without a callback is refused");
Check(calls == 0, "none of these ran a script");
}
// ctx.Run: the command's real exit code, a signal death the way a shell
// reports it, and ShellQuote carrying awkward text through sh intact.
{
const std::string awkward = "it's a \"test\" $HOME `id` \\ *";
const fs::path echoed = scratch / "echoed file.txt";
Configuration cfg;
cfg.scripts.push_back({"exit", [](ScriptContext& ctx) { return ctx.Run("exit 7"); }});
cfg.scripts.push_back({"signal", [](ScriptContext& ctx) { return ctx.Run("kill -TERM $$"); }});
cfg.scripts.push_back({"quote", [&](ScriptContext& ctx) { return ctx.Run(std::format("printf %s {} > {}", ShellQuote(awkward), ShellQuote(echoed.string()))); }});
// A script is usually several commands: stop at the first failure.
cfg.scripts.push_back({"steps", [&](ScriptContext& ctx) {
if (const std::int32_t code = ctx.Run("exit 5"); code != 0) return code;
return ctx.Run(std::format("touch {}", ShellQuote((scratch / "not-reached").string())));
}});
Check(RunScript(cfg, {.name = "exit", .named = true}) == 7, "ctx.Run returns the command's exit code");
Check(RunScript(cfg, {.name = "signal", .named = true}) == 143, "a command killed by SIGTERM reads as 128+15");
Check(RunScript(cfg, {.name = "quote", .named = true}) == 0, "a quoted command line runs");
const std::vector<std::string> lines = ReadLines(echoed);
Check(lines.size() == 1 && lines[0] == awkward, "ShellQuote passes quotes, spaces and expansions through sh untouched");
Check(RunScript(cfg, {.name = "steps", .named = true}) == 5, "a failed step's code can be returned as the script's");
Check(!fs::exists(scratch / "not-reached"), "and the steps after it do not run");
}
if (!ModuleSourcesInstalled()) {
// A skip must never cover for a failure above.
if (Failures > 0) return 1;
std::println(std::cerr, "SKIP: no module sources to load the fixture project with");
return 77;
}
// The same through the command line, where the parsing lives. Sentinels
// stand in for a built project: a word after `run` that is read as the
// clean verb takes them with it.
const std::string project = std::format("--project={}", (scratch / "project.cpp").string());
const fs::path binSentinel = scratch / "bin" / "sentinel";
const fs::path buildSentinel = scratch / "build" / "sentinel";
fs::create_directories(binSentinel.parent_path());
fs::create_directories(buildSentinel.parent_path());
std::ofstream(binSentinel) << "binary";
std::ofstream(buildSentinel) << "object";
// Everything after the name is the script's, including this tool's own
// options and verbs; what stands before `run` is still the project's.
{
const std::int32_t code = RunWith({"crafter-build", project, "--flavour=x", "run", "record", "a", "--help", "-v", "clean", "--debug", "--version", "run"});
Check(code == 42, std::format("the script ran and its return value is the exit code (got {})", code));
const std::vector<std::string> expected = {
"arg:a", "arg:--help", "arg:-v", "arg:clean", "arg:--debug", "arg:--version", "arg:run",
"projectArg:--flavour=x",
"debug:false",
"project:script-fixture",
};
const std::vector<std::string> record = ReadLines(scratch / "record.txt");
Check(record == expected, "the script got every word after its name and the project args got none of them");
if (record != expected) {
for (const std::string& line : record) std::println(std::cerr, " recorded: {}", line);
}
Check(fs::exists(binSentinel) && fs::exists(buildSentinel), "`clean` as a script argument deleted nothing");
}
// `--` ends this tool's options and goes nowhere itself. In the
// project's args it gave the project a variant of its own, and every
// sibling that inherits the args one too. The word after it is an
// operand even when it looks like an option, here the script's name;
// after the name, a `--` is the script's like any other word.
{
fs::remove(scratch / "record.txt");
const std::int32_t code = RunWith({"crafter-build", project, "--flavour=x", "run", "--", "record", "--", "a"});
Check(code == 42, std::format("the script after `--` ran (got {})", code));
const std::vector<std::string> expected = {
"arg:--", "arg:a",
"projectArg:--flavour=x",
"debug:false",
"project:script-fixture",
};
const std::vector<std::string> record = ReadLines(scratch / "record.txt");
Check(record == expected, "`--` reached neither the project args nor the script");
if (record != expected) {
for (const std::string& line : record) std::println(std::cerr, " recorded: {}", line);
}
Check(RunWith({"crafter-build", project, "run", "--", "-x"}) == 1, "after `--` a word that looks like an option names the script");
}
// The first word after `run` is the name even when it is a verb.
{
fs::remove(scratch / "record.txt");
Check(RunWith({"crafter-build", project, "run", "clean"}) == 1, "`run clean` looks for a script called clean");
Check(fs::exists(binSentinel) && fs::exists(buildSentinel), "`run clean` deleted nothing");
Check(RunWith({"crafter-build", project, "run", "help"}) == 1, "`run help` looks for a script called help");
}
Check(RunWith({"crafter-build", project, "run", "shell"}) == 7, "a command's exit code reaches the process exit code");
Check(RunWith({"crafter-build", project, "run", "-q", "shell"}) == 7, "an option between `run` and the name is still this tool's");
Check(RunWith({"crafter-build", project, "run"}) == 0, "a bare `run` lists");
Check(RunWith({"crafter-build", project, "run", "--list"}) == 0, "`run --list` lists");
Check(!fs::exists(scratch / "record.txt"), "listing ran no script");
Check(RunWith({"crafter-build", project, "run", "nope"}) == 1, "an unknown script fails");
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}