Compare commits

..
Author SHA1 Message Date
c144528481
docs(packaging): add the 6.5.0 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 14m55s
6.5.0 gives a test that sets Test::wayland a headless compositor of its
own, so that the windows a test opens through WAYLAND_DISPLAY no longer
show up on the desktop of whoever runs the suite, ships weston in the
Flatpak for it, and runs every test's command with a TMPDIR of its own,
so that two runs of `crafter-build test` at once no longer write into
each other's temporary files where the test's runner hands it TMPDIR,
as running it directly and qemu-user do, and wine and wasmtime do not.

A minor release, by the version rule: the notes have New and Fixes and
nothing Breaking. The range adds Test::wayland, TestBuilder::Wayland,
TestResult::compositorLog, RunTestsOptions::compositorOverride and the
export of PrivateDirectory, and two parameters at the end of
RunSingleTest, both with defaults, so that the calls to it that
compiled before compile unchanged.
2026-11-28 11:05:51 +01:00
e643f83c00
docs: the TMPDIR each test's command runs with
The README's test conventions say that each test runs with TMPDIR
naming a directory of its own, made for the run, so that
fs::temp_directory_path() in it is the test's alone while another run
goes on, where its runner hands it TMPDIR, which wine does not, a
Windows test's TMP, TEMP and temp directory being the Wine prefix's
whatever the environment gives, and wasmtime, which hands a test no
environment, does not either; how much longer its path is, which a test
that binds a socket there has to leave room for; that what it leaves
there is removed when it passes or skips and kept, with its place in
its log, when it does not; that a later run removes what was kept once
the run's directory has gone a minute unchanged, a minute after that
run ended or, where it was killed, after its last change to it; and
that a test that builds against a sysroot it stages there, or has
crafter-build fetch a repository it stages there, whose path keys
crafter-build's cache and is a new one every run, points XDG_CACHE_HOME
into its TMPDIR as well.

AGENTS.template.md's testing conventions say why the fixed staging
name is safe now, that a test that writes to /tmp by name makes a
directory of its own there, a PrivateDirectory, and that a test that
builds against what it stages keeps its cache in its scratch directory.
2026-11-28 11:05:51 +01:00
0602e282b2
test: HostFlatpak asks about projects in a directory of its own
In the Flatpak, HostFlatpak makes two projects in the sandbox's /tmp,
one there and one through a link in the fixture's build/ that leads
there, and asks whether the host sees them. They had fixed names,
/tmp/crafter-build-host-flatpak and crafter-build-host-flatpak-linked
beside it, and every sandbox of the app has the same /tmp, so two runs
at once asked about, and removed, the same projects. Both are now in a
directory the test makes there, a PrivateDirectory, which the link
leads to, and which goes afterwards with the link, or, when the test is
killed, when a later one is made, once it has not changed for a minute.
The test still names /tmp rather than the TMPDIR it is given, since the
sandbox's /tmp is what it asks the host about, and AGENTS.template.md's
entry for it says it makes a directory of its own there now.
2026-11-28 11:05:51 +01:00
ab8935826d
test: what a test leaves in its TMPDIR, kept when it fails, else gone
TestTemporaryDirectory runs a probe through RunTests that records the
TMPDIR it was given and the directory fs::temp_directory_path() names,
leaves a file there and exits as it is told. Two configurations each
declare a passing test named probe, built differently so that the run
does not refuse them, and the second also a failing one and one for
another target, the host's own triple without its vendor and with x32
after it, which is never the host's and makes a second pass after the
host's, and is skipped before it is built. The run takes one test at a
time, so the failing one comes last in the host's pass, and it dates
the run's directory, and a directory beside it that looks like one a
run let go of, two minutes back before it fails, as a test that ran
that long leaves them. Each test's fs::temp_directory_path() is the
TMPDIR it was given: <run>/<name>, in a directory made for the run in
the temp directory, and probe-2 for the second probe. What the passing
tests left is removed; what the failing one left is kept, named in its
output and its log, and so is the run's directory. A second run gets a
directory of its own, removes it since every test passed, and leaves
the first run's alone; a third, once that one is dated past the minute,
removes it. The other target's pass makes no directory of its own: the
one dated back beside the run's is still there when the run ends. A
fourth run, whose pass for the other target throws, as one does where
CRAFTER_BUILD_RUNNER_ names that target's runner wrong, keeps what its
first pass kept.

The runs make their directories in a temp directory the test makes for
them and names with TMPDIR. The test removes only its own scratch
directory, which holds that one, and the fixture's bin/ and build/, and
dates a directory a probe reports only when it is a run's directory in
that temp directory.

HeadlessCompositor checks that a test that sets wayland and is given a
TMPDIR runs with both: the TMPDIR it is given and its compositor's
display alone, and that one under `host` and given a TMPDIR has it
beside the session's display. Two failing tests of one name each have a
log of their own, twin.log and twin-2.log, that says where what each
left is kept. RunSingleTestExit runs a script whose path has an '=' in
it, given a TMPDIR, which has to run and whose exit decides the
outcome.

Without TMPDIR on the test's command, 13 of TestTemporaryDirectory's
checks fail; with a test's log named after the test alone, the two on
the logs of the tests of one name do; without the date a kept directory
gets as it is let go of, the one on the second run leaving the first
run's alone does; with a directory of its own for a later pass, beside
the run's, the one on the other target's pass does; and with the
directory kept only once RunTests returns, the one on the fourth run
does. With the test's own words as env's command, the two of
RunSingleTestExit on the script whose path has an '=' fail.
2026-11-28 11:05:51 +01:00
93f1c8d9b9
fix(test): run each test's command with a TMPDIR of its own
Tests stage their fixtures under fixed names in the temp directory,
fs::temp_directory_path() / "crafter-build-<name>", and two runs at
once staged into the same ones: natively every process shares the
machine's /tmp, and every sandbox of crafter-build's Flatpak shares the
one the app has, whatever checkout it runs in. A test of one run could
find what it had staged removed or written over by the same test of the
other run, which removes the directory as it starts and stages its copy
anew.

RunTests now makes a directory for the run in the temp directory, a
PrivateDirectory, and runs each test with TMPDIR naming <run>/<name>,
so that fs::temp_directory_path() in the test names it and the fixed
names are the run's alone. The second test of one name in a run, as two
configurations or two targets may each have one, gets <name>-2, so that
removing one's directory does not take the other's. RunSingleTest takes
the directory as a new last parameter and puts TMPDIR into the env
prefix of the test's command, beside a Wayland test's WAYLAND_DISPLAY.
env's command is sh, which execs the test's words, as for a Wayland
test's: env takes a word with an '=' in it ahead of its command for an
assignment, a binary's path among them, and with no command left it
printed its environment and exited 0, a pass for a test that never ran.

What a test that passes or skips leaves is removed when it ends. What
one that fails, crashes or times out leaves is kept for a look, its log
says where, as does what is printed of a test that fails or crashes,
and the run's directory then outlives the run, unlocked, for a later
run to remove a minute after, or, where the run was killed, a minute
after its last change to it; PrivateDirectory gains Keep() for that. A
test's logs, build/test-logs/<name>.log and <name>.compositor.log, are
named as its TMPDIR is, <name>-2 for a later test of one name, so that
two failing tests of one name each keep their own, and with it where
what each left is kept: with one log for both, the second's was written
over the first's. The README's line on the logs says so. The directory
is dated as it is let go of, since the removal of abandoned directories
goes by its date, which is that of what was last made or removed in it:
for the run of a test that fails after a minute, as one that times out
at the default 60 s does, a minute old already, and the next run would
remove it at once. The removal now reads a directory's date only once
it holds the directory's lock: a date read before could be one the
holder replaced as it let go.

The directory is the run's, not a pass's: every pass of a sweep over
targets shares it, so it is made and its surroundings swept once, and
let go of once the last pass is done. A pass that made one of its own
would have made it once the passes before had let go of theirs, and
making it would have removed any of those that had not changed for a
minute: a kept one, after a pass of that long, while its test's output
said where it was. RunTests becomes the wrapper that holds the run's
directory around RunTestsWith, the passes it recurses into, and the
directory is kept the moment a test keeps something in it, by the
worker that ran the test, so that a later pass that throws, as one does
for a target whose runner CRAFTER_BUILD_RUNNER_ gives wrong, or a
worker that cannot be started does not take it with it; Keep() may be
called from several workers at once.

TMPDIR reaches the test where its runner hands it on, as running it
directly and qemu-user do. Under wine a Windows test does not get
TMPDIR, and takes the Wine prefix's TMP, TEMP and temp directory, and
wasmtime gives a test no environment at all; RunSingleTest's comment
says so. A test under `host` gets its TMPDIR as any test does, so that
comment and HostDisplay's now say that `host` leaves the test the
display, not the whole environment, as it is.

In the runner rather than in each of the 74 tests whose main.cpp uses
the temp directory at this commit: a project's own tests are covered
the same way, where their runner hands them TMPDIR. Of the 74 only
SysrootStdModule has to change. It builds against a sysroot it stages
there, and the std module's cache directory is keyed on the sysroot's
path, which is a new one every run now, so every run left one more
directory, with its lock, in the real cache; it keeps its cache in its
scratch directory now, as the tests that have crafter-build fetch a
repository they stage do. AGENTS.template.md says what changes for the
tests: HostFlatpak, whose /tmp is no longer the temp directory a test
is given, is a second test that writes elsewhere, and under
`crafter-build test` a staged copy goes with the test's TMPDIR rather
than at the test's next run.
2026-11-28 11:05:51 +01:00
fcfac0d9cf
docs: tests that open windows, and the compositor each one gets
The README's Tests section gains "Tests that open windows": a test that
sets Test::wayland, or .Wayland() on what AddTest returns, runs with a
headless compositor of its own instead of the session's display. It
says what crafter-build gives the compositor and the test and what it
does afterwards; the default weston command, weston 12 as the first
release that takes its --renderer=, and what its renderer and two
options are for; how CRAFTER_BUILD_COMPOSITOR, --compositor= and
`host` choose another; when the compositor fails the test, how a test
that may run without weston is skipped, and where the compositor's
output goes; and what a crafter-build that is killed leaves.
The CLI examples gain --compositor=host, and examples/tests/README.md's
list of the builder's methods gains .Wayland().
2026-11-28 11:05:51 +01:00
0a91b128cf
feat(packaging): ship a headless weston for tests that set wayland
A test that sets Test::wayland runs with the weston on PATH unless
another compositor is named, and the Sdk has none, so the Flatpak
builds one: weston 16.0.2 with its headless backend, its GL renderer
and its desktop shell, and with none of its other backends or shells
and no Vulkan renderer. Its frontend links libinput, libevdev and
libdisplay-info whatever the backend, and the Sdk has none of those
either, so three modules come before it: libevdev 1.14.0; libinput
1.32.0 without mtdev, libwacom or Lua plugins, of which only the
library and its licence ship, since the headless backend opens no
input device; and libdisplay-info 0.4.0, which weston would otherwise
fetch as a subproject. libinput is a git source pinned by commit, since
its 1.32.0 release has no tarball of its own.

The four sit just before the crafter-build module, so bumping them
rebuilds only them and crafter-build. weston's post-install runs
`weston --version` and checks that the backend and the renderer the
default command names are installed.
2026-11-28 11:05:51 +01:00
67e97d0a2a
test: a test's headless compositor, from its start to its cleanup
HeadlessCompositor drives RunSingleTest with itself in every part. The
harness starts it again as the compositor, which listens on a
wayland-7 socket in the XDG_RUNTIME_DIR it is given and records its
environment, and as the test, which records its own and connects.

A test that sets wayland passes against its compositor and runs with
WAYLAND_DISPLAY naming the compositor's socket, without DISPLAY and
WAYLAND_SOCKET, and with the XDG_RUNTIME_DIR of the process that runs
it. The compositor gets a directory of its own in that one, or in /tmp
where that process has none, and none of the WAYLAND_DISPLAY,
WAYLAND_SOCKET and DISPLAY that process has, each given a value of the
session's in the driver, and afterwards it has been sent SIGTERM, is
gone and so is its directory. The compositor's timeout(1) is the
test's, the wait for its socket and 30 s more, and none for a test with
no time limit; and a test whose binary's path has an '=' in it runs as
any other. A test that does not set wayland, and one run under `host`,
keep that display. Without an override CRAFTER_BUILD_COMPOSITOR names
the compositor, and an override wins over it. A compositor sh cannot
find fails the test with status 127, named, and a line on how a test
that may run without it is skipped; one that ends before it listens
fails it with its status and what it printed, checked on a word the
command does not hold, without running the test; a failing test keeps
what its compositor printed; a compositor killed while the test runs is
reported as ended. A stand-in crafter-build killed in the middle of a
test has its compositor sent SIGTERM and gone, and the directory it
leaves is removed when the next is made, once dated past the minute,
while one changed a moment ago and one that is held stay.

Without PR_SET_PDEATHSIG the two checks on the killed crafter-build
fail, and without the removal of abandoned directories the one on its
directory does; with the test's own words as env's command, the check
on the binary whose path has an '=' fails, with a limit of its own for
the compositor of a test with none the one on that limit does, without
what the compositor printed in the failure the one on that, with
WAYLAND_SOCKET left to the compositor and the test the ones on it, and
without the command in the failure of a compositor sh cannot find the
one on that, which looks for the harness's words, not sh's. No weston
is needed, so the suite runs it in the native loop and in the Flatpak's
build sandbox alike. The driver makes its compositors' directories in a
directory of its own in $XDG_RUNTIME_DIR, or in /tmp where that is not
a directory, rather than in the temp directory, since a socket's path
holds 107 bytes and a temp directory's path can use them up; its check
without an XDG_RUNTIME_DIR has the harness make that compositor's
directory in /tmp itself, as crafter-build does where there is none.
The driver's directory is a PrivateDirectory, now exported for it, so
that one a killed driver left goes when a later one is made, once it
has not changed for a minute, and AGENTS.template.md's line on where
tests write now says that what a test runs writes caches of its own,
crafter-build's builds and wasmtime the modules the wasm tests run, and
names this test as the one that writes anywhere else.
2026-11-28 11:05:51 +01:00
dc8e9e6f9e
feat(test): give a test that sets Test::wayland a compositor of its own
A test that opens a window opened it on the display of whoever ran the
suite: every `crafter-build test` of Crafter.Graphics put the windows
of its window tests on the desktop, and its other GPU tests connect to
the session's compositor too, since Device::Initialize calls
wl_display_connect whether a window follows or not.

A test that sets the new Test::wayland (TestBuilder::Wayland) now runs
with a headless compositor started for it alone. RunSingleTest starts
the compositor through sh, with XDG_RUNTIME_DIR naming a directory made
for it and without WAYLAND_DISPLAY, WAYLAND_SOCKET or DISPLAY, waits up
to 30 s for a wayland-<n> socket in that directory, runs the test with
WAYLAND_DISPLAY set to the socket's path and with DISPLAY and
WAYLAND_SOCKET unset, then stops the compositor's process group and
removes the directory. The test's command is env with those changes,
and env's command is sh, which execs the test's words: env takes every
word with an '=' in it ahead of its command for an assignment, a
binary's path among them. The compositor runs under timeout(1) as long
as the test may, the wait and 30 s more, and with no limit for a test
that has none, a timeout of 0. It is weston on its headless backend
with its GL renderer, unless CRAFTER_BUILD_COMPOSITOR or the new
--compositor= names another command; `host` gives the tests the
session's own display instead, to watch them. A compositor that ends
before it listens, sh not finding it included, or does not listen in
time fails the test with what it printed. A test that may run where its
compositor is missing declares it in requires_ (tool:weston for the
default), the check RunTests makes before the build, so no skip of its
own is added, and no probe of the command: the command is any sh
command, whose first word need not be the compositor. A test that
fails, crashes or times out keeps what its compositor printed
(TestResult::compositorLog), which RunTests writes to
build/test-logs/<name>.compositor.log, and says when the compositor
ended while it ran.

One compositor per test rather than one per run: no two tests share
one, so tests that run at once cannot cover each other's windows or
take each other's focus, for weston's start-up on every test. weston's
GL renderer, because it imports the dmabufs that a GPU's Vulkan driver
presents, as Mesa's and NVIDIA's do, and the headless backend's default
renderer and pixman import none: against pixman, the NVIDIA driver
reports no format for a window's surface, and Crafter.Graphics's
FrameLoopSync stops at its formatCount > 0 assertion. weston cannot
run the test itself, as `weston -- <test>` exits 0 whatever the test
returned, so crafter-build runs the compositor beside it.

:Platform gains BackgroundCommand, the compositor's process, and
PrivateDirectory, its directory. The process is forked with
PR_SET_PDEATHSIG and runs under `timeout`, which passes the SIGTERM it
gets when crafter-build dies on to the compositor's group, so a
crafter-build killed by Ctrl-C leaves no compositor running. The
directory is made in $XDG_RUNTIME_DIR, or in /tmp where that is not a
directory, rather than in the temp directory, since a socket's path
holds 107 bytes, and is flocked while in use; one that a killed
crafter-build left is removed when the next is made beside it, once it
has not changed for a minute.

New members and a parameter with a default, nothing removed: a minor
release.
2026-11-28 11:05:51 +01:00
cb8914d387
docs(packaging): add the 6.4.3 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 13m58s
6.4.3 has lint parse a file for the rules that read its AST with the
libc++ of the compiler that builds it, so that in the Flatpak those
rules run on a file that includes a header of the C++ standard library
(#46), and gives the scan of a build's sources the compiler where it is
installed, so that a build whose compiler is reached through a link
from another directory scans them.

A patch, by the version rule: the notes have Fixes and nothing New or
Breaking. The range adds Toolchain::installedDir,
Toolchain::installedDirAsWritten and
Toolchain::InstalledClangxx(command), which interfaces/ exports, for the
linter and the scan to read. They are not under New, as ObjectPath,
which 6.4.1 exported for the tests, was not.
2026-11-27 16:16:38 +01:00
fe25d7aeff
test(lint): the ast and ast-module cases pass only when their rule ran
RunLint calls a rule that reads the AST only on a file it could parse,
so when the parse failed, the checks inside the "ast" and "ast-module"
rules went untried, and the test, which read nothing of the run but
those checks, passed. That is how the "ast" case, whose file includes
<string>, passed in crafter-build's Flatpak with #46 open: lint printed
"'string' file not found" for that file, and the test exited 0. Both
cases now also check that their rule ran and that the run had no error.
2026-11-27 16:16:38 +01:00
043b1a3015
test(lint): a compiler installed in a directory of its own
LintCompilerHeaders stages an installation of its own: the toolchain's
compiler copied into install/bin, beside links to the rest of the real
installation, and one header more in its c++/v1, crafter_issue46.h.
The toolchain it points the build at with CRAFTER_BUILD_LLVM_DIR has a
bin/clang++ that links to that copy, and no include directory. The
compiler runs from install/bin, so the compile of a file that includes
<algorithm> and crafter_issue46.h finds both, and the build's scan of
the file and lint's parse of it have to as well.

Without the lint fix the parse fails on crafter_issue46.h on a host
whose /usr has a libc++, and on <algorithm> in crafter-build's Flatpak,
whose /usr has none. It fails in the same two ways with argv[0] taken
from the compile command, llvm/bin/clang++. Without the scan fix the
scan, given llvm/bin/clang++ as well, fails the same two ways, and the
build with it, which the test's first check reports. The compiler is
copied because a link would lead clang back to the real installation,
and the copy is of the clang++ in the directory `clang++ --version`
names, so that a wrapper on PATH that runs the compiler is not copied
in its place. The test takes CRAFTER_BUILD_LIBCXX_DIR out of its
environment, which would have every compile take that libc++ in place
of the staged one, and the std module the staged toolchain builds goes
to a cache of its own. It skips where it cannot stage the compiler:
where no clang++ is found, the compiler's installation has no libc++
headers of its own, no llvm-ar or clang-scan-deps is beside the
compiler, or the copy names no resource directory it has.

A second configuration on the same toolchain passes
-no-canonical-prefixes, with which the compiler takes itself to be in
llvm/bin, as written, and reads the clang++.cfg the test writes there,
which adds a directory only it names; its file includes the one header
that directory holds, and none of the C++ standard library, which llvm/
has no include directory for. Given install/bin/clang++ whatever the
command's prefix flags, the scan fails on that header, and the build
with it, and so does the parse. The test takes CLANG_NO_DEFAULT_CONFIG
out of its environment as well, which would have clang read no
configuration file, and where the compile with the flag still does not
read the file beside the link, as where a user or system configuration
directory holds a clang++.cfg, or a <triple>-clang++.cfg, that clang
finds first, it leaves the second configuration out and skips, unless
the first configuration failed.
2026-11-27 16:16:38 +01:00
090d8f6363
fix(build): scan sources with the compiler where it is installed
clang-scan-deps, which reads what a .cppm or .cpp declares and imports
since 6.4.2, builds a clang driver of its own from the compile command
it is given, and that driver looks for clang's own headers, and in a
build for the host whose command names no libc++ directory for libc++'s
too, from the directory of the command's first word: the toolchain's
clangxx, looked up on PATH where it is a bare name, and taken as it
stands where it is a link, whatever the command says of canonical
prefixes. Where clangxx is a link from another directory, as a
CRAFTER_BUILD_LLVM_DIR whose bin/clang++ links into another installation
makes it, and the command's last prefix flag is not
-no-canonical-prefixes, that directory need not lead to either, and the
scan of a source that includes a header of the C++ standard library then
failed, and the build with it, on "'stddef.h' file not found" or on the
header it included, though the compile, which takes itself to be where
the link leads, found them. It is the parse of issue #46 over again, in
the scan.

The scan is now given the compile command with
Toolchain::InstalledClangxx(command) as its first word, the compiler
where clang started with that command takes itself to be, as lint's
parse is given it: in the directory its --version names, or, for a
command whose last prefix flag is -no-canonical-prefixes, in the
directory of clangxx as written, from which such a compile looks and
from which the scan of it looked before. That directory is also where
the driver looks for its default configuration files, clang++.cfg among
them, so for any other command the scan now reads the ones beside the
compiler, which the compile reads, where it read any beside a link. What
is kept of a scan still records the compile command itself, which
decides when a source is scanned again: what the source is compiled with
has not changed. AGENTS.template.md now says which of the two commands
is which.
2026-11-27 16:16:38 +01:00
8019f9d44f
fix(lint): look for libc++ where the compiler does
In crafter-build's Flatpak, whose compiler keeps libc++ in /app and
whose /usr has none, a file that includes a header of the C++ standard
library could not be parsed for the lint rules that read its AST in a
build like that of #46: the file built, and `crafter-build lint` then
ran none of those rules on it, printed "'algorithm' file not found"
and exited 1.

libclang parses through a clang driver of its own. In a build for the
host whose compile command names no libc++ directory, as #46's names
none, where a sysroot or CRAFTER_BUILD_LIBCXX_DIR would name one, that
driver looks for libc++'s headers under ../include from the directory
of its argv[0], then under /usr/local/include and /usr/include.
ParseAst gave libclang the compile command without its compiler, and
clang_parseTranslationUnit names argv[0] plain "clang", in no
directory. So the parse of such a build, natively as in the Flatpak,
took the first libc++ it found under ../include from the working
directory, /usr/local/include and /usr/include, whichever compiler the
build used. The -resource-dir ParseAst passes is for clang's own
headers and changes nothing for libc++.

The compile command's argv[0] would not do on its own: a clang++ from
PATH is the bare name clang++, in no directory either, and a clang++
reached through a link into another directory takes itself to be where
the link leads, as clang finds its installation from the file it runs
as. The compiler says where that is, on the InstalledDir line of
`clang++ --version`, which GetToolchain() already runs for clangVersion.
Toolchain::installedDir keeps it, InstalledClangxx(command) names the
compiler in it, and ParseAst passes that as argv[0], through
clang_parseTranslationUnit2FullArgv, which takes argv[0] from its
caller. With argv[0] there, the parse finds libc++ where the compile
does, whatever the working directory.

A compile command can have the compiler look from elsewhere: with
-no-canonical-prefixes, where the last of it and -canonical-prefixes is
that one, clang takes itself to be at clangxx as written, or, where no
file is there, as is usual for a bare name, at the one PATH gives, a
link not followed, and `clang++ -no-canonical-prefixes --version` names
that directory. GetToolchain() runs that too,
Toolchain::installedDirAsWritten keeps what it names, and
InstalledClangxx(command) names the compiler there for a command whose
last prefix flag is -no-canonical-prefixes, as clang's own driver reads
them.

argv[0] also gives libclang's driver its mode, by its file name, and
the configuration files it reads by default, from its directory. The
parse now runs in the g++ mode the compile runs in, where it ran in
clang's gcc mode, and reads the default configuration files beside the
compiler that the compile reads, clang++.cfg among them; before, it read
none from there, as the driver skips the directory of an argv[0] that
has none.

-resource-dir stays, for a libclang of another release than the
compiler, whose driver would derive the directory from argv[0] for its
own release. The comment on it said libclang found clang's own headers
relative to its own install path; its driver derived them from argv[0],
as it does libc++'s.

Fixes #46
2026-11-27 16:16:38 +01:00
578a1da600
docs(packaging): add the 6.4.2 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 14m6s
6.4.2 reads what each .cppm and .cpp declares and imports with
clang-scan-deps, which preprocesses the source with its compile command,
where it searched the source's text with regular expressions (#45), and
so refuses a module built twice for one program, and interface units
that import each other, once the dependencies are built.

A patch, by the version rule: the notes have Fixes and nothing New or
Breaking. The range takes ResolvePendingImports off Configuration, and
the pendingImports members off Module, ModulePartition and
Implementation, all of which interfaces/ exports, and leaves a
configuration's interfaces and implementations empty until a build has
read its sources. All of it is the build's own bookkeeping of a
configuration's units, as Compile() and `compiled` were, which 6.3.0
took off the same unit classes as "internal and not user facing"
(12e8b90), and no project.cpp of this checkout or of the Catcrafts
checkouts beside it names any of it (callers.txt in the review's
evidence).
2026-11-27 09:25:54 +01:00
efb8fcc8b2
docs: what a source imports is read as its compile reads it
The README said that crafter-build reads the imports of a
configuration's sources from their text without compiling them, so that
one in a string literal, in a comment that spans lines or under #if 0
counted, and that a configuration whose interface units import each
other is refused before anything of it is built. It now says that
clang-scan-deps reads what a .cppm or .cpp declares and imports, with
the command the source is compiled with, as the compiler reads it, once
the configuration's dependencies are built; where the build keeps what
it read, as it keeps objects; that such a configuration is refused once
its sources are read, before any of its .cppm and .cpp is compiled; and
that the scans are among the steps a build runs at most as many of at
once as the machine has hardware threads.

The README's sentence on a project that two paths load with different
lists now names the projects the build stops for, those that export
modules, since DuplicateModuleError refuses a module built twice and
nothing else, and says that such a project is built once where both
lists give it one build directory, as two orders of the same flags of
its own can. The README and the contributor guide also stop naming
nlohmann/json among the vendored headers in lib/, which it left in
4af9280.
2026-11-27 09:25:53 +01:00
15e9831203
test(build): one project loaded with its flags in two orders is built once
DuplicateModule builds its project once more with --wide --reorder, with
which P gives M the list that A passes on, in the other order. The
loader takes the two orders for two lists and makes two configurations
of M, which VariantId, taking the project's own flags sorted, builds
into one directory, and a pass builds that directory once. The case
checks that the two are two configurations with one directory, and then,
in two passes, that the graph builds and that P's main.cpp and A's
interface have their edges to the module of the configuration of M that
the pass built. The first pass builds whichever asks first, and the
other has no modules. The second builds the other one first and records
it for the directory, as BuildAll records a configuration it builds,
before it builds the graph, so that both configurations of M then have
modules, the first still those it read in the first pass.

On the engine of the range's base the graph is refused as "module M is
built twice for P": every configuration had its modules from the
listing, and the refusal told the builds apart by their configurations.
On an engine that reads a dependency's modules off the configuration it
is listed as, the range's fix without BuildResult::built, the first pass
builds and A's interface has no edge to M, P's M being the one built and
A's having no modules, and the second pass is refused as a graph with
two builds of M.
2026-11-27 09:25:53 +01:00
08a506d34b
test(build): a source's declaration and imports, as its compile reads them
SourceScan builds copies of six fixtures and checks what the build read
in their sources, by the modules and units it gives each configuration,
and runs the program where what it does depends on that:

- text, three of the four inputs of #45: `import  Base;` and
  `import Spaced ;` are imports, and an import in a comment that spans
  lines or under #if 0 is none. A build with nothing changed then
  rewrites none of the scans, and one that cannot be read is taken
  again.
- quoted, the fourth: an implementation source whose string literal
  holds "export module std;" is a unit of no module, and the build
  succeeds.
- partition: a .cppm that declares an implementation partition
  (`module X:Impl;`) is the partition Impl of X, and the implementation
  unit that imports it has its edge to it.
- define: an #ifdef on a define that the test sets after listing the
  source decides whether the source imports a module.
- switch: an #if on a header of the library the app is built on decides
  it. The header is edited, and the source is scanned again; then the
  app is built on another library, whose header of that name says the
  other thing, so that only the command the scan was taken with has
  changed.
- missing: an #include of a header that is not there fails the build
  with a message naming the header, and nothing is compiled of the
  source.

On the engine of the range's base, with only this test added, every case
but missing fails. Each of the three inputs of the text case is read the
old way, and its first build fails outright whenever Spaced.cppm, whose
import of Base was missed, is compiled before Base's BMI is there; the
string literal makes the listing throw "Module std not found not found",
and the implementation partition the listing of the partition case, "No
module declaration found"; the import under the #ifdef counts without
the define, and the one under the #if after the edit and after the swap;
and there is no scan to look at. The missing case passes there too, the
compile reporting the header as the scan now does.
2026-11-27 09:25:53 +01:00
3c8f4ddb54
fix(build): read what a source declares and imports with clang-scan-deps
GetInterfacesAndImplementations found the module declarations and the
imports of a configuration's sources by searching their text with
regular expressions, after deleting the comments that fit on one line.
The expressions skipped neither string literals nor comments that span
lines, knew nothing of the preprocessor, and wanted one space after
`import` and none before its semicolon (#45). An implementation source
that held "export module std;" in a string literal was taken for a unit
of a module std, and listing it threw "Module std not found not found".
An import in a comment that spans lines or under #if 0 was followed.
`import  X;` and `import X ;` were missed, so their unit had no edge to
the module it imports and could be compiled before that module's BMI was
written.

What a .cppm or .cpp declares and imports now comes from clang-scan-deps
-format=p1689, which preprocesses the source with the configuration's
C++ compile command, the one Build() compiles every unit of it with:
strings, comments, spacing, macros and #if come out as they do for the
compiler. GetInterfacesAndImplementations only lists the sources, in the
new interfaceSources and implementationSources. Build() reads them
(ReadSources) once the configuration's dependencies and external
dependencies are built: the command takes their include paths, and a
source may include headers of an external dependency, which are not
there before it is fetched. From what it read, Build() makes the
configuration's modules and units, its `interfaces` and
`implementations`, and places each import on a module of the
configuration or of what it is built on, whose own Build() has read its
sources by then. It makes those of its own configuration alone, as the
reset of the units' state did before it.

A build pass builds a directory once, for whichever configuration of it
asks first, and the loader can make two configurations of one directory:
one project loaded along two paths with its args in two orders, which it
keeps apart and VariantId, sorting the args, does not. Only the one that
was built has the modules that build read, so the result of a build now
names the configuration it ran on (BuildResult::built), and a
dependency's modules are looked up through the pass's record of its
directory. 6.4.1 had every configuration's modules from the listing and
took such a graph for one with two builds of a module, which it refused;
it is now built, once, and the units of both sides have their edges.

A scan is kept in the build directory as an object is, in scans/ or, for
a source outside cfg.path, in scans-outside/, as JSON of the command it
was taken with and of what clang-scan-deps wrote, with the dependency
file clang-scan-deps wrote beside it, which lists the source and every
file it included. A build scans a source again unless its scan is newer
than every file that dependency file lists, was taken with the same
command and can be read, so a build with nothing changed runs no
clang-scan-deps. Both files are written beside their places and renamed
into them, as the archive and the list of objects are, for another
crafter-build that may be building the same clone.

A configuration's modules are known only once its build has read its
sources, so the refusals of a module that two configurations of the
graph build (DuplicateModuleError, #41) and of interface units that
import each other (ImportCycleError) now come there: once the
dependencies are built, before any .cppm or .cpp of the configuration is
compiled. They came before the configuration made a directory or built a
dependency. The contributor guide names clang-scan-deps among the
prerequisites and among what :Toolchain resolves, has a test look at the
modules of a configuration only after building it, and has the gotcha
for the new order.

ResolvePendingImports and the pendingImports of the unit classes go.
They placed the imports that a scan at listing time could not, once the
dependencies were wired up, and with the imports placed when the
dependencies are built there is nothing pending. The tests that looked
at a configuration's modules and units before building now look after it
(DependencyLink, ModuleInterface, StaticLib, ConcurrentDependencyReset
and the disabled TransitiveInterfaceChange), IncrementalInterfaceChange
checks the edge that the build of a consumer gives it when its
dependency was assigned after its sources were listed, and ImportCycle
and DuplicateModule check that the refused configuration compiled
nothing of its own. The workarounds for the old scanner are not needed:
MingwSysroot writes its stand-in std module as a plain literal again,
JobLimit writes the declarations of the sources it generates as plain
literals, and Lint's comment on its fixture file no longer gives the
scanner as the reason for it.

The messages of the regex code stay where they still apply. The one for
a source that declares a unit of a module the configuration does not
have loses its doubled "not found", and applies to an implementation
source that declares one, such as an implementation partition
(`module X:P;`). An implementation unit written `module X;` declares no
unit for clang-scan-deps but imports X, and an import needs no module of
the configuration: the compile reports a module no one builds. A .cppm
that declares an implementation partition is built as a partition of its
module, where it was refused as declaring no module.

The Toolchain gains clangScanDeps, resolved as llvm-ar is: in the bin/
of the LLVM prefix, else by name on PATH. The Flatpak has
/app/bin/clang-scan-deps.

Fixes #45
2026-11-27 09:25:53 +01:00
a99647ecff
docs(packaging): add the 6.4.1 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 17m51s
6.4.1 gives each .cpp, .c and .cu of a configuration an object named
from its path, so that two sources no longer share one for having the
same file name (#50), writes a static library's archive anew, so that
it does not keep the object of a source that left the project, and has
the link and the archive step read their objects from a file, so that
their paths no longer make the command too long to run.

A patch, by the version rule: the notes have Fixes and nothing New or
Breaking. The range changes what Implementation::Check and Schedule
take, which interfaces/ exports, and adds ObjectPath beside
ExpectedOutput, for the tests that look at an object. Check and
Schedule are what Build() itself checks and compiles an implementation
unit with, as Compile() was, which 6.3.0 took off the same class as
"internal and not user facing" (12e8b90), and no project.cpp of this
checkout or of the ones beside it calls either.
2026-11-19 11:02:39 +01:00
9df82bc272
docs: where a source's object goes, and what a link reads
The README's "Writing a project.cpp" says that a .cpp, .c or .cu of a
configuration is compiled into an object named from its path, under
objects/ in the build directory at the source's path from cfg.path, or
under objects-outside/ at its whole path for a source outside
cfg.path; that two sources may therefore have the same file name in
different directories, and a .c lie beside a .cpp or a .cu of its
name; that the progress line of such a source's compile names it by
that path; and that the link and a static library's archive step read
their objects from <outputName>.objects in the build directory.

The contributor guide gains two rules beside the one on output paths.
ObjectPath() names an object, which is not to be named from its
source's file name, and a step that takes every object of a
configuration reads them from a response file. And a static library's
archive and the list of a step's objects are written under another
name beside them and renamed into place, as anything else that a link
or archive step of another crafter-build may be reading is to be: two
crafter-builds can build a project loaded with GitProject at once, in
the clone the cache keeps for its source.
2026-11-19 11:02:39 +01:00
f9bd5333da
test(build): sources of one file name, and where their objects go
SameNamedSources builds configurations whose sources share file names,
on a fresh copy of its fixture outside the checkout, and runs what they
link. `names` is an executable of an a/Thing.cpp and a b/Thing.cpp, the
C sources a/unit.c and b/unit.c, a b/Thing.c beside the b/Thing.cpp and
a Thing.cpp in a directory beside the configuration's own; its program
prints what each returns, the first time and again after a header that
only a/Thing.cpp includes has changed and after b/Thing.cpp and
b/unit.c have. `registry` is a debug executable of an a/Self.cpp and a
b/Self.cpp that register themselves when the program starts, which
prints that each did so once. `things` is a static library of
a/Thing.cpp, b/Thing.cpp, b/Thing.c and the two unit.c, and
`things-app` a program of main.cpp and ../shared/Thing.cpp built on
it, which prints what `names` does. `outside` is a static library of
one C source that lies outside its configuration's directory and is
listed relative to the working directory, built from a working
directory with a space in its name; `llvm-ar t` lists its object.

ObjectPath asks the rule for the objects of sources without building
anything: in the configuration's directory and in directories of it,
of one file name in two directories, a .cpp, a .c and a .cu of one
name in one directory, outside the directory, and under a directory of
the configuration's own that is named objects-outside and holds the
whole path of the source outside. No two of them get one object. A
path spelled with . and .., a relative source, and a source of a
configuration whose path ends in a separator or is ./ are each given
the object of the file they lead to, and a .cppm, a .h and a file
without an extension are refused.

CudaCompile gains a static library of its kernel.cu and a kernel.c
beside it, whose archive lists kernel_source.o and kernel_cuda.o.

Before the fix SameNamedSources failed at the link of `names`, with
duplicate symbols, and of `things-app`, with undefined ones, and its
`registry` printed that one of the two sources had registered twice
and the other not at all. `outside` built before the fix as well, its
object lying in the build directory then: it is there for the path
the fix gives that object.
2026-11-19 11:02:39 +01:00
7f8089474b
fix(build): name a source's object from its path
The object of an implementation unit was named from its file's name
alone, <build dir>/<name>_impl.o, and that of a C or CUDA source
likewise, <name>_source.o. Two sources of one configuration with the
same file name in different directories were therefore compiled into
one object, each over the other, with one dependency file between
them, and the link was given that object twice (issue #50). A build of
an a/Thing.cpp and a b/Thing.cpp that each define a function failed at
the link, with duplicate symbols of one of the two and no word of the
other. A debug build of two such files that define nothing another
file names succeeded, and its program had one file's code twice and
the other's not at all. A .c and a .cu of one name shared an object in
one directory as well.

An object, with its dependency file beside it, is now named from where
its source lies: under <build dir>/objects by the source's path from
the configuration's directory, objects/a/Thing_impl.o for a/Thing.cpp,
or, for a source outside that directory, under
<build dir>/objects-outside by its whole path. A .cu's object ends in
_cuda.o; a .cpp's still ends in _impl.o and a .c's in _source.o. Two
sources then have one object only when their paths are one once . and
.. are taken out of them: any other two differ by path or by ending in
one of the two directories, and the two directories share nothing,
whatever a project calls its own directories. They are directories of
their own, and not the build directory itself, because that one holds
files named after other things: an interface unit's object, the record
of the link and the list of its objects and, for an executable, the
BMIs.

ObjectPath gives that name, exported beside ExpectedOutput for what
looks at an object from outside Build(). Build() names each object by
the same rule, once, as it goes over the sources, and the list it
keeps of them for the link is what the check whether an object is
newer than the output reads as well. Before, each put the name
together for itself: Implementation::Check, Implementation::Schedule,
and Build() where it compiles C and CUDA sources, lists the link's
objects and checks whether to link again. Implementation::Check and
Schedule are given the object, where they put its name together from
the build directory. The job that compiles a source makes the
directory of its object first, since the compiler makes none. The C
compile quotes its source, dependency file and object for the shell,
as the CUDA compile does: the object of a source outside the
configuration's directory holds that source's whole path, and so
directories the command did not name before, the working directory's
among them where the source is listed relative to it.

The progress line of the compile of a .cpp, .c or .cu names the source
by the path its object is named from, "Compiling a/Thing.cpp" where it
was "Compiling Thing.cpp" for both, and so does the error for a .cu
without an nvcc.

What else changes: every implementation unit and every C and CUDA
source has its object in a new place, so an existing build directory
compiles them once more. The objects under the old names stay where
they are, unused; a static library's archive does not keep them, being
written anew. Interface units are as they were: a BMI is found by its
module's name, so two interface files of one name would have to be one
module. A source that a configuration lists twice is also as it was,
compiled twice into its one object, which the link is given twice.

In IncrementalHeaderChange, IncrementalInterfaceChange, StdPcmRebuild
and TransitiveInterfaceChange, the lines that spelled out an object's
old name take it from ObjectPath.

Fixes #50
2026-11-19 11:02:39 +01:00
0d81aca13f
test(build): a link of more objects than one argument holds
LinkManyObjects makes a project six directories deep, each with a name
of 200 characters, with 120 C sources and a main.cpp that adds up what
each of them returns. Every object lies in the project's build
directory, so the test first checks that 120 times the length of that
directory's path is more than 131,072 bytes. It then builds the
sources three ways: as one executable, as a static library and as a
shared library, the libraries each with an executable of main.cpp
built on it. Each of the three programs prints the sum.

It then opens the list the static library's archive step read, builds
the library again with one source fewer, and reads what it had opened:
the 120 lines of the first build, while the list in its place has the
119 of the second.

Before the fix each of the three builds ended with "popen() failed!":
the executable's at its link, the other two at the archive step and
the link of the library. No list was written, so the test found none
to open.
2026-11-19 10:33:33 +01:00
93eca17e57
fix(build): give a link its objects in a response file
Build() wrote the path of every object of a configuration into its
link or archive command. A command is run by a shell, which is given
it as one argument, and Linux holds one argument to 32 pages: 131,072
bytes with pages of 4 KiB, the terminating byte included. Once the
objects' paths left the command longer than that, popen started no
shell and the build ended with "popen() failed!". Issue #50 notes the
limit, and that a response file for the objects would take it away.

The step now reads its objects from a file that the command names with
@, <output name>.objects in the build directory, one object to a line.
clang and llvm-ar both take arguments from such a response file, so
the link of an executable or a shared library and the archive step of
a static library are handed their objects the same way, and the
command is as long for a thousand sources as for one. Build() keeps
the objects as a list for that, where it joined their paths into the
command as it went over the sources. Each line is quoted for the
reader of a response file, which differs from the shell's: it takes a
backslash inside quotes to quote the character after it.

The file is written before every run of the step, and one that cannot
be written fails the build: the list of an earlier build would
otherwise stay in its place and the step would read its objects. It is
written under a name of its own beside its place and moved there, as
the archive of a static library is, so that a step of another
crafter-build which reads the list at that moment reads the list it
opened, whole, or the new one.

The record that decides whether an unchanged build links again held
the command, which held the objects. It now holds the command and,
under it, the list. The command only names the file, so taking a
source out of a configuration can leave the command as it was, with no
object newer than the output, as the second build of
StaticLibSourceRemoved does: the list is then all that says the step
has to run again.
2026-11-19 10:33:33 +01:00
c82b2bb18c
test(build): a source that leaves a static library leaves its archive
StaticLibSourceRemoved builds a static library and a program on it, on
a fresh copy of its fixture outside the checkout. The library has three
sources: lib/first.cpp and lib/second.cpp each define Value(), returning
1 and 2, and lib/extra.cpp defines a function nothing calls. It is
built three times, by configurations of one name and directory: from
the first and the extra source, from the first alone, and from the
second in the first's place, as the project of a renamed source lists
it. The program prints 1, 1 and 2, and `llvm-ar t` lists the archive's
members as first_impl.o and extra_impl.o, then first_impl.o, then
second_impl.o.

While the second and the third build run, a thread of the test looks
for the archive again and again and has to find it every time: the new
archive is moved into the place of the old one, where a build that
removed the old one first would leave whatever links the library at
that moment without it.

Before the fix the second build's archive listed first_impl.o and
extra_impl.o, and the third's those two and second_impl.o, with a
program that printed 1.
2026-11-19 09:20:32 +01:00
2138015178
fix(build): write a static library's archive anew
The archive step of a static library ran `llvm-ar rcs` on the archive
the build before had left. `r` adds to an archive that is there: it
replaces the members it is given and keeps every other member as it is.
The object of a source that had left the configuration therefore stayed
in the library, ahead of the members added after it.

The link takes a symbol from the first archive member that defines it.
So after a source of a static library had been renamed, the library
held the object of the file under its old name and, after it, the one
of the file under its new name, and whatever was built on the library
went on linking the first. The object of a source taken out of the
project stayed in the library the same way.

The step now writes its archive under a name of its own, beside the
archive's place, and Build() moves it there once the step has
succeeded, so the archive holds the objects that step lists and no
others. It is moved into place, and the old archive not removed first,
because another crafter-build may be linking against the library at
that moment: a project loaded with GitProject is built in its clone in
the cache, which every project that names the same source shares, and
nothing keeps two crafter-builds from building it at once. llvm-ar put
the new archive in the place of the old one in one step, so such a
link found one of the two, and with the move it still does. A step
that fails leaves the archive of the build before, as it did, and the
next build runs the step again.

build.sh has written the bootstrap's archive anew since 046609f, for
the same reason, by removing it first.
2026-11-19 09:20:32 +01:00
c929dce8e4
docs(packaging): add the 6.4.0 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 14m4s
6.4.0 lets a project.cpp return several configurations from
CrafterBuildConfigurations, which are all built, lets a GitProject or
LocalProject spec pick one of a sibling's configurations by name, keeps
the Configuration of a project loaded through either of them where its
project file built it, and builds a wasm32 library that two
configurations of one build share once when its project file sets the
target itself.

A minor, by the version rule: the notes have New and Fixes and nothing
Breaking.
2026-11-15 02:16:07 +01:00
53485c160b
docs: a project file can return several configurations
The README's opening and the start of "Writing a project.cpp" say that a
project file returns one configuration or several, and so does the
description in the Flatpak's metainfo. The README has a "Several
configurations" section in "Writing a project.cpp":
CrafterBuildConfigurations with an example, how the configurations it
returns have to be kept, and what a build, test, run, lint, format, -r,
install and bundle do with several. "Dependencies" says how a GitProject
or LocalProject spec picks one of a sibling's configurations, and that a
`#pragma crafter dependency` gets the first; its sentences on the args a
sibling gets, on where to make a spec and on IsTopLevelProject() speak
of a project file's entry point, where they named CrafterBuildProject.
"Dependency notes for agents" says how the dependencyNotes of several
configurations combine, and which runs leave AGENTS.md alone now that a
list of configurations can be refused before a build starts: its
sentence on that said that a build that fails still has the notes, and
named an `install` or `bundle` refused before building as the one
refusal that writes none. The table of ScriptContext says that a
script's `project` is the configuration it is declared on.
2026-11-15 02:16:07 +01:00
5795b666f5
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
4283a3ecd2
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.
2026-11-15 02:16:06 +01:00
a7aa22220b
test(wasm): a configuration is the same with its WASI sysroot named or not
WasmSysrootKey makes two wasm32 configurations that differ in one thing:
one names no sysroot and the other names the toolchain's WASI sysroot.
They have to be one configuration: the same VariantId, PcmDir and
BuildDir, the same std module key, and the same compile command, which
names the WASI sysroot. A third, with a sysroot of its own, has another
VariantId.

It then builds two programs for the host in one pass, each on the same
wasm32 library, which names no sysroot. The library carries
-fno-exceptions, which a wasm build is refused for before it makes a
directory, so the case does not depend on the machine having a WASI
sysroot. The library's PcmDir has to be the same after the first
program's build as before it, and the pass has to hold the library
once.

Against the engine as it was before the fix the test fails on each of
the three: the two configurations have different VariantIds, the
library's PcmDir changes with the first build, and the pass holds the
library twice.
2026-11-14 23:42:47 +01:00
1ddba745cf
fix(wasm): resolve the WASI sysroot where it is read, not in Build()
A wasm32 configuration that names no sysroot is built against the
toolchain's WASI sysroot. ApplyStandardArgs stores that sysroot in
cfg.sysroot, for a project file that calls it. For a configuration
whose project file sets the target itself, Build() stored it on its way
in. VariantId hashes the sysroot, so such a configuration had one
BuildDir, BinDir and PcmDir until its build started and others from
then on.

A build pass records each dependency's build under its PcmDir, and a
configuration asks for a dependency by the PcmDir it has at that moment.
A wasm32 library that two configurations of one pass are built on was
recorded under the first directory for the one that asked first. One
that asked after the library's build had started asked under the second
directory, found nothing there, and built the library again.

Configuration::ResolvedSysroot now gives what cfg.sysroot comes to: the
toolchain's WASI sysroot for a wasm32 configuration that names none,
cfg.sysroot as it stands for every other, as ResolvedPackaging gives
what `packaging` comes to. VariantId, the std module's flags, key and
source, the compile and link commands and the check that refuses a wasm
build without a usable sysroot read it, and Build() no longer stores the
sysroot in the configuration. ApplyStandardArgs still does: what a
project file reads in cfg.sysroot after the call stays what it was.

The directories a build writes keep their names: a configuration that
named no sysroot was built into the ones its VariantId named once
Build() had stored it, which are the ones it names now.

StdPcmFlags takes the toolchain, as StdPcmKey does, so that a VariantId
asked for under a toolchain resolves the sysroot under that one.
2026-11-14 23:42:47 +01:00
1440e20231
test(external): a sibling's pointers to its own Configuration hold
SiblingOwnPointers loads a fixture through LocalProject, on a fresh copy
outside the checkout: a library whose project file declares a test with
cfg.AddTest("OwnTest").Dependencies({ &cfg }). The one dependency of
that test has to be the Configuration LocalProject returns. The test
reads the dependency out of that Configuration and compares the two
addresses, without following the dependency.

Against the loader as it was before the fix the test fails: the
dependency is not that Configuration.
2026-11-14 23:42:47 +01:00
8baf14068e
fix(external): keep a sibling project's Configuration where it was built
A project file may take pointers to the Configuration it returns. The
usual one belongs to a test that links the library the file describes,
cfg.AddTest("T").Dependencies({ &cfg }): where the compiler constructs
the local the file returns in place of the return value, &cfg is the
address of what CrafterBuildProject returns.

For the project crafter-build is pointed at, that address stays good:
Run() initialises its Configuration with the call. For a project loaded
through GitProject or LocalProject it did not. LoadProjectFromRoot
assigned the call's result to a local, and from there the Configuration
was moved into the project cache, so what a consumer got was not the
object the project file had built, and every pointer the file had taken
to that one pointed at an object that no longer existed. RunLint follows
such a pointer: for a sibling whose path lies inside the project's
directory it works out the compile command of each of the sibling's
tests when a rule needs an AST, and GetCompileCommand walks the
dependencies of the configuration it is given.

LoadProjectFromRoot now makes the Configuration on the heap with the
call as its initialiser, and StoreProject takes the unique_ptr, so the
Configuration is constructed where the cache keeps it and is never
moved.
2026-11-14 20:19:19 +01:00
12e8b908f6
docs(packaging): add the 6.3.0 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 15m13s
6.3.0 holds a build to as many steps at once as the machine has
hardware threads, where every stale shader, asset to compress, C, CUDA
and C++ unit got a thread of its own and nothing bounded how many ran
at once. It makes the object of a module interface unit that an earlier
build left with its BMI alone, or with the object of before an edit,
and it refuses interface units of one configuration that import each
other, whose first build hung.

A minor, by the version rule: the notes have New and Fixes and nothing
Breaking, and Jorijn's "6.3.0, that's internal and not user facing"
settled it. What he was asked about: the range takes Compile() off
Module, ModulePartition and Implementation, and the `compiled` flag off
the first two, all of which interfaces/ exports. They are what Build()
itself compiled a unit with, and none of the 35 project.cpp files of
this checkout and the ones beside it reads the flag or calls Compile().
2026-11-13 17:59:56 +01:00
621438de5f
docs: say how many steps a build runs at once
The README says in "Writing a project.cpp" that a build runs at most as
many of its steps at once as the machine has hardware threads, which
steps those are, and that an ExternalDependency's CMake build and the
tests are not among them. Under Tests, --jobs= is named as what counts
the tests, and --jobs=1 as one test at a time where it said "serial
mode": the steps of that one test's build still run side by side.
2026-11-13 17:59:56 +01:00
f9d0ec24fe
test(incremental): an interface unit without its object is built again
IncrementalInterfaceObject builds a module with a partition and a
program that prints what the module's function returns, without
optimisation, so that what it prints says which object was linked. It
edits the primary interface, builds, and puts the object of before the
edit back dated two seconds before the new BMI. A build with the
program still there has to make the object again and link the program
again; after the old object is put back once more and the program
deleted, a build has to make the object again and the program print the
edited value. Then it deletes both objects and the program and builds:
both objects have to be back. A last build of the intact tree has to
leave the objects as they are.

On 5b75df3 the old object is never made again, and the build without
the program links it: the program prints 11 where the source says 12.
The build without the objects fails at the link with "no such file or
directory" for each of the two.
2026-11-13 17:59:56 +01:00
6087ce81db
test(build): build many units at once and count the threads it takes
JobLimit makes two projects and one more for every 32 hardware threads
and builds them from nothing at once, each from a thread of its own, as
RunTests builds its tests, while it counts the threads of its own
process. A project is 69 sources: 64 that import nothing, half C and
half C++, then a module of two partitions, one importing the other,
with its implementation unit, and a main.cpp that imports the module.
It is the same size on every machine, so that no command of its build
grows with the machine. The builds together may add as many threads as
the machine has hardware threads, and have to add at least two where
there are two; every program is then run and has to print 995: what
its 64 C and C++ functions return and the module's Top(), which is
built on the two partitions' functions. On 5b75df3 it fails: on a
machine with 56 hardware threads, "3 builds of 207 sources in all ran
on 205 threads at once". The count sees the steps that are jobs. A link
is none: its Build() runs it through RunBuildCommand from a thread that
was there before the count, which does not tell whether the link waited
for a worker.

JobGroup drives pools of its own, of one to four workers. Twelve jobs on
three workers run three at once and no more; a job starts after the
ones it was added after, in a graph of four jobs and in one of 300; the
first error keeps a job that comes after it and the jobs added later
from starting, and so does Fail(); what a job throws is its error; a
chain gets through one worker; Run() runs its work on a worker, on the
calling thread when that is one, where a JobGroup is refused; and
leaving a group's scope waits for the job that runs and starts no
other. It also holds the process's pool to a worker per hardware thread.
2026-11-13 17:59:55 +01:00
913310da86
feat(build): run a build's steps on one worker per hardware thread
Build() started a thread for every stale shader, asset, C, CUDA and C++
unit, and Module::Compile one more for every stale partition, and
nothing bounded how many of them ran their step at once. Jorijn asked
for the amount of parallelism to be limited by the amount of threads
instead of just starting one per file; the threads are taken here to be
the machine's hardware threads.

The new :Jobs partition holds the two pieces. JobPool is worker threads
behind one queue, started as jobs need them up to a fixed number, and
JobPool::Process() is the pool of the process: at most a worker per
hardware thread, one where std:🧵:hardware_concurrency does not
know. JobGroup is the jobs of one build on a pool. A job starts once
the jobs it was added after have finished; the first job to fail keeps
the ones that have not started from starting, and Wait() returns its
error. No job waits for another job, and a JobGroup made on a worker of
its own pool throws: a worker that waited for a job still in the queue
would hold the thread that job needs.

Build() adds what it did on those threads to a JobGroup instead, and
the group's first error replaces the buildCancelled and buildError pair
the threads set. The module units no longer block on the `compiled`
flag of the units they import: Schedule() replaces Compile() on Module,
ModulePartition and Implementation and adds a unit's jobs after the jobs
that write the BMIs it imports. An interface unit is two jobs, its BMI
and then its object from the BMI, so the units importing it start when
the first is done, as they did when one thread ran both commands and
raised the flag in between. A primary interface now waits for the BMIs
of its partitions and no longer for their objects. Each of the two jobs
has a progress line, "Precompiling X.cppm" and "Compiling X.cppm" for
every interface unit, where a module and its partitions shared one
"Compiling interface X".

RunBuildCommand runs its command on a worker of the process's pool: on
the calling thread when that is one, otherwise it waits for one. A link,
an archive, the std module's precompile and project.cpp's compile are
steps under the limit that way. The threads Build() starts per
dependency and per external dependency stay: one of the first runs the
dependency's own Build(), or waits for the thread that does, and one of
the second runs git and cmake.

With the BMI and the object as two jobs, a build that fails between them
has written the BMI and skips the object, and Check, which reads
staleness off the BMI, would call the unit built from then on.
Schedule() therefore adds the object job alone for a unit whose BMI is
up to date and whose object is missing or older than the BMI. A build
interrupted between the two commands, or one whose second command
failed, left the same behind before, and it stayed: the link took the
object of the source before the edit, or failed on the missing one.

ImportCycleError is now what keeps Schedule() from following a round of
imports without end.

The limit is on steps. Outside it, as AGENTS.template.md lists: an
ExternalDependency's cmake --build, which keeps its own --parallel of
as many jobs as there are hardware threads; the tests RunTests runs,
--jobs= of them at once as before; the Crafter.Build modules
EnsureCrafterBuildPcms precompiles one after another; and the threads a
step starts for itself, which lld does for a link and Crafter.Asset's
GDeflate compressor for an asset. The pool is one process's. The --help
text says what a build runs at once and that test --jobs= counts tests.

ConcurrentDependencyReset read the `compiled` flag, which is gone. It
asserts on `checked` and `scheduled` instead, the state a reset from
another build's thread would clear now, with a unit scheduled twice as
the result, and the comment in its fixture says what the implementation
unit comes after now. TransitiveInterfaceChange's comment names
Schedule() where it named Compile() as what honours a partition's
imports. Two comments in :Platform that spoke of worker threads, a word
that now means the pool's, name the threads they mean. The bug-prover
lens's section said shaders compile on a thread of their own each, and
describes the pool now.
2026-11-13 17:59:55 +01:00
eff9868b68
docs: interface units that import each other stop the build
The README says in "Writing a project.cpp" that a unit is built after
the modules and partitions it imports, that interface units of one
configuration that import each other are refused with an error naming
them, and that the imports are read from the source text without
compiling it, so one in a string literal, in a comment that spans lines
or under #if 0 counts too and can make such a round in a project the
compiler accepts.
2026-11-13 17:59:55 +01:00
ee331377a4
test(build): interface units that import each other are refused
ImportCycle builds three fixtures as static libraries, each on a fresh
copy outside the checkout: two partitions that import each other, a
partition that imports its own module, and two modules that import each
other. Each build has to return an error that holds its round,
"Ring:First -> Ring:Second -> Ring:First", "Own -> Own:Part -> Own" and
"East -> West -> East", and leave neither a build nor a bin directory.

Before the refusal the test ran into its timeout: the first of those
builds never returned.
2026-11-13 17:59:55 +01:00
e87dc4f015
fix(build): refuse interface units that import each other
Two partitions that import each other, a partition that imports its own
module, and two modules of one configuration that import each other
cannot be built in any order. Build() compiles each stale unit on a
thread that first waits for the units its unit imports, and a primary
interface waits for every stale partition of its module as well, so a
build that found every unit of such a round stale, as a first build of
them does, hung: every thread waiting, no compiler running, no error.

ImportCycleError follows the imports of a configuration's interface
units at the top of that configuration's Build(), before it makes a
directory or builds a dependency, and Build() returns an error naming
the units of the first round it finds in the order they wait in,
"Ring:First -> Ring:Second -> Ring:First". A primary interface counts
as coming after each partition of its module, whether it imports that
one or not, since that is how it is built. A configuration built on the
one refused has started its own build by then: the check reads the
imports ResolvePendingImports has just placed, which are that Build()'s
to read while it runs.

The imports are the ones the source scanner reads, and it reads one in a
string literal, in a comment that spans lines or under #if 0 as it
reads any other (issue #45), so the units the error names are where to
look for one of those too. The error says so, since the compiler sees
no round in such a project, and AGENTS.template.md has it under Gotchas.
2026-11-13 17:59:55 +01:00
5b75df3b19
docs(packaging): add the 6.2.0 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 14m29s
6.2.0 makes CUDA sources compile in the Flatpak: crafter-build finds
nvcc itself, under CUDA_PATH, /opt/cuda or the host's /usr/local/cuda,
or in an absolute entry of PATH, where it used to run whatever the
sandbox's PATH gave, which never holds the host's toolkit, and it links
that toolkit's static CUDA runtime itself where the toolkit's lib64
holds it. The GPU architecture CUDA sources compile for is configurable
and native by default, and a .cu compiles again when a header it
includes changes.

A minor, by the version rule: the notes have New and Fixes and nothing
Breaking, and Jorijn's "6.2.0 is fine" settled it. The default
architecture moves from sm_89, which carries its PTX, to native, which
carries none, so a program built for native has no PTX for a GPU of a
newer architecture. That is under New rather than Breaking because no
Flatpak release compiled a .cu with the PATH its manifest sets: each ran
a bare nvcc in the sandbox, whose PATH, /app/bin:/usr/bin, holds no
toolkit, so a project had to set another PATH itself to compile one. A
program for other machines takes another architecture, such as
--cuda-arch=all-major, as the notes say. A project that names -lcudart
in cfg.linkFlags keeps building, with its shared runtime first on the
link line. VariantId changes for no configuration without CUDA sources
but one built with --cuda-arch=, which was a project argument and is
crafter-build's own now; a configuration with CUDA sources builds once
in new bin/ and build/ directories, keyed by its architecture, for
native by crafter-build's reading of the machine's GPUs, and by its
nvcc.
2026-11-11 19:34:52 +01:00
df79dcd46d
docs: a CUDA section in the README
cfg.cuda had no section of its own, only mentions in passing. The new
one says how sources are listed and linked, where the toolkit is found
and what the Flatpak sees of it, what cfg.cudaArch picks, and what nvcc
is not given: the include paths, defines and compile flags of the C and
C++ compiles, and -g. The Flatpak output section's advice for other
machines names a --cuda-arch= other than native, such as all-major,
beside --march=x86-64-v3.
2026-11-11 19:34:52 +01:00
99653194ba
test(cuda): build a .cu without link flags, and through a library
CudaCompile's builds name no CUDA library now, but for the last. The
toolkit it names through CUDA_PATH has a lib64 beside its nvcc with the
real toolkit's libcudart_static.a, so the executable links only if
crafter-build links the runtime, and the recorded link names that
archive. Another build puts the .cu in a static library and the C++ unit
in an executable built on it, which links only if the library hands the
runtime on. That lib64 also holds a libcheckpoint.so and a libm.so that
are no libraries, as Arch's lib64 holds a real libcheckpoint.so and a
libOpenCL.so: another build links an executable with CUDA sources on a
library of the project's named checkpoint, and clang++ adds -lm to every
C++ link, so a link that searched the toolkit's lib64 would stop on one
of them wherever its -L stood. The last names -L<lib64> -lcudart, as a
project with CUDA sources had to, and has that -lcudart ahead of the
static archive, so the shared runtime is the one the linker takes. The
test skips where the real toolkit's lib64 holds no static runtime, since
crafter-build then links none. Before crafter-build linked the runtime,
the link failed on an undefined CUDA runtime symbol.

ToolchainResolve checks where the runtime is looked for, on staged
toolkits, so that it runs in CI: the archive in the lib64 beside nvcc's
bin, none where that lib64 holds none, none where it links to itself,
which a look that threw would have stopped the test on, and none without
an nvcc.

CudaCompile is the only check of the runtime link itself, and it skips
without such a toolkit, so AGENTS.template.md's note on when to run it
names the link as well as the compile, and gives the lookup to
ToolchainResolve.
2026-11-11 19:34:52 +01:00
22ea97406d
feat(cuda): link the CUDA runtime of the toolkit that compiles the .cu
A program with CUDA sources needs the CUDA runtime, which cfg.linkFlags
had to name: -L/opt/cuda/lib64 -lcudart for Arch's toolkit, a path into
it. In the Flatpak that holds for /opt/cuda but not for the host's
/usr/local/cuda, which is under /run/host there, at a path crafter-build
resolves for nvcc and a project.cpp does not know. Jorijn chose to have
crafter-build link it.

A configuration with CUDA sources links the static runtime of the
toolkit whose nvcc compiles them, by its path, with the -lrt -lpthread
-ldl that nvcc's own link line puts after it. ResolveToolchain finds it
with nvcc, as Toolchain::cudaRuntime: libcudart_static.a in the lib64
beside nvcc's bin, looked for without starting a process, so a test can
stage a toolkit for it as for nvcc, and crafter-build --version prints
it. The static one, so no run path into the toolkit ends up in the
program; libcuda.so.1, which the runtime loads, comes with the driver.
By its path, not through a -L of the lib64, which would put the
toolkit's libraries, such as Arch's libcheckpoint.so, in the way of a
project's own of the same name. It goes into BuildResult::runtimeLibs,
which a configuration hands its consumers as it does libs and every link
puts after them, so whatever is built on a library with CUDA sources
links the runtime too, and a -lcudart a project names itself comes
first.

Where that lib64 holds none, as where a distribution keeps the toolkit's
libraries in its own directories, cudaRuntime is empty and nothing is
linked, as before: a -lcudart_static the linker could not find would
fail the link even of a project that names its own -lcudart. The archive
is looked for without throwing, so a lib64 that cannot be looked into,
through a link loop or for want of permission, counts as one without it.
2026-11-11 19:34:52 +01:00
6b2da3b1d6
test(cuda): a changed header compiles the .cu again
CudaCompile's .cu includes a header of its own now. After the unchanged
build, the test makes the header newer than the object and builds once
more, which has to run nvcc again. Before nvcc wrote a depfile, it did
not, and the object built from the old header stayed.
2026-11-11 19:34:52 +01:00
c2338d1122
fix(cuda): rebuild a .cu when a header it includes changes
A .cu was compiled again only when it was newer than its object, so one
whose header changed kept the object built from the old header. The C
and C++ paths ask the compiler for a depfile and check every
prerequisite in it; nvcc was left out because its -MD and -MF had never
been run here.

They work with CUDA 13.4 as they do with clang: the depfile lists the
.cu and every header it read, the toolkit's and the system's included.
nvcc puts a space before the rule's colon, which NewestPrerequisite
reads as a target token like any other. An object from before has no
depfile and is compiled once more.
2026-11-11 19:34:52 +01:00
ad021ee652
test(cuda): build a .cu with the toolkit CUDA_PATH names, and with none
CudaCompile puts an nvcc on PATH that fails, names a toolkit through
CUDA_PATH whose nvcc writes down its arguments and runs the real one,
and builds an executable from a C++ unit and a .cu: with the default
architecture, then with another one, which compiles the unchanged .cu
again in a directory of its own, then with nothing changed, which
compiles nothing. With the bare "nvcc" of before, the first build runs
the nvcc on PATH and fails.

It needs a real toolkit, which it looks for as crafter-build does, with
ResolveToolchain and the inputs GetToolchain() gives it, and it skips
without one. Nothing in CI installs one, so AGENTS.template.md says to
run it in the native loop.

CudaMissing needs none, so CI runs it: with CUDA_PATH naming an empty
directory, a build with a .cu fails with "cannot compile kernel.cu: no
nvcc at <directory>/bin/nvcc (CUDA_PATH)", and a build without CUDA
sources in the same process still succeeds. With the bare "nvcc" of
before, that build ran whatever nvcc PATH held, and where PATH held
none, as in the Flatpak, failed with "sh: line 1: nvcc: command not
found". AGENTS.template.md names it beside CudaCompile.
2026-11-11 19:34:52 +01:00
967dd12b06
feat(cuda): make the GPU architecture configurable, native by default
nvcc ran with -arch=sm_89 for every build, which is code for that one
architecture and its PTX, whatever GPU the program was for. Jorijn asked
for the architecture to be configurable, and native when nothing sets
it, as the CPU's is.

cfg.cudaArch is nvcc's -arch now, and it defaults to "native": nvcc
compiles for the GPUs it sees, and where it sees none it warns and uses
its own default architecture. Like -march=native it is for a program
that runs where it is built, since it carries no PTX, and
`crafter-build bundle` warns of a bundle whose CUDA code, in the program
or a library it is built on, is compiled for native, as it warns of
-march=native. ApplyStandardArgs sets it from --cuda-arch= and
CRAFTER_BUILD_CUDA_ARCH as it sets march from --march= and
CRAFTER_BUILD_MARCH; AddTest and AddMarchVariants give their tests the
parent's, as they give them its sysroot and debug flag; and
ForceHostTooling gives host tooling the host's, as it gives it the
host's march, since project.so runs it on the machine that loads it.

A .cu is compiled again only when it is newer than its object, so the
architecture keys VariantId, and so does the nvcc that compiles it, by
what it is rather than where: Toolchain::nvccStamp, its canonical path,
size and time, read without a process, changes when CUDA_PATH names
another toolkit and when an update replaces the one at the same path, as
a package does at /opt/cuda. native is keyed as well, by
Toolchain::cudaNativeKey: the NVIDIA display devices sysfs lists, by PCI
address and device ID, and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER,
which choose and number them, each empty value apart from an unset one,
read without a process. It is crafter-build's reading of the machine,
not nvcc's. The word alone would keep an object compiled for a GPU the
machine no longer has, after a GPU change or on another machine that
shares the checkout, and that object carries no PTX for the GPU it has
now, where sm_89's carried its PTX. Only a configuration with CUDA
sources is keyed, so every other one keeps the directory it had, but for
one built with --cuda-arch=, which was a project argument, hashed as
one, and is crafter-build's own now.
2026-11-11 19:34:52 +01:00
2fd45133a0
test(cuda): resolve nvcc on staged toolkits
ToolchainResolve stages toolkit roots, a PATH and a host root, and
checks the order (CUDA_PATH, then the roots, then PATH), that a
CUDA_PATH without an nvcc is an error and not a fallback, that a
relative one names an absolute nvcc, that a file
that cannot be run is no nvcc and a relative PATH entry no place to
look, what the error says when there is none, and that a toolkit
resolves under the host root through a link: /usr/local/cuda in the
host's /usr to an absolute path, named with a trailing slash too,
through /etc/alternatives and to a relative path, and a link outside
the host's /usr that leads into it. A link to itself finds nothing.
2026-11-11 19:34:52 +01:00
fdba70d176
fix(cuda): look for nvcc instead of leaving it to PATH
cfg.cuda compiled with a bare "nvcc", which the shell looked up on PATH.
In crafter-build's Flatpak PATH is /app/bin:/usr/bin, as its manifest
sets it, which never holds the host's toolkit, so with it every build
with CUDA sources stopped at "sh: line 1: nvcc: command not found",
although the sandbox sees /opt/cuda through --filesystem=host.

ResolveToolchain now finds nvcc as it finds clang++: CUDA_PATH, which is
exclusive as CRAFTER_BUILD_LLVM_DIR is, else /opt/cuda (Arch's package)
or /usr/local/cuda (NVIDIA's installer and packages), else the absolute
entries of PATH, which it searches itself so that a build without a
toolkit can say where it looked. A relative CUDA_PATH is made absolute
there, once, as CRAFTER_MINGW_DIR is, since nvcc runs later from
whatever working directory a build is in. The sandbox shows the host's
/usr and /etc under /run/host, with its own runtime at /usr, and
NVIDIA's /usr/local/cuda is a link, to /usr/local/cuda-<version> or
through /etc/alternatives. A link to an absolute path names a path of
the host, /opt/cuda pointing at /usr/local/cuda-<version> too, and the
sandbox would look it up in its own root, so where the path of a
toolkit, CUDA_PATH, /opt/cuda or /usr/local/cuda, is such a link,
HostPath follows it, and the link its target is in turn, each taken as
the host's; a link partway along that path, or inside the toolkit, is
the kernel's to resolve, in the sandbox's root.

A missing toolkit is reported by the build that has a .cu to compile and
not by GetToolchain(), so no other build fails for want of one.
crafter-build --version prints the nvcc it found, whether or not the
compiler could be resolved.
2026-11-11 19:34:52 +01:00
ff3cc20e70
docs(packaging): add the 6.1.0 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 13m51s
6.1.0 lets a program crafter-build builds run outside its sandbox: an
executable can be packaged as a Flatpak of its own, installed with
`crafter-build install` or bundled into a file with
`crafter-build bundle`, with flatpak-builder modules and data under
/app/share where it needs them. The Flatpak gains the
org.freedesktop.Flatpak permission those two verbs run the host's
flatpak with. It also fixes programs built on a shared library on Linux,
which did not start, compiles that took headers from what a build left
in a dependency's bin/ or build/, `format --check format`, which rewrote
the sources, and wasm tests declared with AddTest, which never ran.

A minor, by the version rule: the notes have New and Fixes and nothing
Breaking. Default still builds an executable as linked, and VariantId
and the bin/ layout change for nothing that is not packaged as a
Flatpak, but for a build given --packaging=, which moves to other bin/
and build/ directories: the argument was a project arg, hashed into
VariantId, and is a standard arg now, for dependencies too. `install`,
`bundle` and `--packaging=` were project args until this range made them
two verbs and a standard arg, and no sibling project.cpp reads any of
them: the only `install` in one is the name of a `run` script, which
`run` takes before any verb. `test test`, `lint lint` and
`format format` now take the second word as a glob. The include walk
leaves out every directory named bin or build now, and that is under
Fixes rather than Breaking: those are the names crafter-build gives what
it writes, and in the Crafter repositories and the dependencies
crafter-build has cloned, the one #include that needs a header found
only there is glslang's, in a source its own CMake build compiles, not
crafter-build. The permission is listed under New, and `flatpak update`
lists it before it asks to proceed.
2026-11-09 01:55:31 +01:00
79b24a93b8
docs: cfg.flatpak.share in the README
The README's Flatpak section shows share entries in its picture of the
bin directory and in the cfg.flatpak example, and says what they are
for, that files/share is kept to what is listed, that the ../share
lookup works under -r as well, that flatpak exports what it exports of
them by its own rules, and what build-export checks of that, that an
entry may not take a field's file, that the app's desktop entry is
checked whichever placed it, and which directories an entry may not
copy: those that hold what the build writes or lie in it.
AGENTS.template.md lists them among what FlatpakApp holds.
2026-11-09 01:55:31 +01:00
e0ac8ee600
feat: install a Flatpak's data under /app/share
A program packaged as a Flatpak could only have its files beside it in
files/bin, where cfg.files goes. One that finds its data at <its
directory>/../share/<name>, as Crafter.Review finds its process/
directory, had no way to get it there: files/share belongs to the
writer, which removes anything it did not put there, and a module of
flatpak-builder's would have placed it only in the installed app, never
under -r. cfg.flatpak.share lists files and directories of the project
and the path under /app/share each goes to. The writer copies them into
files/share with the desktop entry, metainfo and icons, keeps them while
they are listed and removes them once they are not, as it does those. -r
runs the program from files/bin, so the same ../share lookup finds them
there. What is exported of them is flatpak build-finish's to decide, by
its own rules, as for any app's files: the app's D-Bus services, MIME
types, search providers and KRunner plugins, which have no field of
their own, are placed like any other file. A library's are not passed on
to the programs built on it, since data a library needs at run time
already goes through cfg.files. A dependency that packages its own
executable has the sources rebased by the loader, as its cfg.files are.
Share entries change files/share and not what is compiled, so they are
not keyed into VariantId, which its test checks.

Every file bound for files/share, the desktop entry, metainfo and icons
included, now goes through one placement check, which refuses two files
for one path, a field's file among them, and a file where another needs
a directory, naming both. A target that is absolute or leaves share/ is
refused too. Any other place is open to a share entry, a second desktop
entry, an add-on's metainfo and any icon included, as for any app's
files: flatpak build-export refuses an exported icon that is not a
square image and a D-Bus service that is not a key file, warns of the
app's own desktop entry where desktop-file-validate rejects it or its
Icon= is not the app's, and exports a second desktop entry, a MIME
package or metainfo as it is. The app's own desktop entry,
applications/<app-id>.desktop, is held to cfg.flatpak.desktopFile's
checks whichever placed it: its Icon= and desktop-file-validate are
keyed to that place now, not to the field. A source directory that holds
what the build writes is refused as well, since it would be copied into
itself, growing each time the app is built or exported: files/, and the
app's directory, where install and bundle put another copy of files/ and
the exported app, compared as written and where links lead, so that the
project's own directory is refused where its bin/ is a link elsewhere
too. So is one that lies in them, the build's own output, which the next
build, install or bundle writes again. The loader leaves an empty source
empty, as it does an empty desktop file.

FlatpakShareLarge holds the writer to comparing an entry with its copy
at constant memory, which the program's data, gigabytes of it in a game,
needs on every build: it rewrites a files/ holding a 32 MiB entry, with
nothing changed, in a child process whose address space may grow by 16
MiB, with a stand-in llvm-readelf, since the real one, which a write
starts for the libraries, would not fit under that limit, and a change
in the entry's last byte, in the short block a comparison reads last, is
still copied.
2026-11-09 01:55:31 +01:00
52a767fadc
docs: install, bundle and modules for the Flatpak output
The README's Flatpak section brings in `crafter-build install` and
`bundle` after -r, where the sentence on what build-finish writes was,
says how they make the app, crafter-build writing the build directory's
metadata and the host's flatpak build-finish adding the command and the
permissions to it and writing export/, and where that directory is, for
trying the app on the host without installing it, says where the repo
and remote live and how two installs of one app-id take turns on the
remote, where `install` takes the runtime from, what to install where no
installation has it and that an app with modules needs the Sdk too, how
they ask the host whether it sees the project's bin/ and build/ and
refuse a project it does not and who in the sandbox holds the permission
they run with, and describes cfg.flatpak.runtime,
cfg.flatpak.permissions, which install and bundle print and build-finish
judges, and cfg.flatpak.modules; it names install and bundle among the
invocations that write AGENTS.md. AGENTS.template.md names what :Flatpak
holds now, and says that org.freedesktop.Flatpak is the whole sandbox's
while crafter-build's own code uses it only in the host helper, why the
trust model allows it, how a test reaches the host without touching the
user's installation, and the trap in probing a tool with `command -v`
through RunCommandWithTimeout, whose `timeout` cannot run a shell
builtin, and lists the locks install keeps on the user's remotes among
what goes in ~/.cache/crafter.build/, found by HOME, so that native and
Flatpak crafter-builds share them.
2026-11-09 01:55:31 +01:00
71540b24aa
feat(flatpak): let crafter-build run the host's flatpak
install and bundle run the host's flatpak and flatpak-builder, and the
only way out of the sandbox to them is the Flatpak session helper, so
the manifest grants --talk-name=org.freedesktop.Flatpak. crafter-build's
own code uses it only through HostCommand, for the host's flatpak and
flatpak-builder, but the permission is the whole sandbox's: every
project.cpp crafter-build loads, its scripts, its dependencies' builds
and the programs -r and test start can run host commands through
flatpak-spawn --host as well. --filesystem=host already lets all of
them arrange that, by writing ~/.bashrc or a systemd user unit; the
permission makes it immediate, it does not make it possible. `flatpak
update` lists it among the app's new permissions before it asks to
proceed.

The run flatpak and run install scripts of project.cpp still refuse
inside the Flatpak, now for the reason that holds there: they run
flatpak themselves, which the sandbox does not have.
2026-11-09 01:55:31 +01:00
eff250abb7
feat: install and bundle a Flatpak through the host's flatpak
An executable packaged as a Flatpak came out as the files/ of one, which
only flatpak build-finish makes an app of, and getting it installed or
onto another machine took flatpak commands on the host, typed by hand.
Two verbs do it where the host's flatpak can be reached:
`crafter-build install` builds the project and installs its app for this
user, and `crafter-build bundle` builds it into bin/<variant>.flatpak, a
single file for `flatpak install --user` that names Flathub's repository
for the runtime. Inside crafter-build's Flatpak they need the
org.freedesktop.Flatpak permission, which its manifest does not grant in
this commit. Both put the app into the project's repo first, in
build/flatpak-apps/<app-id>/ (FlatpakAppDir), one per app rather than
per variant, since flatpak-builder's state there is its cache. Every
variant exports into it, so the export and the install or bundle made
from it hold a lock there, and another crafter-build exporting meanwhile
waits rather than leave this one installing or bundling its program. The
user remote an install re-points is every checkout's that builds the
app-id, so re-pointing it and installing from it hold a second lock,
which every crafter-build installing there takes, natively or in the
Flatpak, whatever its XDG_CACHE_HOME: in
~/.cache/crafter.build/flatpak-remotes/, found by HOME, for the user's
own installation, which flatpak hides from the sandbox behind a tmpfs of
the sandbox's own, and in the directory of a private one,
FLATPAK_USER_DIR, one lock for all of them where the sandbox shares that
directory with the host. Without modules, the host's flatpak
build-finish finishes build/flatpak-apps/<app-id>/build-dir, made afresh
each time from a metadata naming the app, its runtime and the Sdk and a
tree of hard links to the build's files/, copies where a link cannot be
made, across filesystems or on one without links, vfat or exFAT: it
writes the command, the sandbox's permissions and export/ by flatpak's
own rules, those of whichever flatpak the host runs, and refuses a
permission it does not know, and flatpak build-export puts the result
into the repo. When cfg.flatpak.modules names flatpak-builder module
files for what the app needs in /app besides the program,
flatpak-builder does both, from a manifest that lists them and copies
the built program in last, so nothing is compiled twice. That manifest
keeps share/locale in the app ("separate-locales": false):
flatpak-builder would split it into a .Locale extension by default,
which a bundle, holding the app alone, leaves out. The loader rebases a
dependency's module files as it does its cfg.files. install uses a user
remote named after the app-id, re-pointed at the repo each time, and
says how to remove both. The app's tree in
build/flatpak-apps/<app-id>/build-dir, where flatpak-builder installs a
module's files too, is left out of the include walk with every other
build/, so the headers a module installed reach no compile.

cfg.flatpak gets the runtime, the Platform or the Sdk at the branch
crafter-build runs on, and the sandbox's permissions, finish-args as
Flatpak spells them, which any configuration may declare: an executable
gets its dependencies' first and its own last, so it can take one back.
The build reads neither, and a change to either links nothing. install
and bundle print the permissions, with where each came from, and hand
them to build-finish, the one judge of what they mean, so a refusal can
be traced to the configuration that declared it. FlatpakPermissions
checks the order everywhere, and that a change to one neither moves the
build to another directory nor links anything, and, where the host's
flatpak runs, what build-finish makes of them and that it refuses a
socket it does not have; FlatpakBundle that build-finish exports the
desktop entry and the icon, and that the build's own files/ is left as
it was; VariantId's test has the runtime, permissions and modules move
no directory.

The host's flatpak and flatpak-builder are reached only through
HostCommand in :Platform, which builds the command lines of
RunHostFlatpak, RunHostFlatpakBuilder and HostFlatpakUnavailable's
probes: flatpak-spawn --host --watch-bus inside crafter-build's Flatpak,
started in the host's / and passing FLATPAK_USER_DIR on, and the command
itself natively. flatpak-spawn would otherwise start a command in
crafter-build's own working directory, which the host need not have, and
from /app, say, every host command would fail. HostFlatpakUnavailable
says why the host cannot be reached: no org.freedesktop.Flatpak
permission, no session bus (CI's build sandbox has neither), a host that
does not see the project's bin/ and build/ where crafter-build does, as
it does not in the sandbox's own /tmp, /var, /usr, /etc and /app or
where a link leads into one, or no flatpak natively. That, and an
executable that is not packaged as a Flatpak, install and bundle refuse
as soon as the project is loaded, before anything is built;
FlatpakVerbRefusal shows the second. The host is asked rather than the
sandbox's paths modelled, which an override sharing a directory inside
the sandbox's own would defeat: its flatpak is started in a directory
just made in each of bin/ and build/ under a name no other has, which it
enters only where it sees that very directory, and the directory is
removed again. --help gets a section on both, and its Clean section says
the repo an install points at goes with build/. FlatpakModules runs
flatpak-builder only with a flatpak-builder program on the host,
crafter-build falling back to the org.flatpak.Builder app, whose
`flatpak run` would write ~/.var/app in the real home, and with the
Platform and Sdk it builds the app with. The library's install function
is InstallFlatpakApp because project.cpp files define an InstallFlatpak
script of their own under `using namespace Crafter`, this repository's
included, and a library InstallFlatpak would make the name an overload
set, which the scripts table's std::function cannot be built from;
BundleFlatpakApp is named to match. JsonQuote writes the manifest's
strings, and variants.json's, which escaped quotes and backslashes only.
FlatpakExport, FlatpakManifestText, ExportFlatpak and FlatpakPermission,
which only :Clang uses, stay out of the API a project.cpp compiles
against, as RecordFlatpakPlaced does, so their names cannot meet a
project's own under `using namespace Crafter`; ExportFlatpak's comment
names the app's lock, which its callers hold, beside
HostFlatpakUnavailable.
2026-11-09 01:55:31 +01:00
4b1585c709
test(cli): format --check with a rule name writes nothing
`crafter-build format --check format` read the second `format` as the
verb again, which set the mode back to applying and recorded no glob, so
it ran every transform and rewrote the project's sources, and exited 0,
though `--check` writes nothing. FormatCheckGlob drives Run() on a
staged project whose one rule, named "format", would change its
main.cpp, and holds the run to exiting 1, the check with a file to
change, with main.cpp as it was. It fails before the verb enum of the
commit before this one and passes with it.
2026-11-09 01:55:30 +01:00
2c3d0b0d1f
refactor: one verb per invocation, as an enum
Run() kept a flag per verb: test, lint, clean and format were each
recognised only when the others' flags were clear, so a verb added among
them meant another condition in each of their branches, while run took
the words after it in a branch ahead of them all. One Verb now records
the first verb on the command line. A verb word after it is taken as
that verb takes any other word: a glob after test, lint and format, the
script's name after run, a project arg after clean, as it already was
for two different verbs. Only a repeated word changes: `test test`,
`lint lint` and `format format` now take the second word as a glob
instead of reading it as the verb again. That fixes
`format --check format`: the second `format` set the mode back to
applying and recorded no glob, so the run applied every rule and rewrote
the project's sources, though --check writes nothing.
2026-11-09 01:55:30 +01:00
194af206cc
docs: the Flatpak output in the README and --help
A section on packaging a program as a Flatpak: how to ask for it, what
its bin directory holds and what flatpak build-finish adds to it, what
cfg.flatpak describes, what cannot be a Flatpak and why, and -march for
other machines. It also says where a program finds its files once
installed, which is not the working directory -r gives it. --help lists
the standard flags with --packaging= among them, says how -r runs a
program, one for the host in its own directory, a wasm32 one under
wasmtime or wasmer and one built for the browser served from its
directory, and names CRAFTER_BUILD_FLATPAK_INFO. The package script
example tars ProgramDir(), the program and its files.
2026-11-09 01:55:30 +01:00
27031ed8e3
feat: lay an executable out as the files/ of a Flatpak
A Linux executable built by the Flatpak crafter-build links the libc++,
libc++abi and libunwind in its /app/lib and the Sdk's glibc, so it runs
inside crafter-build's sandbox and practically nowhere else: a host
needs glibc 2.38 or newer and all three LLVM libraries, which not even
Arch has. A program built here is meant to run in a Flatpak, so it can
now be laid out as one: with cfg.packaging = Packaging::Flatpak, or
--packaging=flatpak where the project.cpp crafter-build was pointed at
calls ApplyStandardArgs, its BinDir() holds files/, what becomes /app in
the app's sandbox, and -r runs the program there against the libraries
the app carries.

The program is linked into files/bin, where its shaders, files and
assets land too (ProgramDir()), with $ORIGIN/../lib as its one run path,
and the new :Flatpak partition writes the rest of files/: files/lib with
the LLVM runtime libraries, located one by one through clang, and
whatever else the program needs, read with llvm-readelf, that the
directories of the shared libraries it is built on hold, the ones an
unpackaged link records as run paths, or the toolchain's own lib dir,
/app/lib in crafter-build's Flatpak, which the link searches too; and
the desktop entry, metainfo and icons under the app-id in files/share,
the entry refused when its Icon= is not the app-id or
desktop-file-validate, where there is one, rejects it, and an icon that
is not an .svg or a square .png. The metadata and export/ of a build
directory are flatpak build-finish's to write, and crafter-build keeps
no copy of its rules: what a permission means and what the host sees of
an app change with flatpak's releases, and a copy would have to follow
every one. The writer copies a file only when its content differs,
compared a block at a time so that a large file costs no more memory
than a small one, and writes one only when what it would write differs,
never deciding by an mtime, which ostree sets to 0 for every file of
/app, and works the program's libraries out on every write, which reads
only their dynamic sections, since a library replaced in place, as by a
toolchain update, can need others, which FlatpakLibraryChange checks; it
prunes from files/bin each top-level entry an earlier build put there
and this one does not, reporting those the program wrote there itself.

What cannot be a Flatpak is refused before anything is built, saying
why: a Windows or wasm executable, a build against a sysroot or for
musl, another architecture than the runtime's, a build against
CRAFTER_BUILD_LIBCXX_DIR, whose libc++ the Flatpak would not carry, and
a build by a native crafter-build, which links the host's glibc: a
native process knows no Flatpak runtime, from /.flatpak-info, unless
CRAFTER_BUILD_FLATPAK_INFO, the tests' hook, names a file with one.
Default stays the executable as linked for now, RunTests runs every test
as linked, whatever its Configuration asks for, and RunLint works out
its compile command so, and a forwarded --packaging= leaves a
dependency's executables alone, since consumers run them by path. A
dependency that packages its own executable gets its desktop file,
metainfo and icons rebased by the loader as its cfg.files are, so they
are its own whatever directory the consumer builds from. Only a Flatpak
is keyed into VariantId, so every other configuration keeps its
directory, but for one given --packaging=, which was a project arg,
hashed into VariantId, and is a standard arg now, a dependency's
included. The app-id and what a Flatpak is installed as are not keyed:
they change files/share, never what is compiled. The asset name map,
kept three times, twice in Build() and once for the browser runtime's
files.json, is one function now, CompressedAssetName; CompressAsset, in
Crafter.Build-Asset.cpp, keeps the list of the extensions it loads,
which has to agree with it. Each copy a Flatpak build makes into the
program's directory, of its shaders, assets, cfg.files and what its
dependencies forward, records the top-level name it places there, the
names of what a directory holds for one copied into it itself ("data/",
"data/."), and those are what the writer keeps in files/bin; a build
that fails after copying adds them to the writer's record all the same,
so the next write removes what no build places any more.

SharedLibraryRuns now also packages its program as a Flatpak, whose
files/lib has to carry libgreet.so for it to start.
2026-11-08 22:48:42 +01:00
7283610128
docs: how a dependency's headers reach its consumers
The README's Dependencies section never said how a dependency's headers
reach the projects built on it, so the fix's rule had nowhere to be
stated: its directory and every include/ in its tree are on their
include path, except under a directory named bin or build, and a header
kept under one of those needs an -I of its own in cfg.compileFlags.
2026-11-07 19:24:12 +01:00
da714a0121
test: the include walk leaves out every bin/ and build/
IncludeWalkOutputs stages a library at a project's root, a program
beside it and one in a directory below it, a project of its own beside
the library with a project.cpp, and an include/ in the bin/ or build/ of
each, as a flatpak-builder tree leaves one. The include flags of both
programs hold the library's include/ and none of the others. Before the
fix every one of them was on the include path.
2026-11-07 19:24:12 +01:00
703c700dc0
fix: leave bin/ and build/ out of the include walk
GetCompileCommand put every directory named include in a dependency's
tree on the include path, bin/ and build/ included, so what a build had
left there came before the system's headers in every C++ and C compile
built on the dependency. In this repository build.sh leaves glslang's
CMake tree in build/glslang/build, and the `run flatpak` script leaves
flatpak-builder's /app tree in build/flatpak/build-dir, whose include/
holds the bundled LLVM's headers, clang-c/ and libc++'s among them:
crafter.build-lib's path is the repository's root, so crafter.build-exe
and every test took them. The walk now leaves out every directory named
bin or build, the names crafter-build gives what it writes, wherever it
sits. Leaving out only the bin/ and build/ of the configurations in the
compile's graph would not do: a dependency's tree holds the outputs of
configurations outside it too, a program in a directory below it or a
project of its own beside it, as Crafter.Graphics' examples are. Of the
#include lines in the Crafter repositories and in the dependencies
crafter-build has cloned, the one that needs a header found only under
such a directory is glslang's own, in a source its CMake build compiles.
2026-11-07 19:24:12 +01:00
0cf2f629eb
test: a program built on a shared library starts
SharedLibraryRuns builds an executable on a LibraryDynamic dependency
and runs it, from its fixture and again from a directory whose name
holds a comma. Before the fix it failed at start with "libgreet.so:
cannot open shared object file".
2026-11-07 19:24:12 +01:00
bc98c87f01
fix: let a program find the shared libraries it is built on
The link of an executable built on a LibraryDynamic dependency took
lib<name>.so from the library's bin dir and recorded nowhere to find it
at run time: no run path pointed there and nothing copied it beside the
program, which mingw does for a DLL. The program failed at start with
"cannot open shared object file". A shared library now hands its bin dir
up as a run path, as a CMake external does with its build directory, and
a program linked against it records it. Run paths reach the linker
through -Xlinker, quoted for the shell (RunPathFlags), in a program's
link and in project.so's: unlike the external cache's directories, the
bin dir is the project's own, and clang splits a -Wl, value at every
comma its name may hold.
2026-11-07 19:24:12 +01:00
aa6b555395
refactor: carry run paths as directories, not -Wl,-rpath flags
ExternalOutputs put an -Wl,-rpath,<dir> per library directory of a CMake
external into its link flags, and the flags travelled up the dependency
graph in BuildResult::libs to every link that consumed them: an
executable's or a shared library's, and that of the project.so
LoadProject links against a project file's pragma dependencies. Whether
a program should record those directories depends on how it is packaged:
a Flatpak has to load its libraries from its own files/lib instead, and
has to know the directories to copy them from. ExternalBuildResult and
BuildResult now carry them as runPaths, merged up the graph beside libs,
and all three links turn each into an -Wl,-rpath as before, so the link
commands differ only in the order of their flags. PragmaSharedExternal
holds project.so's link to them.
2026-11-07 19:24:12 +01:00
06ee1da796
test: a pragma dependency built on a shared CMake external loads
PragmaSharedExternal loads a project file whose #pragma crafter
dependency is a library built on a CMake external that makes a shared
library, and calls into that library while project.cpp loads.
LoadProject links project.so against what each pragma dependency's build
reports, and project.so loads only when that includes where the shared
library is. It passes as the tree stands, and holds project.so to
recording where a pragma dependency's shared CMake external is: without
that run path, LoadProject fails with "libsharedext.so: cannot open
shared object file".
2026-11-07 19:24:12 +01:00
5a63dd81b8
refactor: route an executable's outputs through ProgramDir()
Build() put an executable and the files it reads at run time (its
shaders, cfg.files, assets, and what its dependencies forward to it) in
BinDir() directly, and ExpectedOutput(), -r and the wasm variant copies
each spelled the same directory again. A Flatpak keeps its program in
files/bin of the build directory instead, so those places now ask
Configuration::ProgramDir(), which for every configuration is still its
bin dir. Nothing moves yet.
2026-11-07 19:24:12 +01:00
3044ac34a1
test: a wasm test declared with AddTest runs under wasmtime
WasmTestRuns declares a wasm32-wasip1 test on a fixture project and runs
it through RunTests, which builds it and hands it to the wasmtime runner
its target derives. The test has to pass and print its own output.
Before the fix every such test failed with "failed to open wasm module",
because RunTests left the .wasm off. It skips where the WASI sysroot
with exceptions or wasmtime is missing, as WasmHelloRuns does, so it
runs in the Flatpak and skips on a development box without them.
2026-11-07 03:25:13 +01:00
5d843f3967
fix(test): run the binary the link wrote, .wasm included
RunTests worked each test binary's path out with a rule of its own,
TestBinaryPath: BinDir()/<name>, plus .exe for any triple naming windows
or mingw, and nothing for wasm. The link writes <name>.wasm for a wasm32
executable, so every wasm test declared with AddTest was handed to
wasmtime without its extension and failed with "failed to open wasm
module", inside the Flatpak as well, where wasmtime is bundled. RunTests
now asks ExpectedOutput(), the name the staleness checks and -r read,
which for a wasm32 executable is the <name>.wasm the link writes.
2026-11-07 03:25:13 +01:00
0cc699139c
docs(packaging): add the 6.0.0 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 12m12s
The release of this push and of everything on master since 5.0.0: lldb,
the Khronos validation layer and the SPIRV-Tools programs in the
Flatpak, --die-with-parent in the README's alias, and the release
.flatpakref with the repository's key in it. Its Breaking item, the end
of beta and of the rolling release, makes it a major.
2026-11-02 17:17:02 +01:00
54aaf078b2
docs: a release is a signed tag pushed with master
The README offered master builds as the `beta` branch, AGENTS.template.md
described the `latest` tag CI force-pushed, a release as a tag pushed
after master, and CI as running on every push to master, and the
repo-better-solution lens told reviewers that users get master through
`beta`.

The README now says that releases go to `stable`, the branch its install
commands pick even while the repo still holds the old `beta` branch.
AGENTS.template.md says that every pushed range adds a release entry and
goes out in one push with a signed tag on the commit master receives,
its last commit or, on the pull-request path, the merge, how to write
the entry, what every run checks before building and what a tag run also
checks, publishes and creates, what follows when one fails, what CI runs
for, and what becomes of `beta`; the lens says users get master through
releases on `stable`. The entry's rules are the owner's: at most three
sections, New, Fixes and Breaking, the most important item first and
nothing after them, and a version that is a major for a Breaking
section, a minor for New items and a patch for Fixes alone. The release
paragraph also gets the blank line that keeps it apart from the one on
local builds.
2026-11-02 17:17:02 +01:00
be81fc098e
feat(ci): drop beta and latest, release signed tags on master
A push to master published the `beta` branch and moved the rolling
`latest` tag and its "Latest master build" prerelease, and a pushed
X.Y.Z tag made the release and published `stable`. The owner wants a
release for every push to master, made by the signed tag that goes with
it, and nothing for a push without one. So `beta`, `latest` and the
branch trigger are gone: the workflow runs for pushed tags, pull
requests and manual runs only, and the `latest` tag and its prerelease
have been deleted from the forge.

`beta` gets no more builds, and its installations would not hear of it:
the release notes ship in stable builds only. The Publish step marks
beta's last build end-of-life, once, with a reason that names stable,
and the next `flatpak update` of a beta installation prints it. The
reason also names the branch, because a non-interactive update prints
only the app's name with it.

Before building, a tag run now checks the tag: it has to be annotated
and signed by the owner as Forgejo verifies it, its commit has to be on
master, its version has to be X.Y.Z and newer than every release the
forge has published, its own included (a later tag whose run still
queues does not count), and the metainfo's newest <release> entry has to
be that version. The tag run checked only the last of these. It reads
the tag from the forge's API, because the checkout fetches a pushed tag
again as a plain ref to its commit, so the job's clone never has the
annotated tag, and Forgejo verifies a signed tag's own signature but
falls back to the commit's for an unsigned one, so the step also
requires that the verdict covers the tag's payload. The metainfo's entry
is read once, as the first <release> element: the Version step takes its
version and renders its notes into release-notes.md with the renderer
the Release notes step had, and stops the run when they come out empty,
so a comment or another attribute order cannot give a release one
entry's version and another's notes. It does so on every run, pull
requests and manual runs included, so a broken entry shows before a
release.

Release runs share a concurrency group, so they queue one behind
another; a pull request still cancels its own outdated run. A failed
release run can be re-run while no newer release exists, since its tag
is still on its commit; a release that an attempt left half made has to
be deleted first. The release step runs without `override`, which would
delete a tag that has moved off the run's commit since the Version step
and tag the old commit instead.

A manual run no longer publishes anything; it used to publish `beta`
and move `latest` from whichever branch it was started on. No step
pushes to git, so the checkout keeps no credentials. git describe in
build.sh, project.cpp and the workflow has no `latest` tag left to
exclude.
2026-11-02 17:17:02 +01:00
2babe94a6a
fix(ci): publish under the lock Crafter.Review's workflow takes
Crafter.Review's workflow publishes its Flatpak into the same repo, the
web root's repo/, and holds an flock on .publish.lock in the web root
while it commits and updates the summary. Its comment says that this
protects both only once Crafter.Build's workflow takes the lock too, and
ours never did, so a publish of each could interleave: a
build-commit-from and a build-update-repo --generate-static-deltas
--prune of each workflow on one repo at the same time.

The Publish step now holds the same lock from its commit to the ref
files it writes into the web root, and the job installs util-linux for
flock, as Crafter.Review's jobs do.

AGENTS.template.md says that the repo is shared and the lock taken.
Neither it nor the workflow's header comment says any longer that the
web root and the signing key are this runner's alone, or that the
organisation-wide `flatpak` runner mounts none of them. That runner,
which serves every Catcrafts repository and refused all of this job's
volumes when it last took it, in October, now mounts the web root and
the key for Crafter.Review's publish job, and the volumes a runner
allows are open to every job it runs. The owner has ruled the sharing
intended. The header also stops saying that a job of ours that lands
there fails before building: that held while the runner refused every
volume, and AGENTS.template.md keeps it as the October history.
2026-11-02 14:56:41 +01:00
2447d6ec4f
fix(ci): attach the flatpakref with the repo's key to releases
The Bundle step copied packaging/flatpak/net.catcrafts.CrafterBuild.flatpakref
into dist/ as the checkout has it, with GPGKey=GPG_KEY_BASE64_PLACEHOLDER,
so all six releases, 2.0.0 to 5.0.0, attach a .flatpakref that does not
install: `flatpak install --from` it stops with "GPG: Unable to export
keys: GPGME: No data" (Flatpak 1.18.4) before it adds the remote. The
copy the publish step writes to the web root has the key filled in, and
installing from it goes ahead.

The key is known only from the publish step on, so the release's copy,
and SHA256SUMS over it, are made there from the web root's file instead
of in the Bundle step.
2026-11-02 14:56:41 +01:00
a1bc96a323
fix(review): name each lens section, as crafter-review 1.0 requires
crafter-review 1.0.1, the released build installed on this machine, and
the newer build installed beside it as //local refuse the config key
lensSections: a lens's repository section is named per lens, as
lenses.<name>.section, instead of being found by listing a directory.
With the key in place `crafter-review config` reports it as a problem,
and freeze and run stop at "preflight: config: unknown key lensSections".

The three files in .review-gates/lenses/ are named under lenses, one
entry each, the migration the Crafter.Review session gave; with them
`crafter-review config` reports no problem.
2026-11-02 14:56:41 +01:00
00f07dae88
docs: push reviewed ranges straight to master
All checks were successful
Flatpak / flatpak (push) Successful in 30m58s
AGENTS.template.md had every change go through a pull request against
master. The owner has made pushing straight to master the default.

The commit and push guidelines say so: an approved range is pushed to
master as a fast-forward, with no merge commit, and a pull request is
opened only when the owner asks for one; when master has moved since
the freeze, the range is rebased, frozen and reviewed again. What
follows from that: the README changes in the same push; without a pull
request CI does not run on a range before it reaches master unless
someone starts it by hand, so the review's gate0 is the check before the
push; and the freeze exception for a merge commit applies only to a pull
request. Design rule 8, the testing note and the release steps lose
their pull-request wording, and the testing note no longer speaks of a
commented-out lint step: ci.yaml has no lint step at all.
2026-11-01 23:21:35 +01:00
03951ff458
docs: update the first local Flatpak build's time and size
AGENTS.template.md and project.cpp gave the first run flatpak as about
25 minutes on a 56-core machine and its state as about 2 GB, figures
written on 2026-10-06, before lldb and the Vulkan and SPIR-V modules
were in the manifest. A first run of this commit's manifest, in a fresh
worktree, took 30 min 36 s with 56 CPU threads, 14 min of it for LLVM
with lldb, and left build/flatpak at 4.1 GB, 3.3 GB of it state/.

The figures become those, and the line on later runs says that they
rebuild only the crafter-build module while the manifest is unchanged.
2026-11-01 22:28:08 +01:00
40dcb18a1e
feat(flatpak): ship the SPIRV-Tools programs
Crafter.Graphics' PushConstantRewrite and UIFusedShader tests require
tool:spirv-val, and the Sdk has no spirv-val, so inside the Flatpak they
are skipped. The spirv-tools module the validation layer needs built
only the libraries, and removed them afterwards.

It now builds the programs as well, spirv-val, spirv-opt, spirv-dis and
the rest, which link SPIRV-Tools statically, and ships them. The
headers, the static libraries, the CMake and pkg-config files and
libSPIRV-Tools-shared.so, which nothing here links, are still removed,
and a post-install step runs spirv-val --version.
2026-11-01 22:28:08 +01:00
c8517a41cf
docs(readme): --die-with-parent in the install alias
flatpak run becomes bubblewrap, and without --die-with-parent the
sandbox outlives it. With crafter-build started through the alias in an
interactive bash or zsh on a terminal, SIGKILL to its flatpak run
process alone left a -r program running and a build writing into bin/
and build/. With the flag, both ended with it.

bubblewrap kills the sandbox when flatpak run or its parent dies, and
for crafter-build typed at the prompt, in the foreground or with &, that
parent is the shell: with the flag, the sandbox also ended when the
shell was SIGKILLed, or exited after a disown. In a (crafter-build -r &)
subshell, flatpak run outlives the subshell and is adopted by another
process, so its sandbox outlived the shell with the flag as well. Ctrl-C
ended the program either way.

The README's alias gets the flag, and the paragraph after it says what
that changes: a program started through the alias, as crafter-build ...
or crafter-build ... & at a bash or zsh prompt, ends with its shell,
even after a disown.
2026-11-01 22:28:08 +01:00
a32b8c898a
docs: debugging inside the Flatpak
The README gets a Debugging section: the debugging tools the sandbox
carries, that a program to debug needs cfg.debug (which --debug sets
where the project calls ApplyStandardArgs), how to start the tools with
--command, why a debugger in one flatpak run cannot see a program that
another one started (each has process IDs of its own), and flatpak
enter as the way into a running program's sandbox, with the ptrace
opt-in that takes where ptrace_scope is 1. It warns off lldb's
gdb-remote from a second sandbox: when a process in lldb's own sandbox
has the remote program's process ID, lldb takes that process's
executable for the program's. And it shows which variables turn the
layer and GPU-AV on from the environment, and that VK_LAYER_PATH and
VK_ADD_LAYER_PATH do not reach the sandbox.

AGENTS.template.md gets the module layout and the rule that the layer
follows the Sdk's Vulkan loader. Its CI section says that a change to a
module's sources or build-commands builds it again and every module
after it, so that a new version of swig or libedit, which come before
LLVM, now rebuilds it too, and loses the cold-run time it gave, written
on 2026-10-03, before any of these modules were in the manifest.
2026-11-01 22:28:08 +01:00
16db37bbe6
feat(flatpak): ship lldb and the Khronos validation layers
Programs that -r and the test runner start run inside the Flatpak's
sandbox, and the Sdk it runs on has gdb but neither lldb nor the Khronos
validation layer: in the sandbox of beta 5.0.0, a vkCreateInstance that
asks for VK_LAYER_KHRONOS_validation returns VK_ERROR_LAYER_NOT_PRESENT.
flatpak run clears VK_LAYER_PATH and VK_ADD_LAYER_PATH, so the layer the
host has cannot stand in.

lldb becomes a project of the llvm module and brings lldb-server,
lldb-dap and lldb-mcp. Its Python, libedit, curses, libxml2 and lzma
support are set ON instead of being left to detection, so a dependency
that goes missing fails the configure step rather than shipping an lldb
without it. The Sdk has neither SWIG nor libedit, so both become modules
before llvm, SWIG as build-only.

The layer is Vulkan-ValidationLayers vulkan-sdk-1.4.357.0, the Vulkan
SDK release of the Sdk's loader (libvulkan.so.1.4.357), built from
Vulkan-Headers, Vulkan-Utility-Libraries, SPIRV-Headers and SPIRV-Tools
at the revisions that release's scripts/known_good.json names. Those
four are built into /app at those revisions and removed afterwards. All
five come after the LLVM and WASI modules, so that bumping them reuses
the cached LLVM and WASI builds. UPDATE_DEPS is turned off: it defaults
to ON, which has update_deps.py clone the dependencies, and of all the
modules only crafter-build's build-args share the network.
2026-11-01 19:20:22 +01:00
e2bd0b14ee
feat(review): set up Crafter.Review's pre-push review
All checks were successful
Flatpak / flatpak (push) Successful in 13m7s
Crafter.Review reviews a frozen commit range before it is pushed: the
approach, a static proof of the code's bugs, and every claim in the
messages and in the documentation the range changes, one claude process
per lens and unit, or per whole-range pass, and the owner approves the
exact frozen hash before the push. This sets it up for this repository.

.review-gates/config.json turns on three lenses in the commits mode, at
xhigh: repo-better-solution, repo-bug-prover and repo-facts. The
functional lens is off: it exercises a web application through a
browser, and this repository's product is a command-line tool. The
security lens is off by the owner's ruling: crafter-build stores no
secret of its own, and while its Flatpak runs with the user's SSH agent
(--socket=ssh-auth) and the whole host filesystem (--filesystem=host),
everything it runs is code its user chose to run. The rules CI keeps
around its token and signing key go to the approach lens's section
instead.

gate0 lists the commands run by hand before a freeze. build.sh comes
first, because bin/crafter-build compiles project.cpp against the
interfaces it was bootstrapped with, and lint comes after the self-host
build, because lint's AST rules parse with the module PCMs a build
leaves and lint builds only the std PCM itself.

.review-gates/lenses/ holds this repository's section of each lens's
charter, appended to the text Crafter.Review ships: that AGENTS.md is
absent from the frozen tree, the layers and the consumers of
interfaces/, the execution contexts a bug can hide in, where libc++ and
clang are readable from the review's sandbox, and what a "passes the
suite" claim traces to.

The /prepush skill that crafter-review init writes stays untracked. It
is generated from the installed Crafter.Review and refreshed by every
init, so a committed copy would lag the binary it describes. One init
per checkout restores it, which AGENTS.template.md now says, together
with the rules freeze holds every commit of a range to: signed
(requireSigned), with the owner's address as its author and committer
(authors), and no AI attribution trailer (aiTrailers forbid).
2026-11-01 17:33:27 +01:00
a3fe1bdda7
docs(packaging): add the 5.0.0 release entry
All checks were successful
Flatpak / flatpak (push) Successful in 11m53s
The fix for #43, a mingw build that saw the host's glibc headers and
Linux libraries through a prefix like /usr as clang's sysroot, and what
the review of it brought along: units that recompile after a std module
rebuilt in place, CMake externals built again when their configure
inputs change, std modules keyed on every flag they are compiled with,
and lint that fails rather than passing files it could not parse. A
major, because Toolchain::mingwSysroot is now mingwPrefix and every
build directory moves once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 23:55:28 +01:00
76831d6733 Merge branch 'claude/issue-43': mingw builds without the host's headers, std modules keyed on their flags
All checks were successful
Flatpak / flatpak (push) Successful in 11m41s
Brings in the fix for #43. The mingw target no longer gets a system
prefix (the host's /usr in the Flatpak, or any prefix whose include/
has a C library's features.h) as clang's --sysroot, but a view of its
mingw-w64 parts, made in the cache or in $XDG_RUNTIME_DIR; a prefix of
mingw-w64 alone stays the sysroot whole. From the review of the first
version: the std module's directory is keyed on every flag it is
compiled with and VariantId on that key, so every std PCM and build
directory moves once; units record the BMIs they import; a CMake
external whose configure inputs changed starts from an empty build
directory; lint fails a configuration that has no compile command.
Toolchain::mingwSysroot is now mingwPrefix.

The MingwSysroot test writes its stand-in std module through
std::format, because the module scanner reads string literals as code.
#45 replaces the scanner's regexes with clang-scan-deps.

The branch starts at master's tip, so the merge is a tree identical to
the branch's; that tree passes format, lint and the test suite, natively
and inside the Flatpak sandbox, and CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:35:49 +00:00
c56d98abba
docs: which mingw prefixes are viewed, and what keys the std module
All checks were successful
Flatpak / flatpak (pull_request) Successful in 7m28s
The README said every prefix reached clang as a view of its
x86_64-w64-mingw32/ and lib/gcc/, in ~/.cache. It now says a prefix is
the sysroot as it is unless it also holds a Linux system, names
lib64/gcc/ as well, gives the view's place inside the Flatpak and the
XDG_RUNTIME_DIR fallback, and says messages name headers by their path
in the prefix.

AGENTS.template.md describes MingwSysroot's two outcomes and
MingwViewToPrefix, has the std PCM keyed on its flags in the cache
rule, lists StdPcmKey among what VariantId hashes, and gains two
gotchas: anything that changes how the std module is compiled goes into
StdPcmFlags, and a CMake external whose recorded configure inputs
differ is built again from an empty directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:59:47 +01:00
55ad128b79
test: lint fails when a configuration's std module cannot be built
A host configuration pointed at a sysroot without libc++ cannot get its
std module built, so its files cannot be parsed. With an AST rule
registered, the run has to skip the rule and fail instead of reporting
the files clean, as it did before the fix. The cache is redirected
around this run only: the std module's directory is made before its
build fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:59:38 +01:00
40dcf2271d
fix(lint): fail the files whose configuration has no compile command
When GetCompileCommand threw or the std module failed to build, the
lint driver cleared the configuration's command, and an empty command
means "not a translation unit" (project.cpp, a header): every rule that
needs an AST skipped the files quietly and the run passed them as clean.
MingwSysroot made that reachable for every mingw configuration whose
view cannot be made. The reason is now kept per configuration and
reported as an AST failure for each of its files, which fails the run
and prints it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:59:37 +01:00
0e69e71b11
test: a CMake external configured with other inputs is built from nothing
ExternalReconfigure builds a one-file C library from a local repository
as a CMake external, then plants a file in its build directory to stand
for what an old configure left. Built again with the same inputs, the
directory is kept. With its recorded inputs rewritten the way another
crafter-build's configure would have left them, the next build has to
start from an empty directory and build the library again. Before the
fix the planted file survived the reconfigure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:59:23 +01:00
56b44f616a
fix(external): start a CMake build over when its configure inputs change
ConfigureCMake records the flags it injects (compiler, libc++, and for
the mingw target CMAKE_SYSROOT) and reconfigures when they differ, but
it did so in place. CMake then keeps what the old flags compiled: the
Makefiles generator writes --sysroot into build.make, which make does
not compare, so nothing was recompiled, and the check results the old
configure cached stay too. A mingw external built by a release that gave
clang the host's /usr as the sysroot kept its objects reading
__libc_single_threaded after the fix for #43, and only deleting
<cache>/external/<name>-<hash>/build by hand got rid of them.

A build directory with a CMakeCache.txt whose recorded inputs differ is
now removed before the configure. It keeps its name, since projects
point include directories at headers generated in it. The two
crafter-builds the Flatpak's branches are, sharing one cache, rebuild
such an external from nothing each time they take turns, where they
used to reuse each other's objects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:59:22 +01:00
8e759a8410
test: a std module rebuilt in place recompiles the units importing it
StdPcmRebuild builds a project whose main.cpp imports std, then dates
the source before the object and the object before std.pcm, as a std
module rebuilt after the object leaves them, so that nothing else makes
the object stale. The next build has to compile main.cpp again, and the
idle build before it must compile nothing. Without -fmodule-file-deps
the object was only relinked. The test redirects the cache, since
redating a std PCM the real cache shares would rebuild its other users.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:59:06 +01:00
27697d06aa
fix: recompile the units whose std module was rebuilt in place
A .cpp unit's depfile listed its source and headers, never the BMIs it
imports: clang's driver adds -module-file-deps to --precompile only. A
std module rebuilt in its directory, which happens whenever its source
changes under one compiler and one set of flags (a libc++ update, or
mingw-w64's under the same prefix), left every object that imports it
as it was, and the next build only relinked them. Implementation units
are now compiled with -fmodule-file-deps, so the std PCM and the
project's own PCMs are prerequisites of their objects like headers.

Depfiles written before this lack the edge, so a std module that moves
directories still needs VariantId to move with it (StdPcmKey).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:59:05 +01:00
5d25495621
fix: key the std module's directory on everything it is compiled with
StdPcmDir named the directory by target, march and toolchain, then
grew a case per target for the rest: the wasm flags, and with the first
fix for #43 the mingw prefix. Every other flag BuildStdPcm passes went
unkeyed, so configurations that differed only there took turns
rebuilding one std PCM in place, under the PCMs built against it: a
project with -mtune=generic against project.cpp's -mtune=native on every
run, or two sysroots for one target. And the mingw prefix was keyed only
when there was one, so a build without a prefix landed in the directory
an older release had filled with a CRAFTER_MINGW_DIR=/usr build, and
relinked its objects.

StdPcmFlags is now the one source of the flags BuildStdPcm compiles
with, and StdPcmKey names the directory by target, march and toolchain
followed by a hash of those flags and, for the mingw target, of the
prefix behind its --sysroot. VariantId hashes StdPcmKey in place of the
mingw prefix: units do not notice a std module that moved directories,
so a build has to move with it. Every std PCM directory and build
directory moves once, as after a compiler update; the old ones stay
until `clean` and the cache is cleared by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:58:44 +01:00
06b61e84f9
fix(mingw): view only a prefix that holds a Linux system
The first fix showed clang every mingw prefix through a view of its
mingw-w64 parts. That broke a prefix that holds mingw-w64 alone, where
Windows libraries installed with --prefix land in include/ and lib/:
with CRAFTER_MINGW_DIR=/opt/mingw, <SDL2/SDL.h> and -lSDL2 were no
longer found. Such a prefix is clang's sysroot whole again. Only a
prefix that also holds a Linux system gets the view
(Toolchain::mingwPrefixIsSystem): the host's /usr inside the Flatpak,
whatever its include/ holds, and a prefix whose include/ has a C
library's features.h, which every glibc and musl header includes and
mingw-w64 has no use for, as CRAFTER_MINGW_DIR=/usr has.

MakeMingwSysroot makes the view in the cache, or in
$XDG_RUNTIME_DIR/crafter.build when the cache's filesystem takes no
symbolic links (vfat, exFAT, CIFS without unix extensions): the XDG
spec promises them there, and nothing else in the cache needs them.
Its path is absolute, because CMake runs the compiler from directories
of its own and a relative cache did not resolve from there. The prefix
is resolved once, absolute and lexically normal, so /opt/mingw/ and
/opt/mingw are one prefix and not two builds.

clang names a header by the path it found it at, so every diagnostic
from a viewed mingw-w64 header named a hashed cache directory.
RunBuildCommand now writes paths into the view as paths into the
prefix, as BuildStdPcm did for its manifest messages already.

Also from the review of PR #44: SysrootCompileFlags builds a mingw
command, which can make a view, so it redirects the cache like the
other tests; the manifest filter's comment names what it still keeps
out; the C path asks MingwSysroot() once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:58:30 +01:00
5fdbf2baee
docs: the mingw sysroot view in the README and AGENTS.template.md
All checks were successful
Flatpak / flatpak (pull_request) Successful in 7m2s
The README says which directories of a mingw-w64 prefix clang sees, and
why the rest of a prefix like /usr is kept out of a Windows build.
AGENTS.template.md names MingwSysroot in the :Toolchain partition, with
the reason the prefix itself is never a sysroot, counts the views among
what goes in the cache, and adds the mingw prefix to what VariantId
hashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:48:06 +01:00
b162cc0552
test: a mingw build sees no header from its prefix's include/
MingwSysroot stages a prefix shaped like a Linux system's /usr with a
mingw-w64 cross toolchain in it, without needing a real one: glibc's
<sys/single_threaded.h> in include/, gcc's per-target directory, and a
stand-in mingw-w64 tree whose libstdc++ has an empty std module. A
static library for x86_64-w64-mingw32, so that nothing is linked,
compiles a C++ and a C source that stop with #error when they see the
prefix's include/ or miss mingw-w64's or libstdc++'s headers. Against
the library before the fix, the C++ source stopped on
<sys/single_threaded.h>. The test also checks that the std module is
not cached in the directory older releases built it in against the
prefix itself. It needs only clang, so it runs in CI too, where no
mingw-w64 is installed.

The stand-in std module's source is written through std::format: the
build's import scanner reads string literals as code, and the literal
"export module std;" made the test itself a unit of a module std.

VariantId checks that a prefix gives a mingw configuration a variant of
its own, that two prefixes give two, and that other targets ignore it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:48:06 +01:00
ab998081e1
fix: give the mingw target a sysroot that holds mingw-w64 alone
Inside the Flatpak the mingw-w64 prefix is the host's /usr, and it was
clang's --sysroot as is. clang's mingw driver takes a sysroot for a tree
that holds mingw-w64 alone, and adds its include/ to the include path
and its lib/ to the library path. For /usr those are the Linux system's
own: every header mingw-w64 lacks came from glibc, and libstdc++'s
<ext/atomicity.h>, finding <sys/single_threaded.h>, had shared_ptr read
__libc_single_threaded, which nothing on Windows defines. Every program
that used one failed to link, among them every Crafter.Graphics Win32
executable, through Crafter.Asset's GLB loader. CRAFTER_MINGW_DIR=/usr
did the same outside the Flatpak (#43).

The sysroot is now MingwSysroot(): a directory in the cache, one per
prefix, holding only links to the prefix's x86_64-w64-mingw32/, lib/gcc/
and lib64/gcc/ (where openSUSE keeps gcc). Through it clang finds
mingw-w64, gcc's version and libstdc++ exactly as it does through the
mingw gcc on PATH, and nothing else. It is made by the first mingw
compile, link or CMake configure of a process, so no other command
writes to the cache for it and a failure to make it is that build's
error. The Toolchain field is now mingwPrefix, since clang never gets
the prefix itself, and it is made absolute when the toolchain is
resolved, as it ends up in link targets and directory names. Messages
keep naming paths under the prefix rather than under the view.

The prefix is also part of the mingw target's VariantId and of its std
PCM directory. Units do not track the std PCM they import: when the
fixed release built in a directory a broken build had left, the std
module was rebuilt and the objects compiled against glibc's headers
were only relinked, failing as before. As with a compiler update, a new
directory is what gets them rebuilt. It also keeps two releases that
share a cache, as the Flatpak's branches do, from rebuilding one std PCM
under each other's PCMs, and two prefixes apart. Without a prefix both
stay as they were: clang's own discovery has not changed.

Two shorter ways do not work: --sysroot=<prefix>/x86_64-w64-mingw32
loses the directory gcc's version names, so <string> is not found, and
clang ignores --gcc-toolchain and --gcc-install-dir for this target.

Fixes #43

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:48:06 +01:00
909e027698
feat(ci): leave the install commands out of the release notes
All checks were successful
Flatpak / flatpak (push) Successful in 11m5s
Every release page ended in the two flatpak commands that install
crafter-build, which the top of the README already gives. The notes
now stop at their last section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:36:32 +01:00
7dd9785058
docs(packaging): add the 4.0.0 release entry
Some checks failed
Flatpak / flatpak (push) Has been cancelled
AGENTS.md written from a tracked AGENTS.template.md, so the dependency
notes no longer change a file the project commits. A major, because a
project that kept 3.0.0's notes section in its committed AGENTS.md
stops getting it updated until it moves to the template: the rule is a
major whenever the notes have a Breaking section, even one that no
build fails over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:27:31 +01:00
7678286f0d
Merge branch 'claude/agents-template': AGENTS.md written from a tracked AGENTS.template.md
All checks were successful
Flatpak / flatpak (push) Successful in 11m17s
Brings in the template: a project commits AGENTS.template.md, and
`crafter-build` and `crafter-build test` write a gitignored AGENTS.md
from it with the dependency notes merged in, so a change to a
dependency's notes no longer shows up in the consumer's diff. An
AGENTS.md no build wrote is never replaced, and without a template
AGENTS.md is left alone, with a warning when it still holds a 3.0.0
section. This repository moves its own AGENTS.md to the template.

The branch starts at master's tip, so the merge is a tree identical to
the branch's; that tree passes format --check, lint and the test suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:56:27 +01:00
5c3e9a874b
docs: keep this repository's agent notes in AGENTS.template.md
This repository now uses the template itself. AGENTS.md is written by
the self-host build and `test` and is gitignored, so the notes
Crafter.Math ships reach the agents working here, and a change to them
no longer leaves a tracked file modified, which also made every build
afterwards a dirty-tree version, a new crafter.build-lib variant and a
full rebuild.

The gotcha that described the old arrangement now says where to edit,
that a fresh clone or worktree has no AGENTS.md until its first build
(./build.sh does not write it), and what an older harness does to the
generated file. The paths table and the never-commit list name both
files. The CI error for a missing signing key and a manifest comment
point at the template, since the forge no longer shows an AGENTS.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:56:11 +01:00
2a5f541485
docs: AGENTS.template.md in the README
The dependency notes section now starts from the template: what to
commit and what to ignore, the two commands that move a project with a
committed AGENTS.md over, what a build writes, where the section goes,
and what becomes of an AGENTS.md no build wrote and of one that still
holds a section from 3.0.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:53:42 +01:00
74e8370b2b
feat(agents): write AGENTS.md from a tracked AGENTS.template.md
The dependency notes were kept in a section of the AGENTS.md beside
project.cpp, the file a project commits, so a build could change a
tracked file at any time: a dependency editing its AGENTS.consumer.md,
an unpinned one moving on, a flag pulling a dependency in or out, each
showed up in the consumer's diff as a change nobody made. Users
reported it as the feature clobbering their diffs.

A project now commits its instructions as AGENTS.template.md, and a
build and a test run write AGENTS.md from it: a first line saying the
file is generated and where to edit, the template's text as written,
then the notes section, after it or where the template's marker lines
put it. AGENTS.md is build output and goes into .gitignore. It is
created when missing, since a fresh clone has none, and otherwise
written as before: only when its text changes, in place and under a
lock, so links, ownership and a read-only file are respected.

The first line is also how a build tells its own AGENTS.md from one
someone wrote. Beside a template the second is easily there, as a
committed AGENTS.md nobody has removed yet; it is never replaced, and
each build warns until it is deleted. An empty file counts as a
build's, since that is what a write cut short leaves of a new one. An
AGENTS.md linked to the template is refused: writing it would write
the committed file again. A template the notes cannot be placed in
leaves no empty AGENTS.md behind.

The in-place mode is removed rather than kept as the fallback for a
project without a template. It is the default that put generated text
into tracked files unasked, the moment any dependency started shipping
notes. Without a template a build no longer touches AGENTS.md. One
that still holds a section from 3.0.0 would go stale silently, under a
preamble promising that every build rewrites it, so it gets a warning
naming the move instead.

MergeDependencyNotes keeps its rules and now runs on the template. The
test changes in this commit rather than its own, because it pinned the
in-place behaviour this removes: it now covers the generated file's
shape, edits and markers in the template, the ownership check, a CRLF
template, a link to the template and the cases without one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:53:42 +01:00
260 changed files with 16509 additions and 1807 deletions

View file

@ -1,37 +1,52 @@
name: Flatpak name: Flatpak
# One job, three outcomes: # One job, two outcomes:
# pull request -> build the Flatpak and run the suite inside it # pull request, manual run -> build the Flatpak and run the suite inside it
# push master -> also publish the result as the `beta` branch of the # pushed tag X.Y.Z -> also release the build: publish it as the
# Catcrafts repo and refresh the rolling `latest` release # `stable` branch of the Catcrafts repo and
# tag X.Y.Z -> publish as `stable` and create release X.Y.Z # create release X.Y.Z
#
# A release is a tag that the owner makes and signs locally and pushes with
# the master it releases; a push to master without one runs nothing. The tag
# names the version, and the metainfo's newest <release> entry has to be that
# version: its description is the release notes.
# #
# The `crafter-flatpak` runner label is the privileged runner on the Hetzner # The `crafter-flatpak` runner label is the privileged runner on the Hetzner
# box (bubblewrap needs it) with four volumes allowed: the Sdk install, the # box (bubblewrap needs it) with four volumes allowed: the Sdk install, the
# flatpak-builder state (ccache and the LLVM module, so only crafter-build # flatpak-builder state (ccache and the LLVM module, so only crafter-build
# itself rebuilds on a normal run), the published repo's web root, and the # itself rebuilds on a normal run), the published repo's web root, and the
# repo signing key, which lives on the runner host and never in the forge. # repo signing key, which lives on the runner host and never in the forge.
# No other runner carries that label. Plain `flatpak` also matches the # No other runner carries that label. Plain `flatpak` is the label of the
# organisation's runner, which mounts none of those volumes; a job it picks # organisation's runner, which serves every Catcrafts repository and also
# up fails before building anything. # mounts the web root and the key, for Crafter.Review's publish job, so any
# job it runs can mount them (AGENTS.template.md, CI and publishing).
on: on:
pull_request: pull_request:
branches: [master] branches: [master]
push: push:
branches: [master]
# Bare semver tags. Spelled with globs so it means the same whether the # Bare semver tags. Spelled with globs so it means the same whether the
# forge reads it as a workflow pattern or as a plain glob; `latest`, the # forge reads it as a workflow pattern or as a plain glob.
# rolling tag this workflow moves itself, does not start with a digit.
tags: ['[0-9]*.[0-9]*.[0-9]*'] tags: ['[0-9]*.[0-9]*.[0-9]*']
workflow_dispatch: workflow_dispatch:
# Pushes are tags only, so every release run is in one group, and a release
# starts only once the one before it has finished. A pull request's group
# also holds its number, which only a pull request's event carries, so a
# new push to it cancels its own outdated run and no other.
concurrency:
group: flatpak-${{ github.event_name }}-${{ github.event.pull_request.number }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env: env:
APP_ID: net.catcrafts.CrafterBuild APP_ID: net.catcrafts.CrafterBuild
BRANCH: stable
MANIFEST: packaging/flatpak/net.catcrafts.CrafterBuild.yaml MANIFEST: packaging/flatpak/net.catcrafts.CrafterBuild.yaml
CI_MANIFEST: packaging/flatpak/ci-manifest.yaml CI_MANIFEST: packaging/flatpak/ci-manifest.yaml
RUNTIME: org.freedesktop.Sdk//26.08 RUNTIME: org.freedesktop.Sdk//26.08
REPO_DIR: /srv/flatpak/repo REPO_DIR: /srv/flatpak/repo
WEB_DIR: /srv/flatpak WEB_DIR: /srv/flatpak
# A release tag carries a signature Forgejo verifies for this address.
RELEASE_SIGNER: jorijnvdgraaf@catcrafts.net
jobs: jobs:
flatpak: flatpak:
@ -45,11 +60,12 @@ jobs:
-v /etc/crafter-flatpak:/run/crafter-flatpak:ro -v /etc/crafter-flatpak:/run/crafter-flatpak:ro
steps: steps:
- name: Install tools - name: Install tools
# util-linux: flock, for the Publish step.
run: | run: |
pacman-key --init pacman-key --init
pacman-key --populate archlinux pacman-key --populate archlinux
pacman -Sy --noconfirm --needed archlinux-keyring pacman -Sy --noconfirm --needed archlinux-keyring
pacman -Syu --noconfirm --needed flatpak flatpak-builder ccache git nodejs jq gnupg go-yq ostree python pacman -Syu --noconfirm --needed flatpak flatpak-builder ccache git nodejs jq gnupg go-yq ostree python util-linux
git config --global --add safe.directory '*' git config --global --add safe.directory '*'
- name: Sdk - name: Sdk
@ -60,40 +76,137 @@ jobs:
flatpak update -y --noninteractive flatpak update -y --noninteractive
- name: Checkout - name: Checkout
# Every branch and tag, for git describe and the release checks; no
# step pushes, so the token is not kept in the checkout.
uses: actions/checkout@v4 uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
persist-credentials: true persist-credentials: false
- name: Version and channel - name: Version
id: meta id: meta
run: | run: |
set -eu set -eu
if [ "${GITHUB_REF_TYPE}" = tag ]; then # The metainfo's newest entry is its first <release> element, the
version="$GITHUB_REF_NAME" # one parse that gives both its version and the release notes,
branch=stable # before anything is built: a comment or another attribute order
# The metainfo's newest release is the release notes and must be # would mislead a text search, and an entry whose notes render
# the version being tagged. # empty stops the run here. The notes go to release-notes.md, for
top=$(grep -m1 -oP '<release version="\K[^"]+' packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml) # the release page, as Markdown. AppStream has no headings, so a
if [ "$top" != "$version" ]; then # paragraph that introduces a list is one: <p>New</p><ul>...</ul>
echo "metainfo lists $top as the newest release, but the tag is $version" >&2 # comes out as "## New" over its items, the shape the notes take
# since 3.0.0. A paragraph on its own stays a paragraph, as the
# older entries are written. <em> and <code> get their Markdown
# spelling; a code span also keeps text such as lib/<triple>/eh
# from being read as an HTML tag by the forge.
newest=$(python3 - <<'EOF'
import sys
import xml.etree.ElementTree as ET
release = ET.parse("packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml").getroot().find("releases/release")
desc = None if release is None else release.find("description")
def text(el):
parts = [el.text or ""]
for child in el:
inner = text(child)
parts.append({"em": f"*{inner}*", "code": f"`{inner}`"}.get(child.tag, inner))
parts.append(child.tail or "")
return " ".join("".join(parts).split())
blocks = [] if desc is None else list(desc)
out = []
for i, el in enumerate(blocks):
heads_list = i + 1 < len(blocks) and blocks[i + 1].tag in ("ul", "ol")
if el.tag == "p":
out.append(f"## {text(el)}" if heads_list else text(el))
elif el.tag == "ul":
out.append("\n".join(f"- {text(li)}" for li in el))
elif el.tag == "ol":
out.append("\n".join(f"{n}. {text(li)}" for n, li in enumerate(el, 1)))
notes = "\n\n".join(out)
if not notes.strip():
sys.exit("the metainfo needs a <release> at the top of <releases> whose <description> renders release notes")
with open("release-notes.md", "w") as f:
print(notes, file=f)
print(release.get("version", ""))
EOF
)
if [ "$GITHUB_EVENT_NAME" = push ]; then
# A release: the only pushes this workflow runs for are tags.
# The tag is the version; it has to be annotated, signed by the
# owner as Forgejo verifies it against the keys its users added,
# on master, newer than every published release, and the version
# of the metainfo's newest entry. The tag itself is read from the
# forge: the checkout fetches a pushed tag again as a plain ref
# to its commit, so the local one is never the annotated tag.
version=$GITHUB_REF_NAME
if ! printf '%s\n' "$version" | grep -qxE '[0-9]+\.[0-9]+\.[0-9]+'; then
echo "the tag $version is not a version of the form X.Y.Z" >&2
exit 1
fi
api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY"
tag=$(curl -sSf "$api/tags/$version")
object=$(printf '%s' "$tag" | jq -r .id)
commit=$(printf '%s' "$tag" | jq -r .commit.sha)
if [ "$commit" != "$GITHUB_SHA" ]; then
echo "the forge has the tag $version on $commit, not on this run's commit $GITHUB_SHA" >&2
exit 1
fi
if [ "$object" = "$commit" ]; then
echo "$version is a lightweight tag; a release tag is annotated and signed: git tag -s $version -m 'crafter-build $version'" >&2
exit 1
fi
# Forgejo verifies a signed tag's own signature, and for an
# unsigned one falls back to its commit's, so the verdict also
# has to cover the tag's payload, not the commit's.
signed=$(curl -sSf "$api/git/tags/$object" |
jq -r --arg c "$commit" --arg v "$version" '"\(.verification.verified) \(.verification.signer.email // "") \(.verification.payload // "" | startswith("object \($c)\ntype commit\ntag \($v)\n"))"')
if [ "$signed" != "true $RELEASE_SIGNER true" ]; then
echo "Forgejo does not verify the tag $version itself as signed by $RELEASE_SIGNER (verified, signer, over the tag's payload: $signed)" >&2
exit 1
fi
if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/master; then
echo "the tag $version is on $(git rev-parse --short "$GITHUB_SHA"), which is not on master: push the tag with the master it releases" >&2
exit 1
fi
# Newer than every release the forge has published, its own
# included, and not every tag: a later tag whose run still
# queues behind this one has no release yet, and a tag that is
# no X.Y.Z version never gets one.
for t in $(git tag --list | awk '/^[0-9]+\.[0-9]+\.[0-9]+$/' | sort -V); do
[ "$(printf '%s\n%s\n' "$t" "$version" | sort -V | tail -n 1)" = "$t" ] || continue
code=$(curl -s -o /dev/null -w '%{http_code}' "$api/releases/tags/$t")
case "$code" in
404) ;;
200)
if [ "$t" = "$version" ]; then
echo "$version is released already; to re-run after a release left half made, delete that release first" >&2
else
echo "$version is not newer than the release $t" >&2
fi
exit 1 ;;
*) echo "the forge answered $code when asked whether $t is released" >&2; exit 1 ;;
esac
done
if [ "$newest" != "$version" ]; then
echo "the metainfo's newest release is \"$newest\", but the tag is $version: the tagged commit needs the <release> entry for $version at the top of packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml" >&2
exit 1 exit 1
fi fi
else else
# A master build names itself after the release it follows, the # Nothing is published. The build names itself after the
# way a local checkout does: 2.0.0-3-g21746b1 is three commits # release it follows, the way a local checkout does:
# past 2.0.0. Before the first tag there is nothing to describe # 5.0.0-3-g21746b1 is three commits past 5.0.0. Before the first
# from and the bare hash gets a placeholder in front. # tag there is nothing to describe from and the bare hash gets a
described=$(git describe --tags --always --exclude=latest) # placeholder in front.
described=$(git describe --tags --always)
case "$described" in case "$described" in
[0-9]*.[0-9]*.[0-9]*) version="$described" ;; [0-9]*.[0-9]*.[0-9]*) version="$described" ;;
*) version="0.0.0-dev+$described" ;; *) version="0.0.0-dev+$described" ;;
esac esac
branch=beta
fi fi
echo "version=$version" >> "$GITHUB_OUTPUT" echo "version=$version" >> "$GITHUB_OUTPUT"
echo "branch=$branch" >> "$GITHUB_OUTPUT" echo "version $version"
echo "version $version, flatpak branch $branch"
- name: Build - name: Build
# The manifest is rewritten beside the original so its relative # The manifest is rewritten beside the original so its relative
@ -106,7 +219,7 @@ jobs:
grep -n 'CRAFTER_BUILD_VERSION' "$CI_MANIFEST" grep -n 'CRAFTER_BUILD_VERSION' "$CI_MANIFEST"
flatpak-builder --force-clean --ccache --disable-rofiles-fuse \ flatpak-builder --force-clean --ccache --disable-rofiles-fuse \
--state-dir=/root/.cache/flatpak-builder \ --state-dir=/root/.cache/flatpak-builder \
--repo=repo --default-branch="${{ steps.meta.outputs.branch }}" \ --repo=repo --default-branch="$BRANCH" \
build-dir "$CI_MANIFEST" build-dir "$CI_MANIFEST"
- name: Smoke test - name: Smoke test
@ -114,18 +227,16 @@ jobs:
flatpak-builder --run build-dir "$CI_MANIFEST" crafter-build --version flatpak-builder --run build-dir "$CI_MANIFEST" crafter-build --version
flatpak-builder --run build-dir "$CI_MANIFEST" sh -c 'cd examples/hello-world && crafter-build && ls bin/*/hello*' flatpak-builder --run build-dir "$CI_MANIFEST" sh -c 'cd examples/hello-world && crafter-build && ls bin/*/hello*'
# Everything below publishes and only runs on master and on tags. # Everything below releases the build and runs only for a pushed tag.
- name: Bundle - name: Bundle
if: github.event_name != 'pull_request' if: github.event_name == 'push'
run: | run: |
mkdir -p dist mkdir -p dist
flatpak build-bundle repo "dist/crafter-build-${{ steps.meta.outputs.version }}.flatpak" "$APP_ID" "${{ steps.meta.outputs.branch }}" flatpak build-bundle repo "dist/crafter-build-${{ steps.meta.outputs.version }}.flatpak" "$APP_ID" "$BRANCH"
cp packaging/flatpak/net.catcrafts.CrafterBuild.flatpakref dist/
(cd dist && sha256sum * > SHA256SUMS)
ls -la dist ls -la dist
- name: Upload bundle - name: Upload bundle
if: github.event_name != 'pull_request' if: github.event_name == 'push'
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v3
with: with:
name: crafter-build-${{ steps.meta.outputs.version }} name: crafter-build-${{ steps.meta.outputs.version }}
@ -133,19 +244,24 @@ jobs:
if-no-files-found: error if-no-files-found: error
- name: Publish to the Catcrafts repo - name: Publish to the Catcrafts repo
if: github.event_name != 'pull_request' if: github.event_name == 'push'
run: | run: |
set -eu set -eu
# The signing key is generated once on the runner host # The signing key is generated once on the runner host
# (/etc/crafter-flatpak: signing-key.asc and key-id) and mounted # (/etc/crafter-flatpak: signing-key.asc and key-id) and mounted
# read-only; it is imported into a throwaway keyring per run. # read-only; it is imported into a throwaway keyring per run.
if [ ! -s /run/crafter-flatpak/signing-key.asc ] || [ ! -s /run/crafter-flatpak/key-id ]; then if [ ! -s /run/crafter-flatpak/signing-key.asc ] || [ ! -s /run/crafter-flatpak/key-id ]; then
echo "no signing key under /etc/crafter-flatpak on the runner host; generate it as described in AGENTS.md (CI and publishing)" >&2 echo "no signing key under /etc/crafter-flatpak on the runner host; generate it as described in AGENTS.template.md (CI and publishing)" >&2
exit 1 exit 1
fi fi
export GNUPGHOME=$(mktemp -d) export GNUPGHOME=$(mktemp -d)
gpg --batch --quiet --import /run/crafter-flatpak/signing-key.asc gpg --batch --quiet --import /run/crafter-flatpak/signing-key.asc
FLATPAK_GPG_KEY_ID=$(cat /run/crafter-flatpak/key-id) FLATPAK_GPG_KEY_ID=$(cat /run/crafter-flatpak/key-id)
# Crafter.Review's workflow publishes into the same repo and holds
# this lock while it does, so a commit and the summary update of
# one workflow never interleave with the other's.
exec 9> "$WEB_DIR/.publish.lock"
flock 9
# The live repo is the canonical copy; builds are promoted into it, # The live repo is the canonical copy; builds are promoted into it,
# never built into it. # never built into it.
# Keyed on the repo's config file, not the directory: the web root # Keyed on the repo's config file, not the directory: the web root
@ -153,81 +269,49 @@ jobs:
[ -f "$REPO_DIR/config" ] || ostree init --repo="$REPO_DIR" --mode=archive [ -f "$REPO_DIR/config" ] || ostree init --repo="$REPO_DIR" --mode=archive
flatpak build-commit-from --src-repo=repo \ flatpak build-commit-from --src-repo=repo \
--gpg-sign="$FLATPAK_GPG_KEY_ID" --gpg-homedir="$GNUPGHOME" \ --gpg-sign="$FLATPAK_GPG_KEY_ID" --gpg-homedir="$GNUPGHOME" \
"$REPO_DIR" "app/$APP_ID/x86_64/${{ steps.meta.outputs.branch }}" "$REPO_DIR" "app/$APP_ID/x86_64/$BRANCH"
# Every push to master used to be published as `beta`. Its last
# build is marked end-of-life, once, so that the next
# `flatpak update` of a beta installation says why nothing follows.
# The reason names the branch: with --noninteractive, flatpak's
# message names only the app.
beta="app/$APP_ID/x86_64/beta"
if ostree rev-parse --repo="$REPO_DIR" "$beta" >/dev/null 2>&1 &&
! ostree show --repo="$REPO_DIR" --print-metadata-key=ostree.endoflife "$beta" >/dev/null 2>&1; then
flatpak build-commit-from --src-ref="$beta" \
--end-of-life="The beta branch gets no more updates: every change now comes as a release on the stable branch. Install stable with flatpak install catcrafts net.catcrafts.CrafterBuild//stable, then remove beta with flatpak uninstall net.catcrafts.CrafterBuild//beta." \
--gpg-sign="$FLATPAK_GPG_KEY_ID" --gpg-homedir="$GNUPGHOME" \
"$REPO_DIR" "$beta"
fi
flatpak build-update-repo --gpg-sign="$FLATPAK_GPG_KEY_ID" --gpg-homedir="$GNUPGHOME" \ flatpak build-update-repo --gpg-sign="$FLATPAK_GPG_KEY_ID" --gpg-homedir="$GNUPGHOME" \
--generate-static-deltas --prune "$REPO_DIR" --generate-static-deltas --prune "$REPO_DIR"
# The repo description and the app ref carry the public key. # The repo description and the app ref carry the public key.
key=$(gpg --export "$FLATPAK_GPG_KEY_ID" | base64 --wrap=0) key=$(gpg --export "$FLATPAK_GPG_KEY_ID" | base64 --wrap=0)
sed "s|GPGKey=.*|GPGKey=$key|" packaging/flatpak/catcrafts.flatpakrepo > "$WEB_DIR/catcrafts.flatpakrepo" sed "s|GPGKey=.*|GPGKey=$key|" packaging/flatpak/catcrafts.flatpakrepo > "$WEB_DIR/catcrafts.flatpakrepo"
sed "s|GPGKey=.*|GPGKey=$key|" packaging/flatpak/net.catcrafts.CrafterBuild.flatpakref > "$WEB_DIR/net.catcrafts.CrafterBuild.flatpakref" sed "s|GPGKey=.*|GPGKey=$key|" packaging/flatpak/net.catcrafts.CrafterBuild.flatpakref > "$WEB_DIR/net.catcrafts.CrafterBuild.flatpakref"
flock -u 9
# The release attaches this .flatpakref, not the one in the
# checkout: that one has a placeholder where the key goes, and
# flatpak cannot install from it.
cp "$WEB_DIR/net.catcrafts.CrafterBuild.flatpakref" dist/
(cd dist && sha256sum * > SHA256SUMS)
ls -la dist
- name: Rolling 'latest' release
if: github.event_name != 'pull_request' && github.ref_type != 'tag'
run: |
git config user.email "ci@catcrafts.net"
git config user.name "Crafter Build CI"
git tag -f latest
git push origin latest --force
- name: Publish rolling 'latest' release
if: github.event_name != 'pull_request' && github.ref_type != 'tag'
uses: https://code.forgejo.org/actions/forgejo-release@v2
with:
direction: upload
url: ${{ github.server_url }}
repo: ${{ github.repository }}
tag: latest
title: Latest master build
prerelease: true
override: true
release-dir: dist
token: ${{ secrets.GITHUB_TOKEN }}
- name: Release notes
if: github.ref_type == 'tag'
run: |
# The newest <release> block's description as Markdown, for the
# release page. AppStream has no headings, so a paragraph that
# introduces a list is one: <p>New</p><ul>...</ul> comes out as
# "## New" over its items, the shape the notes take since 3.0.0.
# A paragraph on its own stays a paragraph, as the older entries
# are written. <em> and <code> get their Markdown spelling; a code
# span also keeps text such as lib/<triple>/eh from being read as
# an HTML tag by the forge.
python3 - > release-notes.md <<'EOF'
import xml.etree.ElementTree as ET
desc = ET.parse("packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml").getroot().find("releases/release/description")
def text(el):
parts = [el.text or ""]
for child in el:
inner = text(child)
parts.append({"em": f"*{inner}*", "code": f"`{inner}`"}.get(child.tag, inner))
parts.append(child.tail or "")
return " ".join("".join(parts).split())
blocks = list(desc)
out = []
for i, el in enumerate(blocks):
heads_list = i + 1 < len(blocks) and blocks[i + 1].tag in ("ul", "ol")
if el.tag == "p":
out.append(f"## {text(el)}" if heads_list else text(el))
elif el.tag == "ul":
out.append("\n".join(f"- {text(li)}" for li in el))
elif el.tag == "ol":
out.append("\n".join(f"{n}. {text(li)}" for n, li in enumerate(el, 1)))
print("\n\n".join(out))
print("\nInstall:\n\n flatpak remote-add --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo\n flatpak install catcrafts net.catcrafts.CrafterBuild\n")
EOF
- name: Publish release - name: Publish release
if: github.ref_type == 'tag' if: github.event_name == 'push'
# The notes are release-notes.md, which the Version step wrote. No
# `override`: it would delete a tag that has moved off this commit
# since the Version step and tag the old commit instead. Without it
# the action refuses such a tag, and a release that an earlier
# attempt left half made, such as a draft whose upload failed, has
# to be deleted before a re-run.
uses: https://code.forgejo.org/actions/forgejo-release@v2 uses: https://code.forgejo.org/actions/forgejo-release@v2
with: with:
direction: upload direction: upload
url: ${{ github.server_url }} url: ${{ github.server_url }}
repo: ${{ github.repository }} repo: ${{ github.repository }}
tag: ${{ github.ref_name }} tag: ${{ steps.meta.outputs.version }}
title: crafter-build ${{ github.ref_name }} title: crafter-build ${{ steps.meta.outputs.version }}
release-notes-file: release-notes.md release-notes-file: release-notes.md
release-dir: dist release-dir: dist
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.GITHUB_TOKEN }}

4
.gitignore vendored
View file

@ -5,3 +5,7 @@ share/crafter-build/
.claude .claude
# written by CI next to the manifest so relative source paths still resolve # written by CI next to the manifest so relative source paths still resolve
packaging/flatpak/ci-manifest.yaml packaging/flatpak/ci-manifest.yaml
# written by every build and test run from AGENTS.template.md
/AGENTS.md
.review-gates/push/
.review-gates/trees/

38
.review-gates/config.json Normal file
View file

@ -0,0 +1,38 @@
{
"base": "origin/master",
"rangeFrom": "upstream",
"authors": [
"jorijnvdgraaf@catcrafts.net"
],
"aiTrailers": "forbid",
"requireSigned": true,
"lenses": {
"repo-better-solution": {
"section": ".review-gates/lenses/repo-better-solution.md"
},
"repo-bug-prover": {
"section": ".review-gates/lenses/repo-bug-prover.md"
},
"repo-facts": {
"section": ".review-gates/lenses/repo-facts.md"
}
},
"modes": {
"commits": {
"kind": "commits",
"lenses": [
"repo-better-solution",
"repo-bug-prover",
"repo-facts"
],
"effort": "xhigh"
}
},
"gate0": [
"./build.sh",
"./bin/crafter-build",
"./bin/crafter-build test",
"./bin/crafter-build format --check",
"./bin/crafter-build lint"
]
}

View file

@ -0,0 +1,42 @@
## This repository: Crafter.Build
A C++26 modules build system that builds itself. The stated design is
`README.md` (the manual) and `AGENTS.template.md` (the contributor guide;
`AGENTS.md` is written from it by a crafter-build build or test run, not
by `build.sh`, and is not in the tree).
Its "Design rules" and "Security considerations" are the owner's
decisions: a range that departs from one without saying so is a finding;
whether one should change is the owner's call, not a defect of the range.
Among them, for CI, which holds the workflow's token and the signing key
its runner mounts: no secret is added to the workflow, and the
environment is never echoed in it.
The layers: the library (`interfaces/`, `implementations/`), which the
executable wraps and every `project.cpp` is compiled against; this
repository's own `project.cpp`; `build.sh`, the bootstrap that builds the
tool without the tool; the Flatpak (`packaging/flatpak/`), which bundles
the LLVM users build with; CI (`.forgejo/workflows/ci.yaml`). A target
difference branches on `cfg.target` at run time, never on the host; an
output path goes through `BinDir()`, `BuildDir()` or `PcmDir()`; whatever
changes what gets compiled or bundled reaches `VariantId()`.
Search first: the partitions' own helpers (`RunBuildCommand`,
`RunCommandChecked`, `Progress::Diagnostic`, `ApplyStandardArgs`,
`HostTarget`, `GitProject`, `LocalProject`); the Crafter.* libraries the
tree already uses, cloned under `~/.cache/crafter.build/external/`; libc++
and clang as the host installs them (`/run/host/usr/include/c++/v1`,
`/run/host/usr/lib/clang/`); git, cmake and flatpak-builder.
Commit shape here: a fix, its test and its README change are separate
commits when each stands on its own, in that order, and a bug fix ships
with a test that fails before it. That split is not a later commit
repairing an earlier one.
Compatibility: the `project.cpp` of every sibling repository beside this
checkout (`../Crafter.*/project.cpp`) and of every user compiles against
what `interfaces/` exports and is loaded by the binary; the CLI, the
`CRAFTER_BUILD_*` variables, the cache an older version left under
`~/.cache/crafter.build/` and the `bin/` layout CI globs are contracts too.
Users get master through releases on the Flatpak's `stable` branch. A
change an existing `project.cpp` does not survive is a
finding unless the range documents, in the README, what users must change.

View file

@ -0,0 +1,63 @@
## This repository: Crafter.Build
The execution contexts to enumerate, beside the charter's:
- `project.cpp` is compiled to a shared object and loaded into the running
crafter-build, resolving `Crafter::` symbols from the executable
(`--export-dynamic`); its static initialisers run at load. Its sibling
projects (`GitProject`, `LocalProject`) load the same way into the same
process, and its `#pragma crafter dependency` targets are built for the
host first, on every load.
- The clang++, clang and llvm-ar the tool spawns, and the git and cmake it
runs, are shell commands (`popen`, `std::system` in `:Platform`), many in
parallel; such a step fails on its exit code, never because it printed.
Running a test or a built artifact is a shell command too (`:Test`,
`:Clang`). A path, file name or flag that reaches one with a space or a
shell metacharacter in it is an input to attack. Other steps run inside
the process, among them glslang's shader compiles (`:Shader`), the
compression of an asset in Crafter.Asset, which starts threads of its own
(`:Asset`), and lint's parse through the libclang the linter dlopens
(`:Lint`).
- A build's steps run as jobs on the workers of `JobPool::Process()`
(`:Jobs`): up to as many threads as the machine has hardware threads, one
where that is one or unknown. The compiles of a configuration's stale
shaders, C, CUDA and C++ units, the compression of its stale assets, and
its copies of `cfg.files` and of the other files of an asset directory
go through the `JobGroup` of its `Build()`, which starts a job once the
jobs it was added after have finished; a `RunBuildCommand` waits for a
worker when its caller is not one. Jobs are waited for by threads that
are not workers, among them one that runs a `Build()` (its caller's, one
of `RunTests`', one of `BuildAll`'s, one a `Build()` starts per
dependency) and the one that loads a project file (`LoadConfigurations`,
`LoadProject`), for the compiles of the std module and of
`project.cpp`. The threads a `Build()` starts per external dependency are
not workers either and wait for no job: they run git and cmake. An
executable's copies of what its dependencies forward run on the thread of
its `Build()`.
- Several crafter-build processes share `~/.cache/crafter.build/` at once:
the std and Crafter.Build PCMs per target and march (the
`ConcurrentCacheRace` test), and the external clones with their `.lock`
files.
- Three builds of the tool: the bootstrap from `build.sh` (without
`CRAFTER_BUILD_HAS_ASSET`), the self-hosted binary on the host's LLVM, and
the Flatpak on its own LLVM under `/app`, in a sandbox whose `/usr` is the
Freedesktop SDK's. Their toolchains can be a release apart.
- Targets: the host triple, a sysroot (aarch64, musl), `x86_64-w64-mingw32`
under wine, `wasm32-wasi*` under wasmtime (or wasmer for `-r`), and
browser builds through the runtime in `wasi-runtime/`.
- Incremental builds: a first build, a rebuild after an edit, a rebuild
after a toolchain or flag change and a build after `clean` start from
different states; whatever changes what gets compiled has to reach
`VariantId()`, or a stale artifact is reused.
- Tests: each its own subprocess, in parallel, with a 60 s timeout. A test
that edits or touches files stages a copy under
`fs::temp_directory_path()`; one that only builds its fixture builds it in
place, into the fixture's own `bin/` and `build/` in the checkout.
Semantics to read on disk rather than recall: libc++ and clang as the host
installs them (`/run/host/usr/include/c++/v1`,
`/run/host/usr/share/libc++/v1/std.cppm`,
`/run/host/usr/lib/clang/<major>/include`), the dependencies as cloned
(`~/.cache/crafter.build/external/<Name>-<hash>/`), the vendored
`lib/DirStackFileIncluder.h`. The Flatpak's own LLVM is not readable from
here: a semantic that may differ between LLVM releases is unverified for
the Flatpak build.

View file

@ -0,0 +1,18 @@
## This repository: Crafter.Build
- A claim that a tree passes `build.sh`, the self-host build, the test
suite, `format --check` or `lint` traces to the Gate 0 log among the
evidence paths INPUTS names: each command with its exit code and the sha
it ran at. A claim of a run anywhere else (the Flatpak through
`run flatpak`, CI, wine, qemu, node, a browser) traces to a capture of
that run that names the commit, or is unverifiable.
- A test a message names exists as a `cfg.AddTest("<Name>")` line in
`project.cpp` and a `tests/<Name>/main.cpp` whose checks pin what the
message says.
- `AGENTS.md` is generated from `AGENTS.template.md` and the dependencies'
`AGENTS.consumer.md` and is not in the tree: a claim about it is checked
against those sources.
- A `<release>` entry in
`packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml` is the
release notes users read: every sentence in it is a claim about the code
since the previous tag.

197
AGENTS.md
View file

@ -1,197 +0,0 @@
# AGENTS.md
Guidance for coding agents and contributors working on crafter-build itself. The [README](README.md) is the user-facing manual; this file holds what you need to change the build system. When the two disagree, the code wins: check the interface in `interfaces/` and the `--help` output of the built binary.
## Project overview
crafter-build is a C++26 modules build system. A project is described by a `project.cpp` that returns a `Crafter::Configuration`; the tool compiles that file to a shared object, loads it in-process and builds what it describes. This repository is self-hosting: its own `project.cpp` builds crafter-build with crafter-build, and its tests link the library and drive `Build()` in-process.
| Path | What lives there |
|---|---|
| `interfaces/Crafter.Build-<Partition>.cppm` | Module interface partitions. `Crafter.Build.cppm` is the umbrella that re-exports them. |
| `implementations/Crafter.Build-<Partition>.cpp` | Implementation units, one per partition, named `Crafter.Build:<Partition>_impl`. `main.cpp` is a thin wrapper around `Crafter::Run`. |
| `project.cpp` | The self-host build description: a `crafter.build-lib` library, a `crafter.build-exe` executable, the test declarations, the lint rules and the `flatpak` and `install` scripts. |
| `tests/<Name>/main.cpp` | One self-test per directory; `tests/<Name>/fixture/` holds the sample project it builds. |
| `examples/` | Standalone user-facing projects, MIT licensed. |
| `build.sh` | Bootstrap script. It compiles everything by hand, without crafter-build. |
| `wasi-runtime/` | `runtime.js` and `index.html.in`, shipped for browser targets. |
| `lib/` | Vendored third-party headers (nlohmann/json, glslang's DirStackFileIncluder). Do not edit. |
| `share/crafter-build/`, `bin/`, `build/`, `lib/*.a` | Generated and gitignored. |
| `packaging/flatpak/`, `.forgejo/workflows/ci.yaml` | The Flatpak manifest with its metainfo, repo and ref files, and the Forgejo Actions CI that builds and publishes it. |
Partitions and what they own:
- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release.
- `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types.
- `:Platform` runs commands, implements `LoadProject` (compile and load `project.cpp`), the host PCM cache, `#pragma crafter dependency`, and all OS-specific code.
- `:Interface` and `:Implementation` model module units, their staleness checks and their compiles.
- `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`.
- `:Test` holds `AddTest`, `RunTests` and `TestRunner`.
- `:Lint` is the lint/format driver plus the libclang token and AST layer.
- `:Script` is the driver behind `crafter-build run`: it looks a name up in `cfg.scripts`, calls the callback and turns what it returns into the exit code.
- `:Agents` keeps the dependency notes section of a project's AGENTS.md: it walks the dependencies `cfg.dependencyNotes` selects, reads each one's `AGENTS.consumer.md` and merges them between the section's markers. Which Configurations belong to another project, and where it lives, comes from the loader (`LoadedProjectOf` in `:External`, `PragmaDependencies` in `:Platform`), because only the Configuration `GitProject` and `LocalProject` return has its `path` rebased.
- `:Progress` is console output. `:Shader` compiles shaders through glslang. `:Asset` is the hook into Crafter.Asset.
## Dev environment
The shipped artifact is the Flatpak (see "CI and publishing"); the loop below is the native development loop.
Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime), `lld`, `libc++` with its std module source (`share/libc++/v1/std.cppm`), `cmake`, `git`. `crafter-build --version` prints which compiler was resolved; `CRAFTER_BUILD_LLVM_DIR` points it at another LLVM prefix, and `build.sh` honours the same variable. Network access to `forgejo.catcrafts.net` and `github.com` is needed: loading `project.cpp` fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into `~/.cache/crafter.build/external/`, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs `git pull` on them.
```bash
./build.sh # bootstrap: bin/crafter-build, lib/libcrafter-build.a, share/crafter-build/
./bin/crafter-build # self-host build through project.cpp
```
Three things to know about this loop:
- `bin/crafter-build` is the bootstrap binary and the harness for every command below. The self-host build writes to `bin/crafter.build-exe-<variant>/crafter-build` and does not replace it.
- Changes under `implementations/` are picked up by the self-host build and by the tests, which link the local library. Changes under `interfaces/` are not: the harness compiles against the copies in `share/crafter-build/` and the PCM cache built from them, so a new or changed declaration is invisible until you run `./build.sh` again. The symptom is `use of undeclared identifier` for the symbol you just added. A changed default member initialiser has no symptom at all: `project.cpp` compiles against the old one and quietly gets the old default, as `project.cpp`'s sibling loads do with a harness that predates `GitProjectSpec::args = ProjectArgs()`.
- A new exported symbol that a `project.cpp` reaches on its default path also needs `./build.sh`: the old binary does not export it, and `LoadProject` fails with an undefined symbol.
`./build.sh` clones and builds glslang on first run and takes several minutes; later runs are faster. `./bin/crafter-build clean` deletes `bin/` and `build/` without loading `project.cpp`. That takes `bin/crafter-build` itself with it, and `build/flatpak`, the state of the local Flatpak build (see "CI and publishing"): about 2 GB, and the next `run flatpak` rebuilds LLVM. Set `CRAFTER_BUILD_HOME` only when running a binary from outside this tree; `CRAFTER_BUILD_MARCH` and `CRAFTER_BUILD_MTUNE` default to `native`.
## Build, test and style commands
```bash
./bin/crafter-build # build (self-host)
./bin/crafter-build test # build and run every self-test
./bin/crafter-build test 'Incremental*' # name glob
./bin/crafter-build test --list # enumerate without running
./bin/crafter-build test --jobs=1 --timeout=120
./bin/crafter-build lint # dry style gate, exit 1 on any finding
./bin/crafter-build format # apply the transform rules in place
./bin/crafter-build format --check # CI-style dry run
./bin/crafter-build run # list the scripts project.cpp defines
./bin/crafter-build run <name> [args...] # run one; everything after the name is the script's
./bin/crafter-build clean
```
Before you call a change done, all three must exit 0: `format` (then re-read your diff), `lint`, `test`. CI runs `./build.sh` and `crafter-build test` on every PR; its lint step is currently commented out, so lint is enforced only by you. Failed, crashed and timed-out tests leave their output in `build/test-logs/<name>.log`.
## Testing instructions
Tests are declared, not discovered. Each one is a line in `project.cpp`:
```cpp
cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() });
```
The source is `tests/<Name>/main.cpp`. The test inherits target, march and the rest from the root configuration and links the local `crafter.build-lib`, so `import Crafter.Build;` resolves to the code in this checkout. A test that calls `LoadProject` also needs `.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl")`, as the existing ones show. The declarations sit in an `if (linuxTarget)` block that matches any `*-linux-gnu` or `*-linux-musl` target: the suite is Linux-host only today.
A test is an ordinary `int main()`. Exit 0 passes, nonzero fails, 77 skips (for a missing tool, never for a failed assertion). Each runs in its own subprocess, in parallel, with a 60 s default timeout.
Conventions the existing tests follow:
- Open `main.cpp` with a comment that states the behaviour under test and the failure it guards against. `tests/CompilerWarning/main.cpp` shows the shape.
- Collect failures with a `Check(cond, msg)` helper that prints `FAIL: ...` to stderr and counts, then return nonzero at the end. Do not stop at the first failure unless later steps are meaningless without it.
- Drive the engine in-process: `Build(cfg, depResults, depMutex)`, `RunTests`, the lint driver. Do not shell out to `bin/crafter-build` and grep its stdout.
- Fixtures under `tests/<Name>/fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-<name>"` and removes it on the next run. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy.
- Use a fresh `depResults` map per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe. `Build()` itself is safe to call repeatedly on the same `Configuration`.
- Set `cfg.path` before calling `GetInterfacesAndImplementations`, and spell `cFiles` as absolute paths: both resolve against the working directory, not the configuration.
A bug fix ships with a test that fails before the fix and passes after it, in its own `test:` commit when it documents the behaviour on its own.
Cross-target runs use `test --target=<triple>` with `--runner=local` or `--runner=cmd:<wrapper>` (wine, qemu-user, valgrind), or `CRAFTER_BUILD_RUNNER_<TRIPLE>` as the persistent form. A failed runner probe skips its tests rather than failing the suite.
## Code style
`project.cpp` pulls in [Crafter.LintRules](https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules) through `#pragma crafter dependency` and applies its lite set, `LintRules::AddLiteRules`: the 8 rules that ask for different code, without the ones that only decide layout, whitespace and naming. `lint` reports all 8; `format` applies the two transforms among them, `format-concat` and `fixed-width-types`, and leaves everything else as written. Enforced:
- The first three lines of every source: `// SPDX-License-Identifier: LGPL-3.0-only`, `// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®`, blank. Examples use MIT.
- `enum class` only. `std::println` instead of iostream. `std::format` instead of string concatenation. `std::int32_t` and friends instead of `int` or `long` (exempt: `main`, `argc`/`argv`, `extern "C"` and foreign API signatures). No `char*` outside C interop.
- `const` on scalar locals that are never written; `constexpr` on constants with constant initialisers.
Not checked, so match the surrounding code:
- Four-space indentation, no tabs, no trailing whitespace, final newline.
- `PascalCase` for types, functions, statics and constants; `camelCase` for variables; a trailing `_` is allowed.
- One declaration per statement. K&R braces. `if (x) return;` on one line when it fits, and no hand-wrapping of a statement that fits on one line. `if (` and `for (` with a space; no space before a call's `(`.
Suppress one finding with `// lint-disable-next-line <rule>` or a whole file with `// lint-disable-file <rule>`. Both are rare in this tree and need a reason.
Beyond the rules:
- `import std;` everywhere; standard headers are never `#include`d. C headers (`clang-c/Index.h`, `dlfcn.h`) go in the global module fragment after `module;`.
- Comments explain why: the failure mode, the constraint, the rejected alternative. The codebase carries long comments on purpose. Do not strip them, and write them for new non-obvious code. Commit bodies follow the same rule.
- There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests.
- A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`.
- Every output path goes through `Configuration::BinDir()`, `BuildDir()` and `PcmDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones.
- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, uninterpreted project args and the toolchain (`Toolchain::Key()`).
## Design rules
These were decided deliberately. Do not undo them without the maintainer's say-so.
1. **Configuration is C++.** No JSON, YAML, TOML or DSL for project, runner or lint configuration. Lint rules are C++ callbacks; there is no clang-format or clang-tidy integration and no separate "format rule" type. A rule that calls `ctx.SetContent` is a transform, and that is the whole mechanism.
2. **Per-project artifacts go in `<project>/build` and `<project>/bin`. Only cross-project things go in `~/.cache/crafter.build/`:** the std PCM and Crafter.Build PCMs per target and march, and external clones keyed by their spec hash.
3. **Sources ship, PCMs build locally.** The Flatpak installs `*.cppm` under `/app/share/crafter-build/`. Nothing target-baked ships except the executable and the toolchain beside it, and the executable is built for a portable `-march`.
4. **crafter-build is a monolithic executable with `--export-dynamic`.** `project.so` resolves `Crafter::` symbols from the running binary at dlopen time. There is no Windows host; `x86_64-w64-mingw32` is a cross-compile target for user projects only.
5. **Convention over configuration.** Lead with the zero-config path. Env var, then CLI flag, then full `project.cpp` are the escalation, not the entry point.
6. **One skip mechanism** (runner probe plus exit 77) and **one `TestRunner` shape** (template fields with `{bin}`, `{bundle}` and similar placeholders; `Cmd(...)` covers any wrapper). Do not add a special-case runner class or a hardcoded "skip on this OS" branch.
7. **The house-style rules stay in their own repo.** They are not library API of crafter-build and are not forced on downstream projects.
8. **Fix warts inline; do not stack workarounds.** The previous version of this tool died of accumulated hacks. If a change needs a shortcut, say so in the PR rather than hiding it.
9. **`project.cpp` keeps the library/executable split.** `crafter.build-lib` owns the sources, dependencies and glslang; `crafter.build-exe` is `main.cpp` plus link flags.
10. **Host-tooling builds** (the target of a `#pragma crafter dependency`) get `-fPIC` and the host triple scoped to that build. Keep it scoped.
## Commit and PR guidelines
- Branch from `master` and open the PR against `master` on the project's Forgejo at `forgejo.catcrafts.net/Catcrafts/Crafter.Build`. Issue work uses `claude/issue-<n>` branch names. Pushes go over SSH; HTTPS push is disabled on the server.
- Subject line: `type(scope): imperative summary`, with `feat`, `fix`, `refactor`, `docs` or `test`; the scope (`lint`, `incremental`, ...) is optional. Body: what was wrong, why, and why the fix has this shape, wrapped at about 75 columns. Read `git log` for the voice.
- Separate commits for the fix, its test and the README change when each stands on its own.
- Update the README in the same PR when user-visible behaviour changes.
- `format`, `lint` and `test` green before pushing. CI builds the Flatpak and runs the suite inside it on PRs, publishes the `beta` branch of the Catcrafts repo on every push to `master`, and the `stable` branch plus a release on an `X.Y.Z` tag.
- Never commit `bin/`, `build/`, `share/crafter-build/`, `lib/*.a` or fixture build outputs (all gitignored), and never edit the vendored files in `lib/`.
- Keep `CRAFTER_BUILD_MARCH=x86-64-v2` in the manifest for the shipped binary: it has to run on any x86_64 machine. User projects still default to `native`.
## Security considerations
- `project.cpp` is compiled and loaded into the crafter-build process, and every `GitProject`, `#pragma crafter dependency` and `ExternalDependency` clones a repository and runs its build on the host. Treat a dependency URL as code you are choosing to run. This repo's own dependencies are sibling Catcrafts repos tracking their default branch on purpose; pin with `commit` when adding anything else, and whenever reproducibility matters.
- Unpinned dependencies `git pull` on every invocation, so builds and tests need network. A missing or private repo surfaces as a clone failure before anything is built.
- `--runner=cmd:<command>` executes the named wrapper around every test binary. Wrappers come from `--runner=` or `CRAFTER_BUILD_RUNNER_*`; do not hardcode hosts, wrappers or credentials in `project.cpp` or tests.
- `crafter-build run <name>` executes whatever the script does, with your permissions. Only the scripts of the project crafter-build was pointed at can be run, never a dependency's; keep it that way.
- The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library.
- CI force-pushes the rolling `latest` tag and publishes a prerelease on every push to `master` with the workflow's own token, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it.
- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`. Keep it that way.
## CI and publishing
`.forgejo/workflows/ci.yaml` runs on the `crafter-flatpak` runner label: a dedicated privileged forgejo-runner on the Hetzner box (`forgejo-runner-flatpak.service`, config `/etc/forgejo-runner/config-flatpak.yaml`), registered to this repository only and the only runner with that label. It is privileged because bubblewrap inside the job container needs it, and separate from the other runners so that privilege is not shared with any other repository. Its config allows four volumes, which the workflow mounts: `crafter-flatpak-system` (the Sdk install at `/var/lib/flatpak`), `crafter-flatpak-builder` (flatpak-builder state and ccache, so the LLVM and WASI modules are rebuilt only when their sources change; a cold run takes about 80 minutes on 8 cores, a warm one a fraction of that), `/var/www/flatpak`, the web root Caddy serves as `https://flatpak.catcrafts.net/`, and `/etc/crafter-flatpak`, which holds the repo signing key (`signing-key.asc`, no passphrase, and `key-id`), generated once on the host and mounted read-only into the job; nothing is stored in the forge. The live repo at `/var/www/flatpak/repo` is canonical; builds are promoted into it with `flatpak build-commit-from`, never built into it.
Keep the label unique to that runner. Plain `flatpak` also belongs to the organisation-wide runner (`forgejo-runner-org-flatpak.service`), which serves every Catcrafts repository and on purpose allows no volumes. Whenever this job lands there, flatpak-builder stops with `The state dir (/root/.cache/flatpak-builder) is not on the same filesystem as the target dir`; the top of the job log shows which runner took it and lists every volume it ignored.
The key is made once, as root on the runner host, and the step fails with a message pointing here when it is missing:
```bash
install -d -m 700 /etc/crafter-flatpak/gnupg && export GNUPGHOME=/etc/crafter-flatpak/gnupg
gpg --batch --pinentry-mode loopback --passphrase '' --quick-generate-key 'Catcrafts Flatpak Repository <flatpak@catcrafts.net>' ed25519 sign never
KEYID=$(gpg --list-secret-keys --with-colons | awk -F: '/^sec/{print $5; exit}')
gpg --batch --pinentry-mode loopback --passphrase '' --export-secret-keys --armor "$KEYID" > /etc/crafter-flatpak/signing-key.asc
printf '%s\n' "$KEYID" > /etc/crafter-flatpak/key-id && chmod 600 /etc/crafter-flatpak/signing-key.asc /etc/crafter-flatpak/key-id
```
To release: add a `<release>` to `packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml` (its description becomes the release notes), merge, and push the tag `X.Y.Z`. CI refuses a tag that does not match the newest entry.
Local builds are two scripts in `project.cpp`. Run them with the native binary: the Flatpak build of crafter-build has no `flatpak` to drive.
```bash
./bin/crafter-build run flatpak [--jobs=<N>] # build the Flatpak, then print its version from inside the sandbox
./bin/crafter-build run install # install that build as branch `local` and make it current
```
`run flatpak` needs `flatpak-builder` or the `org.flatpak.Builder` app, and the Sdk (`flatpak install flathub org.freedesktop.Sdk//26.08`). It builds the working tree, uncommitted changes included, runs the whole suite inside the sandbox and reports version `0.0.0-dev`. Its state is `build/flatpak/` (`state/`, `repo/`, `build-dir/`). The first run builds LLVM and the WASI sysroot, about 25 minutes on a 56-core machine; later runs rebuild only the crafter-build module, a few minutes, because flatpak-builder never caches a `type: dir` source. The checkout must not be under `/tmp`, which `org.flatpak.Builder` cannot see. Use it for anything toolchain-sensitive: the native loop compiles with the distro's clang and the Flatpak with its bundled LLVM, and the two can be a major version apart.
`run install` does not build; it installs what `run flatpak` last exported. It points the user remote `crafter-build-local` at `build/flatpak/repo`, installs `net.catcrafts.CrafterBuild//local` from it next to whichever published branch is installed, and makes it the branch `flatpak run net.catcrafts.CrafterBuild` starts. `flatpak make-current --user net.catcrafts.CrafterBuild <branch>` switches back. Before `crafter-build clean`, or before deleting the checkout, run `flatpak uninstall --user net.catcrafts.CrafterBuild//local` and `flatpak remote-delete --user crafter-build-local`; otherwise the remote is left pointing at a repo that is gone.
## Gotchas
- A new partition is listed in four places, in import order: `PARTITIONS` in `build.sh`, `CrafterBuildModules` in `Crafter.Build-Platform.cpp`, both arrays in `project.cpp`, and the umbrella `Crafter.Build.cppm`. Then `./build.sh`.
- A `#pragma crafter dependency` target is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away.
- A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because `LoadProject` fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard.
- `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache.
- The bootstrap binary is compiled without `CRAFTER_BUILD_HAS_ASSET`, so `cfg.assets` only works in the self-hosted binary. Changing asset extensions means updating two maps in `Crafter.Build-Clang.cpp`: `assetOutput` and the transitive copy loop.
- A warning is printed only when its unit actually recompiles. A build with nothing to do is silent, which is not evidence that a warning is gone.
- A std module source only compiles against the headers of its own libc++ release, and a sysroot does not always ship one (Alpine). The Flatpak therefore carries the sources of the release next to the bundled one under `share/crafter-build/libc++-modules/<major>/`, one `libcxx-<major>-modules` manifest module each. When the bundled LLVM is bumped, keep the release it leaves behind as such a module: sysroots on the stable distro stay on it for months. The native loop has no such directory; stage one by hand under `share/crafter-build/` to test against a foreign sysroot.
- The wasm compile flags live in one place, `WasmBaselineFlags` in `Crafter.Build-Clang.cppm`: the std module and every unit have to agree on them, and `VariantId()` and the std PCM directory hash them, so a change rebuilds instead of mixing old and new BMIs. They enable C++ exceptions, so the link takes the exception-enabled libc++ and libunwind from the sysroot's `lib/<triple>/eh/` (wasi-sdk 33 and later). The Flatpak's sysroot has them and a distro's may not; where they are missing the wasm tests skip, so run those through the Flatpak. A browser page checks the engine with the `WasmBaselineProbes` named in `variants.json`.
- `WasiBrowserRuntimeExit` runs `wasi-runtime/runtime.js` under node and skips where there is none. The Flatpak has no node, so CI never runs it: after touching `runtime.js`, run the suite in the native loop with node on `PATH`.
- `VariantId()` names the output directory, so CI globs `bin/crafter.build-exe-<target>-<march>-*/` rather than predicting the hash. The hash includes the compiler, so after a toolchain update the previous variant's directories stay in `bin/` and `build/` until `clean`, and such a glob matches both.
- The self-host build and `test` keep the dependency notes section of this very file. None of Crafter.Math, Crafter.Asset and Crafter.LintRules ships an `AGENTS.consumer.md` yet. Once one does, a build here can change AGENTS.md whenever that repository changes its notes, since all three are unpinned. The tree is then dirty, so the next build's `git describe --dirty` version differs, which is a new `crafter.build-lib` variant and a full rebuild. Commit the section to settle it.

223
AGENTS.template.md Normal file
View file

@ -0,0 +1,223 @@
# AGENTS.md
Guidance for coding agents and contributors working on crafter-build itself. The [README](README.md) is the user-facing manual; this file holds what you need to change the build system. When the two disagree, the code wins: check the interface in `interfaces/` and the `--help` output of the built binary.
## Project overview
crafter-build is a C++26 modules build system. A project is described by a `project.cpp` that returns a `Crafter::Configuration`, or several of them; the tool compiles that file to a shared object, loads it in-process and builds what it describes. This repository is self-hosting: its own `project.cpp` builds crafter-build with crafter-build, and its tests link the library and drive `Build()` in-process.
| Path | What lives there |
|---|---|
| `interfaces/Crafter.Build-<Partition>.cppm` | Module interface partitions. `Crafter.Build.cppm` is the umbrella that re-exports them. |
| `implementations/Crafter.Build-<Partition>.cpp` | Implementation units, one per partition, named `Crafter.Build:<Partition>_impl`. `main.cpp` is a thin wrapper around `Crafter::Run`. |
| `project.cpp` | The self-host build description: a `crafter.build-lib` library, a `crafter.build-exe` executable, the test declarations, the lint rules and the `flatpak` and `install` scripts. |
| `AGENTS.template.md` | The source of AGENTS.md. Every build and test run writes AGENTS.md from it, with the notes the dependencies ship; AGENTS.md is gitignored, so changes go here. |
| `tests/<Name>/main.cpp` | One self-test per directory; `tests/<Name>/fixture/` holds the sample project it builds. |
| `examples/` | Standalone user-facing projects, MIT licensed. |
| `build.sh` | Bootstrap script. It compiles everything by hand, without crafter-build. |
| `wasi-runtime/` | `runtime.js` and `index.html.in`, shipped for browser targets. |
| `lib/` | Vendored third-party headers (glslang's DirStackFileIncluder). Do not edit. |
| `share/crafter-build/`, `bin/`, `build/`, `lib/*.a` | Generated and gitignored. |
| `packaging/flatpak/`, `.forgejo/workflows/ci.yaml` | The Flatpak manifest with its metainfo, repo and ref files, and the Forgejo Actions CI that builds and publishes it. |
| `.review-gates/` | The pre-push review's `config.json` and this repository's lens sections (`lenses/`), read by Crafter.Review. Its `push/` and `trees/` are generated and gitignored. |
Partitions and what they own:
- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, clang-scan-deps, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages.
- `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types.
- `:Platform` runs commands, implements `LoadConfigurations` and `LoadProject` (compile and load `project.cpp`), the host PCM cache and `#pragma crafter dependency`.
- `:Jobs` is what build steps run on: `JobPool`, worker threads behind one queue, started as jobs need them up to a fixed number, with `JobPool::Process()` the pool of at most one worker per hardware thread that `Build()` and `RunBuildCommand` use, and `JobGroup`, the jobs of one configuration's build, each started once the jobs it was added after have finished, with the first error among them and what `Build()` reports to it through `Fail()`.
- `:Interface` and `:Implementation` model module units, their staleness checks and the jobs that compile them (`Schedule`).
- `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`.
- `:Test` holds `AddTest`, `RunTests` and `TestRunner`, and starts the headless compositor of a test that sets `Test::wayland` (`RunSingleTest`), through `:Platform`'s `BackgroundCommand` and `PrivateDirectory`.
- `:Lint` is the lint/format driver plus the libclang token and AST layer.
- `:Script` is the driver behind `crafter-build run`: it looks a name up in the `scripts` of the configurations it is given, calls the callback and turns what it returns into the exit code.
- `:Agents` writes a project's AGENTS.md from its AGENTS.template.md: it walks the dependencies `cfg.dependencyNotes` selects, reads each one's `AGENTS.consumer.md` and merges them into the template's dependency notes section. Which Configurations belong to another project, and where it lives, comes from the loader (`LoadedProjectOf` in `:External`, `PragmaDependencies` in `:Platform`), because only the Configurations returned by a project file that `GitProject` or `LocalProject` loaded have their `path` rebased.
- `:Progress` is console output. `:Shader` compiles shaders through glslang. `:Asset` is the hook into Crafter.Asset.
- `:Flatpak` is an executable packaged as a Flatpak: `FlatpakApp` (app-id, runtime, permissions, desktop file, metainfo, icons, share entries, modules), the writer of its `files/`, which becomes `/app` in the app's sandbox, and what makes the app of that for `install` and `bundle`: the host's `flatpak build-finish`, which writes the metadata and `export/` by flatpak's own rules, then `flatpak build-export` into a repo, or flatpak-builder from a generated manifest when there are modules. It works on plain data; `Build()` and the `InstallFlatpakApp` and `BundleFlatpakApp` of `:Clang` gather it from the Configuration. The host's flatpak and flatpak-builder are reached through `RunHostFlatpak` and `RunHostFlatpakBuilder` in `:Platform`.
## Dev environment
The shipped artifact is the Flatpak (see "CI and publishing"); the loop below is the native development loop.
Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime, and `clang-scan-deps`, which a build reads what each C++ source declares and imports with), `lld`, LLVM's `llvm-ar` and `llvm-readelf`, `libc++` with its std module source (`share/libc++/v1/std.cppm`), `cmake`, `git`. `crafter-build --version` prints which compiler was resolved; `CRAFTER_BUILD_LLVM_DIR` points it at another LLVM prefix, and `build.sh` honours the same variable. Network access to `forgejo.catcrafts.net` and `github.com` is needed: loading `project.cpp` fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into `~/.cache/crafter.build/external/`, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs `git pull` on them.
```bash
./build.sh # bootstrap: bin/crafter-build, lib/libcrafter-build.a, share/crafter-build/
./bin/crafter-build # self-host build through project.cpp
```
Three things to know about this loop:
- `bin/crafter-build` is the bootstrap binary and the harness for every command below. The self-host build writes to `bin/crafter.build-exe-<variant>/crafter-build` and does not replace it.
- Changes under `implementations/` are picked up by the self-host build and by the tests, which link the local library. Changes under `interfaces/` are not: the harness compiles against the copies in `share/crafter-build/` and the PCM cache built from them, so a new or changed declaration is invisible until you run `./build.sh` again. The symptom is `use of undeclared identifier` for the symbol you just added. A changed default member initialiser has no symptom at all: `project.cpp` compiles against the old one and quietly gets the old default, as `project.cpp`'s sibling loads do with a harness that predates `GitProjectSpec::args = ProjectArgs()`.
- A new exported symbol that a `project.cpp` reaches on its default path also needs `./build.sh`: the old binary does not export it, and loading `project.cpp` fails with an undefined symbol.
`./build.sh` clones and builds glslang on first run and takes several minutes; later runs are faster. `./bin/crafter-build clean` deletes `bin/` and `build/` without loading `project.cpp`. That takes `bin/crafter-build` itself with it, and `build/flatpak`, the state of the local Flatpak build (see "CI and publishing"): about 4 GB after a first run, and the next `run flatpak` rebuilds LLVM. Set `CRAFTER_BUILD_HOME` only when running a binary from outside this tree; `CRAFTER_BUILD_MARCH` and `CRAFTER_BUILD_MTUNE` default to `native`.
## Build, test and style commands
```bash
./bin/crafter-build # build (self-host)
./bin/crafter-build test # build and run every self-test
./bin/crafter-build test 'Incremental*' # name glob
./bin/crafter-build test --list # enumerate without running
./bin/crafter-build test --jobs=1 --timeout=120
./bin/crafter-build lint # dry style gate, exit 1 on any finding
./bin/crafter-build format # apply the transform rules in place
./bin/crafter-build format --check # CI-style dry run
./bin/crafter-build run # list the scripts project.cpp defines
./bin/crafter-build run <name> [args...] # run one; everything after the name is the script's
./bin/crafter-build clean
```
Before you call a change done, all three must exit 0: `format` (then re-read your diff), `lint`, `test`. CI runs `./build.sh` and `crafter-build test` for every release tag, every pull request into `master` and every manual run, and has no lint step, so lint is enforced only by you. Failed, crashed and timed-out tests leave their output in `build/test-logs/<name>.log`.
## Testing instructions
Tests are declared, not discovered. Each one is a line in `project.cpp`:
```cpp
cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() });
```
The source is `tests/<Name>/main.cpp`. The test inherits target, march and the rest from the root configuration and links the local `crafter.build-lib`, so the engine it calls is the one built from this checkout. A test that loads a project file, through `LoadConfigurations`, `LoadProject`, `LocalProject`, `GitProject` or `Run()`, also needs `.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl")`, as the existing ones show. The declarations sit in an `if (linuxTarget)` block that matches any `*-linux-gnu` or `*-linux-musl` target: the suite is Linux-host only today.
A test is an ordinary `int main()`. Exit 0 passes, nonzero fails, 77 skips (for a missing tool, never for a failed assertion). Each runs in its own subprocess, in parallel, with a 60 s default timeout.
Conventions the existing tests follow:
- Open `main.cpp` with a comment that states the behaviour under test and the failure it guards against. `tests/CompilerWarning/main.cpp` shows the shape.
- Collect failures with a `Check(cond, msg)` helper that prints `FAIL: ...` to stderr and counts, then return nonzero at the end. Do not stop at the first failure unless later steps are meaningless without it.
- Drive the engine in-process: `Build(cfg, depResults, depMutex)`, `RunTests`, the lint driver. Do not shell out to `bin/crafter-build` and grep its stdout.
- Fixtures under `tests/<Name>/fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-<name>"`, after removing what an earlier run left there, which matters where the test runs by hand: under `crafter-build test` the copy is in the test's own `TMPDIR`, which goes when the test ends unless the test failed, crashed or timed out and left something in it: then it is kept until a later run removes it, a minute after the run that kept it ended, or, where that run was killed, a minute after its last change to the run's directory. Most tests here remove their copy themselves before they report, and so leave nothing to keep. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy. The fixed name is safe because `RunTests` gives every test a `TMPDIR` of its own for the run, so two runs at once, natively or in the Flatpak, whose sandboxes all share the app's `/tmp`, stage into different directories. A test that writes to `/tmp` by name, as `HostFlatpak` has to, makes a directory of its own there, a `PrivateDirectory`, which a later run removes, where a killed run left it, once it has not changed for a minute. A test that builds against a sysroot it stages, or has crafter-build fetch a repository it stages, points `XDG_CACHE_HOME` into its scratch directory too, as `SysrootStdModule` and the external-dependency tests do: the cache's key holds that path or URL, which is a new one every run.
- Use a fresh `depResults` map per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe. `Build()` itself is safe to call repeatedly on the same `Configuration`.
- Set `cfg.path` before calling `GetInterfacesAndImplementations`, and spell `cFiles` as absolute paths: both resolve against the working directory, not the configuration.
- `GetInterfacesAndImplementations` only lists the sources. A configuration's `interfaces` and `implementations`, its modules and units with what each imports, are made by `Build()` from what it reads in them, so a test that looks at them builds first.
- A test that needs the host's flatpak goes through `RunHostFlatpak`, skips (77) with the reason `HostFlatpakUnavailable` gives (flatpak-builder's build sandbox, where CI runs, has no way out), and installs only into a private `FLATPAK_USER_DIR` under its fixture's `build/`, as `FlatpakInstall` does. It never runs an installed app: `flatpak run` makes `~/.var/app/<app-id>` in the real home.
- A test that packages a Flatpak stages the runtime: it writes a `.flatpak-info` whose `[Application]` group has a `runtime=runtime/org.freedesktop.Sdk/x86_64/26.08` line, as the parser takes only that group's, and points `CRAFTER_BUILD_FLATPAK_INFO` at it with `setenv`, first thing in `main`, since the toolchain is read once per process. That works natively and wins over the sandbox's own file in the Flatpak; `FlatpakNative` stages an empty one for the native case.
A bug fix ships with a test that fails before the fix and passes after it, in its own `test:` commit when it documents the behaviour on its own.
Cross-target runs use `test --target=<triple>` with `--runner=local` or `--runner=cmd:<wrapper>` (wine, qemu-user, valgrind), or `CRAFTER_BUILD_RUNNER_<TRIPLE>` as the persistent form. A failed runner probe skips its tests rather than failing the suite.
## Code style
`project.cpp` pulls in [Crafter.LintRules](https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules) through `#pragma crafter dependency` and applies its lite set, `LintRules::AddLiteRules`: the 8 rules that ask for different code, without the ones that only decide layout, whitespace and naming. `lint` reports all 8; `format` applies the two transforms among them, `format-concat` and `fixed-width-types`, and leaves everything else as written. Enforced:
- The first three lines of every source: `// SPDX-License-Identifier: LGPL-3.0-only`, `// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®`, blank. Examples use MIT.
- `enum class` only. `std::println` instead of iostream. `std::format` instead of string concatenation. `std::int32_t` and friends instead of `int` or `long` (exempt: `main`, `argc`/`argv`, `extern "C"` and foreign API signatures). No `char*` outside C interop.
- `const` on scalar locals that are never written; `constexpr` on constants with constant initialisers.
Not checked, so match the surrounding code:
- Four-space indentation, no tabs, no trailing whitespace, final newline.
- `PascalCase` for types, functions, statics and constants; `camelCase` for variables; a trailing `_` is allowed.
- One declaration per statement. K&R braces. `if (x) return;` on one line when it fits, and no hand-wrapping of a statement that fits on one line. `if (` and `for (` with a space; no space before a call's `(`.
Suppress one finding with `// lint-disable-next-line <rule>` or a whole file with `// lint-disable-file <rule>`. Both are rare in this tree and need a reason.
Beyond the rules:
- `import std;` everywhere; standard headers are never `#include`d. C headers (`clang-c/Index.h`, `dlfcn.h`) go in the global module fragment after `module;`.
- Comments explain why: the failure mode, the constraint, the rejected alternative. The codebase carries long comments on purpose. Do not strip them, and write them for new non-obvious code. Commit bodies follow the same rule.
- There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests.
- A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`.
- Give a build step that keeps a hardware thread busy to the pool, not a thread of its own: that is what holds a build to as many steps at once as there are hardware threads. Add a step of a configuration's build to its `JobGroup` in `Build()`, after the jobs whose output it reads; run a step that stands by itself, as a link does, through `RunBuildCommand`, which runs on a worker of `JobPool::Process()` whoever calls it. Do not wait for a job inside a job, or anywhere else on a worker, where the wait would hold the thread the job needs: a `JobGroup` made on a worker of its own pool throws. A job owns what it uses, or uses only what outlives its group.
- Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`.
- `ObjectPath()` names the object of a `.cpp`, `.c` or `.cu`, from where its source lies: `objects/a/Thing_impl.o` in the build directory for `a/Thing.cpp`. Do not name one from its source's file name: two sources of one name in different directories then share an object, each compiled over the other (issue #50). A step that takes every object of a configuration reads them from a response file, as the link does, and not from its command, which the system holds to a length.
- A static library's archive and the list of objects a step reads are written under another name beside them and renamed into place (`WrittenBeside` and `MoveIntoPlace` in `Crafter.Build-Clang.cpp`), not removed first or written over where they lie: a link or archive step of another crafter-build may be reading them. Two crafter-builds can build a project loaded with `GitProject` at once, in the clone the cache keeps for its source, and one then links against the library, or reads that list, while the other writes it. Write anything else such a step reads the same way.
- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`), the GPU architecture (`cudaArch`), for `native` crafter-build's reading of the GPUs it compiles for, the NVIDIA display devices sysfs lists with `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` (`Toolchain::cudaNativeKey`, which is not what nvcc detects), and the nvcc (`Toolchain::nvccStamp`; `Toolchain::Key()` leaves both out) of a configuration with CUDA sources and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory.
## Design rules
These were decided deliberately. Do not undo them without the maintainer's say-so.
1. **Configuration is C++.** No JSON, YAML, TOML or DSL for project, runner or lint configuration. Lint rules are C++ callbacks; there is no clang-format or clang-tidy integration and no separate "format rule" type. A rule that calls `ctx.SetContent` is a transform, and that is the whole mechanism.
2. **Per-project artifacts go in `<project>/build` and `<project>/bin`. Only cross-project things go in `~/.cache/crafter.build/`:** the std PCM and Crafter.Build PCMs per target, march, toolchain and std module flags, external clones keyed by their spec hash, the mingw sysroot views keyed by prefix, and the locks `install` holds on the remotes of the user's installation (`flatpak-remotes/`, found by `HOME` and never by `XDG_CACHE_HOME`, in the Flatpak as well, so that every crafter-build installing for the user takes the same one; that of a private installation, `FLATPAK_USER_DIR`, is kept in it).
3. **Sources ship, PCMs build locally.** The Flatpak installs `*.cppm` under `/app/share/crafter-build/`. Nothing target-baked ships except the executable and the toolchain beside it, and the executable is built for a portable `-march`.
4. **crafter-build is a monolithic executable with `--export-dynamic`.** `project.so` resolves `Crafter::` symbols from the running binary at dlopen time. There is no Windows host; `x86_64-w64-mingw32` is a cross-compile target for user projects only.
5. **Convention over configuration.** Lead with the zero-config path. Env var, then CLI flag, then full `project.cpp` are the escalation, not the entry point.
6. **One skip mechanism** (runner probe plus exit 77) and **one `TestRunner` shape** (template fields with `{bin}`, `{bundle}` and similar placeholders; `Cmd(...)` covers any wrapper). Do not add a special-case runner class or a hardcoded "skip on this OS" branch.
7. **The house-style rules stay in their own repo.** They are not library API of crafter-build and are not forced on downstream projects.
8. **Fix warts inline; do not stack workarounds.** The previous version of this tool died of accumulated hacks. If a change needs a shortcut, say so in its commit message rather than hiding it.
9. **`project.cpp` keeps the library/executable split.** `crafter.build-lib` owns the sources, dependencies and glslang; `crafter.build-exe` is `main.cpp` plus link flags.
10. **Host-tooling builds** (the target of a `#pragma crafter dependency`) get `-fPIC` and the host triple scoped to that build. Keep it scoped.
## Commit and push guidelines
- Branch from `master`; issue work uses `claude/issue-<n>` branch names. Once the owner approves its frozen hash, a range goes straight to `master` on the project's Forgejo at `forgejo.catcrafts.net/Catcrafts/Crafter.Build`, as a fast-forward push with no merge commit and no pull request; open a pull request against `master` only when the owner asks for one. If `master` has moved since the freeze, rebase onto it, then freeze and review the rebased range again. Pushes go over SSH; HTTPS push is disabled on the server.
- Subject line: `type(scope): imperative summary`, with `feat`, `fix`, `refactor`, `docs` or `test`; the scope (`lint`, `incremental`, ...) is optional. Body: what was wrong, why, and why the fix has this shape, wrapped at about 75 columns. Read `git log` for the voice.
- Separate commits for the fix, its test and the README change when each stands on its own.
- Update the README in the same push when user-visible behaviour changes.
- `format`, `lint` and `test` green before pushing. CI builds the Flatpak and runs the suite inside it for every release tag, every pull request into `master` and every manual run. Without a pull request, CI does not run on a range before it reaches `master` unless someone starts it by hand (`workflow_dispatch`), so the review's gate0, the commands in `.review-gates/config.json`, is the check before the push.
- Every push to `master` is a release, made by the signed tag pushed with it (see "CI and publishing"). Every pushed range adds a `<release>` entry for its version at the top of `packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml`, in a commit of its own (`docs(packaging): add the X.Y.Z release entry`), dated the day of the push in UTC. Its notes have up to three sections, `<p>New</p>`, `<p>Fixes</p>` and `<p>Breaking</p>` in that order, each followed by a `<ul>` of its items, the most important first, and nothing after the last section. The version follows from them: a Breaking section makes it a major, New items a minor, and Fixes alone a patch. Once the owner has approved the frozen hash, the commit `master` is to receive gets the signed tag of that version, made locally, and both go out in one push: `git tag -s X.Y.Z -m 'crafter-build X.Y.Z'`, then `git push --atomic origin HEAD:master X.Y.Z`. That commit is the range's last one, or, when the owner asks for a pull request instead, the merge of the reviewed branch into `master`.
- Every push of new commits goes through Crafter.Review's pre-push review first, and goes out only once the owner approves the frozen hash. Run `flatpak run net.catcrafts.CrafterReview init` once in a fresh checkout or worktree: it writes the `/prepush` skill that drives the review, and the skill stays untracked. `freeze` refuses merge commits: a range reaches `master` as a fast-forward, and when the owner asks for a pull request instead, the merge of the reviewed branch into `master` is pushed without a freeze of its own.
- Every commit of a pushed range is GPG-signed, has `jorijnvdgraaf@catcrafts.net` as its author and committer, and carries no AI attribution trailer in its message, neither `Co-Authored-By:` nor `Assisted-by:`. `freeze` refuses a range with a commit that breaks any of these (`requireSigned`, `authors` and `aiTrailers` in `.review-gates/config.json`).
- Never commit `bin/`, `build/`, `share/crafter-build/`, `lib/*.a`, `AGENTS.md` or fixture build outputs (all gitignored), and never edit the vendored files in `lib/`.
- Keep `CRAFTER_BUILD_MARCH=x86-64-v2` in the manifest for the shipped binary: it has to run on any x86_64 machine. User projects still default to `native`.
## Security considerations
- `project.cpp` is compiled and loaded into the crafter-build process, and every `GitProject`, `#pragma crafter dependency` and `ExternalDependency` clones a repository and runs its build on the host. Treat a dependency URL as code you are choosing to run. This repo's own dependencies are sibling Catcrafts repos tracking their default branch on purpose; pin with `commit` when adding anything else, and whenever reproducibility matters.
- Unpinned dependencies `git pull` on every invocation, so builds and tests need network. A missing or private repo surfaces as a clone failure before anything is built.
- `--runner=cmd:<command>` executes the named wrapper around every test binary. Wrappers come from `--runner=` or `CRAFTER_BUILD_RUNNER_*`; do not hardcode hosts, wrappers or credentials in `project.cpp` or tests.
- `--compositor=` and `CRAFTER_BUILD_COMPOSITOR` name the command that crafter-build runs through `sh` beside every test that sets `Test::wayland`, unless they name `host`; the default is the weston on `PATH`.
- `crafter-build run <name>` executes whatever the script does, with your permissions. Only the scripts of the project crafter-build was pointed at can be run, never a dependency's: `run` leaves out a configuration that another project's file returned and the project file returns in turn, and the load refuses one that another project keeps to itself (`KeptBy`); keep it that way.
- The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library.
- crafter-build's Flatpak has `--talk-name=org.freedesktop.Flatpak`, and the permission is the whole sandbox's: anything that runs there can run commands on the host through `flatpak-spawn --host`. That is every process of crafter-build's sandbox: crafter-build itself, every `project.cpp` it loads with its scripts, the builds of its dependencies and pragma dependencies, the programs `-r` and `test` start, and whatever `flatpak run --command=` and `flatpak enter` start in it, the debuggers of the README's Debugging section and the programs under them included. crafter-build's own code uses it only through `HostCommand` in `:Platform`, which builds the command lines of `RunHostFlatpak`, `RunHostFlatpakBuilder` and `HostFlatpakUnavailable`'s probes, for the host's `flatpak` and `flatpak-builder` behind `install` and `bundle`; add no other host command to crafter-build. `RunHostFlatpak` is exported for the tests, and gives a `project.cpp` nothing the sandbox does not. The trust model allows the permission because `--filesystem=host` already lets sandboxed code write `~/.bashrc`, `~/.config/autostart` and `~/.config/systemd/user`: it makes running something on the host immediate, not newly possible, for everything the sandbox runs.
- CI creates a release for each release tag with the workflow's own token, pushes nothing to git, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it.
- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`, and in the caches of what they run, unless they point `XDG_CACHE_HOME` elsewhere: crafter-build's, what a build puts there, and wasmtime's, the modules the wasm tests run. Keep it that way. Two tests write elsewhere, and both remove what they make, and a later run removes what a killed one left once that has not changed for a minute (`PrivateDirectory`): `tests/HeadlessCompositor`, which makes its compositors' directories in a directory of its own in `$XDG_RUNTIME_DIR`, or in `/tmp` when that is not a directory, and has one made in `/tmp` itself, as crafter-build makes it where there is no `$XDG_RUNTIME_DIR`, because a socket's path holds 107 bytes and a temp directory's path can use them up; and `tests/HostFlatpak`, which in the Flatpak makes a directory of its own in the sandbox's `/tmp`, the place it asks the host about.
## CI and publishing
`.forgejo/workflows/ci.yaml` runs on the `crafter-flatpak` runner label: a dedicated privileged forgejo-runner on the Hetzner box (`forgejo-runner-flatpak.service`, config `/etc/forgejo-runner/config-flatpak.yaml`), registered to this repository only and the only runner with that label. It is privileged because bubblewrap inside the job container needs it, and no other repository's job runs on it. Its config allows four volumes, which the workflow mounts: `crafter-flatpak-system` (the Sdk install at `/var/lib/flatpak`), `crafter-flatpak-builder` (flatpak-builder state and ccache, which later runs reuse: flatpak-builder builds a module again when its sources or its `build-commands` change, and every module after it with it, so a new version of `swig` or `libedit`, which come before LLVM, also rebuilds the LLVM and WASI modules), `/var/www/flatpak`, the web root Caddy serves as `https://flatpak.catcrafts.net/`, and `/etc/crafter-flatpak`, which holds the repo signing key (`signing-key.asc`, no passphrase, and `key-id`), generated once on the host and mounted read-only into the job; nothing is stored in the forge. The web root and the key are not this runner's alone: the organisation-wide `flatpak` runner (`forgejo-runner-org-flatpak.service`), which serves every Catcrafts repository, mounts both for Crafter.Review's publish job, and the volumes a runner allows (`valid_volumes` in its config) are open to every job it runs, so a job of any Catcrafts repository that runs there can mount them as well. The live repo at `/var/www/flatpak/repo` is canonical; builds are promoted into it with `flatpak build-commit-from`, never built into it. Crafter.Review's workflow publishes into the same repo, and each workflow holds an flock on `/var/www/flatpak/.publish.lock` while it commits and updates the summary.
Keep the label unique to that runner. Plain `flatpak` belongs to the organisation-wide runner. When this job still asked for `flatpak` and that runner took it (runs #368 and #370, in October 2026), the runner allowed none of the job's volumes, and flatpak-builder stopped with `The state dir (/root/.cache/flatpak-builder) is not on the same filesystem as the target dir`; the top of such a job's log shows which runner took it and lists every volume it ignored.
The key is made once, as root on the runner host, and the step fails with a message pointing here when it is missing:
```bash
install -d -m 700 /etc/crafter-flatpak/gnupg && export GNUPGHOME=/etc/crafter-flatpak/gnupg
gpg --batch --pinentry-mode loopback --passphrase '' --quick-generate-key 'Catcrafts Flatpak Repository <flatpak@catcrafts.net>' ed25519 sign never
KEYID=$(gpg --list-secret-keys --with-colons | awk -F: '/^sec/{print $5; exit}')
gpg --batch --pinentry-mode loopback --passphrase '' --export-secret-keys --armor "$KEYID" > /etc/crafter-flatpak/signing-key.asc
printf '%s\n' "$KEYID" > /etc/crafter-flatpak/key-id && chmod 600 /etc/crafter-flatpak/signing-key.asc /etc/crafter-flatpak/key-id
```
A release is a tag `X.Y.Z`, annotated and signed, pushed with the `master` it releases; a push to `master` without one runs nothing. Before building, every run renders the release notes from the newest `<release>` entry in `packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml`, and stops when the metainfo does not parse or the notes come out empty. A tag run also checks that Forgejo verifies the tag as signed by the address the workflow's `RELEASE_SIGNER` names, that the tag's commit is on `master`, that its version has the form `X.Y.Z` and is newer than every release the forge has published, its own included, and that the newest entry is that version. Once the build and the suite inside it pass, the tag run publishes `stable` and creates the release, with the notes, the bundle, the `.flatpakref` and `SHA256SUMS` attached. Release runs queue one behind another, and a failed one can be re-run while no newer release exists, once a release it left half made is deleted; when the fix needs a commit of its own, that push is the next version's release. Pull requests and manual runs publish nothing. The `beta` branch, which every push to `master` used to go to, gets no more builds: the publish step marks its last build end-of-life, once, and the next `flatpak update` of a beta installation prints the reason.
Local builds are two scripts in `project.cpp`. Run them with the native binary: they run `flatpak` and `flatpak-builder` themselves, which the Flatpak build of crafter-build has none of. crafter-build's own `install` and `bundle` reach the host's through `RunHostFlatpak` and `RunHostFlatpakBuilder` instead.
```bash
./bin/crafter-build run flatpak [--jobs=<N>] # build the Flatpak, then print its version from inside the sandbox
./bin/crafter-build run install # install that build as branch `local` and make it current
```
`run flatpak` needs `flatpak-builder` or the `org.flatpak.Builder` app, and the Sdk (`flatpak install flathub org.freedesktop.Sdk//26.08`). It builds the working tree, uncommitted changes included, runs the whole suite inside the sandbox and reports version `0.0.0-dev`. Its state is `build/flatpak/` (`state/`, `repo/`, `build-dir/`). The first run builds every module, LLVM with lldb, the WASI sysroot and the Vulkan validation layer among them, in about 30 minutes with 56 CPU threads; later runs rebuild only the crafter-build module while the manifest is unchanged, a few minutes, because flatpak-builder never caches a `type: dir` source. The checkout must not be under `/tmp`, which `org.flatpak.Builder` cannot see. Use it for anything toolchain-sensitive: the native loop compiles with the distro's clang and the Flatpak with its bundled LLVM, and the two can be a major version apart.
`run install` does not build; it installs what `run flatpak` last exported. It points the user remote `crafter-build-local` at `build/flatpak/repo`, installs `net.catcrafts.CrafterBuild//local` from it next to whichever published branch is installed, and makes it the branch `flatpak run net.catcrafts.CrafterBuild` starts. `flatpak make-current --user net.catcrafts.CrafterBuild <branch>` switches back. Before `crafter-build clean`, or before deleting the checkout, run `flatpak uninstall --user net.catcrafts.CrafterBuild//local` and `flatpak remote-delete --user crafter-build-local`; otherwise the remote is left pointing at a repo that is gone.
## Gotchas
- A new partition is listed in four places, in import order: `PARTITIONS` in `build.sh`, `CrafterBuildModules` in `Crafter.Build-Platform.cpp`, both arrays in `project.cpp`, and the umbrella `Crafter.Build.cppm`. Then `./build.sh`.
- A `#pragma crafter dependency` target is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away.
- A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because loading a project file fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard.
- `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache.
- A project file returns one configuration from `CrafterBuildProject` or several from `CrafterBuildConfigurations`, and `Crafter::Run` works on the list `LoadConfigurations` gives it for both. A new verb has to say what it does with several, and whether it takes all of them or leaves out another project's: `test` and `run` leave out a configuration that another project's file returned and this one returns in turn, which `LoadedProjectOf` tells apart. The load has refused, before a verb sees the list, a returned configuration that a loaded project keeps to itself (`KeptBy`): one the loader took down when that project's file was loaded, among what the configurations the file returned led to through `dependencies` and `tests`, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps.
- The limit of as many steps at once as there are hardware threads holds for what runs on `JobPool::Process()`: the jobs `Build()` adds and the commands of `RunBuildCommand`. Among what runs outside it: an `ExternalDependency`'s `cmake --build`, which `BuildCMake` gives `--parallel <hardware threads>` of its own; the tests `RunTests` runs, `--jobs=` of them at once on threads of its own, while other tests may still be building; the Crafter.Build modules `EnsureCrafterBuildPcms` precompiles for the host cache, one after another; and the threads a step starts for itself, lld's for a link and, for an asset, those of the GDeflate compressor in Crafter.Asset, up to 31 for each stream it compresses. The pool is one process's: a self-test of this repository that builds a fixture does so in its own process, on a pool of its own.
- An interface unit takes two compiler runs, one for its BMI and one for the object made from the BMI, and they are two jobs so that the units importing it start once the first is done. `Check` reads staleness off the BMI; the object is `Schedule`'s to look at, which adds the object job alone for a unit whose BMI is up to date and whose object is missing or older than the BMI. A build that fails between the two jobs leaves a unit like that, since no job starts after a failure.
- `Build()` reads what each `.cppm` and `.cpp` declares and imports with clang-scan-deps (`ReadSources` in `Crafter.Build-Clang.cpp`) once the configuration's dependencies and external dependencies are built: the compile command takes their include paths, and a source may include their headers. Until then nothing knows a configuration's modules, so `DuplicateModuleError` and `ImportCycleError` refuse a graph there, after the dependencies are built and before any `.cppm` or `.cpp` of the configuration is compiled; its `.c` and `.cu` sources, which compile while the dependencies are built, may have been by then. A scan is kept in the build directory as an object is, in `scans/` or, for a source outside `cfg.path`, in `scans-outside/`, as JSON holding the compile command it was taken for and what clang-scan-deps wrote, with a dependency file beside it, and taken again when that command differs, when the source or a file the dependency file lists is newer, and when it cannot be read; clang-scan-deps is given that command with its first word made the compiler where clang started with that command takes itself to be: the directory it is installed in, or, for a command whose last of `-canonical-prefixes` and `-no-canonical-prefixes` is `-no-canonical-prefixes`, that of the compiler as written (`ScannedAs`, `Toolchain::InstalledClangxx`). A `Build()` makes its own configuration's modules and units, never a dependency's: those are the dependency's own `Build()`'s to make, and the builds of other configurations built on it read them, through the pass record (`BuildResult::built`): a pass builds a directory once, so of two configurations of one directory, as the loader makes of one project loaded with its args in two orders, only the one it built has the modules of that build.
- Units see a std module rebuilt in place, because their depfiles list the BMIs they import (`-fmodule-file-deps`), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes into `StdPcmFlags`, which `BuildStdPcm` compiles with and `StdPcmKey` hashes. `VariantId()` hashes `StdPcmKey`, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are.
- A CMake external whose recorded configure inputs (`<build>/.crafter-options`) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or `--sysroot` compiled, and the check results it cached.
- The bootstrap binary is compiled without `CRAFTER_BUILD_HAS_ASSET`, so `cfg.assets` only works in the self-hosted binary. What an asset is compressed to is decided in one place, `CompressedAssetName` in `Crafter.Build-Clang.cpp`, which an executable's own assets, the ones its dependencies forward and the browser runtime's `files.json` all use; a Flatpak's `files/bin` keeps what those copies record as placed. `CompressAsset` in `Crafter.Build-Asset.cpp` does the compressing and has to load every extension that function maps.
- A warning is printed only when its unit actually recompiles. A build with nothing to do is silent, which is not evidence that a warning is gone.
- `RunCommandWithTimeout` runs its command under `timeout`, which can only start programs, so a shell builtin such as `command -v` fails there wherever no program of that name is on PATH, as on Arch and in the Sdk: a probe built on it reports the tool missing, and whatever it guards is skipped without a word. Probe through `RunCommandChecked`, which goes through `sh`, or `std::system` in a test.
- A std module source only compiles against the headers of its own libc++ release, and a sysroot does not always ship one (Alpine). The Flatpak therefore carries the sources of the release next to the bundled one under `share/crafter-build/libc++-modules/<major>/`, one `libcxx-<major>-modules` manifest module each. When the bundled LLVM is bumped, keep the release it leaves behind as such a module: sysroots on the stable distro stay on it for months. The native loop has no such directory; stage one by hand under `share/crafter-build/` to test against a foreign sysroot.
- The Flatpak carries the debugging tools for what it builds, because those programs run in its sandbox: lldb is a project of the `llvm` module, with `LLDB_ENABLE_PYTHON`, `LIBEDIT`, `CURSES`, `LIBXML2` and `LZMA` set ON so that a missing dependency fails the configure step (SWIG through Python, which needs it), and the `swig` and `libedit` modules come before it. The Khronos validation layer is the `vulkan-validation-layers` module plus four modules before it, build-only except for SPIRV-Tools' programs (`spirv-val` and the rest), all after the LLVM and WASI modules, so that bumping them reuses the cached LLVM and WASI builds. The layer follows the Sdk's Vulkan loader: when `runtime-version` moves to a runtime with a newer loader, move the layer to the Vulkan SDK release of that loader and take the other four revisions from that release's `scripts/known_good.json`.
- The Flatpak carries weston for the tests that set `Test::wayland`: the `libevdev`, `libinput`, `libdisplay-info` and `weston` modules, just before `crafter-build`, so that bumping them rebuilds only them and crafter-build. weston's frontend links the first three whatever the backend, so they ship. weston is configured with its headless backend, its GL renderer and its desktop shell, and with none of its other backends or shells and no Vulkan renderer. libinput is a `git` source pinned by commit, since its 1.32.0 release has no tarball attached. `tests/HeadlessCompositor` stands in a fake compositor, so the suite needs no weston: only a project's own tests that set `Test::wayland` run the real one.
- The wasm compile flags live in one place, `WasmBaselineFlags` in `Crafter.Build-Clang.cppm`: the std module and every unit have to agree on them, and `VariantId()` and the std PCM directory hash them, so a change rebuilds instead of mixing old and new BMIs. They enable C++ exceptions, so the link takes the exception-enabled libc++ and libunwind from the sysroot's `lib/<triple>/eh/` (wasi-sdk 33 and later). The Flatpak's sysroot has them and a distro's may not; where they are missing the wasm tests skip, so run those through the Flatpak. A browser page checks the engine with the `WasmBaselineProbes` named in `variants.json`.
- `WasiBrowserRuntimeExit` runs `wasi-runtime/runtime.js` under node and skips where there is none. The Flatpak has no node, so CI never runs it: after touching `runtime.js`, run the suite in the native loop with node on `PATH`.
- `CudaCompile` builds with a real CUDA toolkit whose `lib64` beside `bin/nvcc` holds `libcudart_static.a`, and skips everywhere else, and nothing in CI installs one: after touching how `cfg.cuda` is compiled, or how the CUDA runtime is linked and handed on through `BuildResult::runtimeLibs`, run it in the native loop on a machine with such a toolkit, as Arch's `/opt/cuda` is. Where nvcc is looked for, `/run/host` and its links included, is `ToolchainResolve`'s to check, on staged directories, so that one runs everywhere, and so is whether the `lib64` beside it holds the static runtime. `CudaMissing` checks what a build with a `.cu` says when no nvcc is found, and needs no toolkit either.
- `VariantId()` names the output directory, so CI globs `bin/crafter.build-exe-<target>-<march>-*/` rather than predicting the hash. The hash includes the compiler, so after a toolchain update the previous variant's directories stay in `bin/` and `build/` until `clean`, and such a glob matches both.
- AGENTS.md is build output: the self-host build and `test` write it from `AGENTS.template.md`, with the `AGENTS.consumer.md` of each dependency that ships one (Crafter.Math, today) merged in, and it is gitignored. Edit the template; an edit made in AGENTS.md is gone after the next build. A fresh clone or worktree has no AGENTS.md until its first `./bin/crafter-build` or `test`, since `./build.sh` does not write it. A harness from before the template (3.0.0 and older) never creates one and keeps its section in one it finds; the next build with a current harness writes it over.

243
README.md
View file

@ -1,22 +1,24 @@
# Crafter Build # Crafter Build
A C++26 modules build system. Project descriptions are written in C++ with no JSON, no Lua, no embedded DSL. You write a `project.cpp` that constructs a `Configuration` and returns it. Crafter Build compiles, loads, and executes it. A C++26 modules build system. Project descriptions are written in C++ with no JSON, no Lua, no embedded DSL. You write a `project.cpp` that constructs a `Configuration`, or several, and returns them. Crafter Build compiles, loads, and executes it.
## Install ## Install
crafter-build ships as a Flatpak that carries its own clang, lld, libc++ and WASI sysroot, so every machine builds with the same compiler: crafter-build ships as a Flatpak that carries its own clang, lld, libc++ and WASI sysroot, so every machine builds with the same compiler, and lldb and the Vulkan validation layers to debug the result (see [Debugging](#debugging)):
```bash ```bash
flatpak remote-add --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo flatpak remote-add --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo
flatpak install catcrafts net.catcrafts.CrafterBuild flatpak install catcrafts net.catcrafts.CrafterBuild
alias crafter-build='flatpak run net.catcrafts.CrafterBuild' alias crafter-build='flatpak run --die-with-parent net.catcrafts.CrafterBuild'
``` ```
Pre-release builds of `master` are the `beta` branch (`flatpak install catcrafts net.catcrafts.CrafterBuild//beta`), and every release also attaches a single-file bundle on the Forgejo releases page (`flatpak install --user crafter-build-<version>.flatpak`). The sandbox sees the whole host filesystem, so projects can live anywhere. Binaries built for the host link the bundled `libc++.so.1` through an rpath into the Flatpak: they run inside it (`-r`, the test runner), and are not meant to be copied out onto the host. `--die-with-parent` ends the sandbox with the `flatpak run` that started it. Without the flag, killing only the `flatpak run` process leaves the sandbox running: a build carries on writing into `bin/` and `build/`, and a program started with `-r` keeps running. With it, bubblewrap kills everything in the sandbox with SIGKILL when the `flatpak run` process dies or when that process's parent does. For `crafter-build …` or `crafter-build … &` typed at a bash or zsh prompt, that parent is the shell, so the sandbox ends with the shell, even after a `disown`. Ctrl-C reaches the program either way.
Releases are published to the `stable` branch that the commands above install, and every release also attaches a single-file bundle on the Forgejo releases page (`flatpak install --user crafter-build-<version>.flatpak`). The sandbox sees the host's own files where it shares them, the home, `/mnt`, `/opt`, `/srv` and `/run/media` among them, so a project can live there; it has its own `/tmp`, `/var`, `/usr`, `/etc` and `/app`. Binaries built for the host link the bundled `libc++.so.1` through an rpath into the Flatpak: they run inside it (`-r`, the test runner), and are not meant to be copied out onto the host. To run a program outside crafter-build's sandbox, package it as a Flatpak of its own ([Flatpak output](#flatpak-output)).
## Writing a project.cpp ## Writing a project.cpp
Crafter Build loads a `project.cpp` from the current directory. The file exports one function that returns a populated `Configuration`: Crafter Build loads a `project.cpp` from the current directory. The file exports one function: `CrafterBuildProject`, which returns a populated `Configuration`, or `CrafterBuildConfigurations` for [several](#several-configurations):
```cpp ```cpp
import std; import std;
@ -39,13 +41,119 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
} }
``` ```
Run `crafter-build` in that directory, outputs land at `bin/myapp-<target>-<march>-<mtune>-<hash>/myapp` and intermediates at `build/myapp-<target>-<march>-<mtune>-<hash>/`. The hash covers everything that changes what is compiled (build type, defines, flags, sysroot, the compiler itself), so two such builds never share a directory. After a compiler update, a new crafter-build release included, the first build starts a fresh directory and recompiles. `crafter-build clean` removes the ones left behind. Add `-r` to run the produced executable straight after a successful build. Run `crafter-build` in that directory, outputs land at `bin/myapp-<target>-<march>-<mtune>-<hash>/myapp` and intermediates at `build/myapp-<target>-<march>-<mtune>-<hash>/`. The hash covers everything that changes what is compiled (build type, defines, flags, sysroot, the compiler itself), so two such builds never share a directory. After a compiler update, a new crafter-build release included, the first build starts a fresh directory and recompiles. `crafter-build clean` removes the ones left behind. Add `-r` to run the produced executable straight after a successful build, in its own directory, where its shaders, `cfg.files` and assets are; a wasm32 one runs under wasmtime, or wasmer where there is no wasmtime, with no directory given to it, and one built for the browser (`EnableWasiBrowserRuntime`) is served over HTTP from that directory instead.
A `.cpp`, `.c` or `.cu` of a configuration is compiled into an object named from its path: `a/Thing.cpp` into `objects/a/Thing_impl.o` in that `build/` directory, at the source's path from `cfg.path`, and a source outside `cfg.path` into `objects-outside/` there, at its whole path. Two sources may therefore have the same file name in different directories, and a `.c` may lie beside a `.cpp` or a `.cu` of its name. The progress line of such a source's compile names it by the same path, `Compiling a/Thing.cpp`. The link, and the archive step of a static library, read their objects from a file in that directory, `<outputName>.objects`, so the command is no longer for many sources than for one.
crafter-build orders a configuration's units by what their sources import: a unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. What a `.cppm` or `.cpp` declares and imports is read by clang-scan-deps, which preprocesses the source with the command it is compiled with, so it reads them as the compiler does: an import in a comment, in a string literal or in a branch that `#if` leaves out is none, and a define or a header decides one as it does for the compile. It reads them once the configuration's dependencies are built, since the command takes their include paths, and keeps what it found in the `build/` directory, as it keeps objects: in `scans/` at the source's path from `cfg.path`, and in `scans-outside/` at its whole path for a source outside `cfg.path`, until the source, a file it includes or the command changes. Interface units of one configuration that import each other cannot be built in any order: two partitions, a partition and its own module, or two modules. Such a configuration is refused once its sources are read, before any of its `.cppm` and `.cpp` is compiled, with an error that names the units in the order they wait.
A build runs at most as many of its steps at once as the machine has hardware threads, however many sources are stale: the scans and the compiles of its sources, its shaders and assets, and its links and archives, counted together for the project and the dependencies it is built on. An `ExternalDependency`'s CMake build is not among them and is given that many jobs of its own, and the tests `crafter-build test` runs are counted by `--jobs=`. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts.
### Several configurations
A project that builds more than one thing, such as a library and the tool that comes with it or the programs of one repository, returns all of them from `CrafterBuildConfigurations` instead. They need not have anything to do with each other, and `crafter-build` builds every one of them:
```cpp
extern "C" std::vector<Configuration*> CrafterBuildConfigurations(std::span<const std::string_view> args) {
static std::deque<Configuration> owned;
Configuration& lib = owned.emplace_back();
lib.path = "./";
lib.name = "mylib";
lib.outputName = "mylib";
lib.type = ConfigurationType::LibraryStatic;
std::array<fs::path, 1> libIfaces = { "interfaces/MyLib" };
std::array<fs::path, 1> libImpls = { "implementations/MyLib" };
lib.GetInterfacesAndImplementations(libIfaces, libImpls);
Configuration& tool = owned.emplace_back();
tool.path = "./";
tool.name = "mytool";
tool.outputName = "mytool";
tool.type = ConfigurationType::Executable;
tool.dependencies = { &lib };
std::array<fs::path, 0> toolIfaces = {};
std::array<fs::path, 1> toolImpls = { "implementations/main" };
tool.GetInterfacesAndImplementations(toolIfaces, toolImpls);
return { &lib, &tool };
}
```
A project file has one of the two functions, never both. `CrafterBuildConfigurations` gets the same args as `CrafterBuildProject`, and `ProjectArgs()` and `IsTopLevelProject()` answer the same inside it. It returns pointers, so the configurations have to stay where they are for as long as crafter-build runs. A `std::deque` that the file only adds to keeps them there, with a new set for every call; a `std::vector` would move them when it grows, and a single static `Configuration` would be filled in again by every load of the file. A pointer that `GitProject` or `LocalProject` returned can be in the list as well, which is how one file builds a set of sibling projects.
With several configurations:
- **A build** builds all of them in one pass, so what two of them depend on is built once. One that fails does not stop the others, and the build then fails with the errors of the ones that failed.
- **`test`** runs the tests of every one the file made itself, in one run. By default a test is built from `tests/<Name>/` into `build/<Name>-<variant>/` and `bin/<Name>-<variant>/`, whichever configuration declares it, so a test belongs to one of them: where two each declare a test that would be built into the same directories, both tests fail without being built and name the two configurations. Give each test a name of its own.
- **`run`** offers the scripts of every one the file made itself: a script gets the configuration it is declared on as `ctx.project`, and a name two of them declare is an error.
- **`lint`** and **`format`** take the rules and the sources of every one that lies in the project's directory, and a rule two of them register under one name runs once.
- **`-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 to choose from they stop and name them, as `install` and `bundle` do when none is packaged: `-r` once everything is built, `install` and `bundle` before anything is.
- **A configuration of another project**, which the file got from `GitProject` or `LocalProject` and returns, is built with the rest and counts for `-r`, `install` and `bundle`. Its tests and its scripts stay that project's.
- **Two that would be built into the same directory**, as two with the same `path` and `name` and no other difference are, are refused by a build, `test`, `-r`, `install` and `bundle`, before anything is built. Give each a `name` of its own. A build, `-r`, `install` and `bundle` refuse two more sets before they build anything: configurations 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.
- **`cfg.dependencyNotes`** is read on every one the file made itself (see [Dependency notes for agents](#dependency-notes-for-agents)).
## Flatpak output
A program crafter-build's Flatpak links for Linux without a sysroot takes the libc++, libc++abi and libunwind of its LLVM and the glibc of its runtime, so outside the Flatpak it starts only on a host that has those libraries and a glibc with every symbol version they and the program reference, 2.38 or newer for the bundled libc++. A build lays the program out as a Flatpak of its own when it is packaged:
```cpp
cfg.packaging = Packaging::Flatpak; // or, for one build: --packaging=flatpak, where project.cpp calls ApplyStandardArgs
```
Its bin directory then holds `files/`, what becomes `/app` inside the app's sandbox:
```
bin/myapp-<variant>/
└── files/
├── bin/ myapp and the files it reads beside it: shaders, cfg.files, assets
├── lib/ libc++, libc++abi, libunwind, and the shared libraries it links from its dependencies and from crafter-build's /app/lib
└── share/ the desktop entry, metainfo and icons under the app-id, and cfg.flatpak.share
```
`-r` runs `files/bin/myapp` from that directory, inside crafter-build's sandbox, against the libraries in `files/lib`, the ones the app carries. To install the app for yourself, or to hand it to someone else:
```bash
crafter-build install # build it and install it for this user: `flatpak run local.crafterbuild.myapp`
crafter-build bundle # build it into bin/myapp-<variant>.flatpak, for `flatpak install --user <file>`
```
Both make the app first. Without modules, crafter-build makes `build/flatpak-apps/<app-id>/build-dir` of `files/`, as hard links to the build's own where they can be made and copies where they cannot, and a `metadata` naming the app, its runtime and the Sdk, and the host's `flatpak build-finish` finishes it by flatpak's own rules: it adds the command and the sandbox's permissions to the metadata and writes `export/`, what the host sees of the app, such as its desktop entry and icons. With modules, flatpak-builder does all of it.
`install` puts the app into a repo of the project's, in `build/flatpak-apps/<app-id>/`, and installs it from a user remote named `crafter-build-<app-id>`, updating what an earlier install left; it prints how to remove both, which matters before `crafter-build clean` deletes the repo. Installs of one app-id from two checkouts take turns on that remote, by a lock in `~/.cache/crafter.build/flatpak-remotes/` that every crafter-build installing for the user takes, the Flatpak's too. `bundle` writes a single file that `flatpak install --user` installs, naming Flathub's repository in it for the runtime. `install` takes the runtime from an installation that has it, the system's or the user's, or from a remote of the user's installation; where none does, flatpak stops with `requires the runtime ... which was not found`, and `flatpak install flathub org.freedesktop.Platform//26.08`, or the Sdk for an app that runs on it, puts it in place. An app with modules needs `org.freedesktop.Sdk//26.08` whatever it runs on, since flatpak-builder makes it with that: `flatpak install flathub org.freedesktop.Sdk//26.08`. Both run the host's `flatpak`, and with modules its flatpak-builder, which crafter-build's Flatpak reaches through the Flatpak session helper (the `org.freedesktop.Flatpak` permission) and uses for nothing else. The permission belongs to the whole sandbox, so a `project.cpp`, its scripts, the builds of its dependencies and the programs `-r` and `test` start can reach the host through it too; through the sandbox's `--filesystem=host` they could already write files the host runs, such as `~/.bashrc`. The host sees the project at the path crafter-build does where the sandbox shares the host's directories, as it does the home, `/mnt`, `/opt`, `/srv` and `/run/media`, and not in the sandbox's own `/tmp`, `/var`, `/usr`, `/etc` and `/app`. Before building, `install` and `bundle` ask the host whether it sees the project's `bin/` and `build/` where crafter-build does, following their links as the host does: they start its `flatpak` in a directory made in each for the question and removed again, and refuse the project where it cannot start there. To try the app on the host without installing it, run `flatpak build --runtime --readonly build/flatpak-apps/<app-id>/build-dir myapp` there after an `install` or `bundle`: it runs on the app's runtime, with the filesystems and the environment its metadata grants.
Installed, the program starts in the directory it is started from, when its permissions let it see that directory, and in `$HOME` otherwise. A program that reads its own files therefore finds them next to its executable (`/proc/self/exe`) rather than in the working directory, which is only its own under `-r`.
What the app is installed as is `cfg.flatpak`; a hello world sets none of it:
```cpp
cfg.flatpak.appId = "net.example.MyGame"; // default: local.crafterbuild.<outputName>
cfg.flatpak.runtime = FlatpakRuntime::Sdk; // default Platform; the Sdk has git, gcc and the like
cfg.flatpak.permissions = { "--socket=pulseaudio" }; // finish-args, spelled as in a Flatpak manifest
cfg.flatpak.desktopFile = "packaging/MyGame.desktop"; // installed as <appId>.desktop; its Icon= is the app-id
cfg.flatpak.metainfo = "packaging/MyGame.metainfo.xml";
cfg.flatpak.icons = { "packaging/icon.svg" }; // an .svg is scalable, a square .png goes under its size
cfg.flatpak.share = { // under /app/share, not beside the program like cfg.files
{ "data", "mygame/data" }, // a directory: every regular file in it, at its path inside it
{ "LICENSE", "licenses/net.example.MyGame/LICENSE" },
};
cfg.flatpak.modules = { "packaging/flatpak/node.yaml" }; // flatpak-builder modules for more in /app
```
- **Permissions** are the sandbox's: sockets, devices, shares, filesystems, bus names, environment. A library declares what every program built on it needs in its own `cfg.flatpak.permissions`, and those reach the program before the program's own, which can take one back (`--nosocket=x11`). `install` and `bundle` print the resulting list, with where each came from, and hand it to `flatpak build-finish`, which refuses a misspelled argument, and a share, socket, device or feature flatpak does not have, naming the ones it has. The build itself does not read them, so changing one builds nothing.
- **The runtime** is always at the branch crafter-build runs on (26.08 today), since the program links that runtime's glibc. The Platform is enough to run a program; the Sdk is for one that runs tools such as git at run time.
- **Share entries** are files of the project the program reads from `/app/share` instead of from beside itself: data it finds at `<its directory>/../share/<name>`, licences. `files/share` is the build's own, so they are kept there as long as they are listed and removed once they are not, and anything else put there is removed too. `-r` runs the program from `files/bin`, so the same `../share` lookup finds them. Any file can be one, a second desktop entry or an add-on's metainfo among them: what flatpak exports of an app's `share/`, it exports of them too, by its own rules, such as an icon, D-Bus service, MIME package, search provider or KRunner plugin named after the app-id. `flatpak build-export` refuses an exported icon that is not a square image and a D-Bus service that is not a key file, and warns of the app's own desktop entry where `desktop-file-validate` rejects it; a second desktop entry, a MIME package or metainfo it exports as it is. A directory entry places every regular file in it, and every link to one, at its path inside it; anything else in it is left out: empty directories, links to directories, dangling links, FIFOs and sockets. Two files for one path in `share/`, a field's own file among them, or a file where another entry needs a directory, fail the build. The app's desktop entry, `applications/<app-id>.desktop`, is held to `desktopFile`'s checks whichever placed it. A directory that holds what the build writes fails too, since it would be copied into itself, growing each time the app is built or exported: `files/`, and the app's directory in `build/flatpak-apps/`, where `install` and `bundle` put another copy of `files/` and the exported app, the project's own directory holding both, as written and where links lead, so also where `bin/` is a link elsewhere. So does one that lies in them, which is the build's own output.
- **Modules** are for what the app needs in `/app` besides the program: a runtime it starts, a tool it runs, data built from source. They are flatpak-builder module files in Flatpak's own format, which crafter-build names and never reads. With any, `install` and `bundle` have the host's flatpak-builder (or the `org.flatpak.Builder` app) make the app with `org.freedesktop.Sdk//26.08`, which the host then needs as well as the runtime, from a manifest in `build/flatpak-apps/<app-id>/` that lists them and copies the built program in last, so it is not compiled again; flatpak-builder's defaults then also strip it and split its debug info into a `.Debug` extension. Translations under `share/locale` stay in the app rather than going into a `.Locale` extension, which a bundle would leave out. `-r` runs the program without them.
- **What cannot be a Flatpak** fails the build saying why: Windows and wasm targets, which keep their `.exe` and `.wasm`; a build against a sysroot, which links that sysroot's libraries and not the runtime's, or one for musl, a C library no runtime has; an architecture other than the runtime's; a build against `CRAFTER_BUILD_LIBCXX_DIR`, since a Flatpak carries the toolchain's own libc++, built against the runtime's glibc; and a build by a native crafter-build, whose programs link the host's glibc, unless `CRAFTER_BUILD_FLATPAK_INFO`, which the tests set, names a runtime. A dependency's executables stay as linked even when `--packaging=flatpak` reaches their project, since their consumers run them by path, and tests are never packaged. A dependency that sets `cfg.packaging` in its own `project.cpp` is packaged, and the files its `cfg.flatpak` names are found in its own directory, as its `cfg.files` are.
- **For other machines**, build with `--march=x86-64-v3` rather than the default `native`, which can crash with SIGILL on an older CPU. Pass it on the command line or in `CRAFTER_BUILD_MARCH`: either reaches every configuration of the program that `ApplyStandardArgs` is called on, a sibling's whose `project.cpp` calls it included, while CMake externals are compiled without `-march`, and a `#pragma crafter dependency`, tooling built for `project.so` alone, with `-march=native`. A program with CUDA sources also needs a `--cuda-arch=` other than `native`, such as `all-major` (see CUDA), and `bundle` warns of a bundle built for either `native`.
Without packaging (`Packaging::None`, and for now `Default`), a program is the executable as linked: it runs inside crafter-build's sandbox (`-r`, `test`, `run` scripts), and on a host only where the host has what it links.
## Dependencies ## Dependencies
Three kinds, all fetched/built incrementally: Three kinds, all fetched/built incrementally:
**Cross-project Crafter sub-projects** — point `cfg.dependencies` at another `Configuration*`. Cross-project module imports (`import OtherProject;`) are tracked per-import: only the modules that actually import a changed dep rebuild. **Cross-project Crafter sub-projects** — point `cfg.dependencies` at another `Configuration*`. Cross-project module imports (`import OtherProject;`) are tracked per-import: only the modules that actually import a changed dep rebuild. A dependency's headers reach the C++ and C compiles of the projects built on it by themselves: its directory and every directory named `include` in its tree are on their include path, except those under a directory named `bin` or `build`, where builds leave their output. A header kept under one of those needs an `-I` of its own in the `cfg.compileFlags` of the projects that include it. A `cfg.cuda` source gets neither.
**External git+cmake deps** — for things like glslang. Declare in `cfg.externalDependencies`: **External git+cmake deps** — for things like glslang. Declare in `cfg.externalDependencies`:
@ -74,13 +182,21 @@ Configuration* sibling = LocalProject({ .projectFile = "../Crafter.Math/project.
cfg.dependencies = { math }; cfg.dependencies = { math };
``` ```
The sibling's `CrafterBuildProject` gets the args this `project.cpp` was loaded with (`ProjectArgs()`), so `--target=`, `--march=`, `--debug` and the project's own flags reach every sibling down the chain. That is all of them: `cfg.projectArgs` holds only what `ApplyStandardArgs` did not interpret, and passing it on would drop the target and the build type. Set `.args` to send something else: `{}` for nothing, or a list built from the project's args, such as one without a flag only this project reads. Build such a list once and give it to every sibling. A project that two paths load with different lists would end up in the program twice, so the build stops with an error that names both paths. Releases up to 2.2.0 forward nothing when `.args` is left out. The sibling's entry point gets the args this `project.cpp` was loaded with (`ProjectArgs()`), so `--target=`, `--march=`, `--debug` and the project's own flags reach every sibling down the chain. That is all of them: `cfg.projectArgs` holds only what `ApplyStandardArgs` did not interpret, and passing it on would drop the target and the build type. Set `.args` to send something else: `{}` for nothing, or a list built from the project's args, such as one without a flag only this project reads. Build such a list once and give it to every sibling. A project that exports modules and that two paths load with different lists would end up in the program twice, so the build stops with an error that names both paths, unless both lists give the project one build directory, as two orders of the same flags of its own can: it is then built once. Releases up to 2.2.0 forward nothing when `.args` is left out.
The default is read when the spec is made, so make it inside `CrafterBuildProject`, on the thread that calls it. A spec made at namespace scope, on a thread of your own or in a script forwards nothing. The default is read when the spec is made, so make it inside the entry point, `CrafterBuildProject` or `CrafterBuildConfigurations`, on the thread that calls it. A spec made at namespace scope, on a thread of your own or in a script forwards nothing.
Clones share the external cache and identical specs share one `Configuration`. An unpinned source is `git pull`ed on every invocation, set `.commit` for reproducible, offline-after-first-fetch builds. Clones share the external cache and identical specs share one `Configuration`. An unpinned source is `git pull`ed on every invocation, set `.commit` for reproducible, offline-after-first-fetch builds.
A project loaded this way runs its `CrafterBuildProject` as a dependency, and `IsTopLevelProject()` is `false` while it does (`true` in the project crafter-build was pointed at, and outside any project file). Wire test-only dependencies behind it: a library whose test links crafter-build itself would otherwise load crafter-build's `project.cpp` from inside crafter-build and recurse. A sibling whose project file returns [several configurations](#several-configurations) gives its first one, or the one `.configuration` names by its `name`:
```cpp
Configuration* packer = LocalProject({ .projectFile = "../tools/project.cpp", .configuration = "packer" });
```
Only the configuration a consumer names is built for it, with what that one depends on, and specs that differ only in `.configuration` share one load of the sibling. A name the sibling does not have is an error that lists the ones it has, and a name two of its configurations share is an error too. A library that comes to return a second configuration puts it after the first, so that a consumer that names none keeps getting the one it had. Its consumers then need a crafter-build that has `CrafterBuildConfigurations`: an older one loads only a `CrafterBuildProject`.
A project loaded this way runs its entry point as a dependency, and `IsTopLevelProject()` is `false` while it does (`true` in the project crafter-build was pointed at, and outside any project file). Wire test-only dependencies behind it: a library whose test links crafter-build itself would otherwise load crafter-build's `project.cpp` from inside crafter-build and recurse.
### Dependencies of project.cpp itself ### Dependencies of project.cpp itself
@ -97,13 +213,27 @@ import Crafter.LintRules;
#pragma crafter dependency "<source>" [branch "<name>" | commit "<sha>"] [project "<file>"] #pragma crafter dependency "<source>" [branch "<name>" | commit "<sha>"] [project "<file>"]
``` ```
Such a dependency is built for the host, whatever the project targets, and its `project.cpp` gets none of the project's args. Such a dependency is built for the host, whatever the project targets, and its `project.cpp` gets none of the project's args. Of a project that returns [several configurations](#several-configurations), the dependency is the first.
### Dependency notes for agents ### Dependency notes for agents
An agent working on a project reads its `AGENTS.md`, which says nothing about the libraries the project builds against unless someone copied that in by hand. A library ships it instead: an `AGENTS.consumer.md` beside its `project.cpp`, written for whoever uses the library rather than whoever works on it. When a consumer has an `AGENTS.md` beside its own `project.cpp`, `crafter-build` and `crafter-build test` keep its dependencies' notes in a section of it: An agent working on a project reads its `AGENTS.md`, which says nothing about the libraries the project builds against unless someone copied that in by hand. A library ships it instead: an `AGENTS.consumer.md` beside its `project.cpp`, written for whoever uses the library rather than whoever works on it.
A consumer that wants its dependencies' notes writes its own instructions in an `AGENTS.template.md` beside its `project.cpp`, and commits that instead of an `AGENTS.md`. `crafter-build`, `crafter-build test`, `crafter-build install` and `crafter-build bundle` then write `AGENTS.md` from the template with the notes added, so `AGENTS.md` is build output and stays out of version control: a dependency that changes its notes changes nothing a diff shows. A project with a committed `AGENTS.md` moves over from the directory of its `project.cpp`:
```bash
git mv AGENTS.md AGENTS.template.md
echo /AGENTS.md >> .gitignore
```
What a build then writes:
```markdown ```markdown
<!-- Written by crafter-build from AGENTS.template.md, and rewritten on every build. Edit that file, not this one. -->
# The template's text
...
<!-- crafter-build: dependency notes begin --> <!-- crafter-build: dependency notes begin -->
<!-- Written by crafter-build from the AGENTS.consumer.md each dependency ships, and rewritten on every build. Edit those files, not this section; cfg.dependencyNotes in project.cpp picks which dependencies are included. --> <!-- Written by crafter-build from the AGENTS.consumer.md each dependency ships, and rewritten on every build. Edit those files, not this section; cfg.dependencyNotes in project.cpp picks which dependencies are included. -->
@ -116,11 +246,13 @@ An agent working on a project reads its `AGENTS.md`, which says nothing about th
``` ```
- Each file goes in as written, under a line naming the dependency: its repository's name, or a `LocalProject`'s directory name. That reads the same on every machine, and for a `--local` checkout and its git clone alike. The file lands among the consumer's own headings, so start it with a `##` heading that names the library. - Each file goes in as written, under a line naming the dependency: its repository's name, or a `LocalProject`'s directory name. That reads the same on every machine, and for a `--local` checkout and its git clone alike. The file lands among the consumer's own headings, so start it with a `##` heading that names the library.
- The section is appended the first time, after a blank line, and rewritten in place after that, wherever it has been moved to. Edits inside it are lost on the next build; the text around it is left as it is. The file is written only when the section changes, in place, so hard links, ownership and a read-only `AGENTS.md` are respected, and an `AGENTS.md` is never created. - The section goes after the template's text and a blank line. To have it elsewhere, put the begin and end marker lines in the template where it should go: whatever they enclose is replaced. A template moved over from a committed `AGENTS.md` has them where its section was, around notes that can be deleted.
- The update runs once `project.cpp` has loaded and before the project compiles, so a build that fails still has the notes. A `project.cpp` that fails to load gets no update. `test --list`, `lint`, `format`, `run` and `clean` leave the file alone. - `AGENTS.md` is written only when its text changes, in place, so a `CLAUDE.md` linked to it, its ownership and a read-only `AGENTS.md` are respected. An edit made in it is gone after the next build, and a fresh clone has none until its first build. The template is never written.
- An `AGENTS.md` that no build wrote, such as a committed one still next to a new template, is never replaced: each build warns instead, until it is deleted. Without a template, `AGENTS.md` is never touched. One that still holds a section from crafter-build 3.0.0, which kept the notes in a committed `AGENTS.md`, gets a warning: move it over as above, or delete the section.
- In a build or a test run that is not refused before it starts, the update runs once `project.cpp` has loaded and before the project compiles, so a build that fails while it compiles still has the notes. It does not run for a `project.cpp` that fails to load, for `test --list`, `lint`, `format`, `run` and `clean`, or for a verb that is refused before it starts a build: an `install` or `bundle` of a project that is not packaged as a Flatpak, or for which crafter-build cannot run the host's flatpak, and a build, `test`, `install` or `bundle` of [several configurations](#several-configurations) that are refused as a set.
- The section follows what the build loaded: a dependency that only some flags pull in (a `--target=`, a flag of the project's own) comes and goes with them. An unpinned dependency's notes follow its default branch, as its code does, so the section can change on any build. Pin a `commit` to decide when. - The section follows what the build loaded: a dependency that only some flags pull in (a `--target=`, a flag of the project's own) comes and goes with them. An unpinned dependency's notes follow its default branch, as its code does, so the section can change on any build. Pin a `commit` to decide when.
- A library reached through two specs, pinned at one revision here and another further down, is described once, as the nearer one has it. - A library reached through two specs, pinned at one revision here and another further down, is described once, as the nearer one has it.
- When there are notes to write, unbalanced markers leave the file as it is, with a warning. A notes file that would break the section (a code block it never closes, a marker line of its own) is left out, also with a warning. Markers quoted inside a fenced code block don't count. - When there are notes to write, unbalanced markers in the template leave `AGENTS.md` as it is, with a warning. A notes file that would break the section (a code block it never closes, a marker line of its own) is left out, also with a warning. Markers quoted inside a fenced code block don't count.
`cfg.dependencyNotes` picks the dependencies: `cfg.dependencyNotes` picks the dependencies:
@ -128,10 +260,27 @@ An agent working on a project reads its `AGENTS.md`, which says nothing about th
|---|---| |---|---|
| `DependencyNotes::Transitive` (default) | everything the project builds against, all the way down: its `dependencies` and its own `#pragma crafter dependency` tooling | | `DependencyNotes::Transitive` (default) | everything the project builds against, all the way down: its `dependencies` and its own `#pragma crafter dependency` tooling |
| `DependencyNotes::Direct` | only the projects the project's own configurations and `#pragma crafter dependency` lines name | | `DependencyNotes::Direct` | only the projects the project's own configurations and `#pragma crafter dependency` lines name |
| `DependencyNotes::None` | none, and a section from an earlier build is removed | | `DependencyNotes::None` | none: `AGENTS.md` holds the template's text alone |
Three things never count: the project's own `AGENTS.consumer.md`; its tests' dependencies, since a plain build never looks at the tests; and a dependency's `#pragma crafter dependency` tooling, which is about how the dependency is built, not how it is used. Three things never count: the project's own `AGENTS.consumer.md`; its tests' dependencies, since a plain build never looks at the tests; and a dependency's `#pragma crafter dependency` tooling, which is about how the dependency is built, not how it is used.
In a project of [several configurations](#several-configurations), the `dependencyNotes` of each one the file made itself selects among what that one is built against, and a dependency's notes are in when a configuration that asks for them leads to it: what a `Direct` configuration names is followed further when a `Transitive` one reaches it too. The project's own `#pragma crafter dependency` tooling, and a configuration of another project that the file returns, which counts as a dependency here, go by the widest setting among the configurations the file made itself.
## CUDA
`cfg.cuda` lists CUDA sources, named without `.cu`. A relative name is read from the directory crafter-build runs in, except in a project loaded through `GitProject` or `LocalProject`, whose relative names crafter-build rebases onto that project's directory:
```cpp
cfg.cuda = { fs::absolute("kernels/blur") }; // kernels/blur.cu
```
nvcc compiles each into an object that joins the configuration's other objects, and the configuration links the CUDA runtime of nvcc's toolkit, as does whatever is built on it: `libcudart_static.a` from the toolkit's `lib64`, with the `-lrt -lpthread -ldl` nvcc's own link puts after it. Being static, it takes no run path into the toolkit. It comes after `cfg.linkFlags` and the libraries of what the configuration is built on, so a `-lcudart` named there is the one the linker takes. A toolkit whose `lib64` holds no `libcudart_static.a`, as where a distribution keeps the toolkit's libraries in its own directories, gets no runtime linked: `cfg.linkFlags` names it, as before.
- **The toolkit** is the one `CUDA_PATH` names, else the first of `/opt/cuda`, where Arch's package installs it, and `/usr/local/cuda`, the link NVIDIA's installer and packages make to theirs, that has a `bin/nvcc`, else the first `nvcc` in an absolute entry of `PATH`. A `CUDA_PATH` without a `bin/nvcc` is an error, not a reason to look elsewhere. `crafter-build --version` prints the nvcc it found and, where there is one, the static runtime beside it; a build with a `.cu` to compile and no nvcc says where it looked.
- **In the Flatpak**, `/opt` and your home are where the host has them, the host's `/usr/local/cuda` is found under `/run/host`, as is the toolkit it is a link to, and `PATH` is the sandbox's own `/app/bin:/usr/bin`, so for a toolkit anywhere else, set `CUDA_PATH`. nvcc compiles the host code with the Sdk's `g++` (GCC 16.2), not the host's: `NVCC_CCBIN` still applies, and names a path inside the sandbox. The programs `-r` and `test` start find the driver's `libcuda.so.1` in the runtime's NVIDIA GL extension for the host's driver.
- **The GPU architecture** is `cfg.cudaArch`, nvcc's `-arch`. It defaults to `native`, the GPUs of the machine that builds, as `march` defaults to its CPU; where there is none, nvcc warns and uses its own default (sm_75 in CUDA 13.4). Like `-march=native`, it is for a program that runs where it is built: it carries no PTX, which a GPU of a newer architecture compiles when it loads the program. For other machines, build with `--cuda-arch=all-major`, nvcc's major architectures (`sm_*0`) and its earliest, with the PTX of the newest major, or name one, such as `sm_89`, which comes with its own PTX. `--cuda-arch=` and `CRAFTER_BUILD_CUDA_ARCH` set it where `project.cpp` calls `ApplyStandardArgs`, as `--march=` and `CRAFTER_BUILD_MARCH` set `march`, and a test inherits it. Another architecture builds in a directory of its own, and so does `native` when the GPUs change: the NVIDIA GPUs on the machine's PCI bus (its display devices, PCI class 0x03), the slots they are in, `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` key it. That is crafter-build's reading of the machine, not nvcc's own: after a change it cannot see, such as a GPU bound to another driver, run `crafter-build clean`, or build with a named architecture, which depends on nothing on the machine.
- **nvcc gets** `-O3` and `-arch`, beside `-c`, the `.cu` and its outputs (`-o`, and `-MD -MF` for the depfile): none of the include paths, defines and `cfg.compileFlags` the C and C++ compiles get, and no `-g` for `cfg.debug`. A `.cu` compiles again when it, or a header it includes, is newer than its object, as a C or C++ source does.
## Tests ## Tests
Tests live under `tests/<Name>/`. The simplest case is a single C++ file: Tests live under `tests/<Name>/`. The simplest case is a single C++ file:
@ -150,8 +299,9 @@ Test conventions:
- **Exit codes**: `0` = ✅ pass, nonzero = ❌ fail, **`77`** = ⏭ skipped (autoconf convention; use it for runtime opt-outs like "tool not on PATH"). - **Exit codes**: `0` = ✅ pass, nonzero = ❌ fail, **`77`** = ⏭ skipped (autoconf convention; use it for runtime opt-outs like "tool not on PATH").
- Each test runs in its own subprocess — a segfault doesn't take the runner down. - Each test runs in its own subprocess — a segfault doesn't take the runner down.
- Default timeout is 60 s per test, runs in parallel up to `hardware_concurrency()`. - Each test runs with `TMPDIR` naming a directory of its own, `<run>/<name>` in a directory made for the run in the temp directory, or, where the run has given that name out already, the first of `<name>-2`, `<name>-3` and on that it has not, so `fs::temp_directory_path()` in a test is the test's alone, even with another run going at the same time. Its path is longer than the temp directory's by 28 bytes and the name of the test's own directory, room a test that binds a Unix socket there has to leave: a socket's path holds 107 bytes. That takes a runner that hands the test `TMPDIR`, as running it directly and qemu-user do: under wine a Windows test does not get `TMPDIR`, and its `TMP`, `TEMP` and temp directory are the Wine prefix's, which every run in that prefix shares; wasmtime gives a test no environment at all. What a test leaves in its `TMPDIR` is removed when it passes or skips. When it fails, crashes or times out, what it left is kept, and its log in `build/test-logs/` says where, as does what is printed of a test that fails or crashes. A later run removes it once the run's directory has gone a minute unchanged: a minute after the run that kept it ended, or, where that run was killed, a minute after it last made or removed a test's directory there. A test that builds against a sysroot or mingw prefix it stages there, or has crafter-build fetch a repository it stages there (an `ExternalDependency` or a `GitProject` of it), keys crafter-build's cache on that path or URL, which is a new one every run: point `XDG_CACHE_HOME` into its `TMPDIR` as well, or every run leaves an entry of its own in the cache.
- Stdout+stderr is captured and printed atomically on completion. Failed/crashed/timed-out tests also write to `build/test-logs/<name>.log`. - Default timeout is 60 s per test, runs in parallel up to `hardware_concurrency()` tests (`--jobs=`). The steps of their builds share one limit, a build's: as many at once as there are hardware threads.
- Stdout+stderr is captured and printed atomically on completion. A test that fails, crashes or times out once it is built also writes what it printed, and what crafter-build said of it, to `build/test-logs/<name>.log`, when that is anything, and, where it sets `Test::wayland` and ran, what its compositor printed, if anything, to `<name>.compositor.log` beside it (what a compositor that did not start printed is in `<name>.log`); one that failed to build, or did not get that far, writes neither. `<name>` is the test's name with `-2`, `-3` and on after it where the run has given that name out already, as two configurations or two targets may each declare a test of one name.
- A broken fixture `project.cpp` is reported as a single failed test, not a fatal error — other tests still run. - A broken fixture `project.cpp` is reported as a single failed test, not a fatal error — other tests still run.
CLI: CLI:
@ -162,8 +312,9 @@ crafter-build test 'Unit*' # glob-filter te
crafter-build test --list # enumerate without running crafter-build test --list # enumerate without running
crafter-build test --target=x86_64-w64-mingw32 # only tests for this target crafter-build test --target=x86_64-w64-mingw32 # only tests for this target
crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine
crafter-build test --jobs=1 # serial mode crafter-build test --jobs=1 # one test at a time
crafter-build test --timeout=5 # override per-test timeout crafter-build test --timeout=5 # override per-test timeout
crafter-build test --compositor=host # Wayland tests on this session's display
``` ```
Outcomes: ✅ pass, ❌ fail, 💥 crash (with signal name), ⏱ timeout, ⏭ skipped. The runner exits 0 only if every non-skipped test passed. Outcomes: ✅ pass, ❌ fail, 💥 crash (with signal name), ⏱ timeout, ⏭ skipped. The runner exits 0 only if every non-skipped test passed.
@ -185,11 +336,11 @@ For elaborate setups (rsync, ssh ControlMaster, env vars on the spawn, `QEMU_LD_
For cross-arch builds, set `cfg.sysroot` on the `Configuration` to point at a sysroot for the target. `BuildStdPcm` and the compile/link commands both consume it: `--sysroot=<path>` is passed to clang, and the std module is precompiled against the sysroot's libc++ headers. Ordinary compiles are pointed at the same headers (`-nostdinc++ -isystem <sysroot>/usr/include/c++/v1`), so a unit that `#include`s a standard header gets the sysroot's libc++ and not the host toolchain's. The module source has to come from the same libc++ release as those headers, so it is taken from `<sysroot>/usr/share/libc++/v1/std.cppm` when the sysroot ships it, else from the toolchain when both are the same major release, else from the sources crafter-build carries for other releases (`share/crafter-build/libc++-modules/<major>/`, `crafter-build --version` lists them). Alpine is the common case for the last two: its `libc++-dev` has the headers and no module source. When nothing matches, the build stops with one line naming both releases, installing that release's `share/libc++/v1` directory into the sysroot resolves it. The cheapest aarch64 sysroot is an extracted [Arch Linux ARM rootfs](http://os.archlinuxarm.org/) plus `libc++` + `libc++abi` + `gcc` installed into it via `pacman --root <rootfs> --config <alarm-pacman.conf> --dbpath <rootfs>/var/lib/pacman -Sy …` (point pacman at ALARM's mirrors via explicit config to avoid pulling host-arch packages). For cross-arch builds, set `cfg.sysroot` on the `Configuration` to point at a sysroot for the target. `BuildStdPcm` and the compile/link commands both consume it: `--sysroot=<path>` is passed to clang, and the std module is precompiled against the sysroot's libc++ headers. Ordinary compiles are pointed at the same headers (`-nostdinc++ -isystem <sysroot>/usr/include/c++/v1`), so a unit that `#include`s a standard header gets the sysroot's libc++ and not the host toolchain's. The module source has to come from the same libc++ release as those headers, so it is taken from `<sysroot>/usr/share/libc++/v1/std.cppm` when the sysroot ships it, else from the toolchain when both are the same major release, else from the sources crafter-build carries for other releases (`share/crafter-build/libc++-modules/<major>/`, `crafter-build --version` lists them). Alpine is the common case for the last two: its `libc++-dev` has the headers and no module source. When nothing matches, the build stops with one line naming both releases, installing that release's `share/libc++/v1` directory into the sysroot resolves it. The cheapest aarch64 sysroot is an extracted [Arch Linux ARM rootfs](http://os.archlinuxarm.org/) plus `libc++` + `libc++abi` + `gcc` installed into it via `pacman --root <rootfs> --config <alarm-pacman.conf> --dbpath <rootfs>/var/lib/pacman -Sy …` (point pacman at ALARM's mirrors via explicit config to avoid pulling host-arch packages).
For `--target=x86_64-w64-mingw32` (Windows from Linux), the pipeline cross-compiles as long as `mingw-w64` is installed, with libstdc++ 15 or newer for its std module. clang finds it by the `x86_64-w64-mingw32-gcc` on `PATH`; `CRAFTER_MINGW_DIR` names another prefix (the directory holding `x86_64-w64-mingw32/` and `lib/gcc/`), and inside the Flatpak the host's `/usr` is used when it has mingw-w64. Without one the build stops with a message saying where it looked. Pair it with `--runner=cmd:wine` to run the result. Only the MinGW ABI is supported, there is no MSVC target and no Windows host. `-fuse-ld=lld` is auto-injected on every link, and `-lstdc++exp` is auto-linked for the mingw target so user projects don't need to declare those flags. For `--target=x86_64-w64-mingw32` (Windows from Linux), the pipeline cross-compiles as long as `mingw-w64` is installed, with libstdc++ 15 or newer for its std module. clang finds it by the `x86_64-w64-mingw32-gcc` on `PATH`; `CRAFTER_MINGW_DIR` names another prefix (the directory holding `x86_64-w64-mingw32/` and `lib/gcc/`), and inside the Flatpak the host's `/usr` is used when it has mingw-w64. Without one the build stops with a message saying where it looked. The prefix is clang's sysroot as it is, so Windows libraries installed into its `include/` and `lib/` are found, unless it also holds a Linux system: the host's `/usr` in the Flatpak, or any prefix whose `include/` has a C library's `features.h`, as `/usr` does. clang searches a sysroot's `include/` and `lib/`, and in such a prefix those hold glibc's headers and Linux libraries, so clang is shown only its `x86_64-w64-mingw32/`, `lib/gcc/` and `lib64/gcc/`, as links in `mingw-sysroot/` in the cache (`~/.cache/crafter.build/`, in the Flatpak `~/.var/app/net.catcrafts.CrafterBuild/cache/crafter.build/`, or `$XDG_RUNTIME_DIR/crafter.build/` when the cache's filesystem takes no symbolic links). Compiler messages still name those headers by their paths in the prefix. Pair it with `--runner=cmd:wine` to run the result. Only the MinGW ABI is supported, there is no MSVC target and no Windows host. `-fuse-ld=lld` is auto-injected on every link, and `-lstdc++exp` is auto-linked for the mingw target so user projects don't need to declare those flags.
For `--target=wasm32-wasip1`, the WASI sysroot is the one beside the toolchain (the Flatpak bundles one) unless `CRAFTER_BUILD_WASI_SYSROOT` names another, and tests run under `wasmtime`. C++ exceptions work as on the other targets: every unit and the std module are compiled with `-fwasm-exceptions` in the standardized form of WebAssembly exception handling (exnref), against the exception-enabled libc++ in the sysroot's `lib/<triple>/eh/`, and `-lunwind` is linked automatically. A sysroot without that libc++ (wasi-sdk before 33) stops the build with one line saying so. The result runs on engines with that proposal: Chrome 137, Firefox 131 and Safari 18.4 or newer, and the wasmtime the Flatpak bundles. A page from `EnableWasiBrowserRuntime` checks first and names what an older browser lacks in the console, instead of failing to compile the module. An exception that escapes `main` leaves the program as an uncaught WebAssembly exception (wasmtime reports `thrown Wasm exception` and exits 1, a page gets a `WebAssembly.Exception`) without calling `std::terminate`, so a `std::set_terminate` handler does not run and nothing prints the exception's type or `what()`: wasm exception handling unwinds in a single phase, and nothing finds out that no handler is left until the stack is gone. Catch it in `main` to report it. For `--target=wasm32-wasip1`, the WASI sysroot is the one beside the toolchain (the Flatpak bundles one) unless `CRAFTER_BUILD_WASI_SYSROOT` names another, and tests run under `wasmtime`. C++ exceptions work as on the other targets: every unit and the std module are compiled with `-fwasm-exceptions` in the standardized form of WebAssembly exception handling (exnref), against the exception-enabled libc++ in the sysroot's `lib/<triple>/eh/`, and `-lunwind` is linked automatically. A sysroot without that libc++ (wasi-sdk before 33) stops the build with one line saying so. The result runs on engines with that proposal: Chrome 137, Firefox 131 and Safari 18.4 or newer, and the wasmtime the Flatpak bundles. A page from `EnableWasiBrowserRuntime` checks first and names what an older browser lacks in the console, instead of failing to compile the module. An exception that escapes `main` leaves the program as an uncaught WebAssembly exception (wasmtime reports `thrown Wasm exception` and exits 1, a page gets a `WebAssembly.Exception`) without calling `std::terminate`, so a `std::set_terminate` handler does not run and nothing prints the exception's type or `what()`: wasm exception handling unwinds in a single phase, and nothing finds out that no handler is left until the stack is gone. Catch it in `main` to report it.
A wasm build refuses three things before it starts, each with a message that says why: `-flto` in `compileFlags` or `linkFlags` (LTO code generation drops the exception handling, [WebAssembly/wasi-sdk#629](https://github.com/WebAssembly/wasi-sdk/issues/629)), `-fno-exceptions` (the std module is built with exceptions, and a unit without them cannot import it) and a shared library (the exception-enabled libc++ is static archives only). `setjmp` and `longjmp` work in C and C++ sources, with `-lsetjmp` linked automatically like `-lunwind`; a `longjmp` across a `noexcept` function ends the program, because it is a wasm exception and the function's terminate handler catches it. Outside the Flatpak, a wasmtime older than 47 has exception handling off and needs `-W exceptions=y`, and a `wasm-opt` on `PATH` from a binaryen that cannot read the standardized encoding breaks release links, since clang runs it on optimized wasm links when it finds one. A wasm build refuses four things before it starts, each with a message that says why: `-flto` in `compileFlags` or `linkFlags` (LTO code generation drops the exception handling, [WebAssembly/wasi-sdk#629](https://github.com/WebAssembly/wasi-sdk/issues/629)), `-fno-exceptions` (the std module is built with exceptions, and a unit without them cannot import it), a shared library (the exception-enabled libc++ is static archives only) and packaging as a Flatpak (a wasm build stays a `.wasm`; see [Flatpak output](#flatpak-output)). `setjmp` and `longjmp` work in C and C++ sources, with `-lsetjmp` linked automatically like `-lunwind`; a `longjmp` across a `noexcept` function ends the program, because it is a wasm exception and the function's terminate handler catches it. Outside the Flatpak, a wasmtime older than 47 has exception handling off and needs `-W exceptions=y`, and a `wasm-opt` on `PATH` from a binaryen that cannot read the standardized encoding breaks release links, since clang runs it on optimized wasm links when it finds one.
In a page from `EnableWasiBrowserRuntime`, `exit` and `_Exit` end the program as they would anywhere else: none of its code runs on the way out, no destructor and no `catch (...)`, its status is in `window.crafter_wasi.exitCode`, and bridges that call into it on their own are expected to stop. A program that hands the thread to the browser for good and goes on serving calls, as Crafter.Graphics's `Window::StartSync()` does, parks instead of exiting. Parking never returns, runs nothing of the program either, and leaves `main`'s locals valid for the calls that follow: In a page from `EnableWasiBrowserRuntime`, `exit` and `_Exit` end the program as they would anywhere else: none of its code runs on the way out, no destructor and no `catch (...)`, its status is in `window.crafter_wasi.exitCode`, and bridges that call into it on their own are expected to stop. A program that hands the thread to the browser for good and goes on serving calls, as Crafter.Graphics's `Window::StartSync()` does, parks instead of exiting. Parking never returns, runs nothing of the program either, and leaves `main`'s locals valid for the calls that follow:
@ -226,6 +377,24 @@ cmd:<command> # cmd:wine, cmd:qemu-aarch64, cmd:valgrind, ...
Each runner carries a `probe` command (e.g. `which wine`), if it fails, every test using that runner is reported as ⏭ skipped and the rest of the suite continues. Skipped tests count toward the summary but don't fail the suite (`AllPassed()` returns true on skip-only runs). Each runner carries a `probe` command (e.g. `which wine`), if it fails, every test using that runner is reported as ⏭ skipped and the rest of the suite continues. Skipped tests count toward the summary but don't fail the suite (`AllPassed()` returns true on skip-only runs).
### Tests that open windows
A test that talks to a Wayland compositor sets `Test::wayland`, and every run of it gets a headless compositor of its own instead of your session's display, so the windows it opens through `WAYLAND_DISPLAY` show up there and not on your desktop:
```cpp
cfg.AddTest("Swapchain").Wayland(); // or, on a Test you build yourself: test.wayland = true;
```
Before the test, crafter-build starts the compositor with `XDG_RUNTIME_DIR` set to a directory made for it (in your `XDG_RUNTIME_DIR`, else in `/tmp`) and without `WAYLAND_DISPLAY`, `WAYLAND_SOCKET` or `DISPLAY`, and waits up to 30 s for a `wayland-<n>` socket to appear there. The test then runs with `WAYLAND_DISPLAY` set to that socket's full path and with `DISPLAY` and `WAYLAND_SOCKET` unset; its `XDG_RUNTIME_DIR` stays yours. Afterwards the compositor's process group is sent SIGTERM, what is left of the group SIGKILL once the compositor has ended or 5 s have passed, and the directory is removed. No two tests share a compositor, so tests that run at once cannot cover each other's windows or take each other's focus.
The compositor is `weston --backend=headless --renderer=gl --no-config --idle-time=0` unless `CRAFTER_BUILD_COMPOSITOR` names another, and `--compositor=` wins over both. The Flatpak ships weston 16.0.2; outside it, install weston 12 or newer, the first release to take `--renderer=`. Its GL renderer takes the GPU buffers (dmabufs) that a GPU's Vulkan driver presents, as Mesa's and NVIDIA's do, and which the headless backend's default, a renderer that draws nothing, and pixman take none of; `--no-config` keeps your `weston.ini` out, and `--idle-time=0` keeps the output from going idle after 5 minutes, which would stop frame callbacks. Another compositor is any command, run through `sh`, that listens on a `wayland-<n>` socket in the `XDG_RUNTIME_DIR` it is given. `host` starts none and gives these tests your own display, to watch what they draw:
```bash
crafter-build test --compositor=host 'Swapchain*'
```
A compositor that ends before it listens, `sh` not finding it included, or does not listen within 30 s fails the test with what it printed. A test that may run where weston is missing declares it with `.Requires("tool:weston")`, and is then skipped there before it is built, as for any tool it declares. When a test that ran fails, crashes or times out, what its compositor printed, if anything, goes to `build/test-logs/<name>.compositor.log`, named as the test's own log is, and the test's output says so, and also when the compositor ended before the test did; what a compositor that did not start printed is in the test's own failure, in `build/test-logs/<name>.log`. A crafter-build that is killed takes its compositors with it; the directories it leaves behind are removed by a test that starts a compositor after they have gone a minute unchanged.
### Linking the parent project's library ### Linking the parent project's library
A test fixture can depend on the project's own library so it can `import` and exercise its API: A test fixture can depend on the project's own library so it can `import` and exercise its API:
@ -326,7 +495,7 @@ The callback returns the exit status, and `crafter-build run` exits with it. `ct
cfg.scripts.push_back({"package", [](Crafter::ScriptContext& ctx) { cfg.scripts.push_back({"package", [](Crafter::ScriptContext& ctx) {
const std::string dist = Crafter::ShellQuote((ctx.projectDir / "dist").string()); const std::string dist = Crafter::ShellQuote((ctx.projectDir / "dist").string());
if (const std::int32_t code = ctx.Run(std::format("mkdir -p {}", dist)); code != 0) return code; if (const std::int32_t code = ctx.Run(std::format("mkdir -p {}", dist)); code != 0) return code;
return ctx.Run(std::format("tar -czf {}/myapp.tar.gz -C {} .", dist, Crafter::ShellQuote(ctx.project.BinDir().string()))); return ctx.Run(std::format("tar -czf {}/myapp.tar.gz -C {} .", dist, Crafter::ShellQuote(ctx.project.ProgramDir().string())));
}}); }});
``` ```
@ -334,7 +503,7 @@ cfg.scripts.push_back({"package", [](Crafter::ScriptContext& ctx) {
| Member | Meaning | | Member | Meaning |
|---|---| |---|---|
| `project` | the `Configuration` that `project.cpp` returned. Read the project through this; a `cfg` captured by reference is gone by the time a script runs | | `project` | the `Configuration` the script is declared on: the one `project.cpp` returned, or of several the one whose `scripts` holds it. Read the project through this rather than through a `cfg` captured by reference |
| `projectDir` | absolute directory of the project file | | `projectDir` | absolute directory of the project file |
| `args` | everything typed after the script's name, untouched | | `args` | everything typed after the script's name, untouched |
| `Run(command)` | run a shell command with the terminal attached and return its exit code | | `Run(command)` | run a shell command with the terminal attached and return its exit code |
@ -348,6 +517,32 @@ Things to know:
- Inside the Flatpak, commands run in its sandbox: the host's files are visible, but the tools on `PATH` are the ones the Flatpak ships (`git`, `cmake`, `python3`, `tar`, ...), not everything installed on the host. - Inside the Flatpak, commands run in its sandbox: the host's files are visible, but the tools on `PATH` are the ones the Flatpak ships (`git`, `cmake`, `python3`, `tar`, ...), not everything installed on the host.
- A return value outside 0 to 255 is not an exit status and becomes 1. So does a script that throws, with the exception's message printed. - A return value outside 0 to 255 is not an exit status and becomes 1. So does a script that throws, with the exception's message printed.
## Debugging
Programs that `-r` and the test runner start run inside the Flatpak's sandbox, and so do the tools to debug them: lldb, with `lldb-server`, `lldb-dap` and `lldb-mcp`, from the same LLVM build as the compiler; `gdb`, `gdbserver`, `valgrind` and `strace` from the Freedesktop Sdk; the Khronos Vulkan validation layer; and the SPIRV-Tools programs (`spirv-val`, `spirv-opt`, `spirv-dis`, ...). A default build is optimised (`-O3`, and ThinLTO except for wasm) and carries no debug information: set `cfg.debug = true` for a program you want to debug, which compiles its C++ units with `-g` and links it without LTO; its C and CUDA sources (`cfg.cFiles`, `cfg.cuda`) stay at `-O3` without debug information. A `project.cpp` that calls `ApplyStandardArgs` sets it from the `--debug` argument, as in `crafter-build --debug -r`. Start the tools with `--command`:
```bash
flatpak run --die-with-parent --command=lldb net.catcrafts.CrafterBuild ./bin/myapp-<variant>/myapp
flatpak run --die-with-parent --command=valgrind net.catcrafts.CrafterBuild ./bin/myapp-<variant>/myapp
```
Every `flatpak run` is a sandbox of its own, with process IDs of its own, so a debugger in one cannot see a program that another one, such as `crafter-build -r`, started. Either start the program under the debugger, or run the debugger inside that program's sandbox with `flatpak enter`, giving the instance `flatpak ps` lists for net.catcrafts.CrafterBuild and the debugger's full path:
```bash
flatpak ps --columns=instance,application
flatpak enter <instance> /app/bin/lldb -n myapp
```
Where `/proc/sys/kernel/yama/ptrace_scope` is 1, a debugger in the sandbox, where processes hold no capabilities, can attach to a program that is not its descendant only when the program allowed it with `prctl(PR_SET_PTRACER, …)`: with the debugger's process ID, or with `PR_SET_PTRACER_ANY` for any process. Otherwise the attach fails. A program started under the debugger is its descendant. Prefer `flatpak enter` to `lldb-server gdbserver` in one sandbox and lldb's `gdb-remote` from another: when a process in lldb's own sandbox has the remote program's process ID, lldb takes that process's executable for the program's: symbols come out wrong, and a breakpoint in the program's source finds no location.
The validation layer is enabled the usual ways, by the program itself or from the environment: `flatpak run` passes `VK_INSTANCE_LAYERS`, `VK_LOADER_LAYERS_ENABLE` and the layer's `VK_KHRONOS_VALIDATION_*` settings into the sandbox. `VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1` adds GPU-assisted validation (GPU-AV):
```bash
VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 crafter-build -r
```
The layer is the Vulkan SDK release of the runtime's own Vulkan loader. `VK_LAYER_PATH` and `VK_ADD_LAYER_PATH` are cleared on the way into the sandbox, so a layer installed on the host is out of reach.
## Examples ## Examples
[examples/](examples/) contains progressively larger self-contained projects: [examples/](examples/) contains progressively larger self-contained projects:
@ -367,7 +562,7 @@ This project is licensed under the GNU Lesser General Public License, version 3
The example code under [examples/](examples/) is licensed under the MIT license (see [examples/LICENSE](examples/LICENSE)), so it can be freely copied into your own projects. The example code under [examples/](examples/) is licensed under the MIT license (see [examples/LICENSE](examples/LICENSE)), so it can be freely copied into your own projects.
The [lib/](lib/) directory contains vendored third-party code (nlohmann/json, glslang's DirStackFileIncluder) that remains under its own permissive licenses, see the headers of those files. The [lib/](lib/) directory contains vendored third-party code (glslang's DirStackFileIncluder) that remains under its own permissive license, see the header of that file.
## Copyright ## Copyright

View file

@ -36,10 +36,9 @@ else
STD_CPPM=/usr/share/libc++/v1/std.cppm STD_CPPM=/usr/share/libc++/v1/std.cppm
fi fi
# The version baked into the binary: the environment (CI sets it from the # The version baked into the binary: the environment (CI sets it), else the
# tag), else the nearest tag, else a development marker. `latest` is the # nearest tag, else a development marker.
# rolling CI tag and never a version. VERSION="${CRAFTER_BUILD_VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo 0.0.0-dev)}"
VERSION="${CRAFTER_BUILD_VERSION:-$(git describe --tags --always --dirty --exclude=latest 2>/dev/null || echo 0.0.0-dev)}"
mkdir -p build bin lib share/crafter-build share/crafter-build/wasi-runtime mkdir -p build bin lib share/crafter-build share/crafter-build/wasi-runtime
@ -48,7 +47,7 @@ cp wasi-runtime/index.html.in share/crafter-build/wasi-runtime/
# Partition order is the import order: every unit is listed before the # Partition order is the import order: every unit is listed before the
# units that import it, and the umbrella last. # units that import it, and the umbrella last.
PARTITIONS="Toolchain Shader Platform Interface Implementation External Agents Clang Test Lint Script Progress Asset" PARTITIONS="Toolchain Shader Platform Flatpak Jobs Interface Implementation External Agents Clang Test Lint Script Progress Asset"
cp interfaces/Crafter.Build.cppm share/crafter-build/ cp interfaces/Crafter.Build.cppm share/crafter-build/
for p in $PARTITIONS; do for p in $PARTITIONS; do

View file

@ -37,6 +37,7 @@ builder methods overlay overrides:
- `.Dependencies({ &otherCfg, ... })` - `.Dependencies({ &otherCfg, ... })`
- `.Path(p)` &mdash; rebase the test's source-resolution path - `.Path(p)` &mdash; rebase the test's source-resolution path
- `.LinkFlag(s)` / `.CompileFlag(s)` - `.LinkFlag(s)` / `.CompileFlag(s)`
- `.Wayland()` &mdash; a headless Wayland compositor of the test's own, so that the windows it opens stay off your desktop ([Tests that open windows](../../README.md#tests-that-open-windows))
## Test conventions ## Test conventions

View file

@ -22,12 +22,26 @@ namespace {
// Right under the begin marker, for whoever opens the file: an edit made // Right under the begin marker, for whoever opens the file: an edit made
// inside the section is gone after the next build. // inside the section is gone after the next build.
constexpr std::string_view Preamble = "<!-- Written by crafter-build from the AGENTS.consumer.md each dependency ships, and rewritten on every build. Edit those files, not this section; cfg.dependencyNotes in project.cpp picks which dependencies are included. -->"; constexpr std::string_view Preamble = "<!-- Written by crafter-build from the AGENTS.consumer.md each dependency ships, and rewritten on every build. Edit those files, not this section; cfg.dependencyNotes in project.cpp picks which dependencies are included. -->";
// The first line of every AGENTS.md a build writes. It tells whoever
// opens the file, an agent asked to change it included, where an edit
// has to be made to outlive the next build, and it is how a build tells
// its own AGENTS.md from one someone wrote, which it never replaces. A
// changed word would make every AGENTS.md written before look like
// someone's own.
constexpr std::string_view GeneratedLine = "<!-- Written by crafter-build from AGENTS.template.md, and rewritten on every build. Edit that file, not this one. -->";
constexpr std::string_view NotesFileName = "AGENTS.consumer.md"; constexpr std::string_view NotesFileName = "AGENTS.consumer.md";
constexpr std::string_view TemplateFileName = "AGENTS.template.md";
constexpr std::string_view AgentsFileName = "AGENTS.md";
void Warn(std::string_view message) { void Warn(std::string_view message) {
Progress::Diagnostic(std::format("warning: {}", message)); Progress::Diagnostic(std::format("warning: {}", message));
} }
// The line ending `text` uses, so a CRLF file does not end up mixed.
std::string_view LineEnd(std::string_view text) {
return text.contains("\r\n") ? "\r\n" : "\n";
}
std::string ErrnoMessage() { std::string ErrnoMessage() {
return std::error_code(errno, std::generic_category()).message(); return std::error_code(errno, std::generic_category()).message();
} }
@ -249,9 +263,9 @@ namespace {
} }
// Why `text` cannot go into the section as it is; empty when it can. A // Why `text` cannot go into the section as it is; empty when it can. A
// marker line of its own would end or restart the section once the file // marker line of its own would end or restart the section for whoever
// is read back, and a code block left open would hide the end marker: // reads it, a template copied from the result included, and a code block
// either way the next build could no longer find what this one wrote. // left open would run on over the notes after it and the end marker.
// Lines are numbered from `firstLine`. // Lines are numbered from `firstLine`.
std::string NoteProblem(std::string_view text, std::size_t firstLine) { std::string NoteProblem(std::string_view text, std::size_t firstLine) {
const MarkerScan scan = ScanMarkers(text); const MarkerScan scan = ScanMarkers(text);
@ -331,18 +345,60 @@ namespace {
return DependencyNote{ .name = name, .text = std::move(note.text) }; return DependencyNote{ .name = name, .text = std::move(note.text) };
} }
// The loaded projects `configs` lead to without passing through another // Tells a configuration of another project from one of the project
// loaded project, in the order the configurations name them: one ring // whose AGENTS.md is written, the one of the project file it is made
// further out. `walked` spans the whole collection, so each // with. GitProject and LocalProject hold the configurations of a project
// Configuration is looked at once however many paths reach it. // file they loaded, so held or not does not tell the two apart: the
std::vector<const Configuration*> NextRing(std::span<const Configuration* const> configs, std::unordered_set<const Configuration*>& walked) { // 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*> ring;
std::vector<const Configuration*> pending(configs.rbegin(), configs.rend()); std::vector<const Configuration*> pending(configs.rbegin(), configs.rend());
while (!pending.empty()) { while (!pending.empty()) {
const Configuration* cfg = pending.back(); const Configuration* cfg = pending.back();
pending.pop_back(); pending.pop_back();
if (!cfg || !walked.insert(cfg).second) continue; if (!cfg || !walked.insert(cfg).second) continue;
if (LoadedProjectOf(*cfg)) { if (others.Of(*cfg)) {
ring.push_back(cfg); ring.push_back(cfg);
continue; continue;
} }
@ -351,21 +407,72 @@ namespace {
return ring; return ring;
} }
// The AGENTS.consumer.md of every project `project` depends on, as // The AGENTS.consumer.md of every project the project is built against,
// project.dependencyNotes selects them, ring by ring: first the loaded // as the dependencyNotes of `configurations`, the configurations its
// projects (the ones GitProject and LocalProject returned) that its // project file returns, select them, ring by ring: first the other
// `#pragma crafter dependency` lines and its configurations name, in // projects (the ones GitProject and LocalProject loaded from another
// that order, then the ones those depend on. Its own configurations, and // project file) that its `#pragma crafter dependency` lines and its
// a dependency's internal ones, are only walked through. Direct stops // configurations name, in that order, then the ones those depend on.
// after the first ring. // 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 // 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 // them and a test's dependency can point at the Configuration a
// file returned by value, which has since moved; and a dependency's own // CrafterBuildProject returned by value, which a caller of LoadProject
// pragma tooling, which is about how the dependency is built, not how it // may have moved since; and a dependency's own pragma tooling, which is
// is used, and is no `dependencies` edge to begin with. // about how the dependency is built, not how it is used, and is no
std::vector<DependencyNote> CollectNotes(const Configuration& project, const fs::path& projectFile, const fs::path& projectDir) { // `dependencies` edge to begin with.
std::unordered_set<const Configuration*> walked = { &project }; 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 // The project's own notes are for its consumers, so they never go
// into its own AGENTS.md, whatever dependency they sit beside. Both // into its own AGENTS.md, whatever dependency they sit beside. Both
// places count for a symlinked project file. // places count for a symlinked project file.
@ -375,13 +482,11 @@ namespace {
std::unordered_set<std::string> identities; std::unordered_set<std::string> identities;
std::vector<DependencyNote> notes; std::vector<DependencyNote> notes;
std::vector<const Configuration*> start; for (std::vector<const Configuration*> ring = NextRing(start, walked, others); !ring.empty();) {
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();) {
std::vector<const Configuration*> next; std::vector<const Configuration*> next;
for (const Configuration* cfg : ring) { 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; const fs::path file = loaded->projectFile.parent_path() / NotesFileName;
// One library under two specs (a pin here, another revision // One library under two specs (a pin here, another revision
// further down) is described once, as the ring nearest the // further down) is described once, as the ring nearest the
@ -389,14 +494,40 @@ namespace {
if (identities.insert(loaded->identity).second && files.insert(file).second) { 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)); 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, others);
ring = NextRing(next, walked);
} }
return notes; return notes;
} }
// Whether a build may replace `agentsMd`, the AGENTS.md beside a
// template: one a build wrote, or one with no text at all, which is what
// a write cut short leaves of a new file. Anything else someone wrote,
// and beside a template that is easily the case: an AGENTS.md committed
// before the template was, or one an agent kept its own notes in.
bool Replaceable(std::string_view agentsMd) {
if (agentsMd.find_first_not_of(" \t\r\n") == std::string_view::npos) return true;
std::string_view first = agentsMd.substr(0, agentsMd.find('\n'));
if (first.ends_with('\r')) first.remove_suffix(1);
return first == GeneratedLine;
}
// An AGENTS.md with no template beside it is someone's own, and no build
// writes it. One that still holds a section from the builds that kept the
// notes in a committed AGENTS.md would go stale without a word, under a
// preamble saying every build rewrites it, so each build says so until
// the file has moved to a template or the section is gone.
void WarnStaleSection(const fs::path& agents) {
std::error_code ec;
if (!fs::is_regular_file(agents, ec)) return;
std::string text;
if (!ReadFile(agents, text).empty()) return;
const MarkerScan scan = ScanMarkers(text);
if (scan.begins.empty() && scan.ends.empty()) return;
Warn(std::format("{} has a dependency notes section, which builds no longer update; rename the file to {} and keep {} out of version control to have every build write it with current notes, or delete the section", agents.string(), TemplateFileName, AgentsFileName));
}
// Bring `fd`, which holds `current`, to `wanted`: from the first byte the // Bring `fd`, which holds `current`, to `wanted`: from the first byte the
// two differ at, so the text in front of the section is never rewritten, // two differ at, so the text in front of the section is never rewritten,
// then cut to length and synced. Empty on success, otherwise the error. // then cut to length and synced. Empty on success, otherwise the error.
@ -405,10 +536,9 @@ namespace {
// rename swaps in another file, which drops whatever belongs to the old // rename swaps in another file, which drops whatever belongs to the old
// one (a hard link such as a CLAUDE.md beside it, ACLs, ownership, being // one (a hard link such as a CLAUDE.md beside it, ACLs, ownership, being
// read-only) and needs fsyncs to be crash safe at all. The price is that // read-only) and needs fsyncs to be crash safe at all. The price is that
// a reader can catch the section half written, and that a write failing // a reader can catch the file half written, and that a write failing
// partway, on a full disk say, leaves it so. With the section last, // partway, on a full disk say, leaves it so until the next build writes
// where it is appended, only the section can be damaged, and the next // it again.
// build reports its markers instead of guessing.
std::string WriteChanged(std::int32_t fd, std::string_view current, std::string_view wanted) { std::string WriteChanged(std::int32_t fd, std::string_view current, std::string_view wanted) {
const auto diverge = std::ranges::mismatch(current, wanted); const auto diverge = std::ranges::mismatch(current, wanted);
for (auto done = static_cast<std::size_t>(diverge.in2 - wanted.begin()); done < wanted.size();) { for (auto done = static_cast<std::size_t>(diverge.in2 - wanted.begin()); done < wanted.size();) {
@ -427,24 +557,24 @@ namespace {
} }
} }
std::string Crafter::MergeDependencyNotes(std::string_view agentsMd, std::span<const DependencyNote> notes) { std::string Crafter::MergeDependencyNotes(std::string_view templateMd, std::span<const DependencyNote> notes) {
for (const DependencyNote& note : notes) { for (const DependencyNote& note : notes) {
if (const std::string problem = NoteProblem(note.text, 1); !problem.empty()) throw std::runtime_error(std::format("the notes from {}: {}", note.name, problem)); if (const std::string problem = NoteProblem(note.text, 1); !problem.empty()) throw std::runtime_error(std::format("the notes from {}: {}", note.name, problem));
} }
const MarkerScan scan = ScanMarkers(agentsMd); const MarkerScan scan = ScanMarkers(templateMd);
const bool section = scan.begins.size() == 1 && scan.ends.size() == 1 && scan.begins[0] < scan.ends[0]; const bool section = scan.begins.size() == 1 && scan.ends.size() == 1 && scan.begins[0] < scan.ends[0];
// The file's own line ending, so a CRLF file does not end up mixed. const std::string_view eol = LineEnd(templateMd);
const std::string_view eol = agentsMd.contains("\r\n") ? "\r\n" : "\n";
if (notes.empty()) { if (notes.empty()) {
// With nothing to write, leaving the file alone loses nothing, so // With nothing to place, nothing can land in the wrong place, so
// anything short of a well-formed section is no concern of this one. // anything short of a well-formed section is left as it was written.
if (!section) return std::string(agentsMd); if (!section) return std::string(templateMd);
std::string_view before = agentsMd.substr(0, scan.lines[scan.begins[0]].begin); std::string_view before = templateMd.substr(0, scan.lines[scan.begins[0]].begin);
const std::string_view after = agentsMd.substr(scan.lines[scan.ends[0]].next); const std::string_view after = templateMd.substr(scan.lines[scan.ends[0]].next);
// The blank line a section at the end was appended after goes with // A section that ends the template takes the blank line in front of
// it. One the user moved keeps the text around it apart. // it, which an appended one gets. One placed elsewhere keeps the text
// around it apart.
if (after.empty() && before.ends_with(std::format("{0}{0}", eol))) before.remove_suffix(eol.size()); if (after.empty() && before.ends_with(std::format("{0}{0}", eol))) before.remove_suffix(eol.size());
return std::format("{}{}", before, after); return std::format("{}{}", before, after);
} }
@ -455,75 +585,101 @@ std::string Crafter::MergeDependencyNotes(std::string_view agentsMd, std::span<c
if (!scan.begins.empty() && scan.ends.empty()) throw std::runtime_error(std::format("line {}: a dependency notes begin marker with no end marker after it", scan.begins[0] + 1)); if (!scan.begins.empty() && scan.ends.empty()) throw std::runtime_error(std::format("line {}: a dependency notes begin marker with no end marker after it", scan.begins[0] + 1));
const std::string rendered = RenderSection(notes, eol); const std::string rendered = RenderSection(notes, eol);
if (section) return std::format("{}{}{}", agentsMd.substr(0, scan.lines[scan.begins[0]].begin), rendered, agentsMd.substr(scan.lines[scan.ends[0]].next)); if (section) return std::format("{}{}{}", templateMd.substr(0, scan.lines[scan.begins[0]].begin), rendered, templateMd.substr(scan.lines[scan.ends[0]].next));
// Appended, the section would sit inside that block and never be found // Appended, the section would sit inside that block and read as code.
// again, so every build would add another.
if (scan.unclosedBlock) throw std::runtime_error(std::format("line {}: a code block opens here and never closes", *scan.unclosedBlock + 1)); if (scan.unclosedBlock) throw std::runtime_error(std::format("line {}: a code block opens here and never closes", *scan.unclosedBlock + 1));
if (agentsMd.empty()) return rendered; if (templateMd.empty()) return rendered;
// On a line of its own, after a blank one. // On a line of its own, after a blank one.
return std::format("{}{}{}{}", agentsMd, agentsMd.ends_with('\n') ? std::string_view() : eol, eol, rendered); return std::format("{}{}{}{}", templateMd, templateMd.ends_with('\n') ? std::string_view() : eol, eol, rendered);
} }
bool Crafter::UpdateAgentsMd(const Configuration& project, const fs::path& projectFile) { 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; std::error_code ec;
// Beside the project file as it was named, so a symlinked project.cpp // Beside the project file as it was named, so a symlinked project.cpp
// keeps the AGENTS.md beside the link. // keeps the AGENTS.md beside the link.
const fs::path projectDir = fs::absolute(projectFile, ec).lexically_normal().parent_path(); const fs::path projectDir = fs::absolute(projectFile, ec).lexically_normal().parent_path();
if (ec) return false; if (ec) return false;
const fs::path agents = projectDir / "AGENTS.md"; const fs::path agents = projectDir / AgentsFileName;
if (!fs::is_regular_file(agents, ec)) return false; const fs::path templateFile = projectDir / TemplateFileName;
if (!fs::is_regular_file(templateFile, ec)) {
WarnStaleSection(agents);
return false;
}
// Linked to the template, AGENTS.md would have every build write the
// file that is committed, which is what the template is there to stop.
if (fs::equivalent(agents, templateFile, ec)) {
Warn(std::format("{} and {} are the same file, so {} was not written", agents.string(), templateFile.string(), AgentsFileName));
return false;
}
std::string templateMd;
if (const std::string error = ReadFile(templateFile, templateMd); !error.empty()) {
Warn(std::format("{} could not be read ({}), so {} was not written", templateFile.string(), error, agents.string()));
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));
} catch (const std::exception& e) {
Warn(std::format("{}: {}, so {} was not written", templateFile.string(), e.what(), agents.string()));
return false;
}
// Locked from the read through the write, so two builds never interleave // Created when missing, since a fresh clone has no build output, and only
// their writes, and on the file itself, which also covers two projects // now, with the text in hand, so a template the notes cannot be placed
// that link one AGENTS.md. A read-only descriptor takes the lock as // in leaves no empty AGENTS.md behind. Locked from the read through the
// well, so a read-only AGENTS.md is still read without complaint. // write, so two builds never interleave their writes, and on the file
const Descriptor reading(::open(agents.c_str(), O_RDONLY | O_CLOEXEC)); // itself, which also covers two projects that link one AGENTS.md. A
// read-only descriptor takes the lock as well, so a read-only AGENTS.md
// is still read without complaint.
const Descriptor reading(::open(agents.c_str(), O_RDONLY | O_CREAT | O_CLOEXEC, 0666));
if (!reading.Valid()) { if (!reading.Valid()) {
Warn(std::format("{} could not be read ({}), so its dependency notes were not updated", agents.string(), ErrnoMessage())); Warn(std::format("{} could not be opened ({}), so it was not written", agents.string(), ErrnoMessage()));
return false; return false;
} }
while (::flock(reading.Get(), LOCK_EX) != 0 && errno == EINTR) {} while (::flock(reading.Get(), LOCK_EX) != 0 && errno == EINTR) {}
std::string current; std::string current;
if (const std::string error = ReadAll(reading.Get(), current); !error.empty()) { if (const std::string error = ReadAll(reading.Get(), current); !error.empty()) {
Warn(std::format("{} could not be read ({}), so its dependency notes were not updated", agents.string(), error)); Warn(std::format("{} could not be read ({}), so it was not written", agents.string(), error));
return false; return false;
} }
if (current == wanted) return false;
std::string merged; if (!Replaceable(current)) {
try { Warn(std::format("{} was not written by a build, so it was not replaced by one written from {}; once the template holds what it says, delete it", agents.string(), TemplateFileName));
merged = MergeDependencyNotes(current, notes);
} catch (const std::exception& e) {
Warn(std::format("{}: {}, so its dependency notes were not updated", agents.string(), e.what()));
return false; return false;
} }
if (merged == current) return false;
// Only now, with something to write: a read-only AGENTS.md is refused // Only now, with something to write: a read-only AGENTS.md is refused
// here, and not on every build that leaves it as it is. // here, and not on every build that leaves it as it is.
const Descriptor writing(::open(agents.c_str(), O_WRONLY | O_CLOEXEC)); const Descriptor writing(::open(agents.c_str(), O_WRONLY | O_CLOEXEC));
if (!writing.Valid()) { if (!writing.Valid()) {
Warn(std::format("{} could not be opened for writing ({}), so its dependency notes were not updated", agents.string(), ErrnoMessage())); Warn(std::format("{} could not be opened for writing ({}), so it was not written", agents.string(), ErrnoMessage()));
return false; return false;
} }
if (const std::string error = WriteChanged(writing.Get(), current, merged); !error.empty()) { if (const std::string error = WriteChanged(writing.Get(), current, wanted); !error.empty()) {
// Put back what was there. A full disk that refused the new bytes // Put back what was there. A full disk that refused the new bytes
// usually still takes the old ones, whose space was just freed. // usually still takes the old ones, whose space was just freed.
if (WriteChanged(writing.Get(), merged, current).empty()) { if (WriteChanged(writing.Get(), wanted, current).empty()) {
Warn(std::format("{} could not be written ({}), so its dependency notes were not updated", agents.string(), error)); Warn(std::format("{} could not be written ({}), so it was left as it was", agents.string(), error));
} else { } else {
Warn(std::format("{} could not be written ({}) and may now end in part of the section; the next build reports it if so", agents.string(), error)); Warn(std::format("{} could not be written ({}) and may now be half written; the next build writes it again", agents.string(), error));
} }
return false; return false;
} }
// A build that edits a file the user commits says so. // A file that appears beside project.cpp, or changes there, unasked,
// says where it came from.
if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) { if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) {
Progress::Clear(); Progress::Clear();
if (notes.empty()) { if (notes.empty()) {
std::println("Removed the dependency notes from {}", agents.string()); std::println("Wrote {} from {}", agents.string(), TemplateFileName);
} else { } else {
std::println("Updated the dependency notes in {} ({} {})", agents.string(), notes.size(), notes.size() == 1 ? "dependency" : "dependencies"); std::println("Wrote {} from {} and the notes of {} {}", agents.string(), TemplateFileName, notes.size(), notes.size() == 1 ? "dependency" : "dependencies");
} }
} }
return true; return true;

File diff suppressed because it is too large Load diff

View file

@ -149,7 +149,7 @@ std::string BuildInjectedCMakeFlags(const fs::path& cmakeBuildDir, std::string_v
// The libstdc++ and the mingw-w64 install the project's own compiles // The libstdc++ and the mingw-w64 install the project's own compiles
// use (GetBaseCommand). // use (GetBaseCommand).
out += " -DCMAKE_CXX_FLAGS=-stdlib=libstdc++"; out += " -DCMAKE_CXX_FLAGS=-stdlib=libstdc++";
if (!tc.mingwSysroot.empty()) out += std::format(" -DCMAKE_SYSROOT={}", ShellQuote(tc.mingwSysroot.string())); if (const fs::path& sysroot = MingwSysroot(); !sysroot.empty()) out += std::format(" -DCMAKE_SYSROOT={}", ShellQuote(sysroot.string()));
} }
fs::path absBuildDir = fs::absolute(cmakeBuildDir); fs::path absBuildDir = fs::absolute(cmakeBuildDir);
out += std::format(" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY={}", ShellQuote(absBuildDir.string())); out += std::format(" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY={}", ShellQuote(absBuildDir.string()));
@ -179,6 +179,19 @@ std::string ConfigureCMake(const fs::path& cloneDir, const fs::path& cmakeBuildD
if (!needsConfigure) return ""; if (!needsConfigure) return "";
// A build directory configured with other inputs starts over instead of
// being reconfigured. CMake reconfigures in place without recompiling
// what an old compiler or --sysroot compiled (the Makefiles generator
// writes --sysroot into build.make, which make does not compare) and
// keeps the check results the old configure cached. A mingw external
// built against the host's /usr as the sysroot (issue #43) kept its
// objects reading __libc_single_threaded after the fix that way. The
// directory keeps its name, which projects point generated headers at.
if (fs::exists(cmakeBuildDir / "CMakeCache.txt")) {
std::error_code ec;
fs::remove_all(cmakeBuildDir, ec);
if (ec) return std::format("cannot clear {} for a fresh configure: {}", cmakeBuildDir.string(), ec.message());
}
if (!fs::exists(cmakeBuildDir)) fs::create_directories(cmakeBuildDir); if (!fs::exists(cmakeBuildDir)) fs::create_directories(cmakeBuildDir);
std::string cmd = std::format("cmake -S {} -B {}{}", ShellQuote(fs::absolute(cloneDir).string()), ShellQuote(fs::absolute(cmakeBuildDir).string()), injected); std::string cmd = std::format("cmake -S {} -B {}{}", ShellQuote(fs::absolute(cloneDir).string()), ShellQuote(fs::absolute(cmakeBuildDir).string()), injected);
@ -280,21 +293,21 @@ ExternalBuildResult Crafter::ExternalOutputs(const ExternalDependency& dep, std:
const fs::path cmakeBuildDir = ExternalBuildDir(dep, target); const fs::path cmakeBuildDir = ExternalBuildDir(dep, target);
if (dep.builder != ExternalBuilder::CMake || cmakeBuildDir.empty()) return result; if (dep.builder != ExternalBuilder::CMake || cmakeBuildDir.empty()) return result;
// Each search path gets both a -L (link-time) and a -Wl,-rpath // Each search path is both a -L (link time) and a run path (the
// (runtime-loader). The rpath stays embedded in the produced // loader's), so the program picks its shared dependencies up from the
// binary so it picks up shared deps from the cache without any // cache without any LD_LIBRARY_PATH gymnastics; static ones (.a) need
// LD_LIBRARY_PATH gymnastics. Static deps (.a) ignore the rpath // the run path not at all and are not hurt by it. The PE/COFF target
// harmlessly. The PE/COFF target (mingw) resolves DLLs via PATH or // (mingw) resolves DLLs through PATH or the program's own directory
// adjacency rather than rpath, so lld warns if we pass it. // rather than a run path, and lld warns if it is given one.
const bool isPe = target == "x86_64-w64-mingw32"; const bool isPe = target == "x86_64-w64-mingw32";
std::string buildDirAbs = fs::absolute(cmakeBuildDir).string(); std::string buildDirAbs = fs::absolute(cmakeBuildDir).string();
result.linkFlags.push_back(std::format("-L{}", buildDirAbs)); result.linkFlags.push_back(std::format("-L{}", buildDirAbs));
if (!isPe) result.linkFlags.push_back(std::format("-Wl,-rpath,{}", buildDirAbs)); if (!isPe) result.runPaths.push_back(buildDirAbs);
for (const fs::path& libDir : dep.libDirs) { for (const fs::path& libDir : dep.libDirs) {
fs::path full = libDir.is_absolute() ? libDir : cmakeBuildDir / libDir; fs::path full = libDir.is_absolute() ? libDir : cmakeBuildDir / libDir;
std::string fullAbs = fs::absolute(full).string(); std::string fullAbs = fs::absolute(full).string();
result.linkFlags.push_back(std::format("-L{}", fullAbs)); result.linkFlags.push_back(std::format("-L{}", fullAbs));
if (!isPe) result.linkFlags.push_back(std::format("-Wl,-rpath,{}", fullAbs)); if (!isPe) result.runPaths.push_back(fullAbs);
} }
for (const std::string& lib : dep.libs) { for (const std::string& lib : dep.libs) {
result.linkFlags.push_back(std::format("-l{}", lib)); result.linkFlags.push_back(std::format("-l{}", lib));
@ -323,29 +336,33 @@ ExternalBuildResult Crafter::ExternalOutputs(const ExternalDependency& dep, std:
namespace { namespace {
std::mutex ProjectCacheMutex; std::mutex ProjectCacheMutex;
std::unordered_map<std::string, std::unique_ptr<Configuration>> ProjectCache; // What each project file loaded here returned, in the file's order, by
// Keyed by the Configurations ProjectCache owns, which live as long as // spec and args. An entry is never changed or removed once it is in.
// the process does, so the pointers never dangle. Guarded by std::unordered_map<std::string, std::vector<Configuration*>> ProjectCache;
// ProjectCacheMutex as well. // 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; 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 // What the cache holds under `fullHash`, or nullptr.
// (cfg.path = "./", interfaces/, lib/, ...) resolve against the dep const std::vector<Configuration*>* CachedProject(const std::string& fullHash) {
// root, then rebase cfg.path and all other relative path collections to const std::lock_guard lock(ProjectCacheMutex);
// absolute so Build() can run from any cwd without misresolving them. const auto it = ProjectCache.find(fullHash);
// The mutex is NOT held across LoadProject — the dep may itself call return it == ProjectCache.end() ? nullptr : &it->second;
// GitProject/LocalProject, and a non-recursive lock would deadlock.
Configuration LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span<const std::string_view> args) {
fs::path savedCwd = fs::current_path();
Configuration cfg;
fs::current_path(depRoot);
try {
cfg = LoadProject(projectPath, args);
} catch (...) {
fs::current_path(savedCwd);
throw;
} }
fs::current_path(savedCwd);
// 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(); cfg.path = fs::absolute(depRoot / cfg.path).lexically_normal();
auto abs = [&](const fs::path& p) -> fs::path { auto abs = [&](const fs::path& p) -> fs::path {
return p.is_absolute() ? p : fs::absolute(depRoot / p).lexically_normal(); return p.is_absolute() ? p : fs::absolute(depRoot / p).lexically_normal();
@ -355,22 +372,91 @@ namespace {
for (fs::path& p : cfg.files) p = abs(p); for (fs::path& p : cfg.files) p = abs(p);
for (fs::path& p : cfg.buildFiles) p = abs(p); for (fs::path& p : cfg.buildFiles) p = abs(p);
for (Shader& s : cfg.shaders) s.path = abs(s.path); for (Shader& s : cfg.shaders) s.path = abs(s.path);
return cfg; // A dependency that packages its own executable as a Flatpak names
// the files it is installed with as it names its cfg.files. An
// empty one is none, and stays empty.
if (!cfg.flatpak.desktopFile.empty()) cfg.flatpak.desktopFile = abs(cfg.flatpak.desktopFile);
if (!cfg.flatpak.metainfo.empty()) cfg.flatpak.metainfo = abs(cfg.flatpak.metainfo);
for (fs::path& p : cfg.flatpak.icons) p = abs(p);
for (fs::path& p : cfg.flatpak.modules) p = abs(p);
for (auto& entry : cfg.flatpak.share) {
if (!entry.source.empty()) entry.source = abs(entry.source);
}
} }
// Into ProjectCache under `fullHash`, with `loaded` recorded beside it. // Run the dep's project.cpp from its own directory so its relative paths
// When another thread stored the same spec first, its Configuration // (cfg.path = "./", interfaces/, lib/, ...) resolve against the dep
// wins and `cfg` is dropped. // root, then rebase every configuration it returns onto that root.
Configuration* StoreProject(std::string fullHash, Configuration cfg, LoadedProject loaded) { // The mutex is NOT held across the load — the dep may itself call
std::lock_guard lock(ProjectCacheMutex); // GitProject/LocalProject, and a non-recursive lock would deadlock.
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) { std::vector<Configuration*> LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span<const std::string_view> args) {
return it->second.get(); 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;
} }
auto stored = std::make_unique<Configuration>(std::move(cfg)); fs::current_path(savedCwd);
Configuration* ptr = stored.get(); for (Configuration* cfg : configurations) {
ProjectCache.emplace(std::move(fullHash), std::move(stored)); // One the file loaded from another project file and returns
LoadedProjects.emplace(ptr, std::move(loaded)); // itself was rebased onto that project's root when it was
return ptr; // 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 // `url` as it names a repository: without user info, which is where a
@ -392,10 +478,11 @@ namespace {
Configuration* Crafter::GitProject(const GitProjectSpec& spec) { Configuration* Crafter::GitProject(const GitProjectSpec& spec) {
// Two hashes: the clone is shared across specs that point at the same // Two hashes: the clone is shared across specs that point at the same
// source revision (forwarded args don't change what gets cloned, just // source revision (forwarded args don't change what gets cloned, just
// how the dep's project.cpp interprets them at runtime), while the // how the dep's project.cpp interprets them at runtime), while what the
// in-memory Configuration is keyed by the full spec so each (args) // file returned is keyed by the args as well, so each (args)
// permutation gets its own Configuration object, and host tooling one // permutation gets its own Configuration objects, and host tooling ones
// apart from the target's even for the same args. // 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 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)); std::string srcHash = std::format("{:016x}", std::hash<std::string>{}(srcKey));
@ -405,12 +492,10 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) {
fullKey += a; fullKey += a;
} }
std::string fullHash = std::format("{:016x}", std::hash<std::string>{}(fullKey)); std::string fullHash = std::format("{:016x}", std::hash<std::string>{}(fullKey));
const std::string what = std::format("GitProject({})", spec.source.url);
{ if (const std::vector<Configuration*>* cached = CachedProject(fullHash)) {
std::lock_guard lock(ProjectCacheMutex); return PickConfiguration(*cached, spec.configuration, what);
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) {
return it->second.get();
}
} }
std::string name = DeriveName(spec.source); std::string name = DeriveName(spec.source);
@ -438,15 +523,15 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) {
} }
std::vector<std::string_view> argViews(spec.args.begin(), spec.args.end()); std::vector<std::string_view> argViews(spec.args.begin(), spec.args.end());
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 projectInRepo = spec.projectFile.lexically_normal();
const fs::path below = projectInRepo.parent_path(); 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(), .projectFile = projectPath.lexically_normal(),
.name = below.empty() ? name : std::format("{}/{}", name, below.generic_string()), .name = below.empty() ? name : std::format("{}/{}", name, below.generic_string()),
.identity = std::format("git|{}|{}", RepositoryKey(spec.source.url), projectInRepo.generic_string()), .identity = std::format("git|{}|{}", RepositoryKey(spec.source.url), projectInRepo.generic_string()),
}); }), spec.configuration, what);
} }
fs::path Crafter::GitFetch(const GitSource& source) { fs::path Crafter::GitFetch(const GitSource& source) {
@ -489,23 +574,21 @@ Configuration* Crafter::LocalProject(const LocalProjectSpec& spec) {
fullKey += a; fullKey += a;
} }
std::string fullHash = std::format("{:016x}", std::hash<std::string>{}(fullKey)); std::string fullHash = std::format("{:016x}", std::hash<std::string>{}(fullKey));
const std::string what = std::format("LocalProject({})", canonical.string());
{ if (const std::vector<Configuration*>* cached = CachedProject(fullHash)) {
std::lock_guard lock(ProjectCacheMutex); return PickConfiguration(*cached, spec.configuration, what);
if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) {
return it->second.get();
}
} }
fs::path depRoot = canonical.parent_path(); fs::path depRoot = canonical.parent_path();
std::vector<std::string_view> argViews(spec.args.begin(), spec.args.end()); std::vector<std::string_view> argViews(spec.args.begin(), spec.args.end());
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, .projectFile = canonical,
.name = depRoot.filename().string(), .name = depRoot.filename().string(),
.identity = std::format("local|{}", canonical.string()), .identity = std::format("local|{}", canonical.string()),
}); }), spec.configuration, what);
} }
std::optional<LoadedProject> Crafter::LoadedProjectOf(const Configuration& cfg) { std::optional<LoadedProject> Crafter::LoadedProjectOf(const Configuration& cfg) {
@ -513,3 +596,9 @@ std::optional<LoadedProject> Crafter::LoadedProjectOf(const Configuration& cfg)
if (auto it = LoadedProjects.find(&cfg); it != LoadedProjects.end()) return it->second; if (auto it = LoadedProjects.find(&cfg); it != LoadedProjects.end()) return it->second;
return std::nullopt; 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;
}

View file

@ -0,0 +1,583 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module Crafter.Build:Flatpak_impl;
import :Flatpak;
import :Platform;
import :Progress;
import std;
namespace fs = std::filesystem;
using namespace Crafter;
namespace {
// flatpak's own rule for the characters of a name's segments: a dash is
// allowed in the last segment only, a digit anywhere but first.
bool NameStart(char c, bool lastSegment) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (lastSegment && c == '-');
}
bool NameChar(char c, bool lastSegment) {
return NameStart(c, lastSegment) || (c >= '0' && c <= '9');
}
std::string_view Trim(std::string_view s) {
while (!s.empty() && (s.front() == ' ' || s.front() == '\t' || s.front() == '\n' || s.front() == '\r')) s.remove_prefix(1);
while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\n' || s.back() == '\r')) s.remove_suffix(1);
return s;
}
std::vector<std::string_view> Split(std::string_view s, char separator) {
std::vector<std::string_view> parts;
for (std::size_t begin = 0;;) {
const std::size_t end = s.find(separator, begin);
parts.push_back(s.substr(begin, end == std::string_view::npos ? std::string_view::npos : end - begin));
if (end == std::string_view::npos) return parts;
begin = end + 1;
}
}
// ---- the files ----
std::string ReadAll(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error(std::format("could not read {}", path.string()));
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
// Whether `b` is a regular file holding exactly what `a` does: by size,
// then a block at a time, so comparing costs the same memory whatever
// the files' size. Reading both whole held twice the largest file on
// every build that had nothing to copy, and failed where that did not
// fit.
bool SameContent(const fs::path& a, const fs::path& b) {
std::error_code ec;
if (!fs::is_regular_file(b, ec) || fs::is_symlink(b, ec)) return false;
if (fs::file_size(a) != fs::file_size(b, ec) || ec) return false;
std::ifstream left(a, std::ios::binary);
if (!left) throw std::runtime_error(std::format("could not read {}", a.string()));
std::ifstream right(b, std::ios::binary);
if (!right) return false;
constexpr std::size_t Block = 64 * 1024;
std::vector<char> x(Block);
std::vector<char> y(Block);
while (left && right) {
left.read(x.data(), static_cast<std::streamsize>(Block));
right.read(y.data(), static_cast<std::streamsize>(Block));
if (left.gcount() != right.gcount() || !std::equal(x.begin(), x.begin() + left.gcount(), y.begin())) return false;
}
return left.eof() && right.eof();
}
// Writes `content` to `path` unless the file already holds exactly that,
// so an unchanged build leaves its mtime alone.
void WriteIfDifferent(const fs::path& path, std::string_view content) {
std::error_code ec;
if (fs::is_regular_file(path, ec) && !fs::is_symlink(path, ec) && fs::file_size(path, ec) == content.size() && ReadAll(path) == content) return;
fs::create_directories(path.parent_path());
fs::remove(path, ec);
std::ofstream out(path, std::ios::binary | std::ios::trunc);
out.write(content.data(), static_cast<std::streamsize>(content.size()));
if (!out) throw std::runtime_error(std::format("could not write {}", path.string()));
}
// Makes `dir` hold exactly `wanted`, relative path to the file copied
// there, and nothing else: every other file goes, and the directories
// left empty. A copy is made only when its content differs, and anything
// in the way is replaced rather than written through, a link included.
// Returns the relative paths it copied.
std::set<fs::path> SyncOwned(const fs::path& dir, const std::map<fs::path, fs::path>& wanted) {
std::set<fs::path> copied;
std::error_code ec;
if (fs::exists(dir, ec)) {
std::vector<fs::path> files;
std::vector<fs::path> dirs;
for (const fs::directory_entry& entry : fs::recursive_directory_iterator(dir)) {
if (entry.is_directory() && !entry.is_symlink()) dirs.push_back(entry.path());
else if (!wanted.contains(entry.path().lexically_relative(dir))) files.push_back(entry.path());
}
for (const fs::path& file : files) fs::remove(file);
// Deepest first, so a parent is empty by the time it is looked at.
std::ranges::sort(dirs, std::greater{});
for (const fs::path& d : dirs) {
if (fs::is_empty(d)) fs::remove(d);
}
}
for (const auto& [relative, source] : wanted) {
const fs::path target = dir / relative;
if (!fs::exists(source)) throw std::runtime_error(std::format("{} does not exist", source.string()));
if (SameContent(source, target)) continue;
fs::create_directories(target.parent_path());
if (fs::is_directory(target, ec) && !fs::is_symlink(target, ec)) fs::remove_all(target);
else fs::remove(target, ec);
fs::copy_file(source, target);
copied.insert(relative);
}
return copied;
}
// Whether `path` is `ancestor` or lies inside it, element by element.
bool Within(const fs::path& path, const fs::path& ancestor) {
return std::mismatch(ancestor.begin(), ancestor.end(), path.begin(), path.end()).first == ancestor.end();
}
// Whether `outer` is `inner` or holds it, as written or where their
// links lead: a project whose bin/ is a link elsewhere holds its files/
// as written, and not once the link is followed.
bool Holds(const fs::path& outer, const fs::path& inner) {
std::error_code ec;
if (Within(fs::absolute(inner, ec).lexically_normal(), fs::absolute(outer, ec).lexically_normal())) return true;
const fs::path realOuter = fs::weakly_canonical(outer, ec);
if (ec || realOuter.empty()) return false;
const fs::path realInner = fs::weakly_canonical(inner, ec);
if (ec || realInner.empty()) return false;
return Within(realInner, realOuter);
}
// Adds `relative` to the files a directory is to hold, copied from
// `source`, unless that would put two files at one path, or a file where
// another needs a directory: one share entry over another, or two icons
// of one size. SyncOwned would otherwise copy whichever came last, or
// fail halfway with a filesystem error.
std::string Place(std::map<fs::path, fs::path>& files, const fs::path& relative, const fs::path& source) {
if (auto it = files.find(relative); it != files.end()) {
return std::format("{} and {} both go to share/{}", it->second.string(), source.string(), relative.string());
}
// What lies inside a path sorts right after it, element by element.
if (auto it = files.upper_bound(relative); it != files.end() && Within(it->first, relative)) {
return std::format("{} would make share/{} a file, where {} needs it to be a directory", source.string(), relative.string(), it->second.string());
}
for (fs::path parent = relative.parent_path(); !parent.empty(); parent = parent.parent_path()) {
if (auto it = files.find(parent); it != files.end()) {
return std::format("{} needs share/{} to be a directory, where {} makes it a file", source.string(), parent.string(), it->second.string());
}
}
files.emplace(relative, source);
return "";
}
// Where an icon goes under share/: an .svg as scalable, a .png in the
// directory of its own size, read from its header.
fs::path IconPath(const fs::path& icon, std::string_view appId) {
std::string ext = icon.extension().string();
for (char& c : ext) c = static_cast<char>(std::tolower(static_cast<std::uint8_t>(c)));
if (ext == ".svg") return fs::path("icons") / "hicolor" / "scalable" / "apps" / std::format("{}.svg", appId);
if (ext != ".png") throw std::runtime_error(std::format("{}: an icon has to be an .svg or a .png", icon.string()));
const std::string header = ReadAll(icon).substr(0, 24);
if (header.size() < 24 || !header.starts_with("\x89PNG\r\n\x1a\n") || header.substr(12, 4) != "IHDR") {
throw std::runtime_error(std::format("{}: not a PNG file", icon.string()));
}
const auto bigEndian = [&](std::size_t at) {
std::uint32_t value = 0;
for (std::size_t i = 0; i < 4; ++i) value = (value << 8) | static_cast<std::uint8_t>(header[at + i]);
return value;
};
const std::uint32_t width = bigEndian(16);
const std::uint32_t height = bigEndian(20);
if (width != height) throw std::runtime_error(std::format("{}: an icon has to be square, this one is {}x{}", icon.string(), width, height));
return fs::path("icons") / "hicolor" / std::format("{}x{}", width, width) / "apps" / std::format("{}.png", appId);
}
// The Icon= of a desktop entry's [Desktop Entry] group; empty without one.
std::string DesktopIcon(const fs::path& desktopFile) {
bool inEntry = false;
for (const std::string_view line : Split(ReadAll(desktopFile), '\n')) {
const std::string_view t = Trim(line);
if (t.starts_with("[")) {
inEntry = t == "[Desktop Entry]";
continue;
}
if (!inEntry) continue;
// The key and the value either side of the first '=', without
// the space the Desktop Entry spec lets surround it: `Icon =
// other` is Icon=other to desktop-file-validate and to flatpak.
const std::size_t eq = t.find('=');
if (eq != std::string_view::npos && Trim(t.substr(0, eq)) == "Icon") return std::string(Trim(t.substr(eq + 1)));
}
return "";
}
// ---- the libraries ----
// The libraries clang links into every C++ program it builds against its
// libc++. They are looked up one by one, never by searching the
// directory they are in: on a distribution that keeps libc++ in
// /usr/lib64, that directory holds libc.so.6 as well.
constexpr std::array<std::string_view, 3> LlvmRuntimeLibraries = {"libc++.so.1", "libc++abi.so.1", "libunwind.so.1"};
// The toolchain's own copy of `name`, as the link finds it; empty when
// clang has none (Arch's LLVM ships no libunwind.so.1). Asked once per
// name and process.
fs::path ToolchainLibrary(const fs::path& clangxx, std::string_view name) {
static std::mutex Mutex;
static std::map<std::string, fs::path, std::less<>> Found;
std::lock_guard lock(Mutex);
if (auto it = Found.find(name); it != Found.end()) return it->second;
const CommandResult r = RunCommandChecked(std::format("{} -print-file-name={}", ShellQuote(clangxx.string()), name));
// clang prints the bare name back when it has no such file.
fs::path path = Trim(r.output);
std::error_code ec;
if (r.exitCode != 0 || !path.is_absolute() || !fs::exists(path, ec)) path.clear();
else path = path.lexically_normal();
Found.emplace(std::string(name), path);
return path;
}
std::vector<std::string> NeededLibraries(const fs::path& readelf, const fs::path& file) {
const CommandResult r = RunCommandChecked(std::format("{} --needed-libs {}", ShellQuote(readelf.string()), ShellQuote(file.string())));
if (r.exitCode != 0) {
throw std::runtime_error(std::format("{} could not read {}: {}", readelf.filename().string(), file.string(), Trim(r.output)));
}
std::vector<std::string> names;
bool inList = false;
for (const std::string_view line : Split(r.output, '\n')) {
const std::string_view t = Trim(line);
if (!inList) {
inList = t.starts_with("NeededLibraries [");
continue;
}
if (t == "]") break;
if (!t.empty()) names.emplace_back(t);
}
return names;
}
// The files `program` needs that are not the runtime's, with what they
// need in turn: the LLVM runtime libraries, and any NEEDED name found in
// one of `dirs`, the first one holding it winning as for the loader.
std::vector<fs::path> Libraries(const FlatpakFiles& d, const fs::path& program) {
std::vector<fs::path> libraries;
std::set<std::string> seen;
std::deque<fs::path> pending = {program};
while (!pending.empty()) {
const fs::path file = std::move(pending.front());
pending.pop_front();
for (const std::string& name : NeededLibraries(d.readelf, file)) {
if (!seen.insert(name).second) continue;
fs::path found;
if (std::ranges::contains(LlvmRuntimeLibraries, std::string_view(name))) found = ToolchainLibrary(d.clangxx, name);
std::error_code ec;
for (const fs::path& dir : d.libraryDirs) {
if (!found.empty()) break;
if (fs::exists(dir / name, ec)) found = dir / name;
}
if (found.empty()) continue;
libraries.push_back(found);
pending.push_back(found);
}
}
return libraries;
}
// ---- the record ----
// What a write placed, kept so the next one knows which files in
// files/bin were the build's.
struct Record {
std::set<std::string> placed;
};
Record ReadRecord(const fs::path& file) {
Record record;
std::error_code ec;
if (!fs::exists(file, ec)) return record;
for (const std::string_view line : Split(ReadAll(file), '\n')) {
const std::size_t tab = line.find('\t');
if (tab == std::string_view::npos) continue;
const std::string_view kind = line.substr(0, tab);
const std::string value(line.substr(tab + 1));
if (kind == "placed") record.placed.insert(value);
}
return record;
}
void WriteRecord(const fs::path& file, const Record& record) {
std::string text;
for (const std::string& name : record.placed) text += std::format("placed\t{}\n", name);
WriteIfDifferent(file, text);
}
}
std::string Crafter::DefaultFlatpakAppId(std::string_view outputName) {
std::string segment;
for (const char c : outputName) segment.push_back(NameChar(c, true) ? c : '_');
if (segment.empty() || !NameStart(segment.front(), true)) segment.insert(segment.begin(), '_');
return std::format("local.crafterbuild.{}", segment);
}
std::string Crafter::FlatpakAppIdError(std::string_view appId) {
if (appId.empty()) return "it is empty";
if (appId.size() > 255) return "it is longer than 255 characters";
const std::vector<std::string_view> segments = Split(appId, '.');
if (segments.size() < 3) return "it needs at least three segments, like org.example.App";
for (std::size_t i = 0; i < segments.size(); ++i) {
const std::string_view segment = segments[i];
const bool last = i + 1 == segments.size();
if (segment.empty()) return "it has an empty segment";
for (std::size_t j = 0; j < segment.size(); ++j) {
const char c = segment[j];
if (j == 0 ? NameStart(c, last) : NameChar(c, last)) continue;
if (c == '-') return std::format("its segment '{}' has a '-', which only the last segment may have", segment);
if (j == 0 && c >= '0' && c <= '9') return std::format("its segment '{}' starts with a digit", segment);
return std::format("it holds '{}', which an application ID cannot", c);
}
}
return "";
}
void Crafter::RecordFlatpakPlaced(const fs::path& record, const std::set<std::string>& names) {
try {
Record merged = ReadRecord(record);
const std::size_t before = merged.placed.size();
merged.placed.insert(names.begin(), names.end());
if (merged.placed.size() == before) return;
std::error_code ec;
fs::create_directories(record.parent_path(), ec);
WriteRecord(record, merged);
} catch (const std::exception&) {
// Not written: the next write takes those names for the program's,
// and says so, which is all a record that cannot be written costs.
}
}
std::string Crafter::WriteFlatpakFiles(const FlatpakFiles& d) {
if (const std::string bad = FlatpakAppIdError(d.appId); !bad.empty()) {
return std::format("{} is not a Flatpak application ID: {}", d.appId, bad);
}
try {
const fs::path files = d.root / "files";
const fs::path program = files / "bin" / d.command;
const Record old = ReadRecord(d.record);
Record now;
// Worked out on every write, from the program and what each library
// it carries needs in turn, which reads only their dynamic sections:
// a library replaced in place, as by a toolchain update, can need
// others, and only reading it again finds them. -r would not show a
// library missing, as crafter-build's sandbox has its own /app/lib on
// the loader's path; the installed app would not start.
std::map<fs::path, fs::path> libraries;
for (const fs::path& library : Libraries(d, program)) libraries.emplace(library.filename(), library);
SyncOwned(files / "lib", libraries);
std::map<fs::path, fs::path> share;
const fs::path desktopEntry = fs::path("applications") / std::format("{}.desktop", d.appId);
if (!d.desktopFile.empty()) {
if (!fs::exists(d.desktopFile)) return std::format("{}: the desktop file {} does not exist", d.appId, d.desktopFile.string());
if (const std::string clash = Place(share, desktopEntry, d.desktopFile); !clash.empty()) return std::format("{}: {}", d.appId, clash);
}
if (!d.metainfo.empty()) {
const fs::path metainfo = fs::path("metainfo") / std::format("{}.metainfo.xml", d.appId);
if (const std::string clash = Place(share, metainfo, d.metainfo); !clash.empty()) return std::format("{}: {}", d.appId, clash);
}
for (const fs::path& icon : d.icons) {
const fs::path relative = IconPath(icon, d.appId);
if (const std::string clash = Place(share, relative, icon); !clash.empty()) return std::format("{}: {}", d.appId, clash);
}
// A share entry's file goes where it says, unless the place is
// another file's (Place), a field's included. Whatever it is, a second
// desktop entry or the metainfo of an add-on, say, flatpak checks
// some of what it exports when install or bundle export the app, as
// for any app: an icon that is not a square image, or a D-Bus
// service that is not a key file, stops the export, the app's own
// desktop entry gets a warning where desktop-file-validate rejects it
// or its Icon= is not the app's, and a second desktop entry, a MIME
// package or metainfo goes as it is. The app's own desktop entry and
// the icons the field places are checked here too, at build time.
for (const FlatpakShareEntry& entry : d.share) {
fs::path target = entry.target.lexically_normal();
if (!target.empty() && !target.has_filename()) target = target.parent_path();
if (entry.target.is_absolute() || target.empty() || target == "." || *target.begin() == "..") {
return std::format("{}: the share target '{}' of {} has to be a path inside /app/share, relative to it", d.appId, entry.target.string(), entry.source.string());
}
std::error_code ec;
if (fs::is_directory(entry.source, ec)) {
// A directory that holds what the build writes would be
// copied into itself, growing each time the app is built or
// exported: files/, where share/'s copies land, and the
// app's directory, where install and bundle put another copy
// of files/ and the exported app; the project's own directory
// holds both. One that lies in them is the build's own
// output, which the next build, install or bundle writes
// again, and no file of the project's.
for (const fs::path& output : {files, d.appDir}) {
if (output.empty()) continue;
if (Holds(entry.source, output)) {
return std::format("{}: {} holds {}, which the build writes, so a share entry would copy it into itself, growing each time the app is built or exported: name the files or directories in it instead", d.appId, entry.source.string(), output.string());
}
if (Holds(output, entry.source)) {
return std::format("{}: {} lies in {}, which the build writes and writes again: a share entry names a file of the project's", d.appId, entry.source.string(), output.string());
}
}
// Written with a trailing separator, "data/", the directory is
// taken without it, for each file's path inside it.
const fs::path dir = entry.source.has_filename() ? entry.source : entry.source.parent_path();
for (const fs::directory_entry& file : fs::recursive_directory_iterator(dir)) {
if (!file.is_regular_file()) continue;
if (const std::string clash = Place(share, target / file.path().lexically_relative(dir), file.path()); !clash.empty()) return std::format("{}: {}", d.appId, clash);
}
} else if (fs::is_regular_file(entry.source, ec)) {
if (const std::string clash = Place(share, target, entry.source); !clash.empty()) return std::format("{}: {}", d.appId, clash);
} else {
return std::format("{}: {} does not exist, so it cannot go to share/{}", d.appId, entry.source.string(), target.string());
}
}
// The app's desktop entry, applications/<app-id>.desktop, whether
// cfg.flatpak.desktopFile or a share entry placed it: its Icon= has
// to be the app-id, which the app's icons are installed under.
const auto entry = share.find(desktopEntry);
if (entry != share.end()) {
if (const std::string icon = DesktopIcon(entry->second); !icon.empty() && icon != d.appId) {
return std::format("{}: its Icon= is {}, and has to be the app-id, {}, which its icons are installed as", entry->second.string(), icon, d.appId);
}
}
SyncOwned(files / "share", share);
// desktop-file-validate checks the entry here, where it was written,
// on every write that places one, not only one that copies it: a
// write that copied the entry and then failed would leave it
// unchecked for every write after. Where the tool exists: the Sdk has
// it, a development box may not.
if (entry != share.end() && RunCommandChecked("command -v desktop-file-validate").exitCode == 0) {
const CommandResult r = RunCommandChecked(std::format("desktop-file-validate {}", ShellQuote((files / "share" / desktopEntry).string())));
if (r.exitCode != 0) {
std::error_code ec;
fs::remove(files / "share" / desktopEntry, ec);
return std::format("{} does not pass desktop-file-validate:\n{}", entry->second.string(), Trim(r.output));
}
}
// In files/bin, what an earlier write placed and this one does not
// is a stale build output, a removed cfg.files entry or a renamed
// shader. What neither placed the program wrote, under -r, since it
// runs there.
std::vector<std::string> foreign;
for (const fs::directory_entry& entry : fs::directory_iterator(files / "bin")) {
const std::string name = entry.path().filename().string();
if (d.programEntries.contains(name)) continue;
if (old.placed.contains(name)) fs::remove_all(entry.path());
else foreign.push_back(name);
}
now.placed = d.programEntries;
if (!foreign.empty()) {
std::ranges::sort(foreign);
std::string names;
for (const std::string& name : foreign) names += std::format("{}{}", names.empty() ? "" : ", ", name);
Progress::Diagnostic(std::format("{}: {} in {} {} not put there by the build, so the program wrote {}, presumably under -r. {} with the app; installed, /app is read-only and a program cannot write there.", d.appId, names, (files / "bin").string(), foreign.size() == 1 ? "was" : "were", foreign.size() == 1 ? "it" : "them", foreign.size() == 1 ? "It ships" : "They ship"));
}
WriteRecord(d.record, now);
} catch (const std::exception& e) {
return std::format("{}: {}", d.appId, e.what());
}
return "";
}
std::string Crafter::FlatpakManifestText(const FlatpakExport& app) {
std::string finishArgs;
for (const FlatpakPermission& permission : app.permissions) {
finishArgs += std::format("{}\n {}", finishArgs.empty() ? "" : ",", JsonQuote(permission.argument));
}
std::string modules;
for (const fs::path& module : app.modules) modules += std::format(" {},\n", JsonQuote(module.string()));
// The program's module is named apart from anything a project would
// call one of its own: module names are flatpak-builder's cache keys.
// "separate-locales": false keeps /app/share/locale in the app. By
// default flatpak-builder moves it into an <app-id>.Locale extension,
// which an install fetches with the app but a bundle, which holds the
// app alone, leaves out.
return std::format(
"{{\n"
" \"app-id\": {},\n"
" \"runtime\": {},\n"
" \"runtime-version\": {},\n"
" \"sdk\": \"org.freedesktop.Sdk\",\n"
" \"command\": {},\n"
" \"separate-locales\": false,\n"
" \"finish-args\": [{}{}],\n"
" \"modules\": [\n"
"{}"
" {{\n"
" \"name\": \"crafter-build-program\",\n"
" \"buildsystem\": \"simple\",\n"
" \"build-commands\": [ \"cp -a . /app/\" ],\n"
" \"sources\": [ {{ \"type\": \"dir\", \"path\": {} }} ]\n"
" }}\n"
" ]\n"
"}}\n",
JsonQuote(app.appId),
app.runtime == FlatpakRuntime::Sdk ? "\"org.freedesktop.Sdk\"" : "\"org.freedesktop.Platform\"",
JsonQuote(app.branch),
JsonQuote(app.command),
finishArgs, finishArgs.empty() ? "" : "\n ",
modules,
JsonQuote(app.files.string()));
}
namespace {
// `from` again at `to`: hard links where they can be made, copies where
// they cannot, links as links. flatpak build-finish and build-export
// read files/ and write nothing into it, so a link costs no copy of the
// app's data and leaves the build's files as they are. A link fails
// across filesystems, and on one that has none, vfat or exFAT on a USB
// stick say, with another error; whatever the reason, the copy is made
// instead, and a failure it shares, a full disk say, shows there.
void LinkOrCopyTree(const fs::path& from, const fs::path& to) {
try {
fs::copy(from, to, fs::copy_options::recursive | fs::copy_options::create_hard_links | fs::copy_options::copy_symlinks);
} catch (const fs::filesystem_error&) {
fs::remove_all(to);
fs::copy(from, to, fs::copy_options::recursive | fs::copy_options::copy_symlinks);
}
}
}
std::string Crafter::ExportFlatpak(const FlatpakExport& app) {
// On every install and bundle: the build does not read them, and
// build-finish names only the argument it refuses, not the
// configuration it came from.
if (!app.permissions.empty()) {
std::string report = std::format("{} has these Flatpak permissions:", app.appId);
for (const FlatpakPermission& permission : app.permissions) report += std::format("\n {} (from {})", permission.argument, permission.source);
Progress::Diagnostic(report);
}
try {
fs::create_directories(app.work);
const fs::path repo = app.work / "repo";
const fs::path buildDir = app.work / "build-dir";
if (app.modules.empty()) {
// Made afresh each time: build-finish refuses a directory it
// finished before, and what a finish wrote, such as the export/
// of a desktop entry the app no longer has, must not reach the
// next one.
fs::remove_all(buildDir);
fs::create_directories(buildDir);
const std::string_view runtime = app.runtime == FlatpakRuntime::Sdk ? "org.freedesktop.Sdk" : "org.freedesktop.Platform";
WriteIfDifferent(buildDir / "metadata", std::format("[Application]\nname={}\nruntime={}/{}/{}\nsdk=org.freedesktop.Sdk/{}/{}\n", app.appId, runtime, app.arch, app.branch, app.arch, app.branch));
LinkOrCopyTree(app.files, buildDir / "files");
// The permissions before --command, so the program stays the
// app's command whatever they hold.
std::string finish = "build-finish";
for (const FlatpakPermission& permission : app.permissions) finish += std::format(" {}", ShellQuote(permission.argument));
finish += std::format(" --command={} {}", ShellQuote(app.command), ShellQuote(buildDir.string()));
if (RunHostFlatpak(finish) != 0) {
return std::format("{}: flatpak build-finish failed{}", app.appId, app.permissions.empty() ? "" : "; the permissions it was given are listed above, with where each came from");
}
if (RunHostFlatpak(std::format("build-export {} {}", ShellQuote(repo.string()), ShellQuote(buildDir.string()))) != 0) {
return std::format("{}: flatpak build-export failed", app.appId);
}
return "";
}
// Written only when it changes, so flatpak-builder sees the same
// manifest, and reuses what it built from it, until it does.
const fs::path manifest = app.work / std::format("{}.json", app.appId);
WriteIfDifferent(manifest, FlatpakManifestText(app));
// --force-clean: the build directory is flatpak-builder's scratch,
// made again from its cache each time; the repo keeps what it
// exported.
const std::string arguments = std::format("--force-clean --state-dir={} --repo={} {} {}", ShellQuote((app.work / "state").string()), ShellQuote(repo.string()), ShellQuote(buildDir.string()), ShellQuote(manifest.string()));
if (RunHostFlatpakBuilder(arguments) != 0) return std::format("{}: flatpak-builder failed on {}", app.appId, manifest.string());
} catch (const std::exception& e) {
return std::format("{}: {}", app.appId, e.what());
}
return "";
}

View file

@ -5,6 +5,7 @@ module Crafter.Build:Implementation_impl;
import std; import std;
import :Implementation; import :Implementation;
import :Interface; import :Interface;
import :Jobs;
import :Platform; import :Platform;
namespace fs = std::filesystem; namespace fs = std::filesystem;
@ -12,12 +13,12 @@ namespace Crafter {
Implementation::Implementation(fs::path&& path) : path(std::move(path)) { Implementation::Implementation(fs::path&& path) : path(std::move(path)) {
} }
bool Implementation::Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor) const { bool Implementation::Check(const fs::path& object, const fs::path& pcmDir, fs::file_time_type sourceFloor) const {
std::string objPath = std::format("{}_impl.o", (buildDir/path.filename()).string()); std::string objPath = object.string();
std::string cppPath = std::format("{}.cpp", path.string()); std::string cppPath = std::format("{}.cpp", path.string());
// The depfile clang wrote beside the object lists the headers this TU // The depfile clang wrote beside the object lists the headers this TU
// included; nothing else in the configuration knows about them, since // included when the object was compiled: inputs of the object as
// the source scanner only reads `import` lines. // much as the source and the BMIs it imports.
if(!fs::exists(objPath) || std::max({fs::last_write_time(cppPath), sourceFloor, NewestPrerequisite(std::format("{}.d", objPath))}) >= fs::last_write_time(objPath)) { if(!fs::exists(objPath) || std::max({fs::last_write_time(cppPath), sourceFloor, NewestPrerequisite(std::format("{}.d", objPath))}) >= fs::last_write_time(objPath)) {
return true; return true;
} }
@ -35,28 +36,26 @@ namespace Crafter {
} }
return false; return false;
} }
void Implementation::Compile(const std::string_view clang, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) const { void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, const fs::path& object, std::string_view shown) const {
std::vector<JobGroup::Job> after;
for(ModulePartition* dependency : partitionDependencies) { for(ModulePartition* dependency : partitionDependencies) {
if(!dependency->compiled.load()) { if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
dependency->compiled.wait(false);
}
} }
for(Module* dependency : moduleDependencies) { for(Module* dependency : moduleDependencies) {
if(!dependency->compiled.load()) { if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
dependency->compiled.wait(false); }
} // -MD leaves <name>_impl.o.d beside the object for Check to read, and
} // -fmodule-file-deps puts the BMIs the unit imported in it with the
// headers. The driver adds that for --precompile only, so a std
if (buildCancelled.load(std::memory_order_relaxed)) { // module rebuilt in place, for a mingw-w64 or libc++ update under
return; // the same compiler, left the objects importing it as they were, and
} // the next build only relinked them.
//
// -MD leaves <name>_impl.o.d beside the object for Check to read. // The job makes the directory of its object, which is one for the
std::string result = RunBuildCommand(std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string())); // source's own directory (ObjectPath): the compiler makes none.
jobs.Add(std::format("Compiling {}", shown), [directory = object.parent_path(), command = std::format("{0} {1}.cpp -c -MD -MF {2}.d -fmodule-file-deps -o {2}", clang, path.string(), object.string())] {
bool expected = false; fs::create_directories(directory);
if(!result.empty() && buildCancelled.compare_exchange_strong(expected, true)) { return RunBuildCommand(command);
buildError = std::move(result); }, after);
}
} }
} }

View file

@ -4,11 +4,55 @@
module Crafter.Build:Interface_impl; module Crafter.Build:Interface_impl;
import std; import std;
import :Interface; import :Interface;
import :Jobs;
import :Platform; import :Platform;
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace {
// The job that makes an interface unit's object from its BMI, once the
// jobs in `after` have finished. The command is put together here, as in
// the functions below, so the job owns the one it runs.
void AddObjectJob(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span<const Crafter::JobGroup::Job> after) {
jobs.Add(std::format("Compiling {}.cppm", path.filename().string()), [command = std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string())] {
return Crafter::RunBuildCommand(command);
}, after);
}
// The two compiler runs of a stale interface unit, as jobs of `jobs`: its
// BMI once the jobs in `after` have finished, then its object from that
// BMI. Returns the first, the one the units importing this one come
// after: the object is the link's alone to wait for.
Crafter::JobGroup::Job AddInterfaceJobs(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span<const Crafter::JobGroup::Job> after) {
// -MD records every header the preamble pulled in, next to the BMI as
// <name>.pcm.d, so the next Check can see an edit to one of them.
const Crafter::JobGroup::Job precompile = jobs.Add(std::format("Precompiling {}.cppm", path.filename().string()), [command = std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string())] {
return Crafter::RunBuildCommand(command);
}, after);
const std::array<Crafter::JobGroup::Job, 1> precompiled = {precompile};
AddObjectJob(jobs, clang, path, pcmDir, buildDir, precompiled);
return precompile;
}
// For a unit whose BMI is up to date: the object job alone, when the
// object is missing or older than the BMI it is made from. The two are
// written by two commands, and a build can end between them: by an error
// elsewhere, which keeps the second from starting, by the second failing,
// or by being interrupted. An object written in the same tick of the
// file system's clock as its BMI is taken to be the later of the two,
// which it is whenever the command that writes it ran.
void AddObjectJobIfStale(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir) {
std::error_code ec;
const fs::file_time_type pcmTime = fs::last_write_time(std::format("{}.pcm", (pcmDir/path.filename()).string()), ec);
// No BMI to make it from; Check does not call such a unit up to date.
if (ec) return;
const fs::file_time_type objectTime = fs::last_write_time(std::format("{}.o", (buildDir/path.filename()).string()), ec);
if (!ec && objectTime >= pcmTime) return;
AddObjectJob(jobs, clang, path, pcmDir, buildDir, {});
}
}
namespace Crafter { namespace Crafter {
ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {} ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {}
bool ModulePartition::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) { bool ModulePartition::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) {
if(!checked) { if(!checked) {
@ -44,11 +88,6 @@ namespace Crafter {
} }
} }
needsRecompiling = false; needsRecompiling = false;
compiled.store(true);
// Nothing waits on `compiled` until the compile threads start,
// which is after every Check has run — but notify anyway so the
// flag is never left set without a wake-up behind it.
compiled.notify_all();
return false; return false;
} else { } else {
needsRecompiling = true; needsRecompiling = true;
@ -59,52 +98,25 @@ namespace Crafter {
} }
} }
void ModulePartition::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) { std::optional<JobGroup::Job> ModulePartition::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) {
if (scheduled) return precompileJob;
if (needsRecompiling) {
std::vector<JobGroup::Job> after;
for (ModulePartition* dependency : partitionDependencies) { for (ModulePartition* dependency : partitionDependencies) {
if(!dependency->compiled.load()) { if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
dependency->compiled.wait(false);
}
} }
for (Module* dependency : moduleDependencies) { for (Module* dependency : moduleDependencies) {
if(!dependency->compiled.load()) { if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
dependency->compiled.wait(false);
} }
precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after);
} else {
AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir);
}
scheduled = true;
return precompileJob;
} }
if (buildCancelled.load(std::memory_order_relaxed)) { Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {}
compiled.store(true);
compiled.notify_all();
return;
}
// -MD records every header the preamble pulled in, next to the BMI as
// <name>.pcm.d, so the next Check can see an edit to one of them.
std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
compiled.store(true);
compiled.notify_all();
return;
}
}
compiled.store(true);
compiled.notify_all();
result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
}
}
}
Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {}
bool Module::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) { bool Module::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) {
if(!checked) { if(!checked) {
@ -116,7 +128,7 @@ namespace Crafter {
if(fs::exists(pcmPath) && std::max({fs::last_write_time(cppmPath), sourceFloor, NewestPrerequisite(std::format("{}.d", pcmPath))}) < fs::last_write_time(pcmPath)) { if(fs::exists(pcmPath) && std::max({fs::last_write_time(cppmPath), sourceFloor, NewestPrerequisite(std::format("{}.d", pcmPath))}) < fs::last_write_time(pcmPath)) {
fs::file_time_type pcmTime = fs::last_write_time(pcmPath); fs::file_time_type pcmTime = fs::last_write_time(pcmPath);
// Every partition gets Check()ed even once one is known stale: // Every partition gets Check()ed even once one is known stale:
// Compile() drives partition rebuilds off their own // Schedule() drives partition rebuilds off their own
// needsRecompiling flags, so short-circuiting here would leave // needsRecompiling flags, so short-circuiting here would leave
// the later ones unevaluated and silently unbuilt. // the later ones unevaluated and silently unbuilt.
bool depCheck = false; bool depCheck = false;
@ -149,14 +161,12 @@ namespace Crafter {
return true; return true;
} else { } else {
needsRecompiling = false; needsRecompiling = false;
compiled.store(true);
compiled.notify_all();
return false; return false;
} }
} else { } else {
// Already known stale, but the dependencies still need // Already known stale, but the dependencies still need
// evaluating: an unchecked local module would never get built, // evaluating: Schedule() below reads their needsRecompiling,
// and Compile() below waits on its `compiled` flag. // and an unchecked local module would never get built.
for(std::unique_ptr<ModulePartition>& partition : partitions) { for(std::unique_ptr<ModulePartition>& partition : partitions) {
partition->Check(pcmDir, sourceFloor); partition->Check(pcmDir, sourceFloor);
} }
@ -171,60 +181,29 @@ namespace Crafter {
} }
} }
void Module::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) { std::optional<JobGroup::Job> Module::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) {
// A sibling module in the same Configuration that this interface unit if (scheduled) return precompileJob;
// imports has to have its PCM on disk before we precompile against it. std::vector<JobGroup::Job> after;
// Safe to block here: Build() Checks every interface before it spawns // All of the module's partitions, not the ones the primary interface
// any compile thread, so a dependency that needs no rebuild already has // names: Build() records no edge for its `import :Part;` lines (see
// `compiled` set and this returns immediately. // Module::moduleDependencies). And of a module that is up to date as
// well: this is where its partitions are scheduled, and one of them
// may be without its object.
for (const std::unique_ptr<ModulePartition>& partition : partitions) {
if (const std::optional<JobGroup::Job> job = partition->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
}
if (needsRecompiling) {
// A sibling module in the same Configuration that this interface
// unit imports has to have its PCM on disk before we precompile
// against it.
for (Module* dependency : moduleDependencies) { for (Module* dependency : moduleDependencies) {
if(!dependency->compiled.load()) { if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
dependency->compiled.wait(false); }
} precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after);
} } else {
AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir);
std::vector<std::thread> threads; }
threads.reserve(partitions.size()); scheduled = true;
for(std::unique_ptr<ModulePartition>& part : partitions) { return precompileJob;
if(part->needsRecompiling) {
threads.emplace_back(&ModulePartition::Compile, part.get(), clang, pcmDir, buildDir, std::ref(buildCancelled), std::ref(buildError));
}
}
for(std::thread& thread : threads){
thread.join();
}
if (buildCancelled.load(std::memory_order_relaxed)) {
compiled.store(true);
compiled.notify_all();
return;
}
// -MD records every header the preamble pulled in, next to the BMI as
// <name>.pcm.d, so the next Check can see an edit to one of them.
std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
compiled.store(true);
compiled.notify_all();
return;
}
}
compiled.store(true);
compiled.notify_all();
result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
}
}
} }
} }

View file

@ -0,0 +1,218 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module Crafter.Build:Jobs_impl;
import std;
import :Jobs;
import :Progress;
namespace {
// The pool this thread is a worker of; null on every other thread.
thread_local const Crafter::JobPool* WorkerOf = nullptr;
}
namespace Crafter {
JobPool::JobPool(std::uint32_t workers) : limit(std::max(workers, 1u)) {}
JobPool::~JobPool() {
{
std::lock_guard lock(mutex);
stopping = true;
}
wake.notify_all();
for (std::thread& thread : threads) thread.join();
}
JobPool& JobPool::Process() {
static JobPool* const pool = new JobPool(std::thread::hardware_concurrency());
return *pool;
}
std::uint32_t JobPool::Workers() const {
return limit;
}
void JobPool::Submit(std::function<void()> job) {
std::lock_guard lock(mutex);
queue.push_back(std::move(job));
if (queue.size() <= idle || threads.size() >= limit) {
wake.notify_one();
return;
}
try {
threads.emplace_back([this] { Work(); });
} catch (...) {
// The system has no thread to give. The workers there are take
// the job when they get to it. With none it would stay queued
// for good, and whoever waits for it with it.
if (!threads.empty()) return;
queue.pop_back();
throw;
}
}
void JobPool::Work() {
WorkerOf = this;
std::unique_lock lock(mutex);
for (;;) {
while (queue.empty() && !stopping) {
++idle;
wake.wait(lock);
--idle;
}
if (queue.empty()) return;
std::function<void()> job = std::move(queue.front());
queue.pop_front();
lock.unlock();
job();
// Before the lock is taken again: what the job captured is
// released without holding up the queue.
job = nullptr;
lock.lock();
}
}
void JobPool::Run(const std::function<void()>& work) {
if (WorkerOf == this) {
work();
return;
}
// Shared with the job, not a local of this function: this thread
// goes on as soon as the value is set, which is before set_value has
// returned on the worker.
const std::shared_ptr<std::promise<void>> done = std::make_shared<std::promise<void>>();
std::future<void> finished = done->get_future();
Submit([&work, done] {
try {
work();
done->set_value();
} catch (...) {
done->set_exception(std::current_exception());
}
});
finished.get();
}
struct JobGroup::Node {
std::string label;
std::function<std::string()> work;
std::unique_ptr<Progress::Task> task;
// The jobs added after this one that it has yet to release, and how
// many jobs this one still waits for. Both under the group's mutex;
// the members above belong to whoever runs the job.
std::vector<Node*> dependents;
std::size_t waiting = 0;
bool finished = false;
};
JobGroup::JobGroup(JobPool& pool) : pool(pool) {
if (WorkerOf == &pool) throw std::logic_error("a JobGroup cannot be made on a worker of its own pool: it would wait there for jobs that need that worker");
}
JobGroup::~JobGroup() {
std::unique_lock lock(mutex);
failed = true;
settled.wait(lock, [this] { return unfinished == 0; });
}
JobGroup::Job JobGroup::Add(std::string label, std::function<std::string()> work, std::span<const Job> after) {
std::unique_ptr<Node> made = std::make_unique<Node>();
// Counted from here on, not from when it starts: the total a build
// shows is then what it has queued, and not only what the workers
// have got to.
made->task = std::make_unique<Progress::Task>(label);
made->label = std::move(label);
made->work = std::move(work);
std::lock_guard lock(mutex);
// Room for the new job in each list it may join, made before the
// group knows of it: from there to the count below nothing can throw,
// so no job is ever waited on by half of what it comes after.
for (const Job job : after) {
if (job >= nodes.size()) throw std::out_of_range("JobGroup::Add: a job can only come after jobs added before it");
std::vector<Node*>& dependents = nodes[job]->dependents;
dependents.reserve(dependents.size() + after.size());
}
const Job id = nodes.size();
Node& node = *nodes.emplace_back(std::move(made));
for (const Job job : after) {
Node& before = *nodes[job];
if (before.finished) continue;
before.dependents.push_back(&node);
++node.waiting;
}
++unfinished;
if (node.waiting != 0) return id;
try {
Start(node);
} catch (...) {
// Not queued (JobPool::Submit), so nothing will ever finish it:
// it is taken back, or Wait() would never return.
node.work = nullptr;
node.task.reset();
node.finished = true;
if (--unfinished == 0) settled.notify_all();
throw;
}
return id;
}
void JobGroup::Start(Node& node) {
pool.Submit([this, &node] { Execute(node); });
}
void JobGroup::Execute(Node& node) {
bool skipped = false;
{
std::lock_guard lock(mutex);
skipped = failed;
}
std::string result;
if (!skipped) {
try {
result = node.work();
} catch (const std::exception& e) {
result = std::format("{}: {}", node.label, e.what());
} catch (...) {
result = std::format("{}: threw something that isn't a std::exception", node.label);
}
}
// Both before the group hears of it: what the work captured is gone,
// and the step counted as done, by the time Wait() returns.
node.work = nullptr;
node.task.reset();
// Nothing of the group is touched once this lock is released: with
// the last job finished, whoever waited may destroy it.
std::lock_guard lock(mutex);
if (!result.empty() && !failed) {
failed = true;
error = std::move(result);
}
node.finished = true;
// Released after a failure as well: they are skipped when they run,
// which is what counts them as finished.
for (Node* dependent : node.dependents) {
if (--dependent->waiting == 0) Start(*dependent);
}
if (--unfinished == 0) settled.notify_all();
}
void JobGroup::Fail(std::string why) {
std::lock_guard lock(mutex);
if (failed) return;
failed = true;
error = std::move(why);
}
bool JobGroup::Failed() const {
std::lock_guard lock(mutex);
return failed;
}
std::string JobGroup::Wait() {
std::unique_lock lock(mutex);
settled.wait(lock, [this] { return unfinished == 0; });
return error;
}
}

View file

@ -8,6 +8,7 @@ export module Crafter.Build:Lint_impl;
import std; import std;
import :Lint; import :Lint;
import :Clang; import :Clang;
import :Test;
import :Platform; import :Platform;
import :Toolchain; import :Toolchain;
import :Progress; import :Progress;
@ -42,6 +43,7 @@ namespace {
decltype(&clang_createIndex) createIndex = nullptr; decltype(&clang_createIndex) createIndex = nullptr;
decltype(&clang_disposeIndex) disposeIndex = nullptr; decltype(&clang_disposeIndex) disposeIndex = nullptr;
decltype(&clang_parseTranslationUnit) parseTranslationUnit = nullptr; decltype(&clang_parseTranslationUnit) parseTranslationUnit = nullptr;
decltype(&clang_parseTranslationUnit2FullArgv) parseTranslationUnit2FullArgv = nullptr;
decltype(&clang_disposeTranslationUnit) disposeTranslationUnit = nullptr; decltype(&clang_disposeTranslationUnit) disposeTranslationUnit = nullptr;
decltype(&clang_getFile) getFile = nullptr; decltype(&clang_getFile) getFile = nullptr;
decltype(&clang_getLocationForOffset) getLocationForOffset = nullptr; decltype(&clang_getLocationForOffset) getLocationForOffset = nullptr;
@ -132,6 +134,7 @@ namespace {
bind(lib.createIndex, "clang_createIndex"); bind(lib.createIndex, "clang_createIndex");
bind(lib.disposeIndex, "clang_disposeIndex"); bind(lib.disposeIndex, "clang_disposeIndex");
bind(lib.parseTranslationUnit, "clang_parseTranslationUnit"); bind(lib.parseTranslationUnit, "clang_parseTranslationUnit");
bind(lib.parseTranslationUnit2FullArgv, "clang_parseTranslationUnit2FullArgv");
bind(lib.disposeTranslationUnit, "clang_disposeTranslationUnit"); bind(lib.disposeTranslationUnit, "clang_disposeTranslationUnit");
bind(lib.getFile, "clang_getFile"); bind(lib.getFile, "clang_getFile");
bind(lib.getLocationForOffset, "clang_getLocationForOffset"); bind(lib.getLocationForOffset, "clang_getLocationForOffset");
@ -704,11 +707,12 @@ namespace {
return decls; return decls;
} }
// libclang locates its builtin headers relative to its own install path, // The resource directory, which holds clang's own headers such as
// which need not agree with the clang++ on PATH that produced the PCMs. // stddef.h, as the compiler names it. libclang's driver would otherwise
// When it disagrees the failure is total and unhelpful — every parse dies // derive one from argv[0] for libclang's own release, so with a libclang
// on "'stddef.h' file not found" — so ask the driver and pass it // of another release than the compiler, a file that includes a header of
// explicitly. Cached like HostTarget, and for the same reason. // the C++ standard library would fail on "'stddef.h' file not found".
// Cached like HostTarget, and for the same reason.
const std::string& ClangResourceDir() { const std::string& ClangResourceDir() {
static const std::string Cached = []() -> std::string { static const std::string Cached = []() -> std::string {
CommandResult r = RunCommandChecked(std::format("{} -print-resource-dir", GetToolchain().clangxx.string())); CommandResult r = RunCommandChecked(std::format("{} -print-resource-dir", GetToolchain().clangxx.string()));
@ -751,7 +755,26 @@ namespace {
// Byte-length preserving, so cursor line/column land on the original. // Byte-length preserving, so cursor line/column land on the original.
std::string buffer = BlankExportKeywords(content, tokens); std::string buffer = BlankExportKeywords(content, tokens);
std::string path = file.string(); std::string path = file.string();
std::vector<std::string> args = CommandToArgs(compileCommand); // In a build for the host whose compile command names no libc++
// directory (a sysroot or CRAFTER_BUILD_LIBCXX_DIR names one), the
// driver inside libclang looks for libc++'s headers in ../include from
// the directory of argv[0], as the compiler's driver does from its
// own, and then in /usr/local/include and in /usr/include. Left to
// name argv[0] itself, libclang names it plain "clang", in no
// directory, so the first of those was ../include from the working
// directory, and where none of them had a libc++, as in the Flatpak,
// whose compiler keeps its own in /app, no file of such a build that
// includes a header of the C++ standard library could be parsed
// (issue #46). The compile command's own argv[0] would not do either:
// a clang++ from PATH is a bare name, and one reached through a link
// into another directory takes itself to be where the link leads,
// unless the command's last prefix flag is -no-canonical-prefixes. So
// argv[0] is the compiler where clang started with this command takes
// itself to be, in the directory it says it is installed in when run
// with the command's last prefix flag, or, where it names none,
// clangxx as the command has it (Toolchain::InstalledClangxx).
std::vector<std::string> args = { GetToolchain().InstalledClangxx(compileCommand).string() };
std::ranges::move(CommandToArgs(compileCommand), std::back_inserter(args));
// Required: libclang will not infer a module interface unit from the // Required: libclang will not infer a module interface unit from the
// .cppm extension, and silently treats every flag as a linker input if // .cppm extension, and silently treats every flag as a linker input if
// left to guess. // left to guess.
@ -771,8 +794,8 @@ namespace {
result.error = "clang_createIndex failed"; result.error = "clang_createIndex failed";
return result; return result;
} }
CXTranslationUnit tu = lc.parseTranslationUnit(index, path.c_str(), argv.data(), static_cast<std::int32_t>(argv.size()), &unsaved, 1, CXTranslationUnit_None); CXTranslationUnit tu = nullptr;
if (!tu) { if (lc.parseTranslationUnit2FullArgv(index, path.c_str(), argv.data(), static_cast<std::int32_t>(argv.size()), &unsaved, 1, CXTranslationUnit_None, &tu) != CXError_Success || !tu) {
lc.disposeIndex(index); lc.disposeIndex(index);
result.error = "clang could not create a translation unit"; result.error = "clang could not create a translation unit";
return result; return result;
@ -865,18 +888,28 @@ namespace {
// whose path lies inside the project root — GitProject / external deps // whose path lies inside the project root — GitProject / external deps
// live under the global cache and are foreign code: they contribute // 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 // neither rules nor files. Root-first order so the root's rules win the
// by-name dedup. // by-name dedup. Of several roots, the configurations a project file
std::vector<Configuration*> CollectLocalConfigs(Configuration& root, const fs::path& projectRoot) { // 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::vector<Configuration*> local;
std::unordered_set<Configuration*> seen; std::unordered_set<Configuration*> seen;
std::function<void(Configuration*)> walk = [&](Configuration* c) { const auto keep = [&](Configuration* c) {
if (!seen.insert(c).second) return; if (PathInsideRoot(fs::absolute(c->path), projectRoot)) local.push_back(c);
if (PathInsideRoot(fs::absolute(c->path), projectRoot)) {
local.push_back(c);
}
for (Configuration* dep : c->dependencies) walk(dep);
}; };
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; return local;
} }
@ -892,15 +925,10 @@ namespace {
// First owner wins, matching the root-first rule dedup: a source // First owner wins, matching the root-first rule dedup: a source
// reachable through two configurations parses with the nearer one. // reachable through two configurations parses with the nearer one.
auto own = [&files, &c](fs::path file) { files.emplace(std::move(file), &c); }; auto own = [&files, &c](fs::path file) { files.emplace(std::move(file), &c); };
for (const std::unique_ptr<Module>& mod : c.interfaces) { // The sources as they are listed: which module each one is a unit
own(fs::path(std::format("{}.cppm", mod->path.string()))); // of, only a build reads.
for (const std::unique_ptr<ModulePartition>& part : mod->partitions) { for (const fs::path& source : c.interfaceSources) own(source);
own(fs::path(std::format("{}.cppm", part->path.string()))); for (const fs::path& source : c.implementationSources) own(source);
}
}
for (const Implementation& impl : c.implementations) {
own(fs::path(std::format("{}.cpp", impl.path.string())));
}
// cFiles/cuda resolve against cwd at build time (see Build's compile // cFiles/cuda resolve against cwd at build time (see Build's compile
// loops); mirror that here. // loops); mirror that here.
for (const fs::path& cf : c.cFiles) { for (const fs::path& cf : c.cFiles) {
@ -1068,6 +1096,11 @@ void Configuration::AddAstLintRule(std::string name, std::function<void(LintCont
} }
LintSummary Crafter::RunLint(Configuration& projectCfg, const RunLintOptions& opts) { 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; LintSummary summary;
// libclang backs the lexer every rule reads through, so a failed load is // libclang backs the lexer every rule reads through, so a failed load is
@ -1080,10 +1113,12 @@ LintSummary Crafter::RunLint(Configuration& projectCfg, const RunLintOptions& op
} }
fs::path projectRoot = opts.projectFile.empty() fs::path projectRoot = opts.projectFile.empty()
? fs::absolute(projectCfg.path) ? fs::absolute(configurations.empty() ? fs::path() : configurations.front()->path)
: opts.projectFile.parent_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);
// Collect rules root-first, dedup by name (first registration wins). // Collect rules root-first, dedup by name (first registration wins).
std::vector<const LintRule*> rules; std::vector<const LintRule*> rules;
@ -1130,7 +1165,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
CollectConfigSources(*c, files); CollectConfigSources(*c, files);
for (const Test& t : c->tests) CollectConfigSources(t.config, 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 // 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. // here and gets no compile command. Token rules still cover it.
if (!opts.projectFile.empty()) files.emplace(opts.projectFile, nullptr); if (!opts.projectFile.empty()) files.emplace(opts.projectFile, nullptr);
@ -1149,6 +1184,10 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
// command per configuration — GetCompileCommand walks the dependency tree. // command per configuration — GetCompileCommand walks the dependency tree.
const bool anyRuleNeedsAst = std::ranges::any_of(rules, [](const LintRule* r) { return r->needsAst; }); const bool anyRuleNeedsAst = std::ranges::any_of(rules, [](const LintRule* r) { return r->needsAst; });
std::unordered_map<const Configuration*, std::string> commands; std::unordered_map<const Configuration*, std::string> commands;
// Why a configuration of the build graph has no command: its files
// cannot be parsed, which fails the run. Cleared to nothing, the command
// read as "not a translation unit" and every semantic rule passed them.
std::unordered_map<const Configuration*, std::string> commandErrors;
if (anyRuleNeedsAst && !opts.noAst) { if (anyRuleNeedsAst && !opts.noAst) {
for (Configuration* c : localConfigs) { for (Configuration* c : localConfigs) {
auto ensure = [&](const Configuration& cfg) { auto ensure = [&](const Configuration& cfg) {
@ -1166,10 +1205,14 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
Progress::Task task(std::format("Building std PCM ({}-{})", cfg.target, cfg.march)); Progress::Task task(std::format("Building std PCM ({}-{})", cfg.target, cfg.march));
fs::create_directories(assembled.stdPcmDir); fs::create_directories(assembled.stdPcmDir);
std::string error = BuildStdPcm(cfg, assembled.stdPcmDir/"std.pcm"); std::string error = BuildStdPcm(cfg, assembled.stdPcmDir/"std.pcm");
if (!error.empty()) command.clear(); if (!error.empty()) {
command.clear();
commandErrors.emplace(&cfg, std::format("building the std module for {}: {}", cfg.target, error));
} }
} catch (const std::exception&) { }
command.clear(); // surfaced per file as an AST reason } catch (const std::exception& e) {
command.clear();
commandErrors.emplace(&cfg, std::format("assembling the compile command for {}: {}", cfg.target, e.what()));
} }
commands.emplace(&cfg, std::move(command)); commands.emplace(&cfg, std::move(command));
}; };
@ -1180,7 +1223,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
for (const auto& [file, owner] : files) { for (const auto& [file, owner] : files) {
std::ifstream in(file, std::ios::binary); std::ifstream in(file, std::ios::binary);
if (!in) continue; // config parse already read it; a vanished file fails the build first if (!in) continue; // a listed file that is not there is the build's to report
std::stringstream buffer; std::stringstream buffer;
buffer << in.rdbuf(); buffer << in.rdbuf();
LintContext ctx; LintContext ctx;
@ -1200,8 +1243,13 @@ format` applies it to disk, and `crafter-build lint` reports where it would.
// decides what is safe to touch. Skip it and make the run fail. // decides what is safe to touch. Skip it and make the run fail.
if (rule->needsAst) { if (rule->needsAst) {
if (opts.noAst) continue; if (opts.noAst) continue;
if (auto failed = commandErrors.find(owner); failed != commandErrors.end()) {
astFailures.emplace(file, failed->second);
skippedAstRules.insert(rule->name);
continue;
}
// No compile command means this file is not a translation unit // 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 // with its own flags, or a header. A semantic rule does not
// apply there, the same way a rule self-filters by extension, // apply there, the same way a rule self-filters by extension,
// so skip it quietly. That is a different thing from a file we // so skip it quietly. That is a different thing from a file we

View file

@ -9,6 +9,8 @@ module;
#include <dlfcn.h> #include <dlfcn.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <sys/file.h> #include <sys/file.h>
#include <sys/prctl.h>
#include <signal.h>
#include <fcntl.h> #include <fcntl.h>
#include <errno.h> #include <errno.h>
module Crafter.Build:Platform_impl; module Crafter.Build:Platform_impl;
@ -18,6 +20,7 @@ import :Toolchain;
import :Clang; import :Clang;
import :Interface; import :Interface;
import :External; import :External;
import :Jobs;
import :Progress; import :Progress;
namespace fs = std::filesystem; namespace fs = std::filesystem;
using namespace Crafter; using namespace Crafter;
@ -25,7 +28,7 @@ using namespace Crafter;
namespace { namespace {
// Exclusive advisory lock over one PCM cache dir (`<cache>/<target>-<march>/`), // Exclusive advisory lock over one PCM cache dir (`<cache>/<target>-<march>/`),
// held for the duration of a (re)build. Concurrent crafter-build invocations — // held for the duration of a (re)build. Concurrent crafter-build invocations —
// and the worker threads inside a single invocation — that share a cache // and the threads of a single invocation that build at once — that share a cache
// serialize their builds through it: the first builder to acquire the lock // serialize their builds through it: the first builder to acquire the lock
// precompiles std.pcm / the Crafter.Build-*.pcm modules while everyone else // precompiles std.pcm / the Crafter.Build-*.pcm modules while everyone else
// blocks, then re-checks freshness and reuses the finished file instead of // blocks, then re-checks freshness and reuses the finished file instead of
@ -276,11 +279,16 @@ bool Crafter::MatchAny(std::span<const std::string> globs, std::string_view name
return false; return false;
} }
// See the declaration in Crafter.Build-Platform.cppm for why this branches on namespace {
// the exit code rather than on whether the command said anything. // RunBuildCommand's command, run on the thread that calls. See the
std::string Crafter::RunBuildCommand(std::string_view cmd) { // declaration in Crafter.Build-Platform.cppm for why this branches on the
// exit code rather than on whether the command said anything.
std::string RunBuildStep(std::string_view cmd) {
Progress::EchoCommand(cmd); Progress::EchoCommand(cmd);
CommandResult r = RunCommandChecked(cmd); CommandResult r = RunCommandChecked(cmd);
// A mingw build against a system prefix sees mingw-w64 through a view in
// the cache, and clang names every header by the path it found it at.
r.output = MingwViewToPrefix(std::move(r.output));
if (r.exitCode == 0) { if (r.exitCode == 0) {
// Warnings from a step that succeeded. Show them — until now they were // Warnings from a step that succeeded. Show them — until now they were
@ -302,6 +310,16 @@ std::string Crafter::RunBuildCommand(std::string_view cmd) {
} }
return r.output; return r.output;
} }
}
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 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;
}
// --- Dependencies of project.cpp itself ------------------------------------- // --- Dependencies of project.cpp itself -------------------------------------
// //
@ -312,7 +330,7 @@ std::string Crafter::RunBuildCommand(std::string_view cmd) {
// file, so this is a directive next to the `import` it enables — where // 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 // `#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 // 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. // resolve recursively.
namespace { namespace {
struct PragmaDependency { struct PragmaDependency {
@ -413,18 +431,18 @@ namespace {
struct ProjectFileFrame { struct ProjectFileFrame {
fs::path project; fs::path project;
// What LoadProject was given, for ProjectArgs(), and only once // What the load was given, for ProjectArgs(), and only once the
// CrafterBuildProject is about to be called (see LoadProject). A view // entry point is about to be called (see OpenProjectFile). A view
// is enough: the caller's storage outlives LoadProject, and the frame // is enough: the caller's storage outlives the load, and the frame
// is popped before LoadProject returns. // is popped before the load returns.
std::span<const std::string_view> args; std::span<const std::string_view> args;
std::vector<Configuration*> dependencies; std::vector<Configuration*> dependencies;
}; };
// LoadProject nests: a dependency's project.cpp loads inside its // Loads nest: a dependency's project.cpp loads inside its consumer's
// consumer's pre-pass, and GitProject inside CrafterBuildProject nests // pre-pass, and GitProject inside an entry point nests again. Several
// again. Several threads may also load at once (ConcurrentCacheRace), so // threads may also load at once (ConcurrentCacheRace), so the stack is
// the stack is per thread. ProjectDependency() reads the top frame. // per thread. ProjectDependency() reads the top frame.
thread_local std::vector<ProjectFileFrame> LoadingFrames; thread_local std::vector<ProjectFileFrame> LoadingFrames;
// A frame's dependencies, kept past the frame for PragmaDependencies(). // A frame's dependencies, kept past the frame for PragmaDependencies().
@ -434,7 +452,7 @@ namespace {
std::mutex PragmaDependenciesMutex; std::mutex PragmaDependenciesMutex;
std::unordered_map<fs::path, std::vector<Configuration*>> PragmaDependenciesByProject; 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. // already on the stack is a cycle, which used to recurse forever.
class ProjectFileGuard { class ProjectFileGuard {
public: public:
@ -475,17 +493,18 @@ namespace {
// A pre-dependency is host tooling: project.so is loaded into the running // 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 // 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 // compiles project.so with, so the dependency's std/Crafter.Build PCMs
// land in the cache dir project.so is built against. Recursive, because // 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 // the dependency's project.cpp is loaded with no arguments and so passes
// none on, while its own deps still read CRAFTER_BUILD_MARCH from the // none on, while its own deps still read CRAFTER_BUILD_MARCH and
// environment. // CRAFTER_BUILD_CUDA_ARCH from the environment.
void ForceHostTooling(Configuration& cfg, const Configuration& host, std::unordered_set<Configuration*>& seen) { void ForceHostTooling(Configuration& cfg, const Configuration& host, std::unordered_set<Configuration*>& seen) {
if (!seen.insert(&cfg).second) return; if (!seen.insert(&cfg).second) return;
cfg.target = host.target; cfg.target = host.target;
cfg.march = host.march; cfg.march = host.march;
cfg.mtune = host.mtune; cfg.mtune = host.mtune;
cfg.cudaArch = host.cudaArch;
cfg.debug = false; cfg.debug = false;
// project.so is a shared object, so the archive it links has to be // project.so is a shared object, so the archive it links has to be
// position-independent; static libraries aren't by default. Part of // position-independent; static libraries aren't by default. Part of
@ -503,7 +522,12 @@ namespace {
struct ProjectFileDependencies { struct ProjectFileDependencies {
std::vector<Configuration*> configs; std::vector<Configuration*> configs;
std::string compileFlags; // " -fprebuilt-module-path=…" for each dependency and its transitive deps std::string compileFlags; // " -fprebuilt-module-path=…" for each dependency and its transitive deps
std::string linkFlags; // every dependency's BuildResult.libs, verbatim // 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 the load
// dlopens project.so.
std::string linkFlags;
fs::file_time_type newestArtifact = fs::file_time_type::min(); fs::file_time_type newestArtifact = fs::file_time_type::min();
}; };
@ -521,10 +545,12 @@ namespace {
std::unordered_set<Configuration*> forced; std::unordered_set<Configuration*> forced;
std::unordered_set<Configuration*> walked; std::unordered_set<Configuration*> walked;
std::set<std::string> libs; std::set<std::string> libs;
std::set<std::string> runtimeLibs;
std::set<std::string> runPaths;
for (const PragmaDependency& pragma : pragmas) { for (const PragmaDependency& pragma : pragmas) {
// Neither spec sets args, and the tool still gets none of the // 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 // frame its args, so ProjectArgs() is empty. Given the consumer's
// --target=, the tool's project.cpp would pick sources and flags // --target=, the tool's project.cpp would pick sources and flags
// for the wrong triple, and its flags would split the tool's // for the wrong triple, and its flags would split the tool's
@ -542,7 +568,7 @@ namespace {
cfg = GitProject(spec); cfg = GitProject(spec);
} else { } else {
if (!pragma.branch.empty() || !pragma.commit.empty()) PragmaError(absProject, pragma.line, "'branch' and 'commit' only apply to a git source"); 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. // from wherever the consumer was invoked.
fs::path local = (absProject.parent_path() / pragma.source).lexically_normal(); fs::path local = (absProject.parent_path() / pragma.source).lexically_normal();
if (fs::is_directory(local)) { if (fs::is_directory(local)) {
@ -565,6 +591,8 @@ namespace {
if (!built.result.empty()) PragmaError(absProject, pragma.line, std::format("project dependency '{}' failed to build: {}", cfg->name, built.result)); if (!built.result.empty()) PragmaError(absProject, pragma.line, std::format("project dependency '{}' failed to build: {}", cfg->name, built.result));
out.configs.push_back(cfg); out.configs.push_back(cfg);
libs.insert(built.libs.begin(), built.libs.end()); libs.insert(built.libs.begin(), built.libs.end());
runtimeLibs.insert(built.runtimeLibs.begin(), built.runtimeLibs.end());
runPaths.insert(built.runPaths.begin(), built.runPaths.end());
// The module path needs the dependency and everything it depends // The module path needs the dependency and everything it depends
// on, same as GetCompileCommand does for a consumer; the newest // on, same as GetCompileCommand does for a consumer; the newest
@ -580,6 +608,8 @@ namespace {
walk(cfg); walk(cfg);
} }
for (const std::string& lib : libs) out.linkFlags += std::format(" {}", lib); for (const std::string& lib : libs) out.linkFlags += std::format(" {}", lib);
for (const std::string& lib : runtimeLibs) out.linkFlags += std::format(" {}", lib);
for (const std::string& dir : runPaths) out.linkFlags += RunPathFlags(dir);
return out; return out;
} }
@ -656,6 +686,10 @@ namespace {
} }
} }
std::string Crafter::RunPathFlags(std::string_view dir) {
return std::format(" -Xlinker -rpath -Xlinker {}", ShellQuote(dir));
}
std::string Crafter::ShellQuote(std::string_view s) { std::string Crafter::ShellQuote(std::string_view s) {
std::string out; std::string out;
out.reserve(s.size() + 2); out.reserve(s.size() + 2);
@ -684,6 +718,118 @@ CommandResult Crafter::RunCommandChecked(std::string_view cmd) {
return result; return result;
} }
std::string Crafter::JsonQuote(std::string_view s) {
std::string out = "\"";
for (const char c : s) {
if (c == '"') out += "\\\"";
else if (c == '\\') out += "\\\\";
else if (c == '\n') out += "\\n";
else if (c == '\t') out += "\\t";
else if (c == '\r') out += "\\r";
else if (static_cast<std::uint8_t>(c) < 0x20) out += std::format("\\u{:04x}", static_cast<std::uint8_t>(c));
else out.push_back(c);
}
out.push_back('"');
return out;
}
namespace {
bool InFlatpak() {
std::error_code ec;
return fs::exists("/.flatpak-info", ec);
}
// The command line that runs `program arguments` on the host: as it is
// natively, through the Flatpak session helper inside crafter-build's
// Flatpak, started there in `directory`. flatpak-spawn would start it in
// crafter-build's own working directory, which the host need not have,
// so it is / unless a caller asks for another: every host command names
// its paths absolutely. --watch-bus ends the host command when
// flatpak-spawn ends. A crafter-build killed outright leaves
// flatpak-spawn running, so the host command runs on until it finishes.
// Every host command of crafter-build's own is built here: the host's
// flatpak and flatpak-builder, for RunHostFlatpak, RunHostFlatpakBuilder
// and HostFlatpakUnavailable's probes.
std::string HostCommand(std::string_view program, std::string_view arguments, const fs::path& directory = "/") {
if (!InFlatpak()) return std::format("{} {}", program, arguments);
std::string env;
if (const char* userDir = std::getenv("FLATPAK_USER_DIR"); userDir && *userDir) {
env = std::format(" {}", ShellQuote(std::format("--env=FLATPAK_USER_DIR={}", userDir)));
}
return std::format("flatpak-spawn --host --watch-bus {}{} {} {}", ShellQuote(std::format("--directory={}", directory.string())), env, program, arguments);
}
std::int32_t RunOnHost(std::string_view program, std::string_view arguments, std::string_view shown) {
if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) std::println("$ {} {}", shown, arguments);
return RunCommandAttached(HostCommand(program, arguments));
}
}
std::string Crafter::HostFlatpakUnavailable(const fs::path& projectDir) {
if (!InFlatpak()) {
// Through the shell: `command` is one of its builtins, which the
// `timeout` RunCommandWithTimeout wraps a command in cannot run.
if (RunCommandChecked("command -v flatpak").exitCode != 0) return "flatpak is not installed";
return "";
}
std::ifstream file("/.flatpak-info", std::ios::binary);
const std::string info((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
if (!info.contains("org.freedesktop.Flatpak=talk")) {
return "crafter-build's Flatpak lacks the org.freedesktop.Flatpak permission it runs the host's flatpak with: it is older than that, or runs in a build sandbox";
}
// The program install and bundle run, built as they build theirs, in
// `directory` on the host; and what it said, for a refusal.
const auto probe = [](const fs::path& directory) { return RunCommandWithTimeout(HostCommand("flatpak", "--version", directory), std::chrono::seconds(30)); };
const auto said = [](const CommandResult& result) {
std::string_view output = result.output;
while (!output.empty() && (output.back() == '\n' || output.back() == '\r')) output.remove_suffix(1);
return std::string(output);
};
if (const CommandResult reached = probe("/"); reached.exitCode != 0) {
return std::format("the host cannot be reached through flatpak-spawn --host: {}", said(reached));
}
// install and bundle hand the host's flatpak paths in the project's bin/
// and build/, so the host has to see those where crafter-build does,
// which it does not in the sandbox's own /tmp, /var, /usr, /etc and /app,
// nor where a link leads into one. The host answers for itself, by its
// own links and by whatever the sandbox shares, overrides included: the
// same program, started in a directory just made in each of them under a
// name no other has, starts only where the host sees that very directory,
// not merely a path it has as well, as it has /tmp. What this makes is
// removed again, bin/ and build/ too where they were not there before, so
// a refusal leaves nothing behind in the project's directory, which the
// caller's project.cpp is in.
std::random_device random;
const std::string mark = std::format(".crafter-build-host-probe-{:08x}{:08x}", random(), random());
for (const std::string_view sub : {"bin", "build"}) {
const fs::path dir = fs::absolute(projectDir / sub).lexically_normal();
std::error_code ec;
const bool existed = fs::exists(fs::symlink_status(dir, ec));
fs::create_directories(dir / mark, ec);
if (ec) return std::format("{} cannot be made, to see whether the host sees it: {}", (dir / mark).string(), ec.message());
const CommandResult seen = probe(dir / mark);
fs::remove(dir / mark, ec);
if (!existed) fs::remove(dir, ec);
if (seen.exitCode != 0) {
return std::format("the host does not see {} where crafter-build does ({}): crafter-build's sandbox has /tmp, /var, /usr, /etc and /app of its own, so keep the project, its bin/ and build/ and where their links lead in a directory the sandbox shares with the host, such as your home", dir.string(), said(seen));
}
}
return "";
}
std::int32_t Crafter::RunHostFlatpak(std::string_view arguments) {
return RunOnHost("flatpak", arguments, "flatpak");
}
std::int32_t Crafter::RunHostFlatpakBuilder(std::string_view arguments) {
// flatpak-builder as a host package, else the org.flatpak.Builder app,
// as the self-host's `run flatpak` script finds it.
if (RunCommandWithTimeout(HostCommand("flatpak-builder", "--version"), std::chrono::seconds(30)).exitCode == 0) {
return RunOnHost("flatpak-builder", arguments, "flatpak-builder");
}
return RunOnHost("flatpak", std::format("run org.flatpak.Builder {}", arguments), "flatpak");
}
std::int32_t Crafter::RunCommandAttached(std::string_view cmd) { std::int32_t Crafter::RunCommandAttached(std::string_view cmd) {
// The child writes straight to the terminal. Anything of ours that is // The child writes straight to the terminal. Anything of ours that is
// still pending — the in-place status line, buffered stdout when it is // still pending — the in-place status line, buffered stdout when it is
@ -730,6 +876,168 @@ CommandResult Crafter::RunCommandWithTimeout(std::string_view cmd, std::chrono::
return result; return result;
} }
namespace {
// How a child that waitid saw end ended, read as DecodeWaitStatus reads
// a pclose: the exit code, or 128+signal when a signal ended it.
std::int32_t ChildExitCode(const siginfo_t& info) {
return info.si_code == CLD_EXITED ? info.si_status : 128 + info.si_status;
}
}
Crafter::BackgroundCommand::BackgroundCommand(std::string_view command, std::span<const EnvironmentChange> environment, const fs::path& log, std::chrono::seconds lifetime) {
// The death signal goes to the process this forks, so that has to be
// the timeout process: `exec` makes the sh it starts as become it.
// timeout passes a SIGTERM on to its whole group and ends what is still
// running 2 s later.
std::string script = std::format("exec timeout -k 2 {} sh -c {}", lifetime.count(), ShellQuote(command));
std::string shell = "sh";
std::string flag = "-c";
std::array<char*, 4> argv = { shell.data(), flag.data(), script.data(), nullptr };
std::vector<std::string> variables;
for (char** entry = environ; *entry != nullptr; ++entry) {
const std::string_view variable(*entry);
const std::string_view name = variable.substr(0, variable.find('='));
if (std::ranges::none_of(environment, [&](const EnvironmentChange& change) { return change.name == name; })) {
variables.emplace_back(variable);
}
}
for (const EnvironmentChange& change : environment) {
if (change.value) variables.push_back(std::format("{}={}", change.name, *change.value));
}
std::vector<char*> envp;
for (std::string& variable : variables) envp.push_back(variable.data());
envp.push_back(nullptr);
// Both close-on-exec: the child keeps them only as its 0, 1 and 2.
const std::int32_t output = ::open(log.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (output < 0) throw std::runtime_error(std::format("cannot write {}: {}", log.string(), std::strerror(errno)));
const std::int32_t input = ::open("/dev/null", O_RDONLY | O_CLOEXEC);
if (input < 0) {
const std::int32_t openError = errno;
::close(output);
throw std::runtime_error(std::format("cannot open /dev/null: {}", std::strerror(openError)));
}
const pid_t parent = ::getpid();
// Everything the child uses was made above: between fork and exec it
// makes async-signal-safe calls only, since another thread of this
// process may hold the allocator's lock at the moment of the fork.
pid = ::fork();
if (pid == 0) {
// The signal is sent when the thread that forked ends, not the
// process; the parent may also have ended before this line.
if (::prctl(PR_SET_PDEATHSIG, SIGTERM) != 0 || ::getppid() != parent) ::_exit(126);
// A signal mask outlives exec, and a SIGTERM blocked in it would
// keep both the death signal and Stop() from reaching timeout.
sigset_t none;
::sigemptyset(&none);
::sigprocmask(SIG_SETMASK, &none, nullptr);
::setpgid(0, 0);
::dup2(input, STDIN_FILENO);
::dup2(output, STDOUT_FILENO);
::dup2(output, STDERR_FILENO);
::execve("/bin/sh", argv.data(), envp.data());
::_exit(127);
}
const std::int32_t forkError = errno;
::close(input);
::close(output);
if (pid < 0) throw std::runtime_error(std::format("cannot start {}: {}", command, std::strerror(forkError)));
// From this side as well, so that the group exists before Stop() can
// signal it, whichever of the two runs first. Once the child has
// exec'd this fails, after the child's own call has made the group.
::setpgid(pid, pid);
}
Crafter::BackgroundCommand::~BackgroundCommand() {
Stop(std::chrono::seconds(5));
}
std::optional<std::int32_t> Crafter::BackgroundCommand::Exited() {
if (exitCode || pid < 0) return exitCode;
siginfo_t info{};
// WNOWAIT leaves an ended command unreaped: its pid, and with it the
// number of its process group, which Stop() signals, cannot be handed
// to another process before Stop() reaps it.
if (::waitid(P_PID, static_cast<id_t>(pid), &info, WEXITED | WNOHANG | WNOWAIT) == 0 && info.si_pid == pid) {
exitCode = ChildExitCode(info);
}
return exitCode;
}
void Crafter::BackgroundCommand::Stop(std::chrono::milliseconds grace) {
if (pid < 0 || reaped) return;
::kill(-pid, SIGTERM);
const auto deadline = std::chrono::steady_clock::now() + grace;
while (!Exited() && std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// What is left of the group: anything the command started that outlived
// it, and the command itself when it did not end within `grace`.
::kill(-pid, SIGKILL);
std::int32_t status = 0;
while (::waitpid(pid, &status, 0) < 0 && errno == EINTR) {}
reaped = true;
}
namespace {
// Removes what PrivateDirectory's destructor would have, for the
// processes that never ran it.
void RemoveAbandonedDirectories(const fs::path& parent, std::string_view prefix) {
std::error_code ec;
const auto now = fs::file_time_type::clock::now();
for (const fs::directory_entry& entry : fs::directory_iterator(parent, ec)) {
std::error_code entryError;
if (!entry.path().filename().string().starts_with(prefix) || !entry.is_directory(entryError) || entry.is_symlink(entryError)) continue;
// Another user's directory does not open: mkdtemp made it 0700.
const std::int32_t held = ::open(entry.path().c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (held < 0) continue;
// Dated only once it is held: a directory that is kept is dated
// by its holder just before it lets go of it, so a date read
// before the lock can be one the holder has replaced since.
if (::flock(held, LOCK_EX | LOCK_NB) == 0) {
const auto changed = fs::last_write_time(entry.path(), entryError);
if (!entryError && now - changed >= std::chrono::minutes(1)) fs::remove_all(entry.path(), entryError);
}
::close(held);
}
}
fs::path MakeDirectory(const fs::path& parent, std::string_view prefix) {
RemoveAbandonedDirectories(parent, prefix);
std::string pattern = (parent / std::format("{}XXXXXX", prefix)).string();
if (::mkdtemp(pattern.data()) == nullptr) {
throw std::runtime_error(std::format("cannot make a directory in {}: {}", parent.string(), std::strerror(errno)));
}
return fs::path(pattern);
}
}
Crafter::PrivateDirectory::PrivateDirectory(const fs::path& parent, std::string_view prefix) : path(MakeDirectory(parent, prefix)) {
// Close-on-exec, so that the lock is this process's alone: a command it
// starts that outlives it does not keep the directory from being
// removed.
fd = ::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (fd >= 0) {
while (::flock(fd, LOCK_EX) != 0 && errno == EINTR) {}
}
}
Crafter::PrivateDirectory::~PrivateDirectory() {
std::error_code ec;
if (kept) {
// Dated now, while it is still held: its date is that of what was
// last made or removed in it, which may be long before, as for the
// run of a test that failed after minutes, and a directory nobody
// holds is removed a minute after its date.
fs::last_write_time(path, fs::file_time_type::clock::now(), ec);
} else {
fs::remove_all(path, ec);
}
if (fd >= 0) ::close(fd);
}
std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
CacheLock lock(stdPcm.parent_path()); CacheLock lock(stdPcm.parent_path());
if(config.target == "x86_64-w64-mingw32") { if(config.target == "x86_64-w64-mingw32") {
@ -737,14 +1045,17 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
// library, naming the std module's source relative to itself. It is // library, naming the std module's source relative to itself. It is
// looked for in the library directories the compiler searches for // looked for in the library directories the compiler searches for
// this target, as it would look for libstdc++ itself, but only in // this target, as it would look for libstdc++ itself, but only in
// those that belong to the mingw toolchain: the list also has the // those that belong to the mingw toolchain. The list also holds
// generic <prefix>/lib, where the host's own (Linux) libstdc++ keeps // clang's resource directory, the sysroot's generic lib/, where a
// its manifest. A toolchain that isn't there is a build error, not // prefix given whole can keep a libstdc++ built for another target,
// an exception: Build() runs this with its worker threads started. // and, when clang finds no gcc directory, an empty entry that would
// name a manifest in the working directory. A toolchain that isn't
// there is a build error, not an exception: Build() runs this with
// the threads of its external dependencies started.
const Toolchain& tc = GetToolchain(); const Toolchain& tc = GetToolchain();
const std::string where = tc.mingwSysroot.empty() const std::string where = tc.mingwPrefix.empty()
? std::string("where clang finds it by the x86_64-w64-mingw32 gcc on PATH") ? std::string("where clang finds it by the x86_64-w64-mingw32 gcc on PATH")
: std::format("under {}", tc.mingwSysroot.string()); : std::format("under {}", tc.mingwPrefix.string());
const std::string missing = std::format("no mingw-w64 libstdc++ with the std module (libstdc++ 15 or newer) {}. Install mingw-w64, or point CRAFTER_MINGW_DIR at its prefix, the directory holding x86_64-w64-mingw32/ and lib/gcc/", where); const std::string missing = std::format("no mingw-w64 libstdc++ with the std module (libstdc++ 15 or newer) {}. Install mingw-w64, or point CRAFTER_MINGW_DIR at its prefix, the directory holding x86_64-w64-mingw32/ and lib/gcc/", where);
// Asked once a run for each compiler and target: every mingw // Asked once a run for each compiler and target: every mingw
// configuration comes through here, up to date or not, and the answer // configuration comes through here, up to date or not, and the answer
@ -775,17 +1086,19 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
} }
} }
if (manifestPath.empty()) return missing; if (manifestPath.empty()) return missing;
// Found through the view MingwSysroot() may have made of the prefix,
// and named from here on by its place in the prefix, the directory
// the user knows and can go and look at.
manifestPath = fs::path(MingwViewToPrefix(manifestPath.string()));
const std::optional<std::string> source = StdModuleSourcePath(FileBytes(manifestPath)); const std::optional<std::string> source = StdModuleSourcePath(FileBytes(manifestPath));
if (!source) return std::format("{} names no std module", manifestPath.string()); if (!source) return std::format("{} names no std module", manifestPath.string());
const fs::path stdCc = (manifestPath.parent_path() / *source).lexically_normal(); const fs::path stdCc = (manifestPath.parent_path() / *source).lexically_normal();
if (!fs::exists(stdCc)) return std::format("{}, which {} names as the std module, is missing", stdCc.string(), manifestPath.string()); if (!fs::exists(stdCc)) return std::format("{}, which {} names as the std module, is missing", stdCc.string(), manifestPath.string());
// -femulated-tls keeps PCM TLS access matching libstdc++'s emutls
// definitions; mismatch surfaces as undefined std::__once_callable.
// The std.cc → std.cppm copy uses a plain filename: held under the // The std.cc → std.cppm copy uses a plain filename: held under the
// cache lock, no other builder writes this path concurrently. // cache lock, no other builder writes this path concurrently.
fs::path stdCppm = stdPcm.parent_path() / "std.cppm"; fs::path stdCppm = stdPcm.parent_path() / "std.cppm";
std::string command = std::format("{} --target={} -march={} -mtune={} -femulated-tls -O3 -std=c++26 -Wno-reserved-identifier -Wno-reserved-module-identifier --precompile {} -o {}", GetBaseCommand(config), config.target, config.march, config.mtune, stdCppm.string(), stdPcm.string()); std::string command = std::format("{}{} --precompile {} -o {}", GetBaseCommand(config), StdPcmFlags(config, GetToolchain()), stdCppm.string(), stdPcm.string());
std::string stamp = HashStamp(command + '\0' + FileBytes(stdCc)); std::string stamp = HashStamp(command + '\0' + FileBytes(stdCc));
if (fs::exists(stdPcm) && ReadStamp(StampPath(stdPcm)) == stamp) return ""; if (fs::exists(stdPcm) && ReadStamp(StampPath(stdPcm)) == stamp) return "";
std::error_code copyEc; std::error_code copyEc;
@ -803,7 +1116,7 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
// <sysroot>/usr/share/libc++/v1/. // <sysroot>/usr/share/libc++/v1/.
std::string stdCppm; std::string stdCppm;
if (isWasm) { if (isWasm) {
stdCppm = std::format("{}/share/libc++/v1/std.cppm", config.sysroot); stdCppm = std::format("{}/share/libc++/v1/std.cppm", config.ResolvedSysroot(GetToolchain()));
} else if (config.sysroot.empty()) { } else if (config.sysroot.empty()) {
stdCppm = GetToolchain().stdCppm.string(); stdCppm = GetToolchain().stdCppm.string();
} else { } else {
@ -815,27 +1128,11 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
if (!source.error.empty()) return source.error; if (!source.error.empty()) return source.error;
stdCppm = source.stdCppm.string(); stdCppm = source.stdCppm.string();
} }
std::string sysrootFlag = config.sysroot.empty()
? std::string()
: std::format(" --sysroot={}", config.sysroot);
// wasm32 rejects -march, and the std module has to be compiled the way
// the units importing it are, a variant pass's flags (e.g.
// -mrelaxed-simd) included, or the BMI is not feature-compatible.
std::string archFlags = isWasm
? WasmCompileFlags(config)
: std::format(" -march={} -mtune={}", config.march, config.mtune);
// non-wasm cross builds: the driver ranks the host toolchain's own
// libc++ headers (<install>/../include/c++/v1) above --sysroot, so
// the PCM would mix host libc++ with the foreign libc — force the
// sysroot's copy.
if (!isWasm && !config.sysroot.empty()) {
archFlags += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1", config.sysroot);
}
// Keyed on the command and the module source's bytes, never on // Keyed on the command and the module source's bytes, never on
// mtimes: an installed std.cppm can be dated at the epoch (OSTree), // mtimes: an installed std.cppm can be dated at the epoch (OSTree),
// and a libc++ update under the same clang changes the bytes but // and a libc++ update under the same clang changes the bytes but
// not the path. // not the path.
std::string command = std::format("{} --target={} -std=c++26{}{} -O3 -Wno-reserved-identifier -Wno-reserved-module-identifier --precompile {} -o {}", GetBaseCommand(config), config.target, sysrootFlag, archFlags, stdCppm, stdPcm.string()); std::string command = std::format("{}{} --precompile {} -o {}", GetBaseCommand(config), StdPcmFlags(config, GetToolchain()), stdCppm, stdPcm.string());
std::string stamp = HashStamp(command + '\0' + FileBytes(stdCppm)); std::string stamp = HashStamp(command + '\0' + FileBytes(stdCppm));
if (fs::exists(stdPcm) && ReadStamp(StampPath(stdPcm)) == stamp) return ""; if (fs::exists(stdPcm) && ReadStamp(StampPath(stdPcm)) == stamp) return "";
std::string result = RunBuildCommand(command); std::string result = RunBuildCommand(command);
@ -862,23 +1159,25 @@ std::string Crafter::GetBaseCommand(const Configuration& config) {
if (config.target == "x86_64-w64-mingw32") { if (config.target == "x86_64-w64-mingw32") {
// libstdc++ from the mingw toolchain, said outright: a clang built to // libstdc++ from the mingw toolchain, said outright: a clang built to
// default to libc++ (the Flatpak's) would otherwise reach for that. // default to libc++ (the Flatpak's) would otherwise reach for that.
// Found by clang's own mingw discovery unless there is a sysroot. // Found by clang's own mingw discovery unless there is a prefix.
command += " -stdlib=libstdc++"; command += " -stdlib=libstdc++";
if (!tc.mingwSysroot.empty()) command += std::format(" --sysroot={}", tc.mingwSysroot.string()); if (const fs::path& sysroot = MingwSysroot(); !sysroot.empty()) command += std::format(" --sysroot={}", sysroot.string());
return command; return command;
} }
command += " -stdlib=libc++"; command += " -stdlib=libc++";
// A sysroot build (wasm, a cross rootfs) takes libc++ from the sysroot; // A sysroot build (wasm, a cross rootfs) takes libc++ from the sysroot;
// only host builds can be pointed at an explicit libc++ install. // only host builds can be pointed at an explicit libc++ install.
if (config.sysroot.empty()) command += tc.LibcxxCompileFlags(); if (config.ResolvedSysroot(tc).empty()) command += tc.LibcxxCompileFlags();
return command; return command;
} }
namespace { namespace {
constexpr std::array<std::string_view, 14> CrafterBuildModules = { constexpr std::array<std::string_view, 16> CrafterBuildModules = {
"Crafter.Build-Toolchain", "Crafter.Build-Toolchain",
"Crafter.Build-Shader", "Crafter.Build-Shader",
"Crafter.Build-Platform", "Crafter.Build-Platform",
"Crafter.Build-Flatpak",
"Crafter.Build-Jobs",
"Crafter.Build-Interface", "Crafter.Build-Interface",
"Crafter.Build-Implementation", "Crafter.Build-Implementation",
"Crafter.Build-External", "Crafter.Build-External",
@ -932,10 +1231,32 @@ namespace {
} }
} }
Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const std::string_view> args) { namespace {
RequireToolchain(); using ProjectFn = Configuration (*)(std::span<const std::string_view>);
fs::path absProject = fs::canonical(projectFile); using ConfigurationsFn = std::vector<Configuration*> (*)(std::span<const std::string_view>);
ProjectFileGuard guard(absProject);
// 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"; fs::path buildDir = absProject.parent_path() / "build";
if (!fs::exists(buildDir)) { if (!fs::exists(buildDir)) {
fs::create_directories(buildDir); fs::create_directories(buildDir);
@ -1019,11 +1340,20 @@ Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const
throw std::runtime_error(std::format("Failed to load project {}: {}", soPath.string(), dlerror())); throw std::runtime_error(std::format("Failed to load project {}: {}", soPath.string(), dlerror()));
} }
using ProjectFn = Configuration (*)(std::span<const std::string_view>); // Looked up in project.so and the libraries it links, which is where
dlerror(); // dlsym searches for a handle: every project file this process has
auto fn = reinterpret_cast<ProjectFn>(dlsym(handle, "CrafterBuildProject")); // loaded exports an entry point under one of these two names, and none
if (const char* err = dlerror()) { // of the others is found here.
throw std::runtime_error(std::format("CrafterBuildProject not found in {}: {}", soPath.string(), err)); 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 // The args only for the call itself, unlike the dependencies. A static
@ -1033,5 +1363,67 @@ Configuration Crafter::LoadProject(const fs::path& projectFile, std::span<const
// Now it gets none, whichever load ran it. The pragma pre-pass above // 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. // also ran on this frame and relies on the args not being there yet.
guard.Frame().args = args; 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;
} }

View file

@ -11,11 +11,18 @@ namespace fs = std::filesystem;
using namespace Crafter; using namespace Crafter;
namespace { 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; std::string out;
for (const Script& script : scripts) { for (const Declared& declared : scripts) {
if (!out.empty()) out += ", "; if (!out.empty()) out += ", ";
out += script.name; out += declared.script->name;
} }
return out; 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::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. // Loading the project may have left an in-place status line behind.
Progress::Clear(); 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()) { if (scripts.empty()) {
std::println(std::cerr, std::println(std::cerr,
R"msg(No scripts defined. 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 // declaration is reported the first time anyone uses `run` and not only
// when that one name is asked for. // when that one name is asked for.
std::unordered_set<std::string_view> seen; 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('-')) { 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); std::println(std::cerr, "script name '{}' cannot be run: a name must not be empty or start with '-'", script.name);
return 1; return 1;
@ -69,36 +89,37 @@ returned; ctx.args holds the arguments.)msg");
} }
if (opts.listOnly || !opts.named) { 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; 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()) { if (found == scripts.end()) {
std::println(std::cerr, "No script named '{}'. Scripts: {}", opts.name, JoinNames(scripts)); std::println(std::cerr, "No script named '{}'. Scripts: {}", opts.name, JoinNames(scripts));
return 1; return 1;
} }
const Script& script = *found->script;
ScriptContext ctx{ ScriptContext ctx{
.project = projectCfg, .project = *found->owner,
// lexically_normal: fs::absolute keeps a "./" component. // 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, .args = opts.args,
}; };
try { try {
const std::int32_t code = found->run(ctx); const std::int32_t code = script.run(ctx);
if (code >= 0 && code <= 255) return code; 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; return 1;
} catch (const std::exception& e) { } catch (const std::exception& e) {
// Never let a script's exception unwind across the project.so // Never let a script's exception unwind across the project.so
// boundary and out of Run: report it as this script's failure. // boundary and out of Run: report it as this script's failure.
Progress::Clear(); Progress::Clear();
std::println(std::cerr, "script '{}' failed: {}", found->name, e.what()); std::println(std::cerr, "script '{}' failed: {}", script.name, e.what());
return 1; return 1;
} catch (...) { } catch (...) {
Progress::Clear(); 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; return 1;
} }
} }

View file

@ -16,11 +16,6 @@ namespace {
return target.find("windows") != std::string_view::npos || target.find("mingw") != std::string_view::npos; return target.find("windows") != std::string_view::npos || target.find("mingw") != std::string_view::npos;
} }
fs::path TestBinaryPath(const Configuration& cfg) {
fs::path outputDir = cfg.BinDir();
return outputDir / (TargetIsWindows(cfg.target) ? std::format("{}.exe", cfg.outputName) : cfg.outputName);
}
// MatchGlob/MatchAny live in :Platform — shared with the lint verb. // MatchGlob/MatchAny live in :Platform — shared with the lint verb.
std::string JoinAndQuoteArgs(std::span<const std::string> args) { std::string JoinAndQuoteArgs(std::span<const std::string> args) {
@ -69,12 +64,78 @@ namespace {
} }
} }
void WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) { // Writes build/test-logs/<name>.log and returns its path, or nothing
// when the directory cannot be made.
std::optional<fs::path> WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) {
fs::path logDir = projectPath / "build" / "test-logs"; fs::path logDir = projectPath / "build" / "test-logs";
std::error_code ec; std::error_code ec;
fs::create_directories(logDir, ec); fs::create_directories(logDir, ec);
if (ec) return; if (ec) return std::nullopt;
std::ofstream(logDir / (std::format("{}.log", name))) << output; const fs::path log = logDir / std::format("{}.log", name);
std::ofstream(log) << output;
return log;
}
// weston on its headless backend: the compositor a test that sets
// Test::wayland runs with unless --compositor= or CRAFTER_BUILD_COMPOSITOR
// names another. Its GL renderer takes the dmabufs that hardware Vulkan
// and EGL drivers present, which the headless backend's default, a
// renderer that draws nothing, and pixman do not. --no-config keeps the
// user's weston.ini out of the test, and --idle-time=0 keeps the output
// from going idle after the default 300 s, which would stop frame
// callbacks.
constexpr std::string_view DefaultCompositor = "weston --backend=headless --renderer=gl --no-config --idle-time=0";
// The compositor named for none of the test's own: the test gets the
// display crafter-build has, to watch its windows, and the TMPDIR it is
// given, as any test does.
constexpr std::string_view HostDisplay = "host";
// How long a compositor may take to listen. weston needs a fraction of a
// second; this is for a machine running a test on every hardware thread.
constexpr std::chrono::seconds CompositorStartup{30};
std::string CompositorCommand(const std::optional<std::string>& compositorOverride) {
if (compositorOverride && !compositorOverride->empty()) return *compositorOverride;
const char* named = std::getenv("CRAFTER_BUILD_COMPOSITOR");
if (named != nullptr && *named != '\0') return named;
return std::string(DefaultCompositor);
}
// The wayland-<n> socket a compositor made in `directory`. Any number:
// libwayland's wl_display_add_socket_auto starts at 0 and weston at 1.
std::optional<fs::path> WaylandSocket(const fs::path& directory) {
constexpr std::string_view prefix = "wayland-";
std::error_code ec;
for (const fs::directory_entry& entry : fs::directory_iterator(directory, ec)) {
const std::string name = entry.path().filename().string();
if (!name.starts_with(prefix) || name.size() == prefix.size()) continue;
if (!std::ranges::all_of(name.substr(prefix.size()), [](char c) { return c >= '0' && c <= '9'; })) continue;
std::error_code statError;
if (fs::is_socket(entry.symlink_status(statError))) return entry.path();
}
return std::nullopt;
}
// Where the directory one test's compositor gets as its XDG_RUNTIME_DIR
// is made: in $XDG_RUNTIME_DIR, where a session's sockets live, when
// that is a directory, else in /tmp. A socket's path holds at most 107
// bytes, so the directory needs a short path, which a project's, a
// scratch directory's or the temp directory TMPDIR names need not be.
fs::path CompositorParent() {
const char* runtime = std::getenv("XDG_RUNTIME_DIR");
std::error_code ec;
if (runtime != nullptr && *runtime != '\0' && fs::is_directory(runtime, ec)) return runtime;
return "/tmp";
}
// That directory, which also holds the compositor's log.
struct CompositorDirectory : PrivateDirectory {
CompositorDirectory() : PrivateDirectory(CompositorParent(), "crafter-build-wayland-") {}
fs::path Log() const { return path / "compositor.log"; }
};
std::string ReadWhole(const fs::path& file) {
std::ifstream in(file, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
} }
void PrintResult(const TestResult& r, std::string_view runnerName) { void PrintResult(const TestResult& r, std::string_view runnerName) {
@ -116,7 +177,8 @@ namespace {
} }
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) { Configuration* FindLibInTree(Configuration* root, std::string_view name, std::unordered_set<Configuration*>& seen) {
if (!seen.insert(root).second) return nullptr; if (!seen.insert(root).second) return nullptr;
@ -129,17 +191,31 @@ namespace {
} }
void Crafter::SetParentProject(Configuration* parent) { 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* Crafter::ParentLib(std::string_view name) {
Configuration* root = ParentProject.load(); std::vector<Configuration*> roots;
if (!root) { {
const std::lock_guard lock(ParentProjectsMutex);
roots = ParentProjects;
}
if (roots.empty()) {
throw std::runtime_error(std::format("Crafter::ParentLib('{}'): no parent project set", name)); throw std::runtime_error(std::format("Crafter::ParentLib('{}'): no parent project set", name));
} }
std::unordered_set<Configuration*> seen; std::unordered_set<Configuration*> seen;
std::string names;
for (Configuration* root : roots) {
if (auto found = FindLibInTree(root, name, seen)) return found; 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)); 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() { TestRunner TestRunner::Local() {
@ -249,27 +325,91 @@ TestRunner TestRunner::FromEnv(std::string_view target, TestRunner fallback) {
return fallback; return fallback;
} }
TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout) { TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout, const std::optional<std::string>& compositorOverride, const fs::path& temporaryDirectory) {
TestResult result; TestResult result;
result.name = test.config.name; result.name = test.config.name;
std::map<std::string, std::string> ph; std::map<std::string, std::string> ph;
ph["{args}"] = JoinAndQuoteArgs(test.args); ph["{args}"] = JoinAndQuoteArgs(test.args);
auto start = std::chrono::steady_clock::now(); std::string cmd;
CommandResult r;
if (test.runner.exec.empty()) { if (test.runner.exec.empty()) {
// Local runner: spawn the binary directly through the host shell. // Local runner: spawn the binary directly through the host shell.
std::string cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]); cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]);
r = RunCommandWithTimeout(cmd, timeout);
} else { } else {
// Prefix runner (qemu-user, wasmtime, wine, ...): templated exec // Prefix runner (qemu-user, wasmtime, wine, ...): templated exec
// wraps the local binary. // wraps the local binary.
ph["{bin}"] = binary.string(); ph["{bin}"] = binary.string();
r = RunCommandWithTimeout(Substitute(test.runner.exec, ph), timeout); cmd = Substitute(test.runner.exec, ph);
} }
// What `env` changes for the test, its -u options and its assignments,
// which it takes in that order.
std::string unset;
std::string set;
if (!temporaryDirectory.empty()) set += std::format(" TMPDIR={}", ShellQuote(temporaryDirectory.string()));
// The test's own compositor, which no other test shares, so that no
// two tests cover each other's windows or take each other's focus. Its
// directory goes after it: declared first, it is destroyed last.
const std::string compositor = test.wayland ? CompositorCommand(compositorOverride) : std::string();
std::optional<CompositorDirectory> directory;
std::optional<BackgroundCommand> process;
if (test.wayland && compositor != HostDisplay) {
directory.emplace();
// Without a WAYLAND_DISPLAY, which the compositor would take for a
// session to open a window in (wlroots does), or a DISPLAY.
const std::array<EnvironmentChange, 4> environment = {{
{"XDG_RUNTIME_DIR", directory->path.string()},
{"WAYLAND_DISPLAY", std::nullopt},
{"WAYLAND_SOCKET", std::nullopt},
{"DISPLAY", std::nullopt},
}};
// As long as the test may run, the wait for its socket and 30 s
// more; none for a test with none, a timeout of 0, which timeout(1)
// takes for no limit, the test's as the compositor's.
const std::chrono::seconds lifetime = timeout.count() > 0 ? timeout + CompositorStartup + std::chrono::seconds(30) : std::chrono::seconds(0);
process.emplace(compositor, environment, directory->Log(), lifetime);
// weston makes its socket once its backend and renderer are up, so a
// socket means a compositor that takes clients.
const auto deadline = std::chrono::steady_clock::now() + CompositorStartup;
std::optional<fs::path> socket = WaylandSocket(directory->path);
std::optional<std::int32_t> ended;
while (!socket && !(ended = process->Exited()) && std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
socket = WaylandSocket(directory->path);
}
if (!socket) {
process->Stop(std::chrono::seconds(5));
std::string printed = ReadWhole(directory->Log());
if (!printed.empty() && !printed.ends_with('\n')) printed.push_back('\n');
// A compositor that is missing fails the test as any other that
// does not start does. The one skip is the test's own requires_,
// tool:weston for the default, which RunTests checks before the
// build; a probe of the command here would not do, since it is any
// sh command, whose first word need not be the compositor.
result.outcome = TestOutcome::Fail;
result.exitCode = -1;
result.output = ended
? std::format("the headless compositor ({}) ended with status {} before it listened for clients; it printed:\n{}", compositor, *ended, printed)
: std::format("the headless compositor ({}) made no wayland-<n> socket in {} within {} s; it printed:\n{}", compositor, directory->path.string(), CompositorStartup.count(), printed);
// sh's status for a command it cannot find.
if (ended == 127) result.output += "install weston, name another compositor with CRAFTER_BUILD_COMPOSITOR or --compositor=, or skip a test that may run without it with requires_, tool:weston for weston\n";
return result;
}
unset += " -u DISPLAY -u WAYLAND_SOCKET";
set += std::format(" WAYLAND_DISPLAY={}", ShellQuote(socket->string()));
}
// env's command is sh, which execs the test's words as they are: env
// takes every word with an '=' in it ahead of its command for an
// assignment, the binary's path among them where it has one (a test
// named a=b), and with no command left it printed its environment and
// exited 0, a pass for a test that never ran.
if (!unset.empty() || !set.empty()) cmd = std::format("env{}{} sh -c 'exec \"$@\"' sh {}", unset, set, cmd);
auto start = std::chrono::steady_clock::now();
CommandResult r = RunCommandWithTimeout(cmd, timeout);
auto end = std::chrono::steady_clock::now(); auto end = std::chrono::steady_clock::now();
result.duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); result.duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
result.output = std::move(r.output); result.output = std::move(r.output);
@ -282,6 +422,19 @@ TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std:
else if (r.exitCode != 0) result.outcome = TestOutcome::Fail; else if (r.exitCode != 0) result.outcome = TestOutcome::Fail;
else result.outcome = TestOutcome::Pass; else result.outcome = TestOutcome::Pass;
if (process) {
// Asked before Stop() ends it, which would make every compositor one
// that ended.
const std::optional<std::int32_t> ended = process->Exited();
process->Stop(std::chrono::seconds(5));
if (result.outcome != TestOutcome::Pass && result.outcome != TestOutcome::Skipped) {
if (ended) {
if (!result.output.empty() && !result.output.ends_with('\n')) result.output.push_back('\n');
result.output += std::format("the headless compositor ({}) ended with status {} while the test ran\n", compositor, *ended);
}
result.compositorLog = ReadWhole(directory->Log());
}
}
return result; return result;
} }
@ -375,6 +528,7 @@ TestBuilder Configuration::AddTest(std::string_view name, std::span<fs::path> in
t.config.mtune = this->mtune; t.config.mtune = this->mtune;
t.config.sysroot = this->sysroot; t.config.sysroot = this->sysroot;
t.config.debug = this->debug; t.config.debug = this->debug;
t.config.cudaArch = this->cudaArch;
// Inherited so a project flag that changes what the library contains also // Inherited so a project flag that changes what the library contains also
// moves the test's own outputs, rather than letting two flag settings share // moves the test's own outputs, rather than letting two flag settings share
// one test bin dir. // one test bin dir.
@ -403,6 +557,7 @@ void Configuration::AddMarchVariants(std::string_view name, std::span<fs::path>
t.config.mtune = tier.mtune; t.config.mtune = tier.mtune;
t.config.sysroot = this->sysroot; t.config.sysroot = this->sysroot;
t.config.debug = this->debug; t.config.debug = this->debug;
t.config.cudaArch = this->cudaArch;
t.config.projectArgs = this->projectArgs; t.config.projectArgs = this->projectArgs;
t.config.type = ConfigurationType::Executable; t.config.type = ConfigurationType::Executable;
@ -432,24 +587,48 @@ TestBuilder& TestBuilder::Define(std::string n, std::string v) {
TestBuilder& TestBuilder::Timeout(std::chrono::seconds s) { Ref().timeout = s; return *this; } TestBuilder& TestBuilder::Timeout(std::chrono::seconds s) { Ref().timeout = s; return *this; }
TestBuilder& TestBuilder::Args(std::vector<std::string> a) { Ref().args = std::move(a); return *this; } TestBuilder& TestBuilder::Args(std::vector<std::string> a) { Ref().args = std::move(a); return *this; }
TestBuilder& TestBuilder::Requires(std::string r) { Ref().requires_.push_back(std::move(r)); return *this; } TestBuilder& TestBuilder::Requires(std::string r) { Ref().requires_.push_back(std::move(r)); return *this; }
TestBuilder& TestBuilder::Dependencies(std::vector<Configuration*> d) { TestBuilder& TestBuilder::Dependencies(std::vector<Configuration*> d) { Ref().config.dependencies = std::move(d); return *this; }
Ref().config.dependencies = std::move(d);
// AddTest already scanned tests/<name>/main.cpp, at which point this test
// had no dependencies, so every `import <DepModule>;` in it came back
// unresolved. Place them now that the libraries are known — without this
// the test's object carries no staleness edge to the interfaces it consumes
// and survives a layout change to them (issue #27). Build() re-runs the
// same sweep as a backstop; doing it here keeps the Configuration coherent
// for anyone inspecting it before the build.
Ref().config.ResolvePendingImports();
return *this;
}
TestBuilder& TestBuilder::LinkFlag(std::string f) { Ref().config.linkFlags.push_back(std::move(f)); return *this; } TestBuilder& TestBuilder::LinkFlag(std::string f) { Ref().config.linkFlags.push_back(std::move(f)); return *this; }
TestBuilder& TestBuilder::CompileFlag(std::string f) { Ref().config.compileFlags.push_back(std::move(f)); return *this; } TestBuilder& TestBuilder::CompileFlag(std::string f) { Ref().config.compileFlags.push_back(std::move(f)); return *this; }
TestBuilder& TestBuilder::Wayland(bool w) { Ref().wayland = w; return *this; }
void Crafter::UnpackageTests(Configuration& cfg) {
for (Test& test : cfg.tests) test.config.packaging = Packaging::None;
}
TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) { TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
std::array<Configuration*, 1> one = { &projectCfg };
return RunTests(std::span<Configuration* const>(one), opts, projectArgs);
}
namespace {
// The directory of one run of `crafter-build test`, in the temp
// directory, which each test's TMPDIR is made in, and the names given
// out in it. Every pass of a sweep over targets shares it: the first
// that runs a test makes it, and RunTests lets go of it once the last
// pass is done. A pass that made one of its own made it once the
// passes before had let go of theirs, and making it removed any of
// those that had not changed for a minute: a kept one after a pass
// that long, while its test's output said where it was kept.
struct RunTemporaries {
std::optional<PrivateDirectory> directory;
std::set<std::string> used;
};
}
// RunTests, with the run's temporaries.
static TestSummary RunTestsWith(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs, RunTemporaries& run) {
// 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 RunTestsWith(distinct, opts, projectArgs, run);
for (Configuration* cfg : configurations) UnpackageTests(*cfg);
// Multi-target sweep: when no --target= was given, the run covers every // 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 // Lets a bare `crafter-build test` exercise cross-arch tests without the
// user having to know which targets exist. An explicit --target=X // user having to know which targets exist. An explicit --target=X
// bypasses the sweep and runs that target only. // bypasses the sweep and runs that target only.
@ -459,9 +638,11 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
// the one shown and filtered on. // the one shown and filtered on.
std::map<std::string, std::string> sweep; std::map<std::string, std::string> sweep;
sweep.emplace(NormalizeTarget(HostTarget()), HostTarget()); sweep.emplace(NormalizeTarget(HostTarget()), HostTarget());
for (const Test& t : projectCfg.tests) { 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); if (!t.config.target.empty()) sweep.emplace(NormalizeTarget(t.config.target), t.config.target);
} }
}
TestSummary aggregate; TestSummary aggregate;
for (const auto& [normalized, target] : sweep) { for (const auto& [normalized, target] : sweep) {
RunTestsOptions perTarget = opts; RunTestsOptions perTarget = opts;
@ -470,7 +651,7 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
Progress::Clear(); Progress::Clear();
std::println("\n=== target: {} ===", target); std::println("\n=== target: {} ===", target);
} }
TestSummary s = RunTests(projectCfg, perTarget, projectArgs); TestSummary s = RunTestsWith(configurations, perTarget, projectArgs, run);
aggregate.passed += s.passed; aggregate.passed += s.passed;
aggregate.failed += s.failed; aggregate.failed += s.failed;
aggregate.crashed += s.crashed; aggregate.crashed += s.crashed;
@ -488,8 +669,11 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
// time) because runnerOverride and FromEnv resolution depend on the // time) because runnerOverride and FromEnv resolution depend on the
// run's options, which the project.cpp doesn't know about. // run's options, which the project.cpp doesn't know about.
std::vector<Test*> filtered; std::vector<Test*> filtered;
filtered.reserve(projectCfg.tests.size()); // The configuration that declares each of them, whose path its log is
for (auto& test : projectCfg.tests) { // 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 (!SameTarget(test.config.target, opts.targetFilter)) continue;
if (!MatchAny(opts.globs, test.config.name)) continue; if (!MatchAny(opts.globs, test.config.name)) continue;
test.runner = TestRunner::FromEnv(test.config.target, TestRunner::ForTarget(test.config)); test.runner = TestRunner::FromEnv(test.config.target, TestRunner::ForTarget(test.config));
@ -499,6 +683,8 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
} }
} }
filtered.push_back(&test); filtered.push_back(&test);
owners.push_back(cfg);
}
} }
if (opts.listOnly) { if (opts.listOnly) {
@ -513,6 +699,60 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
return summary; 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());
}
}
}
// Each test runs with TMPDIR naming a directory of its own, <run>/<name>,
// in the run's directory in the temp directory (RunTemporaries), so that
// fs::temp_directory_path() in the test names it, where its runner hands
// it TMPDIR (RunSingleTest). Tests stage their fixtures under
// fixed names in it (crafter-build-<name>), and two runs at once staged
// into the same ones: natively every process shares the machine's
// /tmp, and every sandbox of crafter-build's Flatpak shares the one the
// app has. A second test of one name in the run, as two configurations
// or two targets may each have one, gets <name>-2. What a test that
// passes or skips leaves there is removed when it ends; what one that
// fails, crashes or times out leaves is kept, its output says where, and
// so is the run's directory, for a later run to remove a minute after
// this one ends, or after its last change to it where this one is
// killed (PrivateDirectory::Keep).
if (!run.directory) run.directory.emplace(fs::temp_directory_path(), "crafter-build-tests-");
std::vector<fs::path> temporary(filtered.size());
for (std::size_t i = 0; i < filtered.size(); ++i) {
std::string name = filtered[i]->config.name;
for (std::int32_t n = 2; !run.used.insert(name).second; ++n) name = std::format("{}-{}", filtered[i]->config.name, n);
temporary[i] = run.directory->path / name;
}
std::int32_t jobs = opts.jobs > 0 std::int32_t jobs = opts.jobs > 0
? opts.jobs ? opts.jobs
: std::max(1u, std::thread::hardware_concurrency()); : std::max(1u, std::thread::hardware_concurrency());
@ -547,6 +787,18 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
TestResult r; TestResult r;
r.name = t.config.name; 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 // Declarative preconditions set via TestBuilder::Requires. Evaluated
// before the build so a missing tool/file/env turns into a Skip without // 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 // paying the compile cost. Reports the first failure only — once one
@ -615,17 +867,53 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
} }
std::chrono::seconds timeout = opts.timeoutOverride.value_or(t.timeout); std::chrono::seconds timeout = opts.timeoutOverride.value_or(t.timeout);
fs::path binary = TestBinaryPath(t.config); // The file the link wrote, by the rule the staleness checks and -r
// use, which for a wasm32 executable is the <name>.wasm the link
// writes. A rule of its own here once added .exe for any Windows
// triple and nothing for wasm, so every wasm test was handed to
// wasmtime without the .wasm it was linked as.
fs::path binary = ExpectedOutput(t.config);
std::error_code temporaryError;
fs::create_directories(temporary[i], temporaryError);
try { try {
r = RunSingleTest(t, binary, timeout); if (temporaryError) throw std::runtime_error(std::format("cannot make the test's TMPDIR {}: {}", temporary[i].string(), temporaryError.message()));
r = RunSingleTest(t, binary, timeout, opts.compositorOverride, temporary[i]);
} catch (const std::exception& e) { } catch (const std::exception& e) {
r.outcome = TestOutcome::Fail; r.outcome = TestOutcome::Fail;
r.output = std::format("runner threw: {}", e.what()); r.output = std::format("runner threw: {}", e.what());
r.exitCode = -1; r.exitCode = -1;
} }
// The logs are named as the test's TMPDIR is, <name>-2 for a later
// test of one name in the run, so that each has its own: with one
// for both, the second's was written over the first's, and with it
// where what the first left is kept.
const std::string logName = temporary[i].filename().string();
// Beside the test's own log rather than in it: weston prints some
// 70 lines starting up, which would bury what the test said.
if (!r.compositorLog.empty()) {
if (const std::optional<fs::path> log = WriteLog(owners[i]->path, std::format("{}.compositor", logName), r.compositorLog)) {
if (!r.output.empty() && !r.output.ends_with('\n')) r.output.push_back('\n');
r.output += std::format("the headless compositor's output is in {}\n", log->string());
}
}
if (!temporaryError) {
std::error_code ec;
const bool failed = r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped;
if (failed && !fs::is_empty(temporary[i], ec) && !ec) {
// Kept at once, so that it stays whatever ends the run:
// a later pass that throws, as one does for a target whose
// runner CRAFTER_BUILD_RUNNER_ gives wrong, or a worker
// that cannot be started unwinds past the end of RunTests.
run.directory->Keep();
if (!r.output.empty() && !r.output.ends_with('\n')) r.output.push_back('\n');
r.output += std::format("what it left in its TMPDIR is kept in {}\n", temporary[i].string());
} else {
fs::remove_all(temporary[i], ec);
}
}
if (r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped && !r.output.empty()) { if (r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped && !r.output.empty()) {
WriteLog(projectCfg.path, r.name, r.output); WriteLog(owners[i]->path, logName, r.output);
} }
{ {
@ -671,3 +959,8 @@ TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions&
return summary; return summary;
} }
TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
RunTemporaries run;
return RunTestsWith(configurations, opts, projectArgs, run);
}

View file

@ -21,9 +21,42 @@ namespace {
"CRAFTER_BUILD_LIBCXX_DIR", "CRAFTER_BUILD_LIBCXX_DIR",
"CRAFTER_BUILD_LIBCLANG", "CRAFTER_BUILD_LIBCLANG",
"CRAFTER_BUILD_WASI_SYSROOT", "CRAFTER_BUILD_WASI_SYSROOT",
"CRAFTER_BUILD_FLATPAK_INFO",
"CRAFTER_MINGW_DIR", "CRAFTER_MINGW_DIR",
"CUDA_PATH",
"PATH",
}; };
// The arch and branch of the runtime=runtime/<id>/<arch>/<branch> line
// in the [Application] group of a .flatpak-info; empty when it has none.
std::pair<std::string, std::string> FlatpakRuntimeOf(std::string_view info) {
bool inApplication = false;
for (std::size_t begin = 0; begin < info.size();) {
std::size_t end = info.find('\n', begin);
if (end == std::string_view::npos) end = info.size();
std::string_view line = info.substr(begin, end - begin);
begin = end + 1;
if (line.ends_with('\r')) line.remove_suffix(1);
if (line.starts_with("[")) {
inApplication = line == "[Application]";
continue;
}
if (!inApplication || !line.starts_with("runtime=")) continue;
std::vector<std::string_view> parts;
std::string_view ref = line.substr(std::string_view("runtime=").size());
for (std::size_t at = 0;;) {
const std::size_t slash = ref.find('/', at);
parts.push_back(ref.substr(at, slash == std::string_view::npos ? std::string_view::npos : slash - at));
if (slash == std::string_view::npos) break;
at = slash + 1;
}
if (parts.size() == 4 && parts[0] == "runtime" && !parts[2].empty() && !parts[3].empty()) {
return {std::string(parts[2]), std::string(parts[3])};
}
}
return {};
}
std::string_view Env(const ToolchainInputs& in, std::string_view name) { std::string_view Env(const ToolchainInputs& in, std::string_view name) {
auto it = in.env.find(name); auto it = in.env.find(name);
return it == in.env.end() ? std::string_view{} : std::string_view(it->second); return it == in.env.end() ? std::string_view{} : std::string_view(it->second);
@ -43,6 +76,97 @@ namespace {
while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ')) s.pop_back(); while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ')) s.pop_back();
return s; return s;
} }
// `link` made a symbolic link to `target`, or found one already. Another
// crafter-build may make the same link at the same moment, which is as
// good as making it; a link to anything else is an error.
void EnsureSymlink(const fs::path& target, const fs::path& link) {
std::error_code ec;
if (fs::read_symlink(link, ec) == target) return;
fs::create_directories(link.parent_path());
fs::create_directory_symlink(target, link, ec);
std::error_code ignored;
if (ec && fs::read_symlink(link, ignored) != target) {
throw fs::filesystem_error("cannot make a link", target, link, ec);
}
}
// `dir` made absolute and spelled one way, once, when the toolchain is
// resolved. The mingw prefix ends up as the target of links and in the
// names of build and cache directories: a relative path read later from
// another working directory would name something else, and /opt/mingw/
// next to /opt/mingw would rebuild everything for the same directory.
fs::path PrefixPath(const fs::path& dir) {
fs::path normal = fs::absolute(dir).lexically_normal();
if (!normal.has_filename() && normal.has_relative_path()) normal = normal.parent_path();
return normal;
}
// A regular file someone may run, as the shell's PATH lookup wants one.
bool IsProgram(const fs::path& file) {
std::error_code ec;
if (!fs::is_regular_file(file, ec)) return false;
constexpr fs::perms Exec = fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec;
return (fs::status(file, ec).permissions() & Exec) != fs::perms::none;
}
// `path`, as the host names it, where this process finds it. A sandbox
// shows the host's /usr and /etc, and the directories beside them its
// own runtime has (bin, sbin, lib, lib64), under hostRoot, and
// everything else, /opt and /home among it, where the host has it. A
// link to an absolute path names the host's path wherever the link is,
// and the sandbox would look it up in its own root instead: NVIDIA's
// /usr/local/cuda is a link, to /usr/local/cuda-<version> or through
// /etc/alternatives, and an /opt/cuda can be one to such a directory.
// So where the path is a link, it is followed here, and so is its
// target where that is one, each taken as the host's. Outside a
// sandbox, `path` itself.
fs::path HostPath(fs::path path, const fs::path& hostRoot) {
if (hostRoot.empty()) return path;
fs::path shown = path;
// As many links as the kernel follows before it gives up on a loop.
for (std::int32_t hops = 0; hops < 40; ++hops) {
if (!path.is_absolute()) return path;
// Without a trailing separator, which has readlink follow the
// link instead of reading it.
path = path.lexically_normal();
if (!path.has_filename() && path.has_relative_path()) path = path.parent_path();
const fs::path relative = path.relative_path();
const fs::path top = relative.empty() ? fs::path() : *relative.begin();
const bool underHostRoot = top == "usr" || top == "etc" || top == "bin" || top == "sbin" || top == "lib" || top == "lib64";
shown = underHostRoot ? hostRoot / relative : path;
std::error_code ec;
const fs::path target = fs::read_symlink(shown, ec);
if (ec) return shown;
path = target.is_absolute() ? target : (path.parent_path() / target).lexically_normal();
}
// Still a link after all of them: a loop, which opens as nothing.
return shown;
}
// The view MingwSysroot() made and the prefix it shows, for
// MingwViewToPrefix. Written once, before ViewMade is set.
fs::path MadeView;
fs::path ViewedPrefix;
std::atomic<bool> ViewMade = false;
}
fs::path Toolchain::InstalledClangxx(std::string_view command) const {
// Every word of the command, as clang's driver.cpp reads its arguments
// before it names its own path; the build quotes neither flag.
bool canonical = true;
for (std::size_t at = 0; at < command.size();) {
const std::size_t end = std::min(command.find(' ', at), command.size());
const std::string_view word = command.substr(at, end - at);
if (word == "-canonical-prefixes") {
canonical = true;
} else if (word == "-no-canonical-prefixes") {
canonical = false;
}
at = end + 1;
}
const fs::path& dir = canonical ? installedDir : installedDirAsWritten;
return dir.empty() ? clangxx : dir / clangxx.filename();
} }
std::string Toolchain::LibcxxCompileFlags() const { std::string Toolchain::LibcxxCompileFlags() const {
@ -50,20 +174,27 @@ std::string Toolchain::LibcxxCompileFlags() const {
return std::format(" -nostdinc++ -isystem {}", (libcxxDir / "include" / "c++" / "v1").string()); return std::format(" -nostdinc++ -isystem {}", (libcxxDir / "include" / "c++" / "v1").string());
} }
std::string Toolchain::LibcxxLinkFlags() const {
// clang searches its per-target runtime directory and the system library // clang searches its per-target runtime directory and the system library
// paths for -lc++, not <prefix>/lib, so a toolchain outside /usr with the // paths for -lc++, not <prefix>/lib, so a toolchain outside /usr with the
// classic layout needs the search path as well as the run-time path. // classic layout needs the search path as well as the run-time path.
fs::path lib; fs::path Toolchain::LibcxxLibDir() const {
if (!libcxxDir.empty()) { if (!libcxxDir.empty()) return libcxxDir / "lib";
lib = libcxxDir / "lib"; if (!prefix.empty() && prefix != "/usr") return prefix / "lib";
} else if (!prefix.empty() && prefix != "/usr") { return {};
lib = prefix / "lib";
} }
std::string Toolchain::LibcxxLinkFlags() const {
const fs::path lib = LibcxxLibDir();
if (lib.empty()) return {}; if (lib.empty()) return {};
return std::format(" -L{} -Wl,-rpath,{}", lib.string(), lib.string()); return std::format(" -L{} -Wl,-rpath,{}", lib.string(), lib.string());
} }
std::string Toolchain::LibcxxSearchFlags() const {
const fs::path lib = LibcxxLibDir();
if (lib.empty()) return {};
return std::format(" -L{}", lib.string());
}
std::string Toolchain::Key() const { std::string Toolchain::Key() const {
std::string identity; std::string identity;
for (const std::string& part : {clangxx.string(), clangVersion, libcxxDir.string(), stdCppm.string()}) { for (const std::string& part : {clangxx.string(), clangVersion, libcxxDir.string(), stdCppm.string()}) {
@ -93,10 +224,14 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) {
tc.clangxx = "clang++"; tc.clangxx = "clang++";
tc.clang = "clang"; tc.clang = "clang";
tc.llvmAr = "llvm-ar"; tc.llvmAr = "llvm-ar";
tc.llvmReadelf = "llvm-readelf";
tc.clangScanDeps = "clang-scan-deps";
} else { } else {
tc.clangxx = tc.prefix / "bin" / "clang++"; tc.clangxx = tc.prefix / "bin" / "clang++";
tc.clang = tc.prefix / "bin" / "clang"; tc.clang = tc.prefix / "bin" / "clang";
tc.llvmAr = tc.prefix / "bin" / "llvm-ar"; tc.llvmAr = tc.prefix / "bin" / "llvm-ar";
tc.llvmReadelf = tc.prefix / "bin" / "llvm-readelf";
tc.clangScanDeps = tc.prefix / "bin" / "clang-scan-deps";
if (tc.prefix != "/usr" && fs::exists(tc.prefix / "include" / "clang-c" / "Index.h")) { if (tc.prefix != "/usr" && fs::exists(tc.prefix / "include" / "clang-c" / "Index.h")) {
tc.llvmIncludeDir = tc.prefix / "include"; tc.llvmIncludeDir = tc.prefix / "include";
} }
@ -136,12 +271,112 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) {
tc.wasiSysroot = "/usr/share/wasi-sysroot"; tc.wasiSysroot = "/usr/share/wasi-sysroot";
} }
if (std::string_view dir = Env(in, "CRAFTER_MINGW_DIR"); !dir.empty()) { if (std::string_view dir = Env(in, "CRAFTER_MINGW_DIR"); !dir.empty()) {
tc.mingwSysroot = fs::path(dir); tc.mingwPrefix = PrefixPath(fs::path(dir));
// A prefix that holds a Linux system as well as mingw-w64, /usr
// itself, has that system's C library in include/: features.h, which
// every glibc and musl header includes and mingw-w64 has no use for.
// One that holds mingw-w64 alone stays the sysroot, so Windows
// libraries installed into its include/ and lib/ stay visible.
tc.mingwPrefixIsSystem = fs::exists(tc.mingwPrefix / "include" / "features.h");
} else if (!in.hostRoot.empty() && fs::exists(in.hostRoot / "usr" / "x86_64-w64-mingw32")) { } else if (!in.hostRoot.empty() && fs::exists(in.hostRoot / "usr" / "x86_64-w64-mingw32")) {
// The sandbox has no mingw-w64 of its own, and no mingw gcc on PATH // The sandbox has no mingw-w64 of its own, and no mingw gcc on PATH
// for clang to find one by. // for clang to find one by. The host's /usr is the host's system,
tc.mingwSysroot = in.hostRoot / "usr"; // whether or not its C library's headers are installed.
tc.mingwPrefix = PrefixPath(in.hostRoot / "usr");
tc.mingwPrefixIsSystem = true;
} }
// 5. nvcc, for cfg.cuda. CUDA_PATH is exclusive, as CRAFTER_BUILD_LLVM_DIR
// is: it names the toolkit, and one without nvcc is an error rather
// than a reason to use another. PATH is searched here, not by the
// shell: in crafter-build's Flatpak it is /app/bin:/usr/bin, which
// never holds the host's toolkit, and every CUDA build there stopped
// at "nvcc: command not found", which named no place to put one.
if (std::string_view cudaPath = Env(in, "CUDA_PATH"); !cudaPath.empty()) {
// Absolute and spelled one way, once, as CRAFTER_MINGW_DIR is: nvcc
// runs later, from whatever working directory a build is in.
const fs::path named = PrefixPath(fs::path(cudaPath));
if (const fs::path nvcc = HostPath(named, in.hostRoot) / "bin" / "nvcc"; IsProgram(nvcc)) {
tc.nvcc = nvcc;
} else {
tc.nvccError = std::format("no nvcc at {} (CUDA_PATH)", (named / "bin" / "nvcc").string());
}
} else {
std::vector<std::string> lookedAt;
for (const fs::path& root : in.cudaRoots) {
if (const fs::path nvcc = HostPath(root, in.hostRoot) / "bin" / "nvcc"; IsProgram(nvcc)) {
tc.nvcc = nvcc;
break;
}
lookedAt.push_back((root / "bin" / "nvcc").string());
}
const std::string_view path = Env(in, "PATH");
for (std::size_t at = 0; tc.nvcc.empty() && at <= path.size();) {
std::size_t end = path.find(':', at);
if (end == std::string_view::npos) end = path.size();
// An empty or a relative entry names a directory under whatever
// the working directory is, and this lookup is made once per
// process: only an absolute one names a place.
if (const std::string_view dir = path.substr(at, end - at); fs::path(dir).is_absolute() && IsProgram(fs::path(dir) / "nvcc")) {
tc.nvcc = fs::path(dir) / "nvcc";
}
at = end + 1;
}
if (tc.nvcc.empty()) {
lookedAt.push_back(std::format("nvcc on PATH ({})", path.empty() ? std::string_view("unset") : path));
std::string places = lookedAt.front();
for (std::size_t i = 1; i < lookedAt.size(); ++i) places += std::format("{}{}", i + 1 == lookedAt.size() ? " and " : ", ", lookedAt[i]);
tc.nvccError = std::format("no CUDA toolkit found: looked for {}; set CUDA_PATH to the directory a toolkit is installed in", places);
}
}
// What VariantId keys a CUDA configuration's nvcc by. Its path stays
// when the toolkit behind it is updated, by a package at /opt/cuda or by
// /usr/local/cuda pointed at another release, and the objects the old
// nvcc compiled would be kept. The binary's canonical path, size and
// time change with it, and reading them starts no process.
if (!tc.nvcc.empty()) {
std::error_code ec;
fs::path real = fs::canonical(tc.nvcc, ec);
if (ec) real = tc.nvcc;
const std::uintmax_t size = fs::file_size(real, ec);
const auto time = fs::last_write_time(real, ec).time_since_epoch().count();
tc.nvccStamp = std::format("{}|{}|{}", real.string(), size, time);
}
// What VariantId keys -arch=native by: nvcc compiles it for the GPUs it
// finds, so a GPU of another model, the same GPUs in each other's slots,
// or CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER choosing another or,
// empty, none, has to build in a directory of its own, where the word
// alone would keep an object compiled for the old GPU, with no PTX for the
// new one. The NVIDIA display devices (class 0x03) by PCI address and
// device ID, in the order of their addresses, from sysfs, which starts no
// process; an entry that cannot be read counts as none, and nothing here
// throws. It is crafter-build's reading of the machine, not nvcc's: a
// change it cannot see, such as a GPU bound to another driver, keeps the
// key.
if (!tc.nvcc.empty()) {
std::vector<std::string> gpus;
std::error_code ec;
for (fs::directory_iterator it(in.pciDevices, ec), end; !ec && it != end; it.increment(ec)) {
const auto field = [&it](std::string_view name) {
std::string value;
std::ifstream(it->path() / name) >> value;
return value;
};
if (field("vendor") == "0x10de" && field("class").starts_with("0x03")) gpus.push_back(std::format("{}={}", it->path().filename().string(), field("device")));
}
std::ranges::sort(gpus);
const auto spelled = [](const std::optional<std::string>& value) { return value ? std::format("={}", *value) : std::string("unset"); };
tc.cudaNativeKey = std::format("{}|{}|{}", std::views::join_with(gpus, std::string(",")) | std::ranges::to<std::string>(), spelled(in.cudaVisibleDevices), spelled(in.cudaDeviceOrder));
}
// The static runtime beside that nvcc, for the link of a configuration
// with CUDA sources. Looked for without throwing: a lib64 that cannot be
// looked into, through a link loop or for want of permission, counts as
// one without it.
if (!tc.nvcc.empty()) {
const fs::path archive = tc.nvcc.parent_path().parent_path() / "lib64" / "libcudart_static.a";
if (std::error_code ec; fs::exists(archive, ec)) tc.cudaRuntime = archive;
}
std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo);
return tc; return tc;
} }
@ -159,6 +394,17 @@ const Toolchain& Crafter::GetToolchain() {
in.crafterPrefix = GetCrafterBuildHome().parent_path().parent_path(); in.crafterPrefix = GetCrafterBuildHome().parent_path().parent_path();
} catch (const std::exception&) {} } catch (const std::exception&) {}
if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host"; if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host";
in.cudaRoots = { "/opt/cuda", "/usr/local/cuda" };
in.pciDevices = "/sys/bus/pci/devices";
if (const char* value = std::getenv("CUDA_VISIBLE_DEVICES")) in.cudaVisibleDevices = value;
if (const char* value = std::getenv("CUDA_DEVICE_ORDER")) in.cudaDeviceOrder = value;
{
auto it = in.env.find("CRAFTER_BUILD_FLATPAK_INFO");
const fs::path info = it != in.env.end() ? fs::path(it->second) : fs::path("/.flatpak-info");
if (std::ifstream file(info, std::ios::binary); file) {
in.flatpakInfo.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
}
Toolchain tc = ResolveToolchain(in); Toolchain tc = ResolveToolchain(in);
if (!tc.error.empty()) return tc; if (!tc.error.empty()) return tc;
@ -170,11 +416,22 @@ const Toolchain& Crafter::GetToolchain() {
return tc; return tc;
} }
tc.hostTriple = Trimmed(std::move(triple.output)); tc.hostTriple = Trimmed(std::move(triple.output));
// The InstalledDir line of a `--version` run; empty where the run
// failed or printed none.
const auto installedDirOf = [](const CommandResult& run) {
constexpr std::string_view InstalledDirLine = "\nInstalledDir: ";
const std::size_t at = run.output.find(InstalledDirLine);
if (run.exitCode != 0 || at == std::string::npos) return fs::path();
const std::size_t begin = at + InstalledDirLine.size();
return fs::path(Trimmed(run.output.substr(begin, run.output.find('\n', begin) - begin)));
};
CommandResult version = RunCommandChecked(std::format("{} --version", tc.clangxx.string())); CommandResult version = RunCommandChecked(std::format("{} --version", tc.clangxx.string()));
if (version.exitCode == 0) { if (version.exitCode == 0) {
std::string first = version.output.substr(0, version.output.find('\n')); std::string first = version.output.substr(0, version.output.find('\n'));
tc.clangVersion = Trimmed(std::move(first)); tc.clangVersion = Trimmed(std::move(first));
} }
tc.installedDir = installedDirOf(version);
tc.installedDirAsWritten = installedDirOf(RunCommandChecked(std::format("{} -no-canonical-prefixes --version", tc.clangxx.string())));
return tc; return tc;
}(); }();
return Resolved; return Resolved;
@ -186,6 +443,69 @@ const Toolchain& Crafter::RequireToolchain() {
return tc; return tc;
} }
fs::path Crafter::MakeMingwSysroot(const fs::path& prefix, std::span<const fs::path> parents) {
std::string reasons;
for (const fs::path& parent : parents) {
// One view per prefix: two shells with different CRAFTER_MINGW_DIRs
// share one cache and would otherwise rewrite each other's.
const fs::path sysroot = parent / "mingw-sysroot" / std::format("{:016x}", std::hash<std::string>{}(prefix.string()));
try {
// All clang's mingw driver takes from a sysroot other than its
// include/ and the rest of its lib/: the mingw-w64 tree (headers,
// libraries, and libstdc++ where a distro's cross gcc installs
// it) and gcc's per-target directory (crtbegin.o, libgcc, and the
// version that names libstdc++'s header directory), which
// openSUSE keeps under lib64. A link to nothing is skipped like a
// missing directory.
for (std::string_view entry : {"x86_64-w64-mingw32", "lib/gcc", "lib64/gcc"}) {
EnsureSymlink(prefix / entry, sysroot / entry);
}
return sysroot;
} catch (const std::exception& e) {
reasons += std::format("; {}", e.what());
}
}
throw std::runtime_error(std::format("cannot make a sysroot that shows clang only the mingw-w64 parts of {}{}", prefix.string(), reasons));
}
const fs::path& Crafter::MingwSysroot() {
// Made on first use rather than by GetToolchain(), so that only what
// compiles for the mingw target, a build or an AST lint of one, writes
// anything for it, and a failure surfaces as that command's error
// instead of on every command.
static const fs::path Sysroot = []() -> fs::path {
const Toolchain& tc = GetToolchain();
if (!tc.mingwPrefixIsSystem) return tc.mingwPrefix;
// In the cache, or where the XDG spec promises symbolic links when
// the cache's filesystem takes none (vfat, exFAT, CIFS without unix
// extensions), which costs nothing else crafter-build caches.
// Absolute, because CMake runs the compiler from directories of its
// own.
std::vector<fs::path> parents = { fs::absolute(GetCacheDir()) };
if (const char* runtime = std::getenv("XDG_RUNTIME_DIR"); runtime && *runtime) {
parents.push_back(fs::absolute(fs::path(runtime) / "crafter.build"));
}
fs::path view = MakeMingwSysroot(tc.mingwPrefix, parents);
MadeView = view;
ViewedPrefix = tc.mingwPrefix;
ViewMade.store(true, std::memory_order_release);
return view;
}();
return Sysroot;
}
std::string Crafter::MingwViewToPrefix(std::string text) {
if (!ViewMade.load(std::memory_order_acquire)) return text;
// With the separator, so a --sysroot= naming the view itself, in a
// command line the output quotes, stays what was run.
const std::string view = (MadeView / "").string();
const std::string prefix = (ViewedPrefix / "").string();
for (std::size_t at = text.find(view); at != std::string::npos; at = text.find(view, at + prefix.size())) {
text.replace(at, view.size(), prefix);
}
return text;
}
std::int32_t Crafter::LibcxxVersion(const fs::path& includeDir) { std::int32_t Crafter::LibcxxVersion(const fs::path& includeDir) {
// "# define _LIBCPP_VERSION 230102", the one place libc++ states its // "# define _LIBCPP_VERSION 230102", the one place libc++ states its
// release in a form the preprocessor does not have to be run for. // release in a form the preprocessor does not have to be run for.

View file

@ -7,10 +7,17 @@ namespace fs = std::filesystem;
// Dependency notes. A crafter-build project ships an AGENTS.consumer.md beside // Dependency notes. A crafter-build project ships an AGENTS.consumer.md beside
// its project.cpp, written for the agents of the projects that depend on it, // its project.cpp, written for the agents of the projects that depend on it,
// and crafter-build keeps those files in each consumer's AGENTS.md. Without // and crafter-build merges those files into each consumer's AGENTS.md. Without
// that, an agent working on a consumer knows nothing about the libraries it // that, an agent working on a consumer knows nothing about the libraries it
// builds against unless someone copied the knowledge in by hand, and a copy // builds against unless someone copied the knowledge in by hand, and a copy
// goes stale the moment the library changes. // goes stale the moment the library changes.
//
// The consumer writes its own instructions in an AGENTS.template.md beside its
// project.cpp, and every build writes AGENTS.md from that, so AGENTS.md is
// build output and stays out of version control. Kept in a committed
// AGENTS.md instead, as they once were, the notes changed that file whenever
// a dependency changed its own, on builds that changed nothing else, and
// every diff and rebase carried changes nobody had made.
export namespace Crafter { export namespace Crafter {
struct Configuration; struct Configuration;
@ -23,7 +30,7 @@ export namespace Crafter {
// Only the projects this one's own configurations and // Only the projects this one's own configurations and
// `#pragma crafter dependency` lines name. // `#pragma crafter dependency` lines name.
Direct, Direct,
// None. A section an earlier build wrote is removed. // None: AGENTS.md holds the template's text alone.
None, None,
}; };
@ -34,39 +41,57 @@ export namespace Crafter {
std::string name; std::string name;
// The file's content, without leading blank lines or trailing // The file's content, without leading blank lines or trailing
// whitespace. Lines end in LF; the merge writes the line ending the // whitespace. Lines end in LF; the merge writes the line ending the
// document uses. // template uses.
std::string text; std::string text;
}; };
// `agentsMd` with its dependency notes section holding `notes`, in order. // `templateMd` with its dependency notes section holding `notes`, in
// A document without a section gets one appended after a blank line; one // order: AGENTS.md as it reads below the line that says a build wrote it.
// with a section has it rewritten in place, wherever it was moved to; and // A template without a section gets one appended after a blank line; one
// empty `notes` remove it. Removing a section that ends the document takes // with a section, which is how a template places it, has it rewritten
// the blank line in front of it too, so a document that ended in a newline // where it stands, whatever it held; and empty `notes` remove it.
// before it gained the section gets its own bytes back. The section uses // Removing a section that ends the template takes the blank line in front
// the document's line ending, so a CRLF file stays CRLF. // of it too, so the result ends as the text before it did. The section
// uses the template's line ending, so a CRLF file stays CRLF.
// //
// The two marker lines count only as whole lines outside fenced code // The two marker lines count only as whole lines outside fenced code
// blocks, which is what lets a document quote them. Throws, naming the // blocks, which is what lets a document quote them. Throws, naming the
// line, when there are notes to write and the markers are unbalanced, or // line, when there are notes to write and the markers are unbalanced, or
// when the section would have to be appended to a document that ends // when the section would have to be appended to a template that ends
// inside a code block: guessing which part of someone's file is generated // inside a code block: a lone or doubled marker is a slip in the
// would overwrite their text, and missing the section would add another on // template, and any guess at what it meant would put the notes, or cut
// every build. With no notes it never throws, since leaving the document // the text, where its author did not, while notes appended inside a code
// alone loses nothing. Also throws for a note that would break the section // block would read as code. With no notes it never throws, since nothing
// when it is read back: one with a marker line of its own, or a code block // has to be placed. Also throws for a note that would break the section
// it never closes. // for whoever reads it: one with a marker line of its own, or a code
std::string MergeDependencyNotes(std::string_view agentsMd, std::span<const DependencyNote> notes); // block it never closes.
std::string MergeDependencyNotes(std::string_view templateMd, std::span<const DependencyNote> notes);
// Refresh the dependency notes section of the AGENTS.md beside // Write the AGENTS.md beside `projectFile` from the AGENTS.template.md
// `projectFile` from the AGENTS.consumer.md of every dependency // beside it, with the AGENTS.consumer.md of every dependency
// project.dependencyNotes selects. `project` is the Configuration that // project.dependencyNotes selects merged in. `project` is the
// file returned, after LoadProject: loading is what found the // Configuration that file returned, once it is loaded: loading is what
// dependencies. Does nothing when there is no AGENTS.md, which is never // found the dependencies. Creates AGENTS.md when it is missing, and
// created. Writes only when the text changes, in place, so hard links, // replaces only one a build wrote: an AGENTS.md someone wrote is left
// ownership and a read-only AGENTS.md are respected; returns whether it // alone, with a warning. Without a template it writes nothing, and only
// wrote. A read or write that fails, a section that cannot be placed and // warns about a section an earlier crafter-build left in AGENTS.md.
// Writes only when the text changes, in place, so hard links, ownership
// and a read-only AGENTS.md are respected; returns whether it wrote. A
// read or write that fails, a template the notes cannot be placed in and
// a dependency's unusable notes are warnings: the notes never fail a // a dependency's unusable notes are warnings: the notes never fail a
// build, and nothing is reported when nothing would have been written. // build, and nothing is reported when nothing would have been written.
bool UpdateAgentsMd(const Configuration& project, const fs::path& projectFile); bool UpdateAgentsMd(const Configuration& project, const fs::path& projectFile);
// The same for a project file that returned several configurations.
// Each one the file made itself selects, by its dependencyNotes, among
// the projects that one is built against, and the notes are merged: a
// dependency's are in when a configuration that asks for them leads to
// it. The file's `#pragma crafter dependency` lines, and a
// configuration it loaded from another project and returns, which
// counts as a dependency here, go by the widest of those settings, and
// by Transitive when the file made no configuration itself. A
// configuration is another project's when GitProject or LocalProject
// loaded it from another project file than `projectFile`, two files
// being one when they resolve to one path: one they loaded from
// `projectFile` itself is that file's own.
bool UpdateAgentsMd(std::span<const Configuration* const> configurations, const fs::path& projectFile);
} }

View file

@ -9,6 +9,7 @@ import :Implementation;
import :External; import :External;
import :Toolchain; import :Toolchain;
import :Agents; import :Agents;
import :Flatpak;
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace Crafter { namespace Crafter {
@ -48,11 +49,35 @@ export namespace Crafter {
// recorded last time, so they come out the same however the // recorded last time, so they come out the same however the
// dependency threads that fill them happen to finish. // dependency threads that fill them happen to finish.
std::set<std::string> libs; std::set<std::string> libs;
// The CUDA runtime that a configuration with CUDA sources, or one it
// is built on, links: Toolchain::cudaRuntime by its path and the -lrt
// -lpthread -ldl it needs, or nothing where the toolkit has none. By
// its path, so no directory of the toolkit's is searched for a
// project's own libraries; after libs on every link, so a -lcudart a
// project names itself is the one the linker takes.
std::set<std::string> runtimeLibs;
// Compile flags (typically -I include paths) the dep wants its // Compile flags (typically -I include paths) the dep wants its
// consumers to see — sourced from its external dependencies' include // consumers to see — sourced from its external dependencies' include
// dirs so headers a dep exposes in its public modules are reachable // dirs so headers a dep exposes in its public modules are reachable
// when a consumer #includes them directly. Propagates transitively. // when a consumer #includes them directly. Propagates transitively.
std::set<std::string> publicCompileFlags; std::set<std::string> publicCompileFlags;
// Absolute directories the shared libraries this links against are
// loaded from at run time, its dependencies' included, and, once a
// shared library is linked, its own bin dir, for its consumers. An
// executable or shared library linked from them records each one as
// a run path, except an executable packaged as a Flatpak: its one run
// path is $ORIGIN/../lib, and WriteFlatpak copies what it needs from
// these directories into files/lib.
std::set<std::string> runPaths;
// The configuration this is the build of: the one whose Build() ran.
// A build pass builds a directory once, so of two configurations
// that would be built into one, as the same project loaded along two
// paths with its args in two orders is, only one is built, and only
// that one has the modules the build read in the sources
// (Configuration::interfaces). What is built on the other finds them
// through this. Null where Build() stopped before it read the
// sources.
const struct Configuration* built = nullptr;
}; };
struct Define { struct Define {
@ -83,6 +108,25 @@ export namespace Crafter {
LibraryDynamic, LibraryDynamic,
}; };
// What an executable is delivered as. Read for executables only; a
// library is never packaged.
enum class Packaging {
// The executable as linked, for now; Flatpak is asked for by name.
Default,
// The files/ of a Flatpak in BinDir(), what becomes /app in the
// app's sandbox: the program and what it reads at run time in
// files/bin, the shared libraries it needs in files/lib, and its
// desktop entry, metainfo and icons in files/share. An x86_64 Linux
// (glibc) executable without a sysroot, built by the Flatpak
// crafter-build, since it links that runtime's glibc.
Flatpak,
// The executable as linked, with its files beside it in BinDir().
// Built by the Flatpak crafter-build, it needs the libc++,
// libc++abi and libunwind in /app/lib, so it runs inside that
// sandbox (-r, test, run scripts) and practically nowhere else.
None,
};
struct Test; struct Test;
struct TestRunner { struct TestRunner {
@ -132,6 +176,11 @@ export namespace Crafter {
std::int32_t signal = 0; std::int32_t signal = 0;
std::chrono::milliseconds duration{0}; std::chrono::milliseconds duration{0};
std::string output; std::string output;
// What the headless compositor of a test that sets Test::wayland
// printed, kept when the test ran and failed, crashed or timed out,
// for RunTests to write beside the test's own log. A compositor that
// did not start has what it printed in `output`.
std::string compositorLog;
}; };
// One lint diagnostic. Produced by LintContext::Report — or derived by // One lint diagnostic. Produced by LintContext::Report — or derived by
@ -392,13 +441,24 @@ export namespace Crafter {
}; };
struct Configuration; struct Configuration;
// The name StdPcmDir gives the directory of this configuration's std
// module under `toolchain`: target, march and the toolchain's key, which
// say what it is, then a hash of everything else it is compiled with,
// each flag BuildStdPcm passes (StdPcmFlags) and for the mingw target the
// prefix behind its --sysroot. Two configurations that would compile the
// std module differently never share a directory, so neither rebuilds it
// under the PCMs the other compiled against it. Declared ahead of
// Configuration, whose VariantId keys on it.
std::string StdPcmKey(const Configuration& config, const Toolchain& toolchain);
// What a Script's callback is handed when `crafter-build run <name>` // What a Script's callback is handed when `crafter-build run <name>`
// starts it. // starts it.
struct ScriptContext { struct ScriptContext {
// The Configuration project.cpp returned. Read the project through // The Configuration the script is declared on: the one project.cpp
// this rather than capturing the local in CrafterBuildProject by // returned, or of several the one whose `scripts` holds it. Read the
// reference: that local is gone by the time a script runs. // project through this rather than capturing a local of the entry
// point by reference: the local need not be the object that the
// entry point returned.
Configuration& project; Configuration& project;
// Absolute directory of the project file. Commands run in the // Absolute directory of the project file. Commands run in the
// directory crafter-build was started from, like everything else it // directory crafter-build was started from, like everything else it
@ -456,10 +516,47 @@ export namespace Crafter {
std::string sysroot; std::string sysroot;
bool debug = false; bool debug = false;
ConfigurationType type = ConfigurationType::Executable; ConfigurationType type = ConfigurationType::Executable;
// What the executable is delivered as (see Packaging).
// ApplyStandardArgs sets it from --packaging=none|flatpak.
Packaging packaging = Packaging::Default;
// What it is installed as when it is packaged as a Flatpak, and the
// sandbox permissions any configuration may declare for the
// executables built on it.
FlatpakApp flatpak;
// The module interface units (.cppm) and the implementation units
// (.cpp) of the configuration, as GetInterfacesAndImplementations
// lists them: absolute, with their extensions.
std::vector<fs::path> interfaceSources;
std::vector<fs::path> implementationSources;
// What those sources are, as Build() found them the last time it read
// all of them without an error: each module whose primary interface
// unit is among interfaceSources, with its partitions, and a unit for
// each of implementationSources, with what each of them imports.
// Build() takes what a source declares and imports from
// clang-scan-deps, which preprocesses the source with the command it
// is compiled with, so it reads them as the compiler does: one in a
// string literal, in a comment or in a branch that #if leaves out is
// not there. It reads them once the configuration's dependencies and
// external dependencies are built, since the command takes their
// include paths and a source may include their headers. Empty until a
// Build() has read the sources. A pass builds a directory once, so a
// configuration whose directory it built for another keeps what it
// had, and what is built on it finds the modules of that build
// through BuildResult::built.
std::vector<std::unique_ptr<Module>> interfaces; std::vector<std::unique_ptr<Module>> interfaces;
std::vector<Implementation> implementations; std::vector<Implementation> implementations;
std::vector<fs::path> cFiles; std::vector<fs::path> cFiles;
std::vector<fs::path> cuda; std::vector<fs::path> cuda;
// The GPU architecture nvcc compiles `cuda` for, as its -arch takes
// one. "native", the default, compiles for the GPUs of the machine
// that builds, as march's default does for its CPU; with none to be
// seen, nvcc warns and uses its own default. Like -march=native it is
// for a program that runs where it is built: it carries no PTX, which
// a newer GPU could compile when it loads the program. "sm_89" is one
// architecture with its PTX; "all-major" or "all" is for a program
// that runs elsewhere. ApplyStandardArgs sets it from
// CRAFTER_BUILD_CUDA_ARCH and --cuda-arch=.
std::string cudaArch = "native";
std::vector<Configuration*> dependencies; std::vector<Configuration*> dependencies;
std::vector<fs::path> files; std::vector<fs::path> files;
// Build-time-only source files this configuration exposes to its own // Build-time-only source files this configuration exposes to its own
@ -529,28 +626,29 @@ export namespace Crafter {
// Not part of VariantId: a script changes nothing that is compiled. // Not part of VariantId: a script changes nothing that is compiled.
std::vector<Script> scripts; std::vector<Script> scripts;
// Which dependencies' AGENTS.consumer.md `crafter-build` and // Which dependencies' AGENTS.consumer.md `crafter-build` and
// `crafter-build test` keep in the AGENTS.md beside project.cpp, when // `crafter-build test` merge into the AGENTS.md they write from the
// there is one (see Crafter.Build:Agents): // AGENTS.template.md beside project.cpp, when there is one (see
// Crafter.Build:Agents):
// cfg.dependencyNotes = DependencyNotes::Direct; // cfg.dependencyNotes = DependencyNotes::Direct;
// Only read on the Configuration project.cpp returns; a dependency's // Only read on the Configuration project.cpp returns; a dependency's
// setting decides nothing for its consumers. Not part of VariantId: // setting decides nothing for its consumers. Of several returned
// the notes change nothing that is compiled. // configurations, each one the project file made itself has its own
// read, for what that one is built against (see UpdateAgentsMd). Not
// part of VariantId: the notes change nothing that is compiled.
DependencyNotes dependencyNotes = DependencyNotes::Transitive; DependencyNotes dependencyNotes = DependencyNotes::Transitive;
// Adds the units `interfaces` and `implementations` name to
// interfaceSources and implementationSources. Each is named without
// its extension, .cppm for an interface unit and .cpp for an
// implementation unit, and resolved against `path` and the working
// directory as they are at the call. Reads none of them: Build()
// does, with the command the configuration has by then, its defines,
// flags and dependencies set after this call included.
void GetInterfacesAndImplementations(std::span<fs::path> interfaces, std::span<fs::path> implementations); void GetInterfacesAndImplementations(std::span<fs::path> interfaces, std::span<fs::path> implementations);
// Retry the `import X;` names GetInterfacesAndImplementations could not
// place, against the dependency DAG as it stands now. Sources are
// scanned when they're declared, but `dependencies` is often assigned
// afterwards (AddTest does exactly this), and an import that resolved to
// nothing leaves no staleness edge — so a dependency's interface could
// change and this Configuration's objects would be silently reused
// against the new layout. Build() calls this before checking mtimes;
// calling it again is harmless.
void ResolvePendingImports();
// Declare a test. Sources default to `tests/<name>/main.cpp` resolved // Declare a test. Sources default to `tests/<name>/main.cpp` resolved
// against this Configuration's path; target/march/mtune/sysroot/debug // against this Configuration's path; target/march/mtune/sysroot/debug
// are inherited from this Configuration so cross-arch projects don't // and cudaArch are inherited from this Configuration so cross-arch
// have to re-specify. Returns a builder for chaining defines, deps, // projects don't have to re-specify. Returns a builder for chaining
// etc. Defined in Crafter.Build:Test. // defines, deps, etc. Defined in Crafter.Build:Test.
struct TestBuilder AddTest(std::string_view name); struct TestBuilder AddTest(std::string_view name);
// Same as AddTest, but compiles the parent's `interfaces` directly // Same as AddTest, but compiles the parent's `interfaces` directly
// into this test's Configuration (rather than going through a dep). // into this test's Configuration (rather than going through a dep).
@ -579,7 +677,8 @@ export namespace Crafter {
void AddAstLintRule(std::string name, std::function<void(LintContext&)> check); void AddAstLintRule(std::string name, std::function<void(LintContext&)> check);
// Suffix that uniquely identifies this Configuration's compile state. // Suffix that uniquely identifies this Configuration's compile state.
// target+march+mtune are spelled out for readability; the rest // target+march+mtune are spelled out for readability; the rest
// (type, debug, sysroot, defines, compileFlags, the toolchain) // (type, debug, sysroot, defines, compileFlags, the std module, the
// toolchain, the GPU architecture and the nvcc of CUDA sources)
// collapse into a short hash so two Configurations sharing a path but // collapse into a short hash so two Configurations sharing a path but
// with different compile state can't clobber each other's outputs. // with different compile state can't clobber each other's outputs.
std::string VariantId() const { return VariantId(GetToolchain()); } std::string VariantId() const { return VariantId(GetToolchain()); }
@ -599,7 +698,7 @@ export namespace Crafter {
compileKey += '|'; compileKey += '|';
compileKey += debug ? '1' : '0'; compileKey += debug ? '1' : '0';
compileKey += '|'; compileKey += '|';
compileKey += sysroot; compileKey += ResolvedSysroot(toolchain);
for (const Define& d : defines) { for (const Define& d : defines) {
compileKey += "|D:"; compileKey += "|D:";
compileKey += d.name; compileKey += d.name;
@ -627,6 +726,15 @@ export namespace Crafter {
compileKey += "|B:"; compileKey += "|B:";
compileKey += WasmBaselineFlags; compileKey += WasmBaselineFlags;
} }
// The std module the units import. Its PCMs and objects record
// it by path, and units do not notice it moving: when the mingw
// prefix stopped being clang's sysroot as is (issue #43), the
// std module was rebuilt and the objects compiled against the
// host's glibc headers were only relinked, failing as before. A
// std module that moves directories, because anything it is
// compiled with changed, moves the build with it.
compileKey += "|S:";
compileKey += StdPcmKey(*this, toolchain);
// Sorted by ApplyStandardArgs, so flag order on the command line // Sorted by ApplyStandardArgs, so flag order on the command line
// doesn't split the cache. // doesn't split the cache.
for (const std::string& a : projectArgs) { for (const std::string& a : projectArgs) {
@ -635,11 +743,66 @@ export namespace Crafter {
} }
compileKey += "|T:"; compileKey += "|T:";
compileKey += toolchain.Key(); compileKey += toolchain.Key();
// The GPU architecture decides what a .cu compiles into, and so
// does the toolkit whose nvcc compiles it, which CUDA_PATH can
// switch and an update can replace at the same path, so the nvcc
// is keyed by what it is (Toolchain::nvccStamp), and native by the
// GPUs it resolves to (Toolchain::cudaNativeKey). None of them
// need touch the files whose times decide whether a .cu is
// compiled again, so each needs a directory of its own. Only keyed
// with CUDA sources, so every other configuration keeps the
// directory it had.
if (!cuda.empty()) {
compileKey += "|C:";
compileKey += cudaArch;
compileKey += '|';
compileKey += toolchain.nvccStamp;
if (cudaArch == "native") {
compileKey += '|';
compileKey += toolchain.cudaNativeKey;
}
}
// A Flatpak lays its bin dir out unlike the executable as linked,
// so the two never share one. Only keyed for a Flatpak, so every
// other configuration keeps the directory it had.
if (ResolvedPackaging() == Packaging::Flatpak) compileKey += "|P:flatpak";
std::size_t configHash = std::hash<std::string>{}(compileKey); std::size_t configHash = std::hash<std::string>{}(compileKey);
return std::format("{}-{}-{}-{}-{:08x}", name, target, march, mtune, configHash); return std::format("{}-{}-{}-{}-{:08x}", name, target, march, mtune, configHash);
} }
fs::path BuildDir() const { return path / "build" / VariantId(); } fs::path BuildDir() const { return path / "build" / VariantId(); }
fs::path BinDir() const { return path / "bin" / VariantId(); } fs::path BinDir() const { return path / "bin" / VariantId(); }
// Where an executable and the files it reads at run time land, and
// the directory `-r` runs a host executable in and serves a browser
// build from: its shaders, cfg.files and assets, and those its
// dependencies forward to it. A Flatpak keeps them in files/bin of
// its bin dir, which becomes /app/bin; every other configuration in
// its bin dir.
fs::path ProgramDir() const { return ResolvedPackaging() == Packaging::Flatpak ? BinDir() / "files" / "bin" : BinDir(); }
// What `packaging` comes to for this configuration: Flatpak for an
// executable that asks for one by name, None for every other
// configuration and for Default.
Packaging ResolvedPackaging() const {
return type == ConfigurationType::Executable && packaging == Packaging::Flatpak ? Packaging::Flatpak : Packaging::None;
}
// What `sysroot` comes to for this configuration under `toolchain`:
// the toolchain's WASI sysroot for a wasm32 target that names none,
// `sysroot` as it stands for every other configuration. The
// commands that compile and link a wasm32 configuration and the
// names of its directories read the sysroot through here, so the
// configuration is the same thing before its build as during it and
// after. Build() used to store the WASI sysroot in `sysroot` on its
// way in instead, and VariantId hashes the sysroot: a wasm32
// configuration whose target was set without ApplyStandardArgs,
// which stores it when the project file is loaded, had one
// BuildDir, BinDir and PcmDir until its build started and others
// from then on. A build pass records a dependency's build under its
// PcmDir, so one that two configurations of the pass were built on
// was looked up under the first directory by the one that asked
// before its build had started and under the second by the one
// that asked after, and was built a second time.
std::string ResolvedSysroot(const Toolchain& toolchain) const {
return sysroot.empty() && target.starts_with("wasm32") ? toolchain.wasiSysroot.string() : sysroot;
}
fs::path PcmDir() const { fs::path PcmDir() const {
return type == ConfigurationType::Executable ? BuildDir() : BinDir(); return type == ConfigurationType::Executable ? BuildDir() : BinDir();
} }
@ -659,12 +822,24 @@ export namespace Crafter {
// unavailable runner becomes a Fail instead of a silent Skip — the // unavailable runner becomes a Fail instead of a silent Skip — the
// dependency has to be declared to be allowed to be missing. // dependency has to be declared to be allowed to be missing.
std::vector<std::string> requires_; std::vector<std::string> requires_;
// The test talks to a Wayland compositor, so every run of it gets one
// of its own: a headless compositor started for it alone and stopped
// when it ends. The test finds it through WAYLAND_DISPLAY, the full
// path of its socket, and runs with DISPLAY unset, so the windows it
// opens through WAYLAND_DISPLAY do not reach the session's display.
// The compositor is weston on
// its headless backend unless --compositor= or CRAFTER_BUILD_COMPOSITOR
// names another, or names `host` to give the test the session's own
// display. A test whose compositor cannot be started fails, unless it
// declares the compositor in requires_ (tool:weston for the default),
// which skips it where that is missing. README, "Tests that open
// windows".
bool wayland = false;
}; };
// Directory holding the std module PCM for this Configuration. Keyed on // Directory holding the std module PCM for this Configuration,
// target+march because a BMI is only loadable by a TU with matching target // GetCacheDir() / StdPcmKey(config, GetToolchain()): a BMI is only
// features, and suffixed with the wasm flags (WasmBaselineFlags, then the // loadable by a unit compiled the way it was.
// variant's) for the same reason.
fs::path StdPcmDir(const Configuration& config); fs::path StdPcmDir(const Configuration& config);
// Where Build leaves this Configuration's linked artifact: the executable // Where Build leaves this Configuration's linked artifact: the executable
@ -674,6 +849,59 @@ export namespace Crafter {
// disagree about the file name. // disagree about the file name.
fs::path ExpectedOutput(const Configuration& config); fs::path ExpectedOutput(const Configuration& config);
// Where Build leaves the object of `source`, one of this Configuration's
// implementation units (.cpp), C sources (.c) or CUDA sources (.cu),
// given with its extension; a relative `source` is taken against the
// working directory, as Build takes cFiles and cuda. The dependency file
// the compiler writes lies beside it, as <object>.d.
//
// The object is named from where the source lies: under
// BuildDir()/objects by the source's path from the Configuration's
// `path`, objects/a/Thing_impl.o for a/Thing.cpp, or, for a source
// outside that directory, under BuildDir()/objects-outside by its whole
// path. The name ends in _impl.o for a .cpp, _source.o for a .c and
// _cuda.o for a .cu. So two sources have one object only when their
// paths are one once `.` and `..` are taken out of them as they are
// written: any other two differ by path or by ending in one of the two
// directories, and the two directories share nothing.
//
// Objects were named from the file name alone, in BuildDir() itself:
// a/Thing.cpp and b/Thing.cpp were both compiled into Thing_impl.o,
// each over the other, and the link was given that object twice. The
// link then failed, or, in a debug build of two sources that define
// nothing another file names, gave a program with one source's code
// twice and the other's not at all (issue #50).
//
// An interface unit's object is not named here. It lies in BuildDir()
// itself, named by the unit's file name alone, as its BMI is: clang
// looks a BMI up by its module's name, so two interface files of one
// name would have to be one module. Throws std::invalid_argument for a
// `source` with any other extension.
fs::path ObjectPath(const Configuration& config, const fs::path& source);
// `crafter-build install`: makes the Flatpak of the files/ `config` was
// built as (see Packaging::Flatpak), with its permissions, puts it into
// the project's repo, and installs it for this user from a user remote
// named after the app-id, updating what an earlier install left. The
// host's flatpak does the work (see HostFlatpakUnavailable and
// ExportFlatpak). Returns why it could not; empty when it did.
std::string InstallFlatpakApp(const Configuration& config);
// `crafter-build bundle`: the same export, then a single-file bundle at
// FlatpakBundlePath(config) that `flatpak install --user <file>` takes
// on any machine, fetching the runtime from Flathub where it is missing.
std::string BundleFlatpakApp(const Configuration& config);
// bin/<variant>.flatpak, beside the bin dir it is made from.
fs::path FlatpakBundlePath(const Configuration& config);
// build/flatpak-apps/<app-id>, where install and bundle keep the app's
// repo and the build directory they finish it in, and with modules the
// manifest and flatpak-builder's state. One per app rather than per
// variant: the state is flatpak-builder's cache, and under a variant's
// name every module would be built again after each compiler update.
fs::path FlatpakAppDir(const Configuration& config);
// The manifest flatpak-builder makes the app from when cfg.flatpak has
// modules (FlatpakManifestText).
std::string FlatpakManifest(const Configuration& config);
// The clang invocation every C++ translation unit in this Configuration is // The clang invocation every C++ translation unit in this Configuration is
// compiled with, before anything that depends on work having happened // compiled with, before anything that depends on work having happened
// (dependency public flags, external dependency flags — Build appends // (dependency public flags, external dependency flags — Build appends
@ -718,6 +946,35 @@ export namespace Crafter {
// checks everything again and pulls unpinned externals again. // checks everything again and pulls unpinned externals again.
BuildResult Build(Configuration& config, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex); BuildResult Build(Configuration& config, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex);
// Builds every one of `configurations`, the configurations a project
// file returns, in the pass `depResults` records. Each is built by
// Build(), as a project's one configuration is, and its result then
// goes into the record under its PcmDir, where Build() records a
// dependency. What two of them depend on is built once, and so is one
// that another of them is built on: it is built before the other
// starts, and the other finds it in the record. The first is built on
// the calling thread and each other one on a thread of its own, all of
// them to the end: one that fails stops none of the others. Returns the
// errors of the ones that failed, in the order given and each message
// once, so a dependency that failed for three of them is reported once,
// and an empty string when all were built. A configuration the list
// names twice is built once.
//
// With a wasm executable that declares wasmVariants among them, or
// among what they are built on, they are built one after the other on
// the calling thread instead: its build rewrites the configurations it
// is built on for each variant, which no other build may be reading.
//
// Refuses, before building anything, two of them that would be built
// into one directory (same path, name, target and compile state), which
// would be two builds writing the same files at once; a set of them in
// which each is built on something that is built into the directory of
// another, so that none could be built first; and one that is built on
// something of its own directory when another of them is built on that
// directory too, since the record holds one result for a directory and
// the other could be given either.
std::string BuildAll(std::span<Configuration* const> configurations, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex);
// Takes main's argv verbatim so the CLI entry point is a one-liner; // Takes main's argv verbatim so the CLI entry point is a one-liner;
// the shape is inherited from the language, not chosen here. // the shape is inherited from the language, not chosen here.
// lint-disable-next-line no-char-pointer // lint-disable-next-line no-char-pointer
@ -773,13 +1030,20 @@ export namespace Crafter {
// --target=<triple> cfg.target = <triple> // --target=<triple> cfg.target = <triple>
// --march=<value> cfg.march = <value> // --march=<value> cfg.march = <value>
// --mtune=<value> cfg.mtune = <value> // --mtune=<value> cfg.mtune = <value>
// --cuda-arch=<value> cfg.cudaArch = <value>
// --lib cfg.type promoted Executable → LibraryStatic // --lib cfg.type promoted Executable → LibraryStatic
// --shared cfg.type promoted LibraryStatic → LibraryDynamic // --shared cfg.type promoted LibraryStatic → LibraryDynamic
// --packaging=<kind> cfg.packaging = None or Flatpak (none, flatpak),
// in the project crafter-build was pointed at only:
// a dependency loaded with the same args keeps its
// executables as they are, since its consumers run
// them by path
// Promotions chain in priority order so `--lib --shared` lands on // Promotions chain in priority order so `--lib --shared` lands on
// LibraryDynamic regardless of arg order; each is a no-op when the // LibraryDynamic regardless of arg order; each is a no-op when the
// baseline doesn't match (e.g. --shared on an Executable, or --lib on a // baseline doesn't match (e.g. --shared on an Executable, or --lib on a
// pre-set library). // pre-set library).
// $CRAFTER_BUILD_MARCH / $CRAFTER_BUILD_MTUNE seed march/mtune. // $CRAFTER_BUILD_MARCH / $CRAFTER_BUILD_MTUNE / $CRAFTER_BUILD_CUDA_ARCH
// seed march/mtune/cudaArch.
// Env applies first, then args, so CLI wins over env wins over caller's // Env applies first, then args, so CLI wins over env wins over caller's
// pre-set defaults. Returns an ArgQuery over the same span so projects // pre-set defaults. Returns an ArgQuery over the same span so projects
// can query their own flags (`--timing`, ...) without re-rolling the // can query their own flags (`--timing`, ...) without re-rolling the
@ -793,4 +1057,9 @@ namespace Crafter {
// compile command and of the std module's, which have to agree flag for // compile command and of the std module's, which have to agree flag for
// flag. // flag.
std::string WasmCompileFlags(const Configuration& config); std::string WasmCompileFlags(const Configuration& config);
// The flags BuildStdPcm compiles the std module with under `toolchain`,
// after the base command and before the source, each with a leading
// space. StdPcmKey hashes the same string, so the command and the
// directory it writes to cannot disagree about what decides the BMI.
std::string StdPcmFlags(const Configuration& config, const Toolchain& toolchain);
} }

View file

@ -38,6 +38,11 @@ export namespace Crafter {
struct ExternalBuildResult { struct ExternalBuildResult {
std::vector<std::string> compileFlags; std::vector<std::string> compileFlags;
std::vector<std::string> linkFlags; std::vector<std::string> linkFlags;
// Absolute directories the dependency's shared libraries are loaded
// from at run time: what a consumer's link records as its run path.
// Kept apart from linkFlags because what becomes of them depends on
// how the consumer is packaged (see BuildResult::runPaths).
std::vector<std::string> runPaths;
fs::file_time_type latestArtifact = fs::file_time_type::min(); fs::file_time_type latestArtifact = fs::file_time_type::min();
}; };
@ -66,19 +71,19 @@ export namespace Crafter {
// short would leave them a clone nobody fetched. // short would leave them a clone nobody fetched.
std::string BuildExternal(const ExternalDependency& dep, std::string_view target); std::string BuildExternal(const ExternalDependency& dep, std::string_view target);
// What a configuration that declares `dep` compiles and links with once // What a configuration that declares `dep` compiles and links with once
// BuildExternal has run: the -I flags and, for CMake, the -L, -rpath and -l // BuildExternal has run: the -I flags and, for CMake, the -L and -l flags,
// flags and the newest library. Per declaration, because two that share a // the run path directories and the newest library. Per declaration, because two that share a
// clone can still differ in includeDirs, libDirs and libs. // clone can still differ in includeDirs, libDirs and libs.
ExternalBuildResult ExternalOutputs(const ExternalDependency& dep, std::string_view target); ExternalBuildResult ExternalOutputs(const ExternalDependency& dep, std::string_view target);
// The args the project file now running its CrafterBuildProject was // The args the project file now running its entry point was loaded
// loaded with: everything that function receives, --target=, --debug and // with: everything that function receives, --target=, --debug and
// the other standard flags included. Not cfg.projectArgs, which holds // the other standard flags included. Not cfg.projectArgs, which holds
// only what ApplyStandardArgs left uninterpreted: `.args = // only what ApplyStandardArgs left uninterpreted: `.args =
// cfg.projectArgs` would drop the target and the build type. Empty // cfg.projectArgs` would drop the target and the build type. Empty
// everywhere else, because it reads the stack LoadProject keeps per // everywhere else, because it reads the stack the loader keeps per
// thread, as IsTopLevelProject does: outside a project file, on any // thread, as IsTopLevelProject does: outside a project file, on any
// thread but the one running it, once CrafterBuildProject has returned // thread but the one running it, once the entry point has returned
// (a script runs later), and before it is called, which covers the // (a script runs later), and before it is called, which covers the
// file's static initialisers and its `#pragma crafter dependency` // file's static initialisers and its `#pragma crafter dependency`
// pre-pass. The specs below default their args to it. Defined beside // pre-pass. The specs below default their args to it. Defined beside
@ -92,7 +97,7 @@ export namespace Crafter {
// GitSource picks the revision: leave branch + commit empty for the // GitSource picks the revision: leave branch + commit empty for the
// remote's default branch HEAD (sloppy but convenient), set branch to // remote's default branch HEAD (sloppy but convenient), set branch to
// track a branch tip, or set commit to pin to an immutable SHA. args are // track a branch tip, or set commit to pin to an immutable SHA. args are
// what the dep's CrafterBuildProject receives. They default to this // what the dep's entry point receives. They default to this
// project's own, read when the spec is made, so --target=, --march=, // project's own, read when the spec is made, so --target=, --march=,
// --debug and the project's own flags reach every sibling down a chain // --debug and the project's own flags reach every sibling down a chain
// without being passed. Set them to forward something else: {} for // without being passed. Set them to forward something else: {} for
@ -100,19 +105,28 @@ export namespace Crafter {
// a flag only this project reads. Give such a list to every sibling: // a flag only this project reads. Give such a list to every sibling:
// Build() refuses a graph in which two paths load one project with two // Build() refuses a graph in which two paths load one project with two
// different lists, since the program would end up with both builds. // different lists, since the program would end up with both builds.
// configuration picks among the configurations of a project file that
// returns several (CrafterBuildConfigurations), by Configuration::name.
// Left empty it is the first one the file returns, so a project that
// grows a second configuration puts it after the one its consumers
// already get.
struct GitProjectSpec { struct GitProjectSpec {
GitSource source; GitSource source;
fs::path projectFile = "project.cpp"; fs::path projectFile = "project.cpp";
std::vector<std::string> args = ProjectArgs(); std::vector<std::string> args = ProjectArgs();
std::string configuration;
}; };
// Clones the spec's git URL into the external cache, recursively // Clones the spec's git URL into the external cache, loads the remote's
// LoadProject's the remote's project.cpp, and returns a stable // project.cpp in turn, and returns a stable Configuration* you can drop
// Configuration* you can drop into cfg.dependencies. The clone is keyed by // into cfg.dependencies: the configuration the spec picks of the ones
// url+branch+commit+projectFile alone, so every arg list builds in the // that file describes. The clone is keyed by url+branch+commit+projectFile
// same working tree, each into variant directories of its own. The // alone, so every arg list builds in the same working tree, each into
// Configuration is owned by an internal cache for the lifetime of the // variant directories of its own. What the file describes is kept in an
// build, keyed by the clone and the args: identical specs share one. // internal cache for the lifetime of the build, keyed by the clone and
// the args: identical specs share one Configuration, and two that differ
// only in `configuration` share one load of the file. Throws when the
// file has no configuration of the name the spec asks for, or two.
Configuration* GitProject(const GitProjectSpec& spec); Configuration* GitProject(const GitProjectSpec& spec);
// Specification for a local sibling crafter-build project (e.g. an // Specification for a local sibling crafter-build project (e.g. an
@ -121,12 +135,13 @@ export namespace Crafter {
struct LocalProjectSpec { struct LocalProjectSpec {
fs::path projectFile; // relative to cwd or absolute fs::path projectFile; // relative to cwd or absolute
std::vector<std::string> args = ProjectArgs(); // as GitProjectSpec::args std::vector<std::string> args = ProjectArgs(); // as GitProjectSpec::args
std::string configuration; // as GitProjectSpec::configuration
}; };
// Same as GitProject but for a local on-disk project — no fetch, no // Same as GitProject but for a local on-disk project — no fetch, no
// cache copy. Resolves projectFile to its canonical absolute path and // cache copy. Resolves projectFile to its canonical absolute path and
// recursively LoadProject's it. Returns a stable Configuration* owned // loads it in turn. Returns a stable Configuration* kept by the same
// by the same internal cache as GitProject. // internal cache as GitProject.
Configuration* LocalProject(const LocalProjectSpec& spec); Configuration* LocalProject(const LocalProjectSpec& spec);
// Clone (or update) the given git source into the shared external // Clone (or update) the given git source into the shared external
@ -142,11 +157,11 @@ export namespace Crafter {
namespace Crafter { namespace Crafter {
// Where GitProject or LocalProject loaded a Configuration from. The // Where GitProject or LocalProject loaded a Configuration from. The
// loader keeps this beside the cache that owns the Configuration, since // loader keeps this beside the cache that holds the Configuration, since
// the Configuration itself cannot say: only the one they return has its // the Configuration itself cannot say: only the ones its project file
// path rebased, and the configurations a dependency's project file makes // returns have their paths rebased, and the configurations a
// for itself keep a path such as "./", which resolves against the // dependency's project file makes for itself and does not return keep a
// consumer's directory. // path such as "./", which resolves against the consumer's directory.
struct LoadedProject { struct LoadedProject {
fs::path projectFile; // absolute fs::path projectFile; // absolute
// What a consumer's AGENTS.md calls it: the repository's name for a // What a consumer's AGENTS.md calls it: the repository's name for a
@ -161,8 +176,20 @@ namespace Crafter {
// Two specs that pin one library differently are one library. // Two specs that pin one library differently are one library.
std::string identity; std::string identity;
}; };
// The LoadedProject behind a Configuration that GitProject or // The LoadedProject behind a Configuration that a project file GitProject
// LocalProject returned; nullopt for any other: the project crafter-build // or LocalProject loaded returned, the ones the spec did not pick
// was pointed at, and every configuration a project file makes itself. // included; nullopt for any other: what the project file crafter-build
// was pointed at makes itself, and what a loaded project file makes for
// itself and does not return.
std::optional<LoadedProject> LoadedProjectOf(const Configuration& cfg); std::optional<LoadedProject> LoadedProjectOf(const Configuration& cfg);
// The project that keeps `cfg` to itself: one GitProject or LocalProject
// loaded whose project file did not return `cfg`, while a configuration
// that file did return led to it when the file was loaded. A
// configuration leads to what it is built on (`dependencies`) and to
// the configurations of its tests (`tests`), and through each of those
// to what that one leads to. nullopt for every other configuration: one
// a loaded project file returned, and one that nothing a loaded project
// file returned led to, such as what the project file crafter-build was
// pointed at makes itself.
std::optional<LoadedProject> KeptBy(const Configuration& cfg);
} }

View file

@ -0,0 +1,223 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Crafter.Build:Flatpak;
import std;
namespace fs = std::filesystem;
// An executable packaged as a Flatpak: what a project declares about it, the
// files/ Build() lays out for it, which becomes /app in the app's sandbox,
// and what `crafter-build install` and `bundle` hand the host's flatpak to
// make the app of it. Everything here works on plain data; Build() and those
// verbs gather it from the Configuration, so this partition knows nothing of
// one.
export namespace Crafter {
// The runtime an executable packaged as a Flatpak runs on. Its branch is
// always the one crafter-build itself runs on: the program is linked
// against that Sdk's glibc, which the Platform of the same branch carries
// as well, and an older runtime's glibc would not load it.
enum class FlatpakRuntime {
// org.freedesktop.Platform: what a program needs to run.
Platform,
// org.freedesktop.Sdk, for a program that runs tools at run time that
// the Platform does not have, git for one.
Sdk,
};
// A file or directory of the project installed under /app/share.
struct FlatpakShareEntry {
// A file, or a directory: every regular file in it, at its path
// inside it, leaving out empty directories and links to directories.
fs::path source;
// Where under /app/share, relative to it: "crafter-review/process",
// "licenses/net.example.App/LICENSE".
fs::path target;
};
// What an executable packaged as a Flatpak is installed as. Read for an
// executable whose Configuration::packaging makes it one, except
// `permissions`, which every configuration may declare: a library's
// reach each executable built on it.
struct FlatpakApp {
// The application ID, reverse-DNS. Empty means
// DefaultFlatpakAppId(outputName).
std::string appId;
FlatpakRuntime runtime = FlatpakRuntime::Platform;
// The sandbox's permissions, spelled as Flatpak's finish-args are:
// "--socket=wayland", "--device=dri", "--filesystem=xdg-documents:ro".
// An executable gets those of its dependencies first and its own
// last, and flatpak takes a later one over an earlier one for the
// same socket, device, path or bus name, so "--nosocket=x11" takes
// back what a library granted. `crafter-build install` and `bundle`
// print the resulting list, naming where each came from, and hand
// it to the host's flatpak build-finish, which refuses one it does
// not know. The build itself does not read them.
std::vector<std::string> permissions;
// A desktop entry, installed as <appId>.desktop. Its Icon= has to be
// the app-id, and desktop-file-validate, where there is one, has to
// pass it, as one a share entry places under that name has to. Empty:
// the app has none but what a share entry places.
fs::path desktopFile;
// AppStream metadata, installed as <appId>.metainfo.xml.
fs::path metainfo;
// The app's icons, each installed under the app-id: an .svg as
// scalable, a .png at its own size, which has to be square.
std::vector<fs::path> icons;
// Files the program reads that belong in /app/share rather than next
// to it, where cfg.files goes: data a program finds at <its
// directory>/../share/<name>, licences. They are copied into
// files/share, kept there as long as they are listed, and gone from
// it once they are not; files/share is the writer's, and anything
// else in it is removed. -r runs the program from files/bin, so the
// same ../share lookup finds them there. Any file may be one, a
// second desktop entry or an add-on's metainfo among them: flatpak
// build-finish exports what it exports of them by its own rules, as
// for any app's, and build-export refuses an icon that is not a
// square image or a D-Bus service that is not a key file, and warns
// of the app's own desktop entry where desktop-file-validate rejects
// it. None may go where another file goes, a field's included, and a
// directory may neither hold what the build writes, which it would
// copy into itself, nor lie in it, the build's own output: files/,
// and the app's directory, FlatpakAppDir(), where install and bundle
// put another copy of files/ and the exported app, however their
// links lead.
std::vector<FlatpakShareEntry> share;
// flatpak-builder module files, in Flatpak's own format (JSON or
// YAML), for what the app needs in /app besides the program: a
// runtime it starts, a tool it runs, data built from source. With
// any, `crafter-build install` and `bundle` have flatpak-builder make
// the app from a manifest that lists them and copies the program in
// last, so the program is not compiled again. crafter-build only
// names them; flatpak-builder reads them.
std::vector<fs::path> modules;
};
// local.crafterbuild.<outputName>: no published application uses the
// .local domain, which is reserved for mDNS, so an app installed under it
// cannot replace one. A character an application ID cannot hold becomes
// `_`, and a leading digit gets a `_` before it.
std::string DefaultFlatpakAppId(std::string_view outputName);
// Why `appId` is not a name Flatpak takes for an application; empty when
// it is one. build-export accepts an invalid one, and only build-bundle
// and an install refuse it, so the build checks.
std::string FlatpakAppIdError(std::string_view appId);
// Everything WriteFlatpakFiles needs, gathered by Build().
struct FlatpakFiles {
// BinDir(): files/ is written here.
fs::path root;
// A file in BuildDir() remembering what the previous write placed.
fs::path record;
std::string appId;
// The program's file name in files/bin: the app's command.
std::string command;
fs::path desktopFile;
fs::path metainfo;
std::vector<fs::path> icons;
std::vector<FlatpakShareEntry> share;
// FlatpakAppDir(): build-dir/files there is files/ again once install
// or bundle has run, so no share entry may copy from it.
fs::path appDir;
// Where the toolchain's clang++ and llvm-readelf are: clang names the
// LLVM runtime libraries the program links, readelf what it needs.
fs::path clangxx;
fs::path readelf;
// Where the program's other shared libraries are found, in the order
// its link searches them: the directories of the shared libraries it
// is built on, which an unpackaged link records as run paths, then
// the toolchain's own lib dir (Toolchain::LibcxxLibDir), /app/lib in
// crafter-build's Flatpak.
std::vector<fs::path> libraryDirs;
// The top-level names the build itself places in files/bin: the
// program, its shaders, cfg.files and assets, and what its
// dependencies forward. Anything else there is not the build's.
std::set<std::string> programEntries;
};
// Lays out what becomes /app around the program Build() linked into
// files/bin: files/share with the desktop file, metainfo and icons under
// the app-id and the `share` entries at the paths they name, and
// files/lib with the shared libraries the program needs that the
// runtime does not have. Those are the LLVM runtime libraries the
// toolchain links into every program, and whatever else of its NEEDED
// entries, and theirs, `libraryDirs` holds; a name found in neither is
// the runtime's. That is the files/ of a Flatpak build directory; its
// metadata and export/ are flatpak build-finish's to write, which
// decides what the sandbox's permissions mean and what the host sees of
// the app.
//
// The writer owns files/lib and files/share outright, and changes a file
// only when what it would write differs, so a build that changed nothing
// leaves every mtime alone. In files/bin it works on top-level entries,
// those `programEntries` names: it removes each that an earlier write
// recorded as placed by the build and this one does not, and reports
// those neither placed, files the program wrote itself under `-r`, which
// would ship with the app. Inside a directory the build copies there, of
// cfg.files or assets, it removes nothing, as the bin dir of an
// unpackaged build does not. Returns why it could not finish; empty when
// it did.
std::string WriteFlatpakFiles(const FlatpakFiles& files);
}
namespace Crafter {
// Adds `names` to the top-level entries of files/bin that the writer's
// record at `record` counts as the build's, for a build that copied
// into files/bin and failed before the writer ran: the next write then
// removes those it does not place, rather than take them for files the
// program wrote. Writes only what changes, and never throws, as Build()
// calls it on every way out.
void RecordFlatpakPlaced(const fs::path& record, const std::set<std::string>& names);
// For :Clang's install and bundle alone, kept out of the API a
// project.cpp compiles against, so that the names cannot meet one of its
// own under `using namespace Crafter`.
// A permission and the configuration that declared it.
struct FlatpakPermission {
std::string argument;
std::string source;
};
// What `crafter-build install` and `bundle` hand the host's flatpak,
// gathered from the Configuration like FlatpakFiles. Paths are absolute:
// the host runs the commands from its /.
struct FlatpakExport {
// BinDir()/files, as WriteFlatpakFiles left it.
fs::path files;
// <project>/build/flatpak-apps/<app-id>: the repo, the build
// directory the app is finished in, and with modules the manifest
// and flatpak-builder's state. One per app rather than per variant,
// because the state is flatpak-builder's cache, and a variant-keyed
// path would build every module again after each compiler update.
fs::path work;
std::string appId;
std::string command;
FlatpakRuntime runtime = FlatpakRuntime::Platform;
// The arch and branch of the runtime crafter-build runs on, from its
// /.flatpak-info: the app's runtime and Sdk are at the same.
std::string arch;
std::string branch;
// The executable's dependencies' first, its own last.
std::vector<FlatpakPermission> permissions;
std::vector<fs::path> modules;
};
// The manifest flatpak-builder makes an app with modules from: the
// app-id, runtime, sdk, command and finish-args, the project's modules,
// and last a module that copies files/ into /app as it is.
std::string FlatpakManifestText(const FlatpakExport& app);
// Makes the app on the host and puts it into work/repo. Without modules,
// the host's flatpak build-finish finishes work/build-dir, made afresh
// each time from a metadata naming the app, its runtime and the Sdk and
// a copy of files/, hard links where they can be made: it writes the
// command and the sandbox's permissions into the metadata, and export/,
// by flatpak's own rules, and refuses a permission it does not know.
// flatpak build-export then puts that into the repo. With modules,
// flatpak-builder makes the app from FlatpakManifestText, written to
// work/<app-id>.json, and runs build-finish itself. Either way the
// permissions are printed first, with where each came from, so a
// refusal can be traced to the configuration that declared it.
// Returns why it could not; empty when it did. HostFlatpakUnavailable is
// the caller's to check first, and the lock on work/ that
// InstallFlatpakApp and BundleFlatpakApp take is the caller's to hold:
// every variant of the app exports into the one repo.
std::string ExportFlatpak(const FlatpakExport& app);
}

View file

@ -3,6 +3,7 @@
export module Crafter.Build:Implementation; export module Crafter.Build:Implementation;
import std; import std;
import :Jobs;
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace Crafter { namespace Crafter {
@ -10,15 +11,21 @@ namespace Crafter {
export class ModulePartition; export class ModulePartition;
export class Implementation { export class Implementation {
public: public:
// What this unit imports, as in ModulePartition: for a unit of a
// module (`module X;`), the module's primary interface among them.
std::vector<Module*> moduleDependencies; std::vector<Module*> moduleDependencies;
std::vector<ModulePartition*> partitionDependencies; std::vector<ModulePartition*> partitionDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies; std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
// See ModulePartition::pendingImports — imports this TU declared that
// no reachable Configuration provided when the source was scanned.
std::vector<std::string> pendingImports;
fs::path path; fs::path path;
Implementation(fs::path&& path); Implementation(fs::path&& path);
bool Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const; // Whether `object`, the object Build() keeps for this unit
void Compile(const std::string_view clang, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) const; // (ObjectPath), has to be written again.
bool Check(const fs::path& object, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const;
// Adds the job that compiles this unit into `object` to `jobs`, after
// the BMIs of the stale interface units it imports
// (ModulePartition::Schedule, Module::Schedule), whose own objects go
// to `buildDir`. For a unit Check found stale. `shown` is the source
// as the job's progress line names it.
void Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, const fs::path& object, std::string_view shown) const;
}; };
} }

View file

@ -3,51 +3,83 @@
export module Crafter.Build:Interface; export module Crafter.Build:Interface;
import std; import std;
import :Jobs;
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace Crafter { namespace Crafter {
export class Module; export class Module;
export class ModulePartition { export class ModulePartition {
public: public:
// What this unit imports, as the Build() that made it read the
// source: modules of its own configuration, partitions of its own
// module, and modules of the configurations it is built on, each of
// those with the BMI that configuration's build writes. An import of
// anything else, `std` or a module from outside the build, has no
// entry.
std::vector<Module*> moduleDependencies; std::vector<Module*> moduleDependencies;
std::vector<ModulePartition*> partitionDependencies; std::vector<ModulePartition*> partitionDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies; std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
// Names from `import X;` that matched neither a module in this // The state of the Build() that made this unit: whether Check has
// Configuration nor one reachable through its dependencies at the time // run, what it found, whether Schedule has added this unit's jobs,
// the source was scanned. Retried by ResolvePendingImports (see // and the one among them that writes its BMI, which is the job the
// Crafter.Build:Clang) so a dependency wired up after // units importing it come after.
// GetInterfacesAndImplementations still produces a staleness edge.
// Names that never resolve (`std`, module-mapped externals) stay here.
std::vector<std::string> pendingImports;
std::atomic<bool> compiled;
bool needsRecompiling = false; bool needsRecompiling = false;
bool checked = false; bool checked = false;
bool scheduled = false;
std::optional<JobGroup::Job> precompileJob;
std::string name; std::string name;
fs::path path; fs::path path;
ModulePartition(std::string&& name, fs::path&& path); ModulePartition(std::string&& name, fs::path&& path);
// Whether this unit's BMI has to be written again. The object made
// from the BMI is not Check's to judge: see Schedule.
bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()); bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min());
void Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError); // Adds the jobs this unit needs to `jobs`, once however often it is
// called, and returns the one that writes its BMI, if there is one.
//
// A unit Check found stale gets two, one for each run of `clang`: the
// BMI, after the BMIs of the stale units this one imports, which are
// scheduled here as well, and then the object from that BMI, which
// only the link waits for, so that the units importing this one start
// when the first is done.
//
// A unit whose BMI is up to date gets the second job alone when its
// object is missing or older than the BMI. A build that fails or is
// interrupted between the two leaves a unit like that, and by its BMI
// alone every build after it would call the unit built: the link then
// took the object of the source before the edit, or found none.
//
// Every unit this one imports must have been checked: Build() checks
// all of a configuration's interfaces before it schedules any.
std::optional<JobGroup::Job> Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir);
}; };
export class Module { export class Module {
public: public:
// A primary module interface unit imports things too — `import Base;` // A primary module interface unit imports things too — `import Base;`
// in `export module Widget;` is as much a layout dependency as the // in `export module Widget;` is as much a layout dependency as the
// same line in a partition. Recorded on the same three vectors, with // same line in a partition. Recorded as a partition records the
// the same meanings, so Check() can see through them and Compile() // modules it imports, with the same meanings, so Check() can see
// can order itself behind a sibling module in the same Configuration // through them and Schedule() can order itself behind a sibling
// (issue #26). // module in the same Configuration (issue #26). The partitions it
// imports need no entry: it is checked and built after all of its
// module's partitions.
std::vector<Module*> moduleDependencies; std::vector<Module*> moduleDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies; std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
std::vector<std::string> pendingImports; // As in ModulePartition.
std::atomic<bool> compiled;
bool needsRecompiling = false; bool needsRecompiling = false;
bool checked = false; bool checked = false;
bool scheduled = false;
std::optional<JobGroup::Job> precompileJob;
std::vector<std::unique_ptr<ModulePartition>> partitions; std::vector<std::unique_ptr<ModulePartition>> partitions;
std::string name; std::string name;
fs::path path; fs::path path;
Module(std::string&& name, fs::path&& path); Module(std::string&& name, fs::path&& path);
bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()); bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min());
void Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError); // As ModulePartition::Schedule, for the primary interface, and
// schedules every partition of the module with it. The primary
// interface comes after every stale partition of the module,
// whichever of them it imports, and after the stale sibling modules
// it imports.
std::optional<JobGroup::Job> Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir);
}; };
} }

View file

@ -0,0 +1,129 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Crafter.Build:Jobs;
import std;
export namespace Crafter {
// The threads build steps run on: a fixed number of workers taking jobs
// from one queue, so that no more steps run at once than there are
// workers, whichever builds they belong to. Process() is the pool every
// build in this process shares, with a worker per hardware thread.
//
// A job is one step of a build: one compiler, linker or archiver run, one
// shader or asset compiled in process. The pool bounds the steps that run
// at once, not the threads a step starts for itself, as lld does for a
// link and the compressor of Crafter.Asset for an asset.
//
// A job never waits for another job. Whatever waits does so on a
// thread that is not a worker: a Build() for the builds of its
// dependencies, a step for the steps it comes after (JobGroup holds it
// back instead). A worker that waited for a job still in the queue would
// keep from it the very thread it needs, and with every worker waiting
// like that nothing would run again.
//
// Before this, Build() started a thread for every stale shader, asset
// to compress, C, CUDA and C++ unit, and nothing bounded how many of
// them ran at once.
class JobPool {
public:
// At most `workers` jobs at once, at least one. The threads are
// started as jobs need them: a build with two stale files starts two.
explicit JobPool(std::uint32_t workers);
// Runs what is still queued, then joins the workers. Nothing may be
// handing it jobs any more: every group on it is gone by then.
~JobPool();
JobPool(const JobPool&) = delete;
JobPool& operator=(const JobPool&) = delete;
// The pool of this process: one worker per hardware thread
// (std::thread::hardware_concurrency), and one where that is not
// known. Never destroyed, so that its workers are not joined while
// the statics the last job may still be using are being destroyed.
static JobPool& Process();
std::uint32_t Workers() const;
// Runs `work` on a worker and returns when it has finished; what it
// throws is thrown here. For a step that stands by itself, as
// RunBuildCommand uses it for a link. Called on a worker of this
// pool it runs `work` there and then, since that thread is the one
// the step would have occupied.
void Run(const std::function<void()>& work);
private:
friend class JobGroup;
// Queues `job`, which must not throw. Throws only when the pool has
// no thread and cannot start one, and then `job` is not queued.
void Submit(std::function<void()> job);
void Work();
const std::uint32_t limit;
std::mutex mutex;
std::condition_variable wake;
std::deque<std::function<void()>> queue;
std::vector<std::thread> threads;
// Workers waiting for a job. A job queued while one waits is its to
// take, so a thread is only started for a job beyond those.
std::uint32_t idle = 0;
bool stopping = false;
};
// The jobs of one piece of work, such as the build of a configuration,
// on the workers of a pool. A job starts once every job it was added
// after has finished, so the order steps need (a unit after the BMIs it
// imports) costs no thread while it is waited for.
//
// The first job to fail fails the group: no job of it starts after that,
// the ones already running finish, and Wait() returns that first error.
// Fail() does the same for work done outside the jobs, so one group
// holds the outcome of everything a build runs at once.
class JobGroup {
public:
using Job = std::size_t;
// Throws std::logic_error on a worker of `pool`: a job that waited
// for jobs of its own would occupy a worker they need (see JobPool).
explicit JobGroup(JobPool& pool = JobPool::Process());
// Keeps what has not started from starting and waits for what is
// running, so a job never outlives what it was given by reference,
// whichever way the scope that made the group is left.
~JobGroup();
JobGroup(const JobGroup&) = delete;
JobGroup& operator=(const JobGroup&) = delete;
// Adds a job, counted as a Progress::Task under `label` from now
// until it has finished or been skipped. It starts once every job in
// `after` has finished, at once when there is none; `after` names
// jobs of this group, so a job can only come after ones added before
// it and no two can wait for each other. `work` returns what went
// wrong, empty when nothing did; an exception it throws is its error
// too. It runs on a worker: it must not wait for other jobs, and it
// must own what it uses or use only what outlives the group.
Job Add(std::string label, std::function<std::string()> work, std::span<const Job> after = {});
// Fails the group with `error`, as a job returning it would. Without
// effect on a group that has already failed.
void Fail(std::string error);
bool Failed() const;
// Returns once every job added so far has finished or been skipped:
// the first error, empty when there was none.
std::string Wait();
private:
struct Node;
void Start(Node& node);
void Execute(Node& node);
JobPool& pool;
mutable std::mutex mutex;
std::condition_variable settled;
// Owned through pointers: a job on a worker holds on to its node
// while Add() grows the vector.
std::vector<std::unique_ptr<Node>> nodes;
std::size_t unfinished = 0;
bool failed = false;
std::string error;
};
}

View file

@ -30,7 +30,8 @@ export namespace Crafter {
// Absolute path of the loaded project.cpp. It is linted too, and its // Absolute path of the loaded project.cpp. It is linted too, and its
// parent directory is the project root that decides which dependency // parent directory is the project root that decides which dependency
// Configurations contribute rules/files (GitProject / cache-dir deps // Configurations contribute rules/files (GitProject / cache-dir deps
// are foreign code and skipped). Empty => fall back to cfg.path. // are foreign code and skipped). Empty => fall back to cfg.path, of
// several configurations the first one's.
std::filesystem::path projectFile; std::filesystem::path projectFile;
}; };
@ -62,4 +63,10 @@ export namespace Crafter {
// findings compiler-style (Report), would-change paths (Check), or // findings compiler-style (Report), would-change paths (Check), or
// formatted paths (Apply), plus a summary line. // formatted paths (Apply), plus a summary line.
LintSummary RunLint(Configuration& projectCfg, const RunLintOptions& opts); LintSummary RunLint(Configuration& projectCfg, const RunLintOptions& opts);
// The same for the several configurations a project file returns, as
// one run over all of them: each is a root, and the roots come before
// what any of them depends on, in the order given. A rule two of them
// register under one name runs once, as the first of them in that order
// registered it, and a source two of them reach is linted once.
LintSummary RunLint(std::span<Configuration* const> configurations, const RunLintOptions& opts);
} }

View file

@ -42,6 +42,11 @@ namespace Crafter {
// Returns an empty string on success (any warnings go to the user via // Returns an empty string on success (any warnings go to the user via
// Progress::Diagnostic), otherwise the compiler's diagnostics. Callers // Progress::Diagnostic), otherwise the compiler's diagnostics. Callers
// therefore keep the `if (!result.empty())` shape they already had. // therefore keep the `if (!result.empty())` shape they already had.
//
// The command runs on a worker of JobPool::Process(), so no more of these
// steps run at once than that pool has workers: called on one of its
// workers it runs there, called from any other thread it waits for one.
// A step that runs a compiler any other way is not counted.
std::string RunBuildCommand(std::string_view command); std::string RunBuildCommand(std::string_view command);
export CommandResult RunCommandWithTimeout(std::string_view command, std::chrono::seconds timeout); export CommandResult RunCommandWithTimeout(std::string_view command, std::chrono::seconds timeout);
// Runs `command` through sh with this process's own stdin, stdout and // Runs `command` through sh with this process's own stdin, stdout and
@ -53,21 +58,148 @@ namespace Crafter {
// and not to crafter-build, which then sees it as exit code 130. // and not to crafter-build, which then sees it as exit code 130.
// Project scripts reach this through ScriptContext::Run. // Project scripts reach this through ScriptContext::Run.
std::int32_t RunCommandAttached(std::string_view command); std::int32_t RunCommandAttached(std::string_view command);
// One change to the environment a command inherits from this process:
// the variable set to `value`, or taken out when there is none.
struct EnvironmentChange {
std::string name;
std::optional<std::string> value;
};
// A command that runs beside its caller, through sh, until Stop() or the
// destructor ends it: the compositor of a test that sets Test::wayland.
// Its stdin is /dev/null and its stdout and stderr go to `log`. It is
// the leader of a process group of its own, so that Stop() reaches what
// it starts in turn, as long as that stays in the group, and runs under `timeout`, which ends that group
// after `lifetime` if nothing else has, a `lifetime` of 0 being none,
// as for timeout(1). The timeout process is also sent
// SIGTERM, which it passes on to the group, when the thread that
// constructed this ends, so a crafter-build that is killed, by Ctrl-C
// or otherwise, leaves no command of this kind running. That is why the
// object has to stay on the thread that made it. Throws when the command
// cannot be started.
class BackgroundCommand {
std::int32_t pid = -1;
std::optional<std::int32_t> exitCode;
bool reaped = false;
public:
BackgroundCommand(std::string_view command, std::span<const EnvironmentChange> environment, const fs::path& log, std::chrono::seconds lifetime);
~BackgroundCommand();
BackgroundCommand(const BackgroundCommand&) = delete;
BackgroundCommand& operator=(const BackgroundCommand&) = delete;
// The command's exit code once it has ended on its own, 128+signal
// when a signal ended it; nullopt while it runs. Does not wait.
std::optional<std::int32_t> Exited();
// Sends the group SIGTERM, then SIGKILL to whatever of it is left
// once the command has ended or `grace` has passed, and waits for the
// command. Further calls do nothing.
void Stop(std::chrono::milliseconds grace);
};
// A new directory in `parent`, named `prefix` and six random characters,
// that only this user may enter (mkdtemp), removed with everything in it
// when this ends, unless it is kept. A process that is killed runs no
// destructor, so this also holds an flock on the directory, which the OS
// drops with the process, and making one removes the directories of
// `prefix` in `parent` that nobody holds and that have not changed for a
// minute: left behind by a process that is gone, or kept. The minute
// covers one that is being made at that moment, between mkdtemp and its
// lock. Throws when the directory cannot be made.
// Exported for the tests that make a directory of their own outside the
// temp directory.
export class PrivateDirectory {
std::int32_t fd = -1;
std::atomic<bool> kept{false};
public:
const fs::path path;
PrivateDirectory(const fs::path& parent, std::string_view prefix);
~PrivateDirectory();
PrivateDirectory(const PrivateDirectory&) = delete;
PrivateDirectory& operator=(const PrivateDirectory&) = delete;
// The destructor leaves the directory where it is, unlocked and
// dated as it lets go of it, so that what is in it can be looked at
// for a minute at least, until it is removed as one that nobody
// holds. Several threads may call it at once.
void Keep() { kept = true; }
};
// The link flags that record `dir` as a run path, with -Xlinker rather
// than -Wl,: clang splits a -Wl, value at every comma, and `dir` may be a
// project's own directory, named whatever its owner chose. Quoted for
// the shell the link runs in.
std::string RunPathFlags(std::string_view dir);
// `s` as one single-quoted sh word, safe to splice into a command line // `s` as one single-quoted sh word, safe to splice into a command line
// whatever it contains: paths with spaces, arguments a user typed. // whatever it contains: paths with spaces, arguments a user typed.
export std::string ShellQuote(std::string_view s); export std::string ShellQuote(std::string_view s);
// `s` as a JSON string, quotes included, whatever it contains: what a
// generated manifest or variants.json writes for a path or an argument.
std::string JsonQuote(std::string_view s);
// Why crafter-build cannot run the host's flatpak for a project in
// `projectDir`; empty when it can. Natively that is the flatpak on PATH.
// Inside crafter-build's Flatpak it takes the org.freedesktop.Flatpak
// permission, a session bus to reach the host's Flatpak session helper
// over (flatpak-builder's build sandbox, where CI runs, has neither), and
// a host that sees the project's bin/ and build/ where crafter-build
// does, which it does not in the sandbox's own /tmp, /var, /usr, /etc or
// /app: the host's flatpak is started in a directory made in each for
// it, so bin/ and build/ are made where they are missing.
export std::string HostFlatpakUnavailable(const fs::path& projectDir);
// Runs `flatpak <arguments>` on the host with the terminal attached,
// after echoing it as ScriptContext::Run does, and returns its exit
// code. Inside crafter-build's Flatpak it goes through flatpak-spawn
// --host --watch-bus, so the host command ends when flatpak-spawn does,
// starts it in the host's /, whatever crafter-build's working directory,
// and passes FLATPAK_USER_DIR on when it is set. crafter-build's own code
// reaches the host only through HostCommand, the builder of host command
// lines this shares with RunHostFlatpakBuilder and HostFlatpakUnavailable's
// probes, for the host's flatpak and flatpak-builder; add no other host
// command (AGENTS.md, Security considerations). The permission is the
// sandbox's, not this function's: anything else that runs there, a
// project.cpp among them, can use it through flatpak-spawn --host
// without this. Exported for the tests. Host commands have no terminal
// of their own, so `arguments` must not need one to answer a prompt.
export std::int32_t RunHostFlatpak(std::string_view arguments);
// `flatpak-builder <arguments>` the same way: the host's flatpak-builder,
// or the org.flatpak.Builder app where the host has none.
std::int32_t RunHostFlatpakBuilder(std::string_view arguments);
std::string GetBaseCommand(const Configuration& config); std::string GetBaseCommand(const Configuration& config);
// The configurations `projectFile` describes, in the order it gives them.
// Compiles the file into a shared object in the build/ beside it, unless
// the one there is current, loads that into this process and calls the
// file's entry point with `args`. A project file defines one of two:
// extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args);
// extern "C" std::vector<Configuration*> CrafterBuildConfigurations(std::span<const std::string_view> args);
// The first is a project of one configuration, which comes back as a
// list of one. The second is a project of several that need not have
// anything to do with each other, such as a library and a tool, or the
// programs of one repository; they come back as the file returned them.
// The two names are how a loaded file says which it is: both are C
// symbols, which carry no return type, so one name with two return types
// would be called as whichever the loader guessed. Throws for a file
// that defines neither or both, and for a CrafterBuildConfigurations
// that returns nothing, a null pointer, one configuration twice, or one
// that a project GitProject or LocalProject loaded keeps to itself
// (KeptBy): every configuration in the list is one the file made or one
// those two returned.
//
// The pointers are used for as long as the process runs. What a
// CrafterBuildConfigurations returns is its project file's to keep that
// long, at addresses that do not change: in a std::deque the file only
// adds to, one new set per call, or what GitProject and LocalProject
// gave it. What a CrafterBuildProject returns is kept here, constructed
// by that call and never moved.
export std::vector<Configuration*> LoadConfigurations(const fs::path& projectFile, std::span<const std::string_view> args);
// What the CrafterBuildProject of `projectFile` returns, loaded as
// LoadConfigurations loads it. Throws for a project file that defines
// CrafterBuildConfigurations: the configurations that one returns stay
// where the file keeps them and cannot be returned by value.
export Configuration LoadProject(const fs::path& projectFile, std::span<const std::string_view> args); export Configuration LoadProject(const fs::path& projectFile, std::span<const std::string_view> args);
// A dependency the project file currently running its CrafterBuildProject // A dependency the project file currently running its entry point
// declared with `#pragma crafter dependency`, so it can also be wired // declared with `#pragma crafter dependency`, so it can also be wired
// into the build graph (a test that links the same module, say) without // into the build graph (a test that links the same module, say) without
// spelling the source twice. `name` is the dependency's Configuration // spelling the source twice. `name` is the dependency's Configuration
// name or any module it exports — whatever the project file `import`s. // name or any module it exports — whatever the project file `import`s.
// Throws when no such dependency was declared, or when called from // Throws when no such dependency was declared, or when called from
// anywhere other than inside LoadProject. // anywhere other than inside a project file's load.
export Configuration* ProjectDependency(std::string_view name); export Configuration* ProjectDependency(std::string_view name);
// True while the project file crafter-build was pointed at runs its // True while the project file crafter-build was pointed at runs its
// CrafterBuildProject, and when no project file is running at all; false // entry point, and when no project file is running at all; false
// inside a dependency's project file (a `#pragma crafter dependency`, // inside a dependency's project file (a `#pragma crafter dependency`,
// GitProject or LocalProject target). Wire anything only the project's // GitProject or LocalProject target). Wire anything only the project's
// own build or test run needs behind it. The case that forced it: a // own build or test run needs behind it. The case that forced it: a
@ -76,9 +208,9 @@ namespace Crafter {
// project file in turn and the two recurse until the cycle guard throws. // project file in turn and the two recurse until the cycle guard throws.
export bool IsTopLevelProject(); export bool IsTopLevelProject();
// What the `#pragma crafter dependency` lines of `projectFile` resolved // What the `#pragma crafter dependency` lines of `projectFile` resolved
// to the last time LoadProject loaded it in this process, in file order; // to the last time it was loaded in this process, in file order;
// empty when it has none or was never loaded. Unlike ProjectDependency // empty when it has none or was never loaded. Unlike ProjectDependency
// this still answers once LoadProject has returned, which is when the // this still answers once the load has returned, which is when the
// dependency notes of the project crafter-build was pointed at are // dependency notes of the project crafter-build was pointed at are
// gathered (Crafter.Build:Agents). // gathered (Crafter.Build:Agents).
std::vector<Configuration*> PragmaDependencies(const fs::path& projectFile); std::vector<Configuration*> PragmaDependencies(const fs::path& projectFile);
@ -93,10 +225,10 @@ namespace Crafter {
// derives <prefix>/share/crafter-build from the running executable's path. // derives <prefix>/share/crafter-build from the running executable's path.
export fs::path GetCrafterBuildHome(); export fs::path GetCrafterBuildHome();
// Newest mtime among the prerequisites a compiler recorded in `depFile` // Newest mtime among the prerequisites a compiler recorded in `depFile`
// (clang's `-MD -MF <artifact>.d`). This is how a build step learns which // (clang's `-MD -MF <artifact>.d`), or clang-scan-deps for the scan of
// headers its source pulled in: the module scanner only reads `import` // a C++ source. This is how a build step learns which headers its
// lines, so an `#include`d file is invisible to it until the compiler // source pulled in: only the tool that preprocessed the source knows
// reports what it actually opened. // which files its #includes opened.
// //
// Returns file_time_type::max() when freshness cannot be proven — no // Returns file_time_type::max() when freshness cannot be proven — no
// depfile (nothing has compiled this artifact since depfiles were emitted, // depfile (nothing has compiled this artifact since depfiles were emitted,

View file

@ -12,8 +12,10 @@ export namespace Crafter::Progress {
// RAII work-unit marker. Construction inflates the running total; destruction // RAII work-unit marker. Construction inflates the running total; destruction
// increments completed and (on Default + TTY) redraws the status line. Move // increments completed and (on Default + TTY) redraws the status line. Move
// semantics are disabled — keep these as plain stack locals inside the worker // semantics are disabled — keep these as plain stack locals around the work
// lambda so the destructor fires when that thread's work ends. // they count, so the destructor fires when it ends. A job of a JobGroup
// gets one from Add(), made when the job is queued, which is what puts
// work that has not started yet in the total.
class Task { class Task {
public: public:
explicit Task(std::string label); explicit Task(std::string label);

View file

@ -19,7 +19,8 @@ export namespace Crafter {
// Print the script names instead of running one. // Print the script names instead of running one.
bool listOnly = false; bool listOnly = false;
// Absolute path of the loaded project.cpp; its directory becomes // Absolute path of the loaded project.cpp; its directory becomes
// ScriptContext::projectDir. Empty => fall back to cfg.path. // ScriptContext::projectDir. Empty => fall back to the path of the
// configuration the script is declared on.
std::filesystem::path projectFile; std::filesystem::path projectFile;
}; };
@ -37,4 +38,10 @@ export namespace Crafter {
// (a raw wait status passed along by mistake) would otherwise wrap to // (a raw wait status passed along by mistake) would otherwise wrap to
// success. // success.
std::int32_t RunScript(Configuration& projectCfg, const RunScriptOptions& opts); std::int32_t RunScript(Configuration& projectCfg, const RunScriptOptions& opts);
// The same over the scripts of several configurations, the ones a
// project file returns, as one list in the order given: a name two of
// them declare is a name declared twice, and a configuration the list
// names twice counts once. The script's ScriptContext::project is the
// configuration it is declared on.
std::int32_t RunScript(std::span<Configuration* const> configurations, const RunScriptOptions& opts);
} }

View file

@ -24,8 +24,8 @@ export namespace Crafter {
// interfaces. The builder only mutates compile state, deps, runtime // interfaces. The builder only mutates compile state, deps, runtime
// args, and requires; it deliberately does NOT expose Sources() to // args, and requires; it deliberately does NOT expose Sources() to
// avoid the double-`GetInterfacesAndImplementations` footgun (calling // avoid the double-`GetInterfacesAndImplementations` footgun (calling
// it twice would re-parse the same .cppm files into duplicate Module // it twice would list the same .cppm files twice, and the build would
// entries). // make a Module entry of each listing).
struct TestBuilder { struct TestBuilder {
Configuration* parent; Configuration* parent;
std::size_t index; std::size_t index;
@ -53,10 +53,17 @@ export namespace Crafter {
TestBuilder& LinkFlag(std::string f); TestBuilder& LinkFlag(std::string f);
// Append a single compile flag. // Append a single compile flag.
TestBuilder& CompileFlag(std::string f); TestBuilder& CompileFlag(std::string f);
// Sets Test::wayland: the test runs with a headless Wayland
// compositor of its own.
TestBuilder& Wayland(bool w = true);
}; };
struct RunTestsOptions { struct RunTestsOptions {
std::vector<std::string> globs; std::vector<std::string> globs;
// Tests built and run at once, from --jobs=; 0 is one per hardware
// thread. It counts tests, not build steps: the steps of their builds
// run on JobPool::Process() under that pool's own limit, and a test
// that is running is not one of them.
std::int32_t jobs = 0; std::int32_t jobs = 0;
std::optional<std::chrono::seconds> timeoutOverride; std::optional<std::chrono::seconds> timeoutOverride;
bool listOnly = false; bool listOnly = false;
@ -71,6 +78,10 @@ export namespace Crafter {
// Target scoping is unnecessary because targetFilter ensures the run // Target scoping is unnecessary because targetFilter ensures the run
// contains only one target's tests. // contains only one target's tests.
std::optional<std::string> runnerOverride; std::optional<std::string> runnerOverride;
// From --compositor=: the compositor every test of the run that sets
// Test::wayland runs with, in place of CRAFTER_BUILD_COMPOSITOR and
// the default. See RunSingleTest.
std::optional<std::string> compositorOverride;
}; };
struct TestSummary { struct TestSummary {
@ -84,14 +95,63 @@ export namespace Crafter {
}; };
TestSummary RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs = {}); TestSummary RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs = {});
TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout); // The tests of several configurations, those a project file returns, as
// one run: one sweep over the targets they declare, one summary, and
// one build pass per target, so a library that tests of two of them link
// is built once. The log a failed, crashed or timed-out test leaves
// goes under the path of the configuration that declares it. A test
// belongs to one configuration: where two of them each declare one that
// would be built into the same directory, which two tests of one name
// compiled alike are, both fail without being built and name the
// configurations. A configuration the list names twice counts once.
TestSummary RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs = {});
// Runs `binary` as `test` with its runner, its arguments and `timeout`,
// and reads the outcome from how it ended (exit 0 passes, 77 skips).
// With a `temporaryDirectory` the test's command runs with TMPDIR naming
// it; RunTests gives each test a directory of its own, made for the run.
// fs::temp_directory_path() in the test names it where the runner hands
// the test TMPDIR, as running it directly and qemu-user do. Under wine a
// Windows test does not get TMPDIR, and takes the Wine prefix's TMP, TEMP
// and temp directory; wasmtime gives a test no environment at all.
//
// When the test sets Test::wayland, a compositor is started for it
// first: `compositorOverride` when it holds a command, else the one
// CRAFTER_BUILD_COMPOSITOR names, else weston on its headless backend.
// The command runs through sh in a process group of its own, with
// XDG_RUNTIME_DIR naming a directory made for it alone and without
// WAYLAND_DISPLAY, WAYLAND_SOCKET or DISPLAY, and is waited for until
// a wayland-<n> socket appears in that directory, with a limit of the
// test's, the wait and 30 s more, or none when `timeout` is 0, which is
// no limit for the test either (timeout(1)). The test then runs
// with WAYLAND_DISPLAY set to the socket's path and DISPLAY and
// WAYLAND_SOCKET unset; afterwards the compositor's group is stopped and
// the directory removed. A compositor that ends before it listens, sh
// not finding it included, or does not listen within 30 s fails the
// test, with what it printed; a test that may run where its compositor
// is missing declares it in requires_ (tool:weston), which RunTests
// checks before the build. `host` starts nothing and leaves the test the
// display this process has, its WAYLAND_DISPLAY, WAYLAND_SOCKET, DISPLAY
// and XDG_RUNTIME_DIR; a `temporaryDirectory` is its TMPDIR all the same.
TestResult RunSingleTest(const Test& test, const std::filesystem::path& binary, std::chrono::seconds timeout, const std::optional<std::string>& compositorOverride = std::nullopt, const std::filesystem::path& temporaryDirectory = {});
// Parent-project access for test fixtures. Run() sets the pointer to the // The configurations of the project crafter-build was pointed at, by
// root project's Configuration before discovery; fixtures call ParentLib() // name. Run() hands SetParentProject what the project file returned,
// to obtain a Configuration* for one of the parent's libraries (or the // once it has loaded. ParentLib() then finds a Configuration* by
// parent itself) so they can declare it as a dependency without rebuilding // Configuration::name among them and what they depend on, searching the
// the lib config from scratch. Lookup is by Configuration::name and // dependency graph of each in the order the file returned them, and
// recurses through the parent's dependency graph. // throws when none has that name or no project is set.
void SetParentProject(Configuration* parent); void SetParentProject(Configuration* parent);
void SetParentProject(std::span<Configuration* const> parents);
Configuration* ParentLib(std::string_view name); Configuration* ParentLib(std::string_view name);
} }
namespace Crafter {
// A test is never packaged, whatever its Configuration asks for: the
// runner starts the binary itself. Sets every test of `cfg` so, for one
// from AddTest or AddMarchVariants and one a project.cpp put into
// cfg.tests itself alike. Every reader of cfg.tests that builds a test
// or works out its compile command, RunTests and RunLint, calls it
// first, so that they agree on the test's VariantId, and so on where its
// module PCMs are.
void UnpackageTests(Configuration& cfg);
}

View file

@ -7,17 +7,22 @@ namespace fs = std::filesystem;
export namespace Crafter { export namespace Crafter {
// The compiler crafter-build drives and what sits next to it, resolved // The compiler crafter-build drives and what sits next to it, resolved
// once per process by GetToolchain(). Every clang++, clang and llvm-ar // once per process by GetToolchain(). Every clang++, clang, llvm-ar and
// the tool spawns, the libclang the linter dlopens, the std module // clang-scan-deps the tool spawns, the libclang the linter dlopens, the
// source and the default sysroots come from here, so a toolchain // std module source and the default sysroots come from here, so a
// installed anywhere other than /usr (the Flatpak carries its own under // toolchain installed anywhere other than /usr (the Flatpak carries its
// /app) needs no per-call-site knowledge. // own under /app) needs no per-call-site knowledge.
struct Toolchain { struct Toolchain {
// LLVM install prefix. Empty when the tools are bare names on PATH. // LLVM install prefix. Empty when the tools are bare names on PATH.
fs::path prefix; fs::path prefix;
fs::path clangxx; fs::path clangxx;
fs::path clang; fs::path clang;
fs::path llvmAr; fs::path llvmAr;
// What a packaged program's shared libraries are read with.
fs::path llvmReadelf;
// What reads the module a C++ source declares and the modules it
// imports, by preprocessing it with its compile command (Build).
fs::path clangScanDeps;
// Where clang-c/Index.h lives when it is not on the default include // Where clang-c/Index.h lives when it is not on the default include
// path; empty otherwise. // path; empty otherwise.
fs::path llvmIncludeDir; fs::path llvmIncludeDir;
@ -39,20 +44,101 @@ export namespace Crafter {
fs::path wasiSysroot; fs::path wasiSysroot;
// The mingw-w64 install prefix, the directory that holds // The mingw-w64 install prefix, the directory that holds
// x86_64-w64-mingw32/ and lib/gcc/x86_64-w64-mingw32/ (/usr for a // x86_64-w64-mingw32/ and lib/gcc/x86_64-w64-mingw32/ (/usr for a
// distro package), passed to clang as --sysroot for the mingw target. // distro package), absolute and lexically normal. Empty means clang's
// Empty means clang's own discovery, which follows the mingw gcc on // own discovery, which follows the mingw gcc on PATH. Set by
// PATH. Set by CRAFTER_MINGW_DIR, else the host's /usr when running // CRAFTER_MINGW_DIR, else the host's /usr when running sandboxed and
// sandboxed and it has mingw-w64 (the sandbox's own /usr never does). // it has mingw-w64 (the sandbox's own /usr never does). What the
fs::path mingwSysroot; // mingw target passes as --sysroot is MingwSysroot(), not this:
// see mingwPrefixIsSystem.
fs::path mingwPrefix;
// The prefix holds a Linux system as well as mingw-w64: the host's
// /usr in the sandbox, or a prefix whose include/ has a C library's
// features.h, as /usr has. clang searches a mingw sysroot's include/
// and lib/, so such a prefix is shown to it only through a view of
// its mingw-w64 parts; any other prefix is the sysroot itself, and
// Windows libraries installed into its include/ and lib/ are found.
bool mingwPrefixIsSystem = false;
// The nvcc that compiles cfg.cuda: <CUDA_PATH>/bin/nvcc when CUDA_PATH
// is set, else bin/nvcc of the first toolkit that has one among
// ToolchainInputs::cudaRoots, else the first nvcc in an absolute entry
// of PATH. In a sandbox, a toolkit is looked up as the host has it:
// under hostRoot where it is in the host's /usr or /etc, and, where
// its path is a link, through that link and the link its target is in
// turn, each taken as the host's, wherever they point. Empty when
// there is none, and nvccError says where it was looked for; only a
// build with a .cu to compile reports that, so no other build fails
// for want of a CUDA toolkit.
fs::path nvcc;
std::string nvccError;
// What that nvcc is, for VariantId: its canonical path, size and
// modification time, which change when the toolkit is updated or
// replaced at the same path, as the path alone does not. Empty
// without an nvcc.
std::string nvccStamp;
// What -arch=native compiles for on this machine, for VariantId: the
// NVIDIA display devices the PCI bus lists, by address and device ID,
// and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose among
// them and number them, each unset apart from empty. Empty without an
// nvcc.
std::string cudaNativeKey;
// The static CUDA runtime a configuration with CUDA sources links:
// libcudart_static.a in the lib64 beside nvcc's bin. Empty without an
// nvcc, and where that lib64 holds none, as where a distribution keeps
// the toolkit's libraries in its own directories, or cannot be looked
// into: then nothing is linked, and cfg.linkFlags names the runtime.
fs::path cudaRuntime;
// The Flatpak runtime crafter-build runs on, from the
// runtime=runtime/<id>/<arch>/<branch> line of /.flatpak-info:
// "x86_64" and "26.08" in the Flatpak, both empty outside one. A
// program built here links that runtime's glibc, so an executable is
// only packaged as a Flatpak when they are set, and for that branch.
// CRAFTER_BUILD_FLATPAK_INFO names another file to read them from,
// for tests that package outside the Flatpak.
std::string flatpakArch;
std::string flatpakBranch;
// `clang++ -print-target-triple` and the first line of // `clang++ -print-target-triple` and the first line of
// `clang++ --version`; both empty when clang++ could not be run. // `clang++ --version`; both empty when clang++ could not be run.
std::string hostTriple; std::string hostTriple;
std::string clangVersion; std::string clangVersion;
// The directory clang++ is installed in, from the InstalledDir line
// of that `clang++ --version`. clang names the directory of the file
// it runs from, so for a clang++ found on PATH, or reached through a
// link into another directory, it is where the compiler really is,
// the directory its driver looks for headers and configuration files
// from (InstalledClangxx). Empty when clang++ could not be run or
// named no directory.
fs::path installedDir;
// The same line of `clang++ -no-canonical-prefixes --version`. With
// that flag clang names the directory of clang++ as written, or, where
// no file is there, as is usual for a bare name, of the one PATH
// gives, a link not followed, and a compile whose last prefix flag is
// that one looks from there. Empty as installedDir is.
fs::path installedDirAsWritten;
// Why clang++ could not be resolved or run; empty when it could. // Why clang++ could not be resolved or run; empty when it could.
std::string error; std::string error;
// clangxx as a program that runs a clang driver of its own over
// `command`, a compile command that starts with clangxx, has to be
// given it: the same file name in the directory clang started with
// that command takes itself to be in, installedDirAsWritten where the
// last of -canonical-prefixes and -no-canonical-prefixes in the
// command is -no-canonical-prefixes, as clang's own driver decides it,
// and installedDir otherwise. That driver takes the directory of the
// compiler it is given as written, without following a link to where
// the compiler is, and looks from there for what the compiler's own
// driver looks for from its directory: clang's own headers where it is
// not told where they are, libc++'s in a build for the host whose
// command names no libc++ directory, and its default configuration
// files. clangxx itself where that directory is empty.
fs::path InstalledClangxx(std::string_view command) const;
// Flags for compiling against libcxxDir; empty without one. // Flags for compiling against libcxxDir; empty without one.
std::string LibcxxCompileFlags() const; std::string LibcxxCompileFlags() const;
// Where libc++.so.1 is when clang would not find it itself: an
// explicit libcxxDir's lib, or <prefix>/lib of a toolchain outside
// /usr, /app/lib in crafter-build's Flatpak, which holds the rest of
// its LLVM as well. Empty for a toolchain in /usr, whose libraries
// are on the linker's and the loader's default paths.
fs::path LibcxxLibDir() const;
// Flags for linking against the libc++ the compiler will use: a -L // Flags for linking against the libc++ the compiler will use: a -L
// and an rpath for <prefix>/lib when the prefix is not the system one // and an rpath for <prefix>/lib when the prefix is not the system one
// (clang searches only its per-target runtime directory and the // (clang searches only its per-target runtime directory and the
@ -60,6 +146,9 @@ export namespace Crafter {
// the linker's nor the loader's default path), or for an explicit // the linker's nor the loader's default path), or for an explicit
// libcxxDir. // libcxxDir.
std::string LibcxxLinkFlags() const; std::string LibcxxLinkFlags() const;
// LibcxxLinkFlags without the rpath: for a program that finds its
// copy of libc++ somewhere else at run time, as a Flatpak does.
std::string LibcxxSearchFlags() const;
// Names this toolchain for cache directory names: the clang version // Names this toolchain for cache directory names: the clang version
// followed by a hash of what decides which headers and libraries a // followed by a hash of what decides which headers and libraries a
// PCM is built against. Two toolchains with different keys never // PCM is built against. Two toolchains with different keys never
@ -69,23 +158,72 @@ export namespace Crafter {
// What ResolveToolchain reads, so a test can feed it a staged layout. // What ResolveToolchain reads, so a test can feed it a staged layout.
struct ToolchainInputs { struct ToolchainInputs {
// The CRAFTER_* variables, present only when set and non-empty. // The CRAFTER_* variables, CUDA_PATH and PATH, present only when set
// and non-empty.
std::map<std::string, std::string, std::less<>> env; std::map<std::string, std::string, std::less<>> env;
// The <prefix> of <prefix>/share/crafter-build; empty when unknown. // The <prefix> of <prefix>/share/crafter-build; empty when unknown.
fs::path crafterPrefix; fs::path crafterPrefix;
// Where the host's root shows inside a sandbox (/run/host in a // Where the host's root shows inside a sandbox (/run/host in a
// Flatpak); empty outside one. // Flatpak); empty outside one.
fs::path hostRoot; fs::path hostRoot;
// What /.flatpak-info holds, or the file CRAFTER_BUILD_FLATPAK_INFO
// names; empty outside a Flatpak.
std::string flatpakInfo;
// Where a CUDA toolkit is installed when CUDA_PATH names none, in the
// order they are tried and as the host names them: GetToolchain()
// passes /opt/cuda, Arch's, and /usr/local/cuda, NVIDIA's installers'.
std::vector<fs::path> cudaRoots;
// The PCI devices sysfs lists, one directory each with its vendor,
// device and class: GetToolchain() passes /sys/bus/pci/devices, which
// the sandbox shows too. What -arch=native compiles for is keyed by
// the NVIDIA display devices among them.
fs::path pciDevices;
// CUDA_VISIBLE_DEVICES, which chooses the GPUs -arch=native compiles
// for, when it is set: set but empty hides them all, which is not the
// same as unset, so it is kept apart from env, which holds non-empty
// values alone.
std::optional<std::string> cudaVisibleDevices;
// CUDA_DEVICE_ORDER, when it is set: it decides which GPU a number in
// CUDA_VISIBLE_DEVICES means, by PCI address or by speed.
std::optional<std::string> cudaDeviceOrder;
}; };
// Pure path resolution: an env override wins, then a toolchain installed // Pure path resolution: an env override wins, then a toolchain installed
// beside crafter-build (<crafterPrefix>/bin/clang++), then bare names on // beside crafter-build (<crafterPrefix>/bin/clang++), then bare names on
// PATH. Never runs a process, so hostTriple and clangVersion stay empty. // PATH. Never runs a process, so hostTriple and clangVersion stay empty.
// nvcc is not left to the shell's PATH lookup but searched for here,
// PATH included, so a build that cannot find one can say where it looked.
Toolchain ResolveToolchain(const ToolchainInputs& inputs); Toolchain ResolveToolchain(const ToolchainInputs& inputs);
// ResolveToolchain over the real environment plus the two clang probes, // ResolveToolchain over the real environment plus the two clang probes,
// computed once and cached. Never throws. // computed once and cached. Never throws.
const Toolchain& GetToolchain(); const Toolchain& GetToolchain();
// GetToolchain(), or a std::runtime_error carrying its error. // GetToolchain(), or a std::runtime_error carrying its error.
const Toolchain& RequireToolchain(); const Toolchain& RequireToolchain();
// Makes, in the first of `parents` that can hold one, a directory that
// shows clang only the mingw-w64 parts of `prefix`: links named
// x86_64-w64-mingw32, lib/gcc and lib64/gcc to the same paths under
// `prefix`, at <parent>/mingw-sysroot/<hash of prefix>, and returns it.
// A view already there is reused; one another process makes at the same
// moment is as good as one made here. Throws when no parent can hold
// one, with the reason for each.
fs::path MakeMingwSysroot(const fs::path& prefix, std::span<const fs::path> parents);
// The --sysroot of every compile, link and CMake configure for the mingw
// target, settled on the first call of a process: empty without a
// mingwPrefix, the prefix itself for one that holds mingw-w64 alone, and
// for a system prefix the view MakeMingwSysroot makes in crafter-build's
// cache, or in $XDG_RUNTIME_DIR/crafter.build when the cache's
// filesystem takes no symbolic links. A system prefix cannot be the
// sysroot: clang takes a mingw sysroot for a tree that holds mingw-w64
// alone and searches its include/ and lib/ as well, which for /usr are
// the Linux system's own. A Windows build then saw glibc's headers, and
// libstdc++, finding <sys/single_threaded.h>, had shared_ptr read
// __libc_single_threaded, which nothing on Windows defines (issue #43).
// Throws when the view cannot be made.
const fs::path& MingwSysroot();
// `text` with every path into the view MingwSysroot() made written as
// the same path into the prefix it shows, so that compiler messages name
// a header where the user installed it rather than in a hashed cache
// directory; `text` unchanged when no view was made.
std::string MingwViewToPrefix(std::string text);
// _LIBCPP_VERSION as the <__config> in `includeDir` (an include/c++/v1) // _LIBCPP_VERSION as the <__config> in `includeDir` (an include/c++/v1)
// defines it, XXYYZZ; 0 when the file is missing or has no such line. // defines it, XXYYZZ; 0 when the file is missing or has no such line.
std::int32_t LibcxxVersion(const fs::path& includeDir); std::int32_t LibcxxVersion(const fs::path& includeDir);

View file

@ -3,8 +3,10 @@
export module Crafter.Build; export module Crafter.Build;
export import :Toolchain; export import :Toolchain;
export import :Flatpak;
export import :Clang; export import :Clang;
export import :Platform; export import :Platform;
export import :Jobs;
export import :Implementation; export import :Implementation;
export import :Shader; export import :Shader;
export import :External; export import :External;

View file

@ -12,9 +12,10 @@
<description> <description>
<p> <p>
A build system for C++26 modules. Project descriptions are C++: a A build system for C++26 modules. Project descriptions are C++: a
project.cpp constructs a Configuration and returns it, and crafter-build project.cpp constructs a Configuration, or several, and returns them,
compiles, loads and executes it. The Flatpak carries its own LLVM, so and crafter-build compiles, loads and executes it. The Flatpak carries
every machine builds with the same clang, lld, libc++ and WASI sysroot. its own LLVM, so every machine builds with the same clang, lld, libc++
and WASI sysroot.
</p> </p>
</description> </description>
<url type="homepage">https://forgejo.catcrafts.net/Catcrafts/Crafter.Build</url> <url type="homepage">https://forgejo.catcrafts.net/Catcrafts/Crafter.Build</url>
@ -25,6 +26,157 @@
</provides> </provides>
<content_rating type="oars-1.1"/> <content_rating type="oars-1.1"/>
<releases> <releases>
<release version="6.5.0" date="2026-11-28">
<description>
<p>New</p>
<ul>
<li>A test that sets <code>Test::wayland</code>, or <code>.Wayland()</code> on what <code>AddTest</code> returns, runs with a headless Wayland compositor of its own instead of your session's display, so the windows it opens through <code>WAYLAND_DISPLAY</code> no longer show up on your desktop. The compositor is started for that test alone and stopped when it ends; the test finds it through <code>WAYLAND_DISPLAY</code>, the full path of its socket, and runs without <code>DISPLAY</code>. It is weston on its headless backend with its GL renderer, unless <code>CRAFTER_BUILD_COMPOSITOR</code> or the new <code>--compositor=</code> names another command, and <code>host</code> gives such tests your own display, to watch what they draw. A test whose compositor cannot be started fails, saying why, unless it declares <code>.Requires("tool:weston")</code>, which skips it where weston is missing, and when a test that ran fails, crashes or times out, what its compositor printed, if anything, goes to <code>build/test-logs/&lt;name&gt;.compositor.log</code>, named as the test's own log is. The README's new "Tests that open windows" section has the details.</li>
<li>The Flatpak ships weston 16.0.2, with its headless backend, its GL renderer and its desktop shell: the compositor those tests get.</li>
</ul>
<p>Fixes</p>
<ul>
<li>Two runs of <code>crafter-build test</code> at once no longer write into each other's temporary files. Each test now runs with <code>TMPDIR</code> naming a directory of its own, made for the run, so <code>fs::temp_directory_path()</code> in a test is the test's alone. Tests that staged files under fixed names there collided with another run doing the same: natively every process shares <code>/tmp</code>, and in the Flatpak every instance of the app shares one. What a test leaves there is removed when it passes or skips, and kept when it fails, crashes or times out, with its place in the test's log, until a later run removes it, a minute after the run that kept it ended, or after its last change to it where that run was killed. This takes a runner that passes the test <code>TMPDIR</code>, as running it directly and qemu-user do; under wine, which does not pass it on, and wasmtime, which passes on no environment at all, a test's temporary directory is what it was. A test that builds against a sysroot it stages there, or has crafter-build fetch a repository it stages there, keys crafter-build's cache on a path that is now a new one every run: point <code>XDG_CACHE_HOME</code> into its temporary directory as well.</li>
</ul>
</description>
</release>
<release version="6.4.3" date="2026-11-27">
<description>
<p>Fixes</p>
<ul>
<li>In crafter-build's Flatpak, <code>crafter-build lint</code> runs the rules that read a file's AST on a source that includes a header of the C++ standard library, such as <code>&lt;algorithm&gt;</code>, in a build for the host that names no libc++ directory of its own through a sysroot, <code>CRAFTER_BUILD_LIBCXX_DIR</code> or its flags (#46). There such a source built, and lint then ran none of those rules on it, printed <code>'algorithm' file not found</code> and exited 1. The parse of such a build took the first libc++ it found under <code>../include</code> from the working directory, <code>/usr/local/include</code> and <code>/usr/include</code>, wherever the build's compiler keeps its own (<code>/app</code> in the Flatpak, whose <code>/usr</code> has none). It now looks for libc++ where the compiler does, and reads the default configuration files beside the compiler that the compile reads, such as <code>clang++.cfg</code>.</li>
<li>A build no longer fails to scan its sources where its compiler is reached through a link from another directory, as a <code>bin/clang++</code> under <code>CRAFTER_BUILD_LLVM_DIR</code> may be. clang-scan-deps, which reads what a source declares and imports since 6.4.2, looked for clang's own headers from the directory of the link, and for libc++'s too in a build for the host that names no libc++ directory of its own, and where they were not to be found from there, the scan of a source that includes a header of the C++ standard library failed, and the build with it, though its compile found the header. It is now given the compiler in the directory the compiler says it is installed in, as lint's parse is, and reads the default configuration files beside the compiler that the compile reads.</li>
</ul>
</description>
</release>
<release version="6.4.2" date="2026-11-27">
<description>
<p>Fixes</p>
<ul>
<li>What a <code>.cppm</code> or <code>.cpp</code> declares and imports is read by clang-scan-deps, which preprocesses the source with the command it is compiled with, where crafter-build searched its text (#45). An import in a comment that spans lines, in a string literal or in a branch that <code>#if</code> leaves out no longer counts; one written with two spaces after <code>import</code>, or with a space before its semicolon, is no longer missed, which let a unit be compiled before the module it imports; and a define or a header decides an import as it does for the compile. A string literal that holds <code>export module std;</code> no longer stops the build. What was read is kept in the build directory, and read again when the source, a file it includes or its compile command changes. The refusal of interface units that import each other, and of a module built twice for one program, comes once the configuration's dependencies are built, before any of its own <code>.cppm</code> and <code>.cpp</code> is compiled, where it came before the configuration built anything.</li>
<li>A project that exports modules and that two paths load with the same flags of its own in two orders is built once where the two orders give it one build directory. The build stopped, taking it for two builds of the project's modules.</li>
</ul>
</description>
</release>
<release version="6.4.1" date="2026-11-19">
<description>
<p>Fixes</p>
<ul>
<li>Two sources of a configuration may have the same file name in different directories, <code>a/Thing.cpp</code> beside <code>b/Thing.cpp</code>, and a <code>.c</code> may lie beside a <code>.cu</code> of its name (#50). An object was named from its source's file name alone, so two such sources were compiled into one object, each over the other, and the link was given that object twice: it failed, or, in a debug build of sources that define nothing another file names, gave a program with one file's code twice and the other's not at all. A <code>.cpp</code>, <code>.c</code> or <code>.cu</code> is now compiled into an object named from its path: in the build directory under <code>objects/</code>, at the source's path from <code>cfg.path</code>, or under <code>objects-outside/</code> at its whole path when it lies outside that directory, and the progress line of its compile names it by that path. An existing build directory compiles those sources once more.</li>
<li>A static library holds the objects of the sources its configuration lists and no others. Its archive was added to where it lay, which kept the object of a source that had left the project: once a source had been renamed, what was built on the library went on linking the object of the file under its old name.</li>
<li>A configuration of many sources links. The path of every object was written into the link or archive command, which the shell that runs it is given as one argument, and Linux holds one argument to 131,072 bytes on x86_64: with objects whose paths came to more, the build ended with <code>popen() failed!</code>. The link and the archive step now read their objects from a file in the build directory.</li>
</ul>
</description>
</release>
<release version="6.4.0" date="2026-11-15">
<description>
<p>New</p>
<ul>
<li>A <code>project.cpp</code> can describe several configurations that need not have anything to do with each other, such as a library and the tool that comes with it, or the programs of one repository. It defines <code>CrafterBuildConfigurations</code>, which returns a pointer to each of them, in place of <code>CrafterBuildProject</code>, which returns one configuration as before. <code>crafter-build</code> builds all of them in one pass, and one that fails does not stop the others. <code>test</code> runs the tests and <code>run</code> offers the scripts of every one the file made itself, <code>-r</code> runs the executable when exactly one of them is one, and <code>install</code> and <code>bundle</code> export the one that is packaged as a Flatpak; with more than one to choose from they stop and name them. The README's new "Several configurations" section has the details.</li>
<li>A <code>GitProject</code> or <code>LocalProject</code> spec picks one of a sibling's configurations by its name with <code>.configuration</code>, and gets the first one without it.</li>
</ul>
<p>Fixes</p>
<ul>
<li>A project loaded through <code>GitProject</code> or <code>LocalProject</code> keeps the pointers its <code>project.cpp</code> took to the <code>Configuration</code> it returns, as a test declared with <code>cfg.AddTest("T").Dependencies({ &amp;cfg })</code> holds one. The loader moved that <code>Configuration</code> after the project file had returned it, which left such a pointer dangling, and <code>crafter-build lint</code> followed it for a sibling inside the project's own directory when a rule needed an AST.</li>
<li>A wasm32 library that two configurations of one build are built on is built once when its <code>project.cpp</code> sets the target without calling <code>ApplyStandardArgs</code>. The directories such a library is built into had one name until its build started and another from then on, so a configuration that asked for the library after that did not find the build already under way and started a second one.</li>
</ul>
</description>
</release>
<release version="6.3.0" date="2026-11-14">
<description>
<p>New</p>
<ul>
<li>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 and archives, counted together for the project and the dependencies it is built on. Until now every stale source and shader, and every asset to compress, got a thread of its own, and nothing bounded how many compilers ran side by side. An <code>ExternalDependency</code>'s CMake build is not among those steps and keeps that many jobs of its own, and <code>crafter-build test --jobs=</code> counts the tests built and run at once, as before. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts. Progress has two lines for every module interface unit, <code>Precompiling X.cppm</code> and <code>Compiling X.cppm</code>, where a module and its partitions shared one <code>Compiling interface X</code>.</li>
</ul>
<p>Fixes</p>
<ul>
<li>A module interface unit left with its BMI and without the object made from it, or with the object of its source before an edit, is given its object by the next build. A build interrupted between the two compiler runs, or whose second run failed, left a unit like that, and every later build called it up to date: the link took the old object, or failed with <code>no such file or directory</code> until the source was touched.</li>
<li>Module interface units that import each other are refused with an error that names them: two partitions, a partition and its own module, or two modules of one configuration. A first build of them used to hang with no compiler running.</li>
</ul>
</description>
</release>
<release version="6.2.0" date="2026-11-11">
<description>
<p>New</p>
<ul>
<li>CUDA sources compile for the GPU architecture <code>cfg.cudaArch</code> names, nvcc's <code>-arch</code>, which <code>--cuda-arch=</code> and <code>CRAFTER_BUILD_CUDA_ARCH</code> set where <code>project.cpp</code> calls <code>ApplyStandardArgs</code>. It defaults to <code>native</code>, the GPUs of the machine that builds, as <code>march</code> defaults to its CPU; it was <code>sm_89</code> for every build. A program built for <code>native</code> carries no PTX for newer GPUs, so build one that runs elsewhere with <code>--cuda-arch=all-major</code>; <code>crafter-build bundle</code> warns of a bundle whose CUDA code is built for <code>native</code>. Another architecture builds in a directory of its own, and so does <code>native</code> on other GPUs. The README's new CUDA section has the details.</li>
<li>A configuration with CUDA sources links the static CUDA runtime of the toolkit whose nvcc compiles them, where the toolkit's <code>lib64</code> holds it, and so does whatever is built on it: <code>cfg.linkFlags</code> then needs no <code>-lcudart</code> and no path into the toolkit, which inside the Flatpak lies under <code>/run/host</code> for the host's <code>/usr/local/cuda</code>. <code>crafter-build --version</code> prints it next to nvcc.</li>
</ul>
<p>Fixes</p>
<ul>
<li>CUDA sources compile in the Flatpak. With the <code>PATH</code> its manifest sets, every build with <code>cfg.cuda</code> there stopped at <code>nvcc: command not found</code>, because that <code>PATH</code> does not hold the host's toolkit. crafter-build now looks for nvcc itself: in <code>$CUDA_PATH/bin</code>, else in <code>/opt/cuda/bin</code> or the host's <code>/usr/local/cuda/bin</code>, else in an absolute entry of <code>PATH</code>. A build that finds none says where it looked, and <code>crafter-build --version</code> prints the one it found.</li>
<li>A <code>.cu</code> compiles again when a header it includes changes, as a C or C++ source does. It used to compile again only when the <code>.cu</code> itself changed, and kept the object built from the old header.</li>
</ul>
</description>
</release>
<release version="6.1.0" date="2026-11-09">
<description>
<p>New</p>
<ul>
<li>An executable can be packaged as a Flatpak of its own, so it runs outside crafter-build's sandbox: with <code>cfg.packaging = Packaging::Flatpak</code>, or <code>--packaging=flatpak</code> for one build of a <code>project.cpp</code> that calls <code>ApplyStandardArgs</code>, its bin directory holds the app's <code>files/</code>, with the program, the libc++, libc++abi and libunwind it links, and anything else it needs from the libraries it is built on, which <code>-r</code> runs it against. <code>cfg.flatpak</code> sets the app-id, the runtime (the Platform or the Sdk, at the branch crafter-build runs on), the sandbox's permissions as finish-args, a desktop entry, metainfo, icons and data under <code>/app/share</code>. A library's permissions reach every program built on it. Without packaging, an executable's bin directory holds what it did before. The README's new "Flatpak output" section has the details.</li>
<li><code>crafter-build install</code> builds the project and installs its Flatpak for the current user, and <code>crafter-build bundle</code> builds it into a single <code>.flatpak</code> file, which <code>flatpak install --user</code> installs elsewhere. Both make the app with the host's <code>flatpak build-finish</code>, which writes its metadata and what the host sees of it by flatpak's own rules and refuses a permission flatpak does not have, and print the permissions, with where each came from. <code>cfg.flatpak.modules</code> names flatpak-builder module files for what the app needs in <code>/app</code> besides the program; with any, the host's flatpak-builder makes the app and copies the program in last, so it is not compiled again.</li>
<li>The Flatpak has the <code>org.freedesktop.Flatpak</code> permission, for <code>install</code> and <code>bundle</code> to run the host's flatpak and flatpak-builder, which <code>flatpak update</code> lists among the app's new permissions before it asks to proceed. Nothing else in crafter-build uses it. It lets anything running in the sandbox, a <code>project.cpp</code> and the programs <code>-r</code> and <code>test</code> start included, run commands on the host, which <code>--filesystem=host</code> already let them arrange by writing files the host runs, such as <code>~/.bashrc</code>.</li>
</ul>
<p>Fixes</p>
<ul>
<li>On Linux, a program built on a shared library (<code>ConfigurationType::LibraryDynamic</code>) starts: its link records where the library is. It used to fail at start with <code>cannot open shared object file</code>.</li>
<li>A compile no longer takes headers from what a build left in a dependency's <code>bin/</code> or <code>build/</code>: the search for the <code>include/</code> directories in a dependency's tree went into them as well, so the headers of a flatpak-builder or CMake tree there came before the system's. A header kept under a directory named <code>bin</code> or <code>build</code> is no longer found that way; add <code>-I</code> with its directory to the <code>cfg.compileFlags</code> of the projects that include it.</li>
<li><code>crafter-build format --check format</code> checks the rules named "format" and writes nothing: it read the second <code>format</code> as the verb again, ran every rule and rewrote the sources. A word repeated after any verb is a glob now, so <code>test test</code> runs the tests matching "test".</li>
<li>A wasm test declared with <code>AddTest</code> runs under wasmtime. It used to fail with <code>failed to open wasm module</code>, because the test runner looked for the program without its <code>.wasm</code>.</li>
</ul>
</description>
</release>
<release version="6.0.0" date="2026-11-02">
<description>
<p>New</p>
<ul>
<li>The Flatpak carries lldb, with <code>lldb-server</code>, <code>lldb-dap</code> and <code>lldb-mcp</code>, from the same LLVM build as the compiler, so programs that <code>-r</code> and the test runner start can be debugged inside the sandbox they run in. The README's new Debugging section says how, including <code>flatpak enter</code> to reach a program that is already running.</li>
<li>The Flatpak carries the Khronos Vulkan validation layer, the Vulkan SDK release of the runtime's own loader. <code>VK_INSTANCE_LAYERS</code> or <code>VK_LOADER_LAYERS_ENABLE</code> turns it on from the environment, and <code>VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1</code> adds GPU-assisted validation. A layer installed on the host cannot stand in: <code>flatpak run</code> clears <code>VK_LAYER_PATH</code> and <code>VK_ADD_LAYER_PATH</code>.</li>
<li>The Flatpak carries the SPIRV-Tools programs (<code>spirv-val</code>, <code>spirv-opt</code>, <code>spirv-dis</code> and the rest), so a test that requires <code>tool:spirv-val</code> runs inside it instead of being skipped.</li>
<li>The alias in the README's install commands passes <code>--die-with-parent</code>, which ends the sandbox when its <code>flatpak run</code> process dies and, for a command typed at a bash or zsh prompt, when that shell does. Without it, killing <code>flatpak run</code> leaves a build writing into <code>bin/</code> and <code>build/</code> and a program started with <code>-r</code> running. An alias set up from an earlier README does not have it.</li>
</ul>
<p>Fixes</p>
<ul>
<li>The <code>.flatpakref</code> attached to a release carries the repository's signing key. Releases 2.0.0 to 5.0.0 attach one with a placeholder in its place, and installing from it fails with <code>GPG: Unable to export keys</code>; the one on flatpak.catcrafts.net has the key.</li>
</ul>
<p>Breaking</p>
<ul>
<li>Master has no builds of its own any more: the beta branch gets no new builds and the rolling "Latest master build" release is gone, and every change reaches users as a release on the stable branch. Beta's last build is marked end-of-life, and the next <code>flatpak update</code> of a beta installation says so: install stable with <code>flatpak install catcrafts net.catcrafts.CrafterBuild//stable</code> and remove beta with <code>flatpak uninstall net.catcrafts.CrafterBuild//beta</code>.</li>
</ul>
</description>
</release>
<release version="5.0.0" date="2026-10-31">
<description>
<p>Fixes</p>
<ul>
<li>A mingw build no longer sees the Linux system's headers and libraries. Inside the Flatpak the mingw-w64 prefix is the host's /usr, and it was clang's <code>--sysroot</code>, so clang searched /usr/include and /usr/lib for the Windows build as well: libstdc++ found glibc's <code>sys/single_threaded.h</code> and had <code>shared_ptr</code> read <code>__libc_single_threaded</code>, and every program that used one failed to link. <code>CRAFTER_MINGW_DIR=/usr</code> did the same outside the Flatpak. A prefix that also holds a Linux system (the host's /usr, or any prefix whose include/ has a C library's features.h) now reaches clang through a view of its mingw-w64 directories in the cache, and compiler messages still name its headers where they are installed. A prefix that holds mingw-w64 alone is the sysroot as before, so Windows libraries installed into its include/ and lib/ are found (#43).</li>
<li>Units that import a std module rebuilt in place, after a libc++ update or a mingw-w64 update under the same compiler, are compiled again. They used to be relinked unchanged.</li>
<li>A CMake external whose configure inputs changed, such as another compiler or <code>--sysroot</code>, is built again from an empty build directory. It used to be reconfigured in place, keeping the objects and check results of the old configure, so a mingw external built by 4.0.0 would have kept failing to link after the fix above.</li>
<li>Configurations that compile the std module differently no longer share one. Two that differed only in <code>-mtune</code> (a project built with <code>CRAFTER_BUILD_MTUNE</code> set, next to its own project.cpp) or only in sysroot took turns rebuilding it, and every module built against it, on every run.</li>
<li><code>crafter-build lint</code> fails, and says why, when a configuration's compile command cannot be assembled or its std module cannot be built. Its files used to pass every rule that needs an AST as if they were clean.</li>
</ul>
<p>Breaking</p>
<ul>
<li><code>Toolchain::mingwSysroot</code> is now <code>mingwPrefix</code>, beside <code>mingwPrefixIsSystem</code>, because clang no longer always gets the prefix itself. A project.cpp that passes the mingw sysroot to a command of its own calls <code>MingwSysroot()</code>; passing <code>mingwPrefix</code> brings the bug above back for a prefix like /usr.</li>
<li>The std module's cache directory is now keyed on every flag it is compiled with, and every build directory on the std module it imports, so the first build of each project after updating starts in fresh directories and compiles everything, as after a compiler update. <code>crafter-build clean</code> removes the old build directories; the old std module directories stay in the cache until it is cleared by hand.</li>
</ul>
</description>
</release>
<release version="4.0.0" date="2026-10-31">
<description>
<p>New</p>
<ul>
<li>A project keeps its agent instructions in <code>AGENTS.template.md</code>, and <code>crafter-build</code> and <code>crafter-build test</code> write <code>AGENTS.md</code> from it with the dependencies' notes merged in: after the template's text, or between its marker lines. <code>AGENTS.md</code> is build output, so it goes into .gitignore, and a fresh clone has none until its first build. A project with a committed <code>AGENTS.md</code> moves over with <code>git mv AGENTS.md AGENTS.template.md</code> and <code>echo /AGENTS.md &gt;&gt; .gitignore</code>. An <code>AGENTS.md</code> no build wrote, such as a committed one still beside a new template, is never replaced; every build warns until it is deleted.</li>
</ul>
<p>Fixes</p>
<ul>
<li>A build no longer changes a file the project commits. The dependency notes lived in a section of the committed <code>AGENTS.md</code>, so a dependency that edited its notes, an unpinned one that moved on, or a flag that pulled one in showed up in the project's diff as a change nobody made.</li>
</ul>
<p>Breaking</p>
<ul>
<li>Without an <code>AGENTS.template.md</code>, a build leaves <code>AGENTS.md</code> alone. A section 3.0.0 kept in it is no longer updated, and every build warns about it until the file is moved to the template or the section is deleted.</li>
</ul>
</description>
</release>
<release version="3.0.0" date="2026-10-31"> <release version="3.0.0" date="2026-10-31">
<description> <description>
<p>New</p> <p>New</p>

View file

@ -5,9 +5,15 @@
# Platform: a build tool needs glibc's headers and crt objects, gcc's # Platform: a build tool needs glibc's headers and crt objects, gcc's
# libgcc_s, cmake, ninja, make, git and python at run time. Everything # libgcc_s, cmake, ninja, make, git and python at run time. Everything
# compiler-shaped is ours and lives under /app: clang, lld, libclang, libc++, # compiler-shaped is ours and lives under /app: clang, lld, libclang, libc++,
# compiler-rt (native and wasm32) and the WASI sysroot, all built from one # compiler-rt (native and wasm32), lldb and the WASI sysroot, all built from
# LLVM source tree so the modules crafter-build builds and the compiler that # one LLVM source tree so the modules crafter-build builds and the compiler
# consumes them can never drift apart. # that consumes them can never drift apart.
#
# Programs that `-r` and the test runner start run in this sandbox, so the
# tools to debug them live here too: lldb (above), the Sdk's gdb, valgrind
# and strace, the Khronos Vulkan validation layers, GPU-assisted validation
# included, which neither the Sdk nor its GL extensions carry, and the
# SPIRV-Tools programs such as spirv-val.
app-id: net.catcrafts.CrafterBuild app-id: net.catcrafts.CrafterBuild
runtime: org.freedesktop.Sdk runtime: org.freedesktop.Sdk
runtime-version: '26.08' runtime-version: '26.08'
@ -25,13 +31,48 @@ finish-args:
- --socket=fallback-x11 - --socket=fallback-x11
- --socket=pulseaudio - --socket=pulseaudio
- --device=all - --device=all
# gdb and friends from the Sdk # lldb, and gdb and friends from the Sdk
- --allow=devel - --allow=devel
# `crafter-build install` and `bundle` run the host's flatpak and
# flatpak-builder, through :Platform's host helpers (RunHostFlatpak,
# RunHostFlatpakBuilder and HostFlatpakUnavailable's probes, every command
# line built by HostCommand); crafter-build's own code reaches the host
# for nothing else. The permission is the whole sandbox's: a project.cpp,
# its scripts, the builds of its dependencies and the programs -r and
# test start can run host commands with it too. --filesystem=host already
# lets them arrange that, by writing ~/.bashrc, so it makes running
# something on the host immediate rather than possible.
- --talk-name=org.freedesktop.Flatpak
- --env=PATH=/app/bin:/usr/bin - --env=PATH=/app/bin:/usr/bin
cleanup: cleanup:
- /share/man - /share/man
- /share/doc - /share/doc
modules: modules:
- name: swig
# Generates lldb's Python bindings while the llvm module builds; nothing
# of it ships.
cleanup:
- '*'
sources:
- type: archive
url: https://downloads.sourceforge.net/project/swig/swig/swig-4.4.1/swig-4.4.1.tar.gz
sha256: 40162a706c56f7592d08fd52ef5511cb7ac191f3593cf07306a0a554c6281fcf
- name: libedit
# Line editing, history and completion at lldb's prompt. The Sdk has the
# ncurses it needs but not libedit itself; liblldb links the shared
# library, so that ships and the rest goes.
config-opts:
- --disable-static
cleanup:
- /include
- /lib/pkgconfig
- /lib/*.la
sources:
- type: archive
url: https://thrysoee.dk/editline/libedit-20260512-3.1.tar.gz
sha256: 432d5e7ea8b0116dd39f2eca7bc11d0eed77faa6b77ea526ace89907c23ea4a0
- name: llvm - name: llvm
buildsystem: cmake-ninja buildsystem: cmake-ninja
builddir: true builddir: true
@ -50,8 +91,20 @@ modules:
config-opts: config-opts:
- -DCMAKE_BUILD_TYPE=Release - -DCMAKE_BUILD_TYPE=Release
- -DLLVM_ENABLE_ASSERTIONS=OFF - -DLLVM_ENABLE_ASSERTIONS=OFF
- -DLLVM_ENABLE_PROJECTS=clang;lld - -DLLVM_ENABLE_PROJECTS=clang;lld;lldb
- -DLLVM_ENABLE_RUNTIMES=compiler-rt;libcxx;libcxxabi;libunwind - -DLLVM_ENABLE_RUNTIMES=compiler-rt;libcxx;libcxxabi;libunwind
# lldb with Python scripting (its bindings generated by the swig module
# above, against the Sdk's Python), libedit (the module above), curses,
# libxml2 and lzma, each set ON rather than left to the default of "if
# found", so a dependency gone missing fails the configure step instead
# of shipping an lldb without it. lldb-server, lldb-dap and lldb-mcp
# come with it.
- -DLLDB_ENABLE_PYTHON=ON
- -DLLDB_ENABLE_LIBEDIT=ON
- -DLLDB_ENABLE_CURSES=ON
- -DLLDB_ENABLE_LIBXML2=ON
- -DLLDB_ENABLE_LZMA=ON
- -DLLDB_ENABLE_LUA=OFF
- -DLLVM_TARGETS_TO_BUILD=X86;AArch64;WebAssembly - -DLLVM_TARGETS_TO_BUILD=X86;AArch64;WebAssembly
# Classic layout: libc++ in lib/ and include/c++/v1, not under a # Classic layout: libc++ in lib/ and include/c++/v1, not under a
# per-target subdirectory, the same shape as a distro install. # per-target subdirectory, the same shape as a distro install.
@ -82,6 +135,7 @@ modules:
- /include/clang - /include/clang
- /include/clang-tidy - /include/clang-tidy
- /include/lld - /include/lld
- /include/lldb
- /lib/cmake - /lib/cmake
- /lib/*.a - /lib/*.a
- /share/opt-viewer - /share/opt-viewer
@ -219,12 +273,225 @@ modules:
url: https://github.com/llvm/llvm-project/releases/download/llvmorg-22.1.8/llvm-project-22.1.8.src.tar.xz url: https://github.com/llvm/llvm-project/releases/download/llvmorg-22.1.8/llvm-project-22.1.8.src.tar.xz
sha256: 922f1817a0df7b1489272d18134ee0087a8b068828f87ac63b9861b1a9965888 sha256: 922f1817a0df7b1489272d18134ee0087a8b068828f87ac63b9861b1a9965888
# The Khronos validation layers and the four modules they are built from,
# after llvm, so that bumping them reuses the cached LLVM build. All five
# are pinned to the Vulkan SDK release of the Sdk's own Vulkan loader and
# headers (1.4.357), at the dependency revisions that release's
# scripts/known_good.json names. When the runtime moves to a newer loader,
# move the layers to the SDK release of that loader and take the other
# four revisions from its known_good.json again. The four are built into
# /app at those revisions rather than taken from the Sdk, whose versions
# follow the runtime, and of them only SPIRV-Tools' programs ship.
- name: vulkan-headers
buildsystem: cmake-ninja
builddir: true
cleanup:
- '*'
sources:
- type: archive
url: https://github.com/KhronosGroup/Vulkan-Headers/archive/refs/tags/v1.4.357.tar.gz
sha256: 7dc0dbcf1d49dd3d7da3761c251c6097dfbaac475321a4a8a99269d3d5abecdc
- name: vulkan-utility-libraries
buildsystem: cmake-ninja
builddir: true
config-opts:
- -DCMAKE_BUILD_TYPE=Release
# CMake searches its install prefix after /usr, where the Sdk has
# Vulkan headers of its own.
- -DCMAKE_PREFIX_PATH=/app
cleanup:
- '*'
sources:
- type: archive
url: https://github.com/KhronosGroup/Vulkan-Utility-Libraries/archive/refs/tags/v1.4.357.tar.gz
sha256: e8688013cdc67dad26f15dcece91fa6b80ad595d551fceb56397fc4795efd00a
- name: spirv-headers
buildsystem: cmake-ninja
builddir: true
cleanup:
- '*'
sources:
- type: archive
url: https://github.com/KhronosGroup/SPIRV-Headers/archive/29981f65241605e08b0ede4cfeb999fe3b723c6a.tar.gz
sha256: 232899f1ad4104fb5bc377b94596c7621575eee62ad9a9e8f929b63a7dd8a7ad
- name: spirv-tools
# The optimizer GPU-assisted validation instruments shaders with, linked
# into the layer statically, and SPIRV-Tools' programs (spirv-val,
# spirv-opt, spirv-dis and the rest), which ship: a program or test that
# checks its SPIR-V with spirv-val, as Crafter.Graphics' do, finds it in
# the sandbox. The libraries and headers stay build-only.
buildsystem: cmake-ninja
builddir: true
build-options:
no-debuginfo: true
strip: true
config-opts:
- -DCMAKE_BUILD_TYPE=Release
# The installed SPIRV-Headers: its include/ holds the grammar files
# SPIRV-Tools generates its tables from, as the source tree does.
- -DSPIRV-Headers_SOURCE_DIR=/app
- -DSPIRV_SKIP_TESTS=ON
- -DSPIRV_WERROR=OFF
cleanup:
- /include/spirv-tools
- /lib/libSPIRV-Tools*.a
# Always built besides the static libraries, and linked by nothing
# here: the programs and the layer take SPIRV-Tools statically.
- /lib/libSPIRV-Tools-shared.so
- /lib/cmake/SPIRV-Tools*
- /lib/pkgconfig/SPIRV-Tools*
post-install:
- spirv-val --version
sources:
- type: archive
url: https://github.com/KhronosGroup/SPIRV-Tools/archive/b707790a898e44038547df54580022fc1cf89c3d.tar.gz
sha256: 05d8af89737bde57571c48dbd36714c9f520a69623e14de72c3be6b600e277d6
- name: vulkan-validation-layers
# VK_LAYER_KHRONOS_validation. The loader finds its manifest under
# /app/share/vulkan/explicit_layer.d through XDG_DATA_DIRS, and the
# manifest names the library without a path, which the sandbox's loader
# finds in /app/lib. GPU-AV is a setting of this layer, not a layer of
# its own (VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1, or the layer settings).
buildsystem: cmake-ninja
builddir: true
build-options:
no-debuginfo: true
strip: true
config-opts:
- -DCMAKE_BUILD_TYPE=Release
- -DCMAKE_PREFIX_PATH=/app
# ON by default: it clones every dependency with update_deps.py, which
# the build sandbox has no network for, instead of using the four
# modules above.
- -DUPDATE_DEPS=OFF
- -DBUILD_TESTS=OFF
- -DBUILD_WERROR=OFF
post-install:
- test -f /app/share/vulkan/explicit_layer.d/VkLayer_khronos_validation.json
- test -f /app/lib/libVkLayer_khronos_validation.so
sources:
- type: archive
url: https://github.com/KhronosGroup/Vulkan-ValidationLayers/archive/refs/tags/vulkan-sdk-1.4.357.0.tar.gz
sha256: 73180b11992a3554e97ebc18e6bf2b45ff9790ded9d87fc526c7bab865d1303f
# weston on its headless backend, the compositor `crafter-build test` starts
# for each test that sets Test::wayland (README, "Tests that open windows"):
# built with the headless backend, the GL renderer, which imports the
# dmabufs a GPU's Vulkan driver presents, and the desktop shell, and with
# none of its other backends or shells and no Vulkan renderer. weston's frontend
# links libinput, libevdev and libdisplay-info whatever the backend, and the
# Sdk has none of them, so they come first; the headless backend never opens
# an input device, so libinput ships without its quirks, udev helpers and
# tools.
- name: libevdev
buildsystem: meson
config-opts:
- -Dtests=disabled
- -Dtools=disabled
- -Ddocumentation=disabled
cleanup:
- /include
- /lib/pkgconfig
sources:
- type: archive
url: https://www.freedesktop.org/software/libevdev/libevdev-1.14.0.tar.xz
sha256: 5a0966c7110648665983848bad696c7acba614a2160d2865d535397101007332
- name: libinput
buildsystem: meson
config-opts:
- -Dlibwacom=false
- -Dmtdev=false
- -Ddebug-gui=false
- -Dtests=false
- -Ddocumentation=false
- -Dlua-plugins=disabled
- -Dudev-dir=/app/lib/udev
- -Dzshcompletiondir=no
cleanup:
- /bin
- /include
- /lib/pkgconfig
- /lib/udev
- /libexec
- /share/libinput
sources:
# libinput publishes no release tarball, only the tag.
- type: git
url: https://gitlab.freedesktop.org/libinput/libinput.git
tag: 1.32.0
commit: 5cf833b572f5a33663888da321dce0ba1abd82a2
- name: libdisplay-info
buildsystem: meson
cleanup:
- /bin
- /include
- /lib/pkgconfig
sources:
- type: archive
url: https://gitlab.freedesktop.org/emersion/libdisplay-info/-/releases/0.4.0/downloads/libdisplay-info-0.4.0.tar.xz
sha256: 43b180baa143e2035654759d84e2b2f5ee77d5fe817c423838c7fe59c0d68459
- name: weston
buildsystem: meson
config-opts:
# The modules above, never a subproject meson would download.
- --wrap-mode=nodownload
- -Dbackend-drm=false
- -Dbackend-headless=true
- -Dbackend-pipewire=false
- -Dbackend-rdp=false
- -Dbackend-vnc=false
- -Dbackend-wayland=false
- -Dbackend-x11=false
- -Dbackend-default=headless
- -Drenderer-gl=true
- -Drenderer-vulkan=false
- -Dxwayland=false
- -Dsystemd=false
- -Ddeprecated-remoting=false
- -Ddeprecated-pipewire=false
- -Dshell-desktop=true
- -Dshell-ivi=false
- -Dshell-kiosk=false
- -Dshell-lua=false
- -Dcolor-management-lcms=false
- -Dimage-jpeg=false
- -Dimage-webp=false
- -Dtools=[]
- -Ddemo-clients=false
- -Dsimple-clients=[]
- -Dtests=false
- -Ddoc=false
- -Dperfetto=false
cleanup:
- /bin/weston-screenshooter
- /include
- /lib/pkgconfig
- /share/libweston-16
- /share/man
- /share/pkgconfig
- /share/wayland-sessions
post-install:
- weston --version
- test -f /app/lib/libweston-16/headless-backend.so
- test -f /app/lib/libweston-16/gl-renderer.so
sources:
- type: archive
url: https://gitlab.freedesktop.org/wayland/weston/-/releases/16.0.2/downloads/weston-16.0.2.tar.xz
sha256: 49dd87d18cb229384264d2f69cb5a51f14f61a111e9227bfedb91b3ca8c39643
- name: crafter-build - name: crafter-build
buildsystem: simple buildsystem: simple
build-options: build-options:
# The self-host build fetches Crafter.Math, Crafter.Asset, # The self-host build fetches Crafter.Math, Crafter.Asset,
# Crafter.LintRules and glslang from git; they are unpinned on purpose # Crafter.LintRules and glslang from git; they are unpinned on purpose
# (sibling repos tracking their default branch, see AGENTS.md). # (sibling repos tracking their default branch, see AGENTS.template.md).
build-args: build-args:
- --share=network - --share=network
# On this module, not at the top of the manifest: top-level build # On this module, not at the top of the manifest: top-level build

View file

@ -16,7 +16,8 @@ namespace {
struct FlatpakPaths { struct FlatpakPaths {
fs::path manifest; fs::path manifest;
// flatpak-builder's downloads, ccache and per-module cache. The // flatpak-builder's downloads, ccache and per-module cache. The
// LLVM build lives here: about 2 GB, and 25 minutes to rebuild. // LLVM build lives here: about 3 GB in all after a first run,
// which takes about 30 minutes with 56 CPU threads.
fs::path state; fs::path state;
// The OSTree repo the build is exported to; `install` reads it. // The OSTree repo the build is exported to; `install` reads it.
fs::path repo; fs::path repo;
@ -46,7 +47,7 @@ namespace {
// itself runs in as a Flatpak has none. // itself runs in as a Flatpak has none.
bool RefusedInSandbox(std::string_view script) { bool RefusedInSandbox(std::string_view script) {
if (!fs::exists("/.flatpak-info")) return false; if (!fs::exists("/.flatpak-info")) return false;
std::println(std::cerr, "run {0}: needs the host's flatpak, which the Flatpak build of crafter-build cannot reach. Use a native build: ./build.sh, then ./bin/crafter-build run {0}", script); std::println(std::cerr, "run {0}: runs flatpak itself, which the Flatpak build of crafter-build does not have (its install and bundle verbs reach the host's through flatpak-spawn instead). Use a native build: ./build.sh, then ./bin/crafter-build run {0}", script);
return true; return true;
} }
@ -156,14 +157,14 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
if (const fs::path& llvmInclude = GetToolchain().llvmIncludeDir; !llvmInclude.empty()) { if (const fs::path& llvmInclude = GetToolchain().llvmIncludeDir; !llvmInclude.empty()) {
CrafterBuildLib->compileFlags.push_back(std::format("-I{}", llvmInclude.string())); CrafterBuildLib->compileFlags.push_back(std::format("-I{}", llvmInclude.string()));
} }
// The version the binary reports: CI sets it from the tag, a checkout // The version the binary reports: CI sets it, a checkout describes
// describes itself, anything else is a development build. A define on // itself, anything else is a development build. A define on the
// the library, so each version is its own library variant. // library, so each version is its own library variant.
std::string version; std::string version;
if (const char* env = std::getenv("CRAFTER_BUILD_VERSION"); env && *env) { if (const char* env = std::getenv("CRAFTER_BUILD_VERSION"); env && *env) {
version = env; version = env;
} else { } else {
auto described = RunCommandWithTimeout("git describe --tags --always --dirty --exclude=latest 2>/dev/null", std::chrono::seconds(10)); auto described = RunCommandWithTimeout("git describe --tags --always --dirty 2>/dev/null", std::chrono::seconds(10));
version = described.output; version = described.output;
while (!version.empty() && (version.back() == '\n' || version.back() == '\r')) version.pop_back(); while (!version.empty() && (version.back() == '\n' || version.back() == '\r')) version.pop_back();
if (described.exitCode != 0 || version.empty()) version = "0.0.0-dev"; if (described.exitCode != 0 || version.empty()) version = "0.0.0-dev";
@ -172,11 +173,13 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
// it reaches clang, which must still see a string literal. // it reaches clang, which must still see a string literal.
CrafterBuildLib->defines.push_back({"CRAFTER_BUILD_VERSION", std::format("\\\"{}\\\"", version)}); CrafterBuildLib->defines.push_back({"CRAFTER_BUILD_VERSION", std::format("\\\"{}\\\"", version)});
{ {
std::array<fs::path, 14> interfaces = { std::array<fs::path, 16> interfaces = {
"interfaces/Crafter.Build", "interfaces/Crafter.Build",
"interfaces/Crafter.Build-Toolchain", "interfaces/Crafter.Build-Toolchain",
"interfaces/Crafter.Build-Shader", "interfaces/Crafter.Build-Shader",
"interfaces/Crafter.Build-Platform", "interfaces/Crafter.Build-Platform",
"interfaces/Crafter.Build-Flatpak",
"interfaces/Crafter.Build-Jobs",
"interfaces/Crafter.Build-Interface", "interfaces/Crafter.Build-Interface",
"interfaces/Crafter.Build-Implementation", "interfaces/Crafter.Build-Implementation",
"interfaces/Crafter.Build-External", "interfaces/Crafter.Build-External",
@ -188,10 +191,12 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
"interfaces/Crafter.Build-Progress", "interfaces/Crafter.Build-Progress",
"interfaces/Crafter.Build-Asset", "interfaces/Crafter.Build-Asset",
}; };
std::array<fs::path, 13> implementations = { std::array<fs::path, 15> implementations = {
"implementations/Crafter.Build-Toolchain", "implementations/Crafter.Build-Toolchain",
"implementations/Crafter.Build-Shader", "implementations/Crafter.Build-Shader",
"implementations/Crafter.Build-Platform", "implementations/Crafter.Build-Platform",
"implementations/Crafter.Build-Flatpak",
"implementations/Crafter.Build-Jobs",
"implementations/Crafter.Build-Interface", "implementations/Crafter.Build-Interface",
"implementations/Crafter.Build-Implementation", "implementations/Crafter.Build-Implementation",
"implementations/Crafter.Build-External", "implementations/Crafter.Build-External",
@ -242,20 +247,34 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
if (linuxTarget) { if (linuxTarget) {
cfg.AddTest("HelloWorld").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("HelloWorld").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("StaticLib").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("StaticLib").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("StaticLibSourceRemoved").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("LinkManyObjects").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("SameNamedSources").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ObjectPath").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ModuleInterface").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ModuleInterface").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("DependencyLink").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("DependencyLink").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("SharedLibraryRuns").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("IncludeWalkOutputs").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("IncrementalInterfaceChange").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("IncrementalInterfaceChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("TransitiveInterfaceChange").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("TransitiveInterfaceChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("IncrementalInterfaceObject").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("StdPcmRebuild").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("CompilerWarning").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("CompilerWarning").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("CleanProject").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("CleanProject").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FormatCheckGlob").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("ShaderCompile").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ShaderCompile").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ShaderVariantBuild").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ShaderVariantBuild").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ShaderIncludeChange").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ShaderIncludeChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("CudaCompile").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("CudaMissing").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("MingwMissing").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("MingwMissing").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("MingwSysroot").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("GitSubmodules").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("GitSubmodules").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("LinkFlagsChange").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("LinkFlagsChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ExternalArtifactTime").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ExternalArtifactTime").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ExternalReconfigure").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ConcurrentExternalFetch").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ConcurrentExternalFetch").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("SharedExternalFetch").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("SharedExternalFetch").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("StandardArgs").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("StandardArgs").Dependencies({ CrafterBuildLib.get() });
@ -269,17 +288,41 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.AddTest("WasiBrowserRuntimeExit").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasiBrowserRuntimeExit").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasmVariants").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmVariants").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasmHelloRuns").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmHelloRuns").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasmTestRuns").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakOutput").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakToolchainLibrary").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakRefusals").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakDependencyExecutable").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("FlatpakLibcxxDir").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakTestsRaw").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakNative").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakIncremental").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakLibraryChange").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakDesktop").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakShare").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakShareLarge").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("HostFlatpak").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakBundle").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakPermissions").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakInstall").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakModules").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("FlatpakVerbRefusal").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("WasmExceptions").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmExceptions").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasiSysrootWithoutExceptions").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasiSysrootWithoutExceptions").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("WasmSysrootKey").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() });
// LoadProject dlopens the synthesized project.so, which references cfg.AddTest("HeadlessCompositor").Dependencies({ CrafterBuildLib.get() });
// Crafter:: symbols (HostTarget, Configuration ctors) that have to be cfg.AddTest("TestTemporaryDirectory").Dependencies({ CrafterBuildLib.get() });
// visible from the test exe — same wiring crafter-build itself uses // Loading a project file dlopens the project.so compiled from it,
// for project.so. // which references Crafter:: symbols (HostTarget, Configuration
// ctors) that have to be visible from the test exe — same wiring
// crafter-build itself uses for project.so.
cfg.AddTest("ConcurrentCacheRace").Dependencies({ CrafterBuildLib.get() }) cfg.AddTest("ConcurrentCacheRace").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
// Same LoadProject wiring as ConcurrentCacheRace above. // Same wiring as ConcurrentCacheRace above.
cfg.AddTest("HostCacheSourceStamp").Dependencies({ CrafterBuildLib.get() }) cfg.AddTest("HostCacheSourceStamp").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("HostCacheToolchainKey").Dependencies({ CrafterBuildLib.get() }) cfg.AddTest("HostCacheToolchainKey").Dependencies({ CrafterBuildLib.get() })
@ -290,14 +333,28 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("HostToolingSibling").Dependencies({ CrafterBuildLib.get() }) cfg.AddTest("HostToolingSibling").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("PragmaSharedExternal").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("DuplicateModule").Dependencies({ CrafterBuildLib.get() }) cfg.AddTest("DuplicateModule").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("Script").Dependencies({ CrafterBuildLib.get() }) cfg.AddTest("Script").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("DependencyNotes").Dependencies({ CrafterBuildLib.get() }) cfg.AddTest("DependencyNotes").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("SiblingOwnPointers").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("ProjectConfigurations").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("SiblingConfigurations").Dependencies({ CrafterBuildLib.get() })
.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl");
cfg.AddTest("ConcurrentDependencyReset").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ConcurrentDependencyReset").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("JobGroup").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("JobLimit").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ImportCycle").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("SourceScan").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("BuildAll").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("LintCompilerHeaders").Dependencies({ CrafterBuildLib.get() });
} }
// Dogfood: the lite house rules, imported from their own repo through // Dogfood: the lite house rules, imported from their own repo through

View file

@ -0,0 +1,10 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Broken;
import std;
// Does not compile: the library two of the test's programs are built on.
export std::int32_t Value() {
return Undeclared;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Broken;
int main() {
return Value();
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("good");
return 0;
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Greeter;
import std;
export namespace Greeter {
std::string Greet(std::string_view name) {
return std::format("hello {}", name);
}
}

View file

@ -0,0 +1,10 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Greeter;
int main() {
std::println("{}", Greeter::Greet("world"));
return 0;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Broken;
int main() {
return Value();
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("tool");
return 0;
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Lower;
import std;
// Built by a configuration with the name, path and type of the one that
// builds Upper, which is built on this one.
export std::int32_t Lower() {
return 1;
}

View file

@ -0,0 +1,10 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Upper;
import std;
import Lower;
export std::int32_t Upper() {
return Lower() + 1;
}

273
tests/BuildAll/main.cpp Normal file
View file

@ -0,0 +1,273 @@
// 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;
// BuildAll builds the configurations a project file returns, which need not
// have anything to do with each other, in one pass: every one of them, and
// what two of them share once.
//
// What it guards against is a configuration that goes missing or is built
// wrongly without a word: left unbuilt because another one failed, or
// because it shares an output directory with another and was taken for it;
// built twice at once because another one depends on it, each build
// writing what the other reads; and built at once with a wasm executable
// that declares variants, which rewrites the configurations it is built on
// while it builds. And against a build that never ends: a configuration
// waiting for a build of its own directory that is waiting for it.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
std::size_t Count(std::string_view text, std::string_view needle) {
std::size_t count = 0;
for (std::size_t pos = text.find(needle); pos != std::string_view::npos; pos = text.find(needle, pos + needle.size())) ++count;
return count;
}
// A library made of `dir`/`interface`.cppm.
void MakeLibrary(Configuration& cfg, const fs::path& dir, std::string_view name, std::string_view interface) {
cfg.path = dir;
cfg.name = name;
cfg.outputName = name;
cfg.target = HostTarget();
cfg.type = ConfigurationType::LibraryStatic;
std::array<fs::path, 1> interfaces = { interface };
std::array<fs::path, 0> implementations = {};
cfg.GetInterfacesAndImplementations(interfaces, implementations);
}
// A program made of `dir`/main.cpp.
void MakeProgram(Configuration& cfg, const fs::path& dir, std::string_view name) {
cfg.path = dir;
cfg.name = name;
cfg.outputName = name;
cfg.target = HostTarget();
cfg.type = ConfigurationType::Executable;
std::array<fs::path, 0> interfaces = {};
std::array<fs::path, 1> implementations = { "main" };
cfg.GetInterfacesAndImplementations(interfaces, implementations);
}
}
int main() {
// Staged: the cases below compare what a build left behind, so each run
// starts from sources alone.
const fs::path scratch = fs::temp_directory_path() / "crafter-build-build-all";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::copy(fs::current_path() / "tests" / "BuildAll" / "fixture", scratch, fs::copy_options::recursive);
// Every one of them is built and left in the record of the pass, where
// a configuration that depends on it looks for it. hello depends on
// greeter, and greeter built from here as well as through hello was two
// builds of it at once, one of which archived the objects while the
// other was still writing them.
{
Configuration greeter;
MakeLibrary(greeter, scratch / "greeter", "greeter", "Greeter");
Configuration hello;
hello.dependencies = { &greeter };
MakeProgram(hello, scratch / "hello", "hello");
Configuration tool;
MakeProgram(tool, scratch / "tool", "tool");
std::array<Configuration*, 3> all = { &greeter, &hello, &tool };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string failed = BuildAll(all, depResults, depMutex);
Check(failed.empty(), std::format("a library, a program built on it and an unrelated program build: {}", failed));
for (const Configuration* cfg : all) {
Check(fs::exists(ExpectedOutput(*cfg)), std::format("{} was built", cfg->name));
Check(depResults.contains(cfg->PcmDir()), std::format("{} is in the record of the pass, where a configuration that depends on it finds its build", cfg->name));
}
// A list that names one of them twice builds it like any other:
// once, from nothing here, since what the build above left of it is
// removed first.
fs::remove_all(tool.BinDir(), ec);
fs::remove_all(tool.BuildDir(), ec);
std::array<Configuration*, 2> twice = { &tool, &tool };
std::unordered_map<fs::path, std::shared_future<BuildResult>> twiceResults;
Check(BuildAll(twice, twiceResults, depMutex).empty() && fs::exists(ExpectedOutput(tool)), "a configuration the list names twice is built");
Check(twiceResults.size() == 1 && twiceResults.contains(tool.PcmDir()), std::format("and is in the record of the pass once ({} entries)", twiceResults.size()));
}
// A configuration built on another of its own name, path and type: the
// two are built into one directory, the dependency first, as they were
// when a project had one configuration and Build() was all there was.
// In the record of the pass while it is still being built, the first
// would be what the record hands its dependency, which would wait for
// it while it waits for the dependency: a build that never ends.
{
Configuration lower;
MakeLibrary(lower, scratch / "twins", "twins", "Lower");
lower.outputName = "lower";
Configuration upper;
upper.dependencies = { &lower };
MakeLibrary(upper, scratch / "twins", "twins", "Upper");
std::array<Configuration*, 1> one = { &upper };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string failed = BuildAll(one, depResults, depMutex);
Check(failed.empty(), std::format("a configuration built on another of the same directory builds: {}", failed));
Check(upper.PcmDir() == lower.PcmDir() && fs::exists(ExpectedOutput(upper)) && fs::exists(ExpectedOutput(lower)), "both into that one directory");
// With a program built on the upper one returned beside it, that
// directory holds two builds and the record of the pass one result:
// the program would be handed the lower one's, and be linked without
// the library it names.
Configuration program;
program.dependencies = { &upper };
MakeProgram(program, scratch / "good", "on-twins");
std::array<Configuration*, 2> both = { &program, &upper };
std::unordered_map<fs::path, std::shared_future<BuildResult>> bothResults;
const std::string refused = BuildAll(both, bothResults, depMutex);
Check(refused.contains("twins and a configuration it is built on would both be built into") && refused.contains("where on-twins looks"), std::format("a configuration built on that one, returned beside it, is refused, both by name: {}", refused));
Check(bothResults.empty() && !fs::exists(program.BuildDir()) && !fs::exists(program.BinDir()), "and refused before anything is built");
}
// Two that are each built on something of the other's directory cannot
// be put in an order, and are refused before either is built. Nothing
// here has a source: the refusal comes first.
{
const auto named = [&](Configuration& cfg, std::string_view name) {
cfg.path = scratch / "crossed";
cfg.name = name;
cfg.outputName = name;
cfg.target = HostTarget();
cfg.type = ConfigurationType::LibraryStatic;
};
Configuration left;
Configuration right;
Configuration leftAgain;
Configuration rightAgain;
named(left, "left");
named(right, "right");
named(leftAgain, "left");
named(rightAgain, "right");
left.dependencies = { &rightAgain };
right.dependencies = { &leftAgain };
std::array<Configuration*, 2> crossed = { &left, &right };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string refused = BuildAll(crossed, depResults, depMutex);
Check(refused.contains("left, right") && refused.contains("none of them can be built first"), std::format("two configurations that each wait for the other's directory are refused, by name: {}", refused));
Check(depResults.empty() && !fs::exists(scratch / "crossed" / "bin") && !fs::exists(scratch / "crossed" / "build"), "and refused before anything is built");
}
// A wasm32 library whose target is set here and not by
// ApplyStandardArgs, so that it names no sysroot, and a program built on
// it: the program finds the library's build in the record, under the
// directory the library has before its build and after it alike. The
// library has a flag no wasm build accepts, so its build is refused on
// every machine, with a WASI sysroot or without, and a refused build is
// recorded like any other. The program is one for the host, whose own
// build gets as far as asking for the library wherever the test runs.
{
Configuration library;
MakeLibrary(library, scratch / "greeter", "wasm-greeter", "Greeter");
library.target = "wasm32-wasip1";
library.compileFlags.push_back("-fno-exceptions");
Configuration program;
program.dependencies = { &library };
MakeProgram(program, scratch / "hello", "on-wasm-greeter");
std::array<Configuration*, 2> all = { &program, &library };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string failed = BuildAll(all, depResults, depMutex);
Check(Count(failed, "wasm-greeter: -fno-exceptions") == 1, std::format("the library's refusal comes back once, for the two of them: {}", failed));
const auto recorded = std::ranges::count_if(depResults, [](const auto& entry) { return entry.first.filename().string().starts_with("wasm-greeter-"); });
Check(recorded == 1 && depResults.contains(library.PcmDir()), std::format("and the library is in the record of the pass once, under the directory it has now ({} times)", recorded));
}
// One that fails stops none of the others, and what failed is said
// once: two programs built on a library that does not compile, and a
// third that has nothing to do with it.
{
Configuration broken;
MakeLibrary(broken, scratch / "broken", "broken", "Broken");
Configuration first;
first.dependencies = { &broken };
MakeProgram(first, scratch / "first", "first");
Configuration second;
second.dependencies = { &broken };
MakeProgram(second, scratch / "second", "second");
Configuration good;
MakeProgram(good, scratch / "good", "good");
std::array<Configuration*, 3> all = { &first, &second, &good };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string failed = BuildAll(all, depResults, depMutex);
Check(failed.contains("Undeclared"), std::format("the library's compile error comes back: {}", failed));
Check(Count(failed, "error:") == 1, std::format("a dependency that failed for two configurations is reported once: {}", failed));
Check(fs::exists(ExpectedOutput(good)), "a configuration that has nothing to do with the failure is still built");
Check(!fs::exists(ExpectedOutput(first)) && !fs::exists(ExpectedOutput(second)), "the two built on the broken library are not");
// Two configurations in one directory would be one piece of work to
// the pass, which would build the first and hand the second its
// result.
Configuration twin;
MakeProgram(twin, scratch / "good", "good");
std::array<Configuration*, 2> clash = { &good, &twin };
fs::remove_all(good.BinDir(), ec);
fs::remove_all(good.BuildDir(), ec);
std::unordered_map<fs::path, std::shared_future<BuildResult>> clashResults;
const std::string refused = BuildAll(clash, clashResults, depMutex);
Check(refused.contains("would both be built into"), std::format("two configurations that build into one directory are refused: {}", refused));
Check(!fs::exists(good.BinDir()), "and refused before either is built");
}
// A wasm executable with variants rewrites the configurations it is
// built on, once for each variant, so with one among them the
// configurations are built one after the other: built at once, a
// library two of them share would change under the other's build. The
// slow one comes first here, a program and the library it is built on,
// and the quick one, a single source, is only linked once the slow one
// is. The wasm one is refused before it builds anything, on every
// machine, for its -fno-exceptions, so no wasm build is waited for.
{
Configuration library;
MakeLibrary(library, scratch / "greeter", "ordered-greeter", "Greeter");
Configuration slow;
slow.dependencies = { &library };
MakeProgram(slow, scratch / "hello", "ordered-slow");
Configuration quick;
MakeProgram(quick, scratch / "good", "ordered-quick");
Configuration variants;
MakeProgram(variants, scratch / "good", "ordered-variants");
variants.target = "wasm32-wasip1";
variants.compileFlags.push_back("-fno-exceptions");
EnableWasiRelaxedSimdVariant(variants);
std::array<Configuration*, 3> all = { &slow, &quick, &variants };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const std::string failed = BuildAll(all, depResults, depMutex);
Check(failed.contains("-fno-exceptions"), std::format("the wasm configuration is the one that is refused: {}", failed));
const fs::file_time_type slowBuilt = fs::last_write_time(ExpectedOutput(slow), ec);
Check(!ec, "the slow configuration is built");
const fs::file_time_type quickBuilt = fs::last_write_time(ExpectedOutput(quick), ec);
Check(!ec && quickBuilt >= slowBuilt, "with a wasm executable that declares variants among them, a configuration is built once the one before it is");
}
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
fs::remove_all(scratch, ec);
return 0;
}

View file

@ -5,6 +5,8 @@ module DepMod;
// Implementation unit of the DepMod interface. Because it declares // Implementation unit of the DepMod interface. Because it declares
// `module DepMod;` it gains an intra-config module dependency on the DepMod // `module DepMod;` it gains an intra-config module dependency on the DepMod
// interface, so its compile waits on DepMod's `compiled` flag — the exact // interface, so its compile job comes after the job that writes DepMod's BMI
// flag a stale recursive reset used to clobber (issue #16). // (Implementation::Schedule), which reads DepMod's per-build state: what a
// recursive reset would clear. Its compile used to wait on DepMod's
// `compiled` flag, the flag such a reset clobbered (issue #16).
int dep_value() { return 21; } int dep_value() { return 21; }

View file

@ -8,26 +8,35 @@ using namespace Crafter;
// Regression for the concurrent dependency-reset deadlock (issue #16). // Regression for the concurrent dependency-reset deadlock (issue #16).
// //
// Build() resets each Module/ModulePartition's per-build `compiled` /`checked` // Each Module/ModulePartition holds the state of one build (`checked`,
// flags so a reused Configuration re-evaluates mtimes. That reset MUST stay // `scheduled` and the job that precompiles the unit). Build() used to reset
// scoped to the configuration being built. It used to recurse into // it so a reused Configuration re-evaluates mtimes, and now makes the units
// cfg.dependencies — but dependency Configurations are shared across the build // anew from what it reads in the sources. Either way that MUST stay scoped
// DAG and each is compiled concurrently by its own Build() call. A parent's // to the configuration being built. The reset used to recurse into
// recursive reset could therefore clear a dependency's module `compiled` flag // cfg.dependencies — but dependency
// Configurations are shared across the build DAG and each is built
// concurrently by its own Build() call. Every unit then had a thread of its
// own and a `compiled` flag that the units importing it waited on, and a
// parent's recursive reset could clear a dependency's module `compiled` flag
// *after* that dependency's module-compile thread had set it true and exited, // *after* that dependency's module-compile thread had set it true and exited,
// but before an intra-config waiter (its impl / a dependent partition) ran // but before an intra-config waiter (its impl / a dependent partition) ran
// `compiled.wait(false)`. The waiter then blocked forever on a flag nothing // `compiled.wait(false)`. The waiter then blocked forever on a flag nothing
// re-signalled: the build froze mid-compile, idle, with no compiler process // re-signalled: the build froze mid-compile, idle, with no compiler process
// alive. // alive.
// //
// Units are jobs now and wait on no flag, but the state is still the building
// configuration's alone: cleared from outside between two Schedule() calls of
// its own build, a unit is scheduled twice and compiled twice at once.
//
// This test pins the invariant deterministically, without depending on thread // This test pins the invariant deterministically, without depending on thread
// timing: build a static-lib dependency fully (its module ends up compiled), // timing: build a static-lib dependency fully (its module ends up checked and
// then build a consumer that depends on it while the dependency is already // scheduled), then build a consumer that depends on it while the dependency is
// cached in depResults (so it is NOT rebuilt). Before the fix, the consumer's // already cached in depResults (so it is NOT rebuilt). A consumer that reset
// recursive reset flipped the dependency's module `compiled` flag back to false // its dependencies, or made their units anew, would leave the dependency's
// and, because the dependency never rebuilds, it stayed false. After the fix // module with `checked` and `scheduled` false and, because the dependency
// the consumer resets only its own modules, so the dependency's flag is left // never rebuilds, they would stay false. The consumer makes only its own
// intact. We assert it is still set once the consumer build completes. // units, so the dependency's flags are left intact. We assert both are still
// set once the consumer build completes.
int main() { int main() {
fs::path fixtureRoot = fs::current_path() / "tests" / "ConcurrentDependencyReset" / "fixture"; fs::path fixtureRoot = fs::current_path() / "tests" / "ConcurrentDependencyReset" / "fixture";
@ -51,11 +60,6 @@ int main() {
dep.GetInterfacesAndImplementations(ifaces, impls); dep.GetInterfacesAndImplementations(ifaces, impls);
} }
if (dep.interfaces.size() != 1) {
std::println(std::cerr, "expected 1 dependency interface, got {}", dep.interfaces.size());
return 1;
}
{ {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults; std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex; std::mutex depMutex;
@ -64,8 +68,12 @@ int main() {
std::println(std::cerr, "dependency build failed: {}", r.result); std::println(std::cerr, "dependency build failed: {}", r.result);
return 1; return 1;
} }
if (!dep.interfaces[0]->compiled.load()) { if (dep.interfaces.size() != 1) {
std::println(std::cerr, "dependency module not marked compiled after its own build"); std::println(std::cerr, "expected 1 dependency interface, got {}", dep.interfaces.size());
return 1;
}
if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) {
std::println(std::cerr, "dependency module not marked checked and scheduled after its own build");
return 1; return 1;
} }
// Seed a consumer-facing cache so the consumer reuses this build instead // Seed a consumer-facing cache so the consumer reuses this build instead
@ -98,10 +106,9 @@ int main() {
} }
// The core regression assertion: building the consumer must not have // The core regression assertion: building the consumer must not have
// reset the (cached, never-rebuilt) dependency's module flag. Before the // reset the (cached, never-rebuilt) dependency's module state.
// fix this was false and an intra-config waiter would have deadlocked. if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) {
if (!dep.interfaces[0]->compiled.load()) { std::println(std::cerr, "FAIL: consumer build reset a cached dependency's module state " "(issue #16 regression): done while that dependency is building, " "this compiles its units twice at once");
std::println(std::cerr, "FAIL: consumer build reset a cached dependency's module 'compiled' " "flag (issue #16 regression) — this is the state that deadlocks a " "concurrent build");
return 1; return 1;
} }

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// A library of the project's own, named like one a CUDA toolkit's lib64
// can hold (Arch's holds a libcheckpoint.so): CudaCompile checks that the
// link takes this one.
extern "C" int SaveCheckpoint() {
return 0;
}

View file

@ -0,0 +1,5 @@
/* SPDX-License-Identifier: LGPL-3.0-only
SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® */
/* A C source of kernel.cu's name, in its directory. */
int KernelInC(void) { return 1; }

View file

@ -0,0 +1,21 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include "kernel.h"
#include <cstdint>
#include <cuda_runtime.h>
__global__ void Double(float* values, std::int32_t count) {
const std::int32_t i = static_cast<std::int32_t>(blockIdx.x * blockDim.x + threadIdx.x);
if (i < count) values[i] = Factor * static_cast<float>(i);
}
extern "C" std::int32_t LaunchDouble(std::int32_t count, float* values) {
float* device = nullptr;
cudaError_t status = cudaMalloc(&device, sizeof(float) * count);
if (status != cudaSuccess) return status;
Double<<<1, 32>>>(device, count);
status = cudaMemcpy(values, device, sizeof(float) * count, cudaMemcpyDeviceToHost);
cudaFree(device);
return status;
}

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#pragma once
// What kernel.cu multiplies every index by: a header of the .cu's own, which
// the test makes newer than the object built from it.
constexpr float Factor = 2.0f;

View file

@ -0,0 +1,13 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
// In kernel.cu: doubles every index into `values` on the GPU, and returns
// cudaSuccess (0) or the CUDA error.
extern "C" std::int32_t LaunchDouble(std::int32_t count, float* values);
int main() {
std::array<float, 8> values{};
return LaunchDouble(static_cast<std::int32_t>(values.size()), values.data());
}

289
tests/CudaCompile/main.cpp Normal file
View file

@ -0,0 +1,289 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// cfg.cuda is compiled with the nvcc ResolveToolchain finds, for the GPU
// architecture cfg.cudaArch names. It used to be whatever "nvcc" meant to the
// shell, for sm_89 alone: crafter-build's Flatpak sets PATH to
// /app/bin:/usr/bin, and with that PATH every CUDA build there stopped at
// "nvcc: command not found" with the host's toolkit in reach at /opt/cuda.
//
// The test puts an nvcc on PATH that fails, names a toolkit through CUDA_PATH
// whose nvcc writes down its arguments and runs the real one, and builds an
// executable from a C++ unit and a .cu: with the default architecture, which
// is native, then with another one, which compiles the unchanged .cu again in
// a directory of its own, then once more with nothing changed, which compiles
// nothing, and once its header is newer than its object, which compiles it
// again: nvcc's depfile is the record of what the .cu includes, and before
// nvcc wrote one, a changed header left the old object in place. Those builds
// name no CUDA library: the configuration links the runtime of the toolkit
// itself, the static archive in its lib64 by its path. Another build puts the
// .cu in a static library and the C++ unit in an executable built on it, which
// links only if the library hands the runtime on. That lib64 also holds a
// libcheckpoint.so and a libm.so that are no libraries, so a link that
// searched it would stop on one: an executable with CUDA sources built on a
// library of the project's named checkpoint has to take the project's, and
// clang++ adds -lm to every C++ link. Another build names the shared runtime
// itself, as a project with CUDA sources had to, and has its -lcudart ahead of
// the static archive. A last one is a static library of the .cu and a C source
// of its name beside it: the archive has to hold an object of each, where the
// two used to be compiled into one (issue #50). Where nvcc is looked for, and
// the runtime beside it, is ToolchainResolve's to check; this is the build
// that uses them. Skips without a CUDA toolkit whose lib64 holds the static
// runtime; CI has none.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// The nvcc crafter-build finds in this environment, looked for with the
// inputs GetToolchain() gives ResolveToolchain, the host's /usr under
// /run/host in a sandbox included, before the test changes CUDA_PATH and
// PATH. ResolveToolchain is pure: GetToolchain()'s cache stays empty.
Toolchain RealToolkit() {
ToolchainInputs in;
for (const std::string_view name : {"CUDA_PATH", "PATH"}) {
if (const char* value = std::getenv(std::string(name).c_str()); value && *value) in.env.emplace(std::string(name), value);
}
if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host";
in.cudaRoots = { "/opt/cuda", "/usr/local/cuda" };
return ResolveToolchain(in);
}
void WriteProgram(const fs::path& file, std::string_view text) {
fs::create_directories(file.parent_path());
std::ofstream(file) << text;
fs::permissions(file, fs::perms::owner_exec, fs::perm_options::add);
}
std::string Read(const fs::path& file) {
std::ifstream in(file, std::ios::binary);
return std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
}
std::vector<std::string> Lines(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;
}
std::string Joined(const std::vector<std::string>& lines) {
return std::views::join_with(lines, std::string(" | ")) | std::ranges::to<std::string>();
}
struct Built {
std::string error;
fs::path binary;
// The link command the build recorded, beside its objects.
fs::path linkRecord;
};
}
int main() {
const Toolchain real = RealToolkit();
if (real.nvcc.empty()) {
std::println("SKIP: {}", real.nvccError);
return 77;
}
const fs::path nvcc = real.nvcc;
// The static runtime crafter-build links, from the lib64 beside nvcc's
// bin. A toolkit without one there gets none linked, and the runtime link
// has nothing to show.
const fs::path realArchive = real.cudaRuntime;
if (realArchive.empty()) {
std::println("SKIP: no libcudart_static.a in the lib64 beside {}, so crafter-build links no CUDA runtime for this toolkit", nvcc.parent_path().string());
return 77;
}
const fs::path scratch = fs::temp_directory_path() / "crafter-build-cuda-compile";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::create_directories(scratch);
const fs::path project = scratch / "project";
fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", project, fs::copy_options::recursive);
// The toolkit CUDA_PATH names: an nvcc that writes down how it was run and
// runs the real one, and a lib64 with the real toolkit's static runtime
// and a libcheckpoint.so and a libm.so that are no libraries at all. A
// toolkit's lib64 can hold a library named like a project's own (Arch's
// holds a libcheckpoint.so) or like one the link takes from the system (a
// libOpenCL.so), and a link that searched it would take that one: the
// libm.so stands for those, as clang++ adds -lm to every C++ link.
const fs::path log = scratch / "nvcc.log";
const fs::path toolkit = scratch / "toolkit";
WriteProgram(toolkit / "bin" / "nvcc", std::format("#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\nexec {} \"$@\"\n", ShellQuote(log.string()), ShellQuote(nvcc.string())));
fs::create_directories(toolkit / "lib64");
fs::create_symlink(realArchive, toolkit / "lib64" / "libcudart_static.a");
std::ofstream(toolkit / "lib64" / "libcheckpoint.so") << "not a library\n";
std::ofstream(toolkit / "lib64" / "libm.so") << "not a library\n";
// What a link names the runtime by: the archive in the toolkit's lib64, by
// its path.
const std::string runtime = (toolkit / "lib64" / "libcudart_static.a").string();
const fs::path decoy = scratch / "decoy";
WriteProgram(decoy / "nvcc", "#!/bin/sh\necho 'the nvcc on PATH ran' >&2\nexit 1\n");
// Before anything resolves the toolchain, which reads the environment
// once per process: the first Configuration does, for its target.
setenv("CUDA_PATH", toolkit.c_str(), 1);
const char* path = std::getenv("PATH");
setenv("PATH", std::format("{}:{}", decoy.string(), path ? path : "").c_str(), 1);
const auto build = [&](std::optional<std::string> arch) {
Configuration app;
app.path = project;
app.name = "cuda";
app.outputName = "cuda";
app.type = ConfigurationType::Executable;
if (arch) app.cudaArch = *arch;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
app.cuda = { project / "kernel" };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult result = Build(app, depResults, depMutex);
return Built{ result.result, app.BinDir() / "cuda", app.BuildDir() / "cuda.link" };
};
const Built native = build(std::nullopt);
Check(native.error.empty(), std::format("the build with the default architecture succeeds: {}", native.error));
Check(fs::exists(native.binary), "it links the executable");
const std::string record = Read(native.linkRecord);
Check(record.contains(runtime), std::format("with the static runtime from the toolkit's lib64, though no link flag names it (link: {})", record));
std::vector<std::string> runs = Lines(log);
Check(runs.size() == 1 && runs.front().contains("-arch=native"), std::format("CUDA_PATH's nvcc compiles the .cu once, with -arch=native (ran: {})", Joined(runs)));
const Built other = build("sm_86");
Check(other.error.empty(), std::format("the build for sm_86 succeeds: {}", other.error));
runs = Lines(log);
Check(runs.size() == 2 && runs.back().contains("-arch=sm_86"), std::format("another architecture compiles the unchanged .cu again, for it (ran: {})", Joined(runs)));
Check(fs::exists(other.binary) && other.binary.parent_path() != native.binary.parent_path(), "in a directory of its own");
const Built again = build("sm_86");
Check(again.error.empty() && Lines(log).size() == 2, std::format("an unchanged build compiles nothing (ran: {})", Joined(Lines(log))));
fs::last_write_time(project / "kernel.h", fs::file_time_type::clock::now());
const Built touched = build("sm_86");
Check(touched.error.empty(), std::format("the build after the header changed succeeds: {}", touched.error));
runs = Lines(log);
Check(runs.size() == 3 && runs.back().contains("-arch=sm_86"), std::format("a changed header compiles the .cu again (ran: {})", Joined(runs)));
{
// The .cu in a static library, the C++ unit in an executable built on
// it: neither names a CUDA library, and the executable's link has the
// runtime only from what the library hands on.
const fs::path split = scratch / "split";
fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", split, fs::copy_options::recursive);
Configuration kernels;
kernels.path = split;
kernels.name = "kernels";
kernels.outputName = "kernels";
kernels.type = ConfigurationType::LibraryStatic;
kernels.cuda = { split / "kernel" };
Configuration program;
program.path = split;
program.name = "program";
program.outputName = "program";
program.type = ConfigurationType::Executable;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
program.GetInterfacesAndImplementations(ifaces, impls);
program.dependencies = { &kernels };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult built = Build(program, depResults, depMutex);
Check(built.result.empty(), std::format("an executable built on a library with CUDA sources links: {}", built.result));
Check(Read(program.BuildDir() / "program.link").contains(runtime), "with the runtime the library hands on");
}
{
// An executable with CUDA sources built on a library of the
// project's named like one in the toolkit's lib64: the linker has to
// take the project's, and stops on the toolkit's file if it searches
// the toolkit's lib64 first.
const fs::path named = scratch / "named";
fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", named, fs::copy_options::recursive);
Configuration checkpoint;
checkpoint.path = named;
checkpoint.name = "checkpoint";
checkpoint.outputName = "checkpoint";
checkpoint.type = ConfigurationType::LibraryStatic;
{
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "checkpoint" };
checkpoint.GetInterfacesAndImplementations(ifaces, impls);
}
Configuration app;
app.path = named;
app.name = "named";
app.outputName = "named";
app.type = ConfigurationType::Executable;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
app.cuda = { named / "kernel" };
app.dependencies = { &checkpoint };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult built = Build(app, depResults, depMutex);
Check(built.result.empty(), std::format("an executable with CUDA sources links a library of its project's named like one in the toolkit's lib64: {}", built.result));
}
{
// A project that names the shared runtime itself, as every project.cpp
// with CUDA sources had to: its -lcudart comes ahead of the static
// archive on the link line, so the linker takes the shared runtime.
const fs::path own = scratch / "own";
fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", own, fs::copy_options::recursive);
Configuration app;
app.path = own;
app.name = "own";
app.outputName = "own";
app.type = ConfigurationType::Executable;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
app.cuda = { own / "kernel" };
app.linkFlags = { std::format("-L{}", ShellQuote(realArchive.parent_path().string())), "-lcudart" };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult built = Build(app, depResults, depMutex);
Check(built.result.empty(), std::format("a build that names -lcudart itself links: {}", built.result));
const std::string link = Read(app.BuildDir() / "own.link");
const std::size_t shared = link.find(" -lcudart ");
const std::size_t archive = link.find(runtime);
Check(shared != std::string::npos && archive != std::string::npos && shared < archive, std::format("with its -lcudart ahead of the static runtime (link: {})", link));
}
{
// A C source of the .cu's name beside it, in a static library: each
// has an object of its own, and the archive lists the two. Both used
// to be compiled into kernel_source.o, each over the other (issue
// #50).
const fs::path twins = scratch / "twins";
fs::copy(fs::current_path() / "tests" / "CudaCompile" / "fixture", twins, fs::copy_options::recursive);
Configuration kernels;
kernels.path = twins;
kernels.name = "twins";
kernels.outputName = "twins";
kernels.type = ConfigurationType::LibraryStatic;
kernels.cFiles = { twins / "kernel" };
kernels.cuda = { twins / "kernel" };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult built = Build(kernels, depResults, depMutex);
Check(built.result.empty(), std::format("a library of a kernel.c and a kernel.cu in one directory builds: {}", built.result));
const auto members = RunCommandWithTimeout(std::format("{} t {}", ShellQuote(GetToolchain().llvmAr.string()), ShellQuote(ExpectedOutput(kernels).string())), std::chrono::seconds(30));
Check(members.exitCode == 0 && members.output == "kernel_source.o\nkernel_cuda.o\n", std::format("with an object of each in its archive: llvm-ar t lists '{}' (exit {})", members.output, members.exitCode));
}
fs::remove_all(scratch, ec);
return Failures == 0 ? 0 : 1;
}

View file

@ -0,0 +1,5 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Never compiled: CudaMissing's CUDA_PATH names a directory without an nvcc.
__global__ void Kernel() {}

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// CudaMissing's program: nothing in it needs CUDA, so it builds without an
// nvcc where its configuration has no CUDA sources.
int main() {
return 0;
}

View file

@ -0,0 +1,73 @@
// 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;
// A build with CUDA sources and no nvcc to compile them fails, saying where
// nvcc was looked for. It used to run a bare "nvcc" through the shell, which
// in crafter-build's Flatpak, whose PATH as its manifest sets it holds no host
// toolkit, stopped such builds at "sh: line 1: nvcc: command not found",
// naming no place to put one. CUDA_PATH names an empty directory here, so the
// test needs no CUDA toolkit and runs in CI, where CudaCompile skips: the
// build with a .cu fails naming that directory's bin/nvcc and CUDA_PATH, and a
// build without CUDA sources in the same process still succeeds, as only a .cu
// needs an nvcc.
extern "C" int setenv(const char* name, const char* value, int overwrite);
namespace {
std::int32_t failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++failures;
}
}
BuildResult BuildOnce(const fs::path& project, std::string_view name, bool withCuda) {
Configuration app;
app.path = project;
app.name = name;
app.outputName = name;
app.type = ConfigurationType::Executable;
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
if (withCuda) app.cuda = { project / "kernel" };
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
return Build(app, depResults, depMutex);
}
}
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-cuda-missing";
fs::remove_all(scratch);
fs::create_directories(scratch);
const fs::path project = scratch / "project";
fs::copy(fs::current_path() / "tests" / "CudaMissing" / "fixture", project, fs::copy_options::recursive);
// A toolkit directory without a bin/nvcc, named before anything resolves
// the toolchain, which reads CUDA_PATH once per process.
const fs::path toolkit = scratch / "toolkit";
fs::create_directories(toolkit);
setenv("CUDA_PATH", toolkit.c_str(), 1);
const BuildResult missing = BuildOnce(project, "cuda", true);
const std::string expected = std::format("cannot compile kernel.cu: no nvcc at {} (CUDA_PATH)", (toolkit.lexically_normal() / "bin" / "nvcc").string());
Check(missing.result == expected, std::format("a build with a .cu and no nvcc fails, saying where it looked (expected '{}', got '{}')", expected, missing.result));
const BuildResult plain = BuildOnce(project, "plain", false);
Check(plain.result.empty(), std::format("a build without CUDA sources needs no nvcc: {}", plain.result));
std::error_code ec;
fs::remove_all(scratch, ec);
if (failures > 0) {
std::println(std::cerr, "{} assertions failed", failures);
return 1;
}
return 0;
}

View file

@ -38,6 +38,15 @@ int main() {
app.GetInterfacesAndImplementations(ifaces, impls); app.GetInterfacesAndImplementations(ifaces, impls);
} }
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
BuildResult r = Build(app, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "build failed: {}", r.result);
return 1;
}
// What the build read in the sources.
if (app.implementations.size() != 1) { if (app.implementations.size() != 1) {
std::println(std::cerr, "expected 1 implementation, got {}", app.implementations.size()); std::println(std::cerr, "expected 1 implementation, got {}", app.implementations.size());
return 1; return 1;
@ -56,14 +65,6 @@ int main() {
return 1; return 1;
} }
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
BuildResult r = Build(app, depResults, depMutex);
if (!r.result.empty()) {
std::println(std::cerr, "build failed: {}", r.result);
return 1;
}
fs::path libArchive = lib->BinDir() / "libcalc.a"; fs::path libArchive = lib->BinDir() / "libcalc.a";
if (!fs::exists(libArchive)) { if (!fs::exists(libArchive)) {
std::println(std::cerr, "dep archive not produced at {}", libArchive.string()); std::println(std::cerr, "dep archive not produced at {}", libArchive.string());

View file

@ -1,4 +0,0 @@
# app
The consumer's own instructions. Nothing in this file may change, except the
section crafter-build appends.

View file

@ -0,0 +1,4 @@
# app
The consumer's own instructions. AGENTS.md has to carry them unchanged, below
its first line and above the dependency notes.

View file

@ -0,0 +1,3 @@
## outer
outer wraps lib.

View file

@ -0,0 +1,21 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// A project that builds against lib, and so against base one ring further
// out. app does not name it: the test loads it for the cases in which a
// project has several configurations, where it is what a second
// configuration names.
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view>) {
Configuration cfg;
cfg.path = "./";
cfg.name = "outer";
cfg.outputName = "outer";
cfg.type = ConfigurationType::LibraryStatic;
// Loaded from outer/, so this resolves against it.
cfg.dependencies = { LocalProject({ .projectFile = "../lib/project.cpp" }) };
return cfg;
}

View file

@ -6,19 +6,22 @@ import Crafter.Build;
namespace fs = std::filesystem; namespace fs = std::filesystem;
using namespace Crafter; using namespace Crafter;
// Dependency notes: every dependency that ships an AGENTS.consumer.md beside // Dependency notes: a consumer with an AGENTS.template.md beside its
// its project.cpp has the file kept in a marked section of its consumer's // project.cpp has every build and test run write AGENTS.md from it, with the
// AGENTS.md, refreshed by each build and test run. // AGENTS.consumer.md each dependency ships merged into a marked section.
// //
// AGENTS.md is the user's own file, committed and edited by hand, so what // The template is the user's own file, committed and edited by hand, and
// this guards against is everything else moving: a section appended again on // AGENTS.md is build output that stays out of version control: notes kept in
// every build, text outside the section rewritten, lost or run together, a // a committed AGENTS.md changed it under every diff. So what this guards
// write when nothing changed (a dirty tree, an editor reloading), an // against is the generated file leaking into the user's: the template
// AGENTS.md created in a project that has none, one written although it is // written, an AGENTS.md someone wrote replaced (one committed before the
// read-only, or replaced so that a hard link to it goes stale, notes from a // template was, or one beside no template at all), one written although it
// test's dependency or a dependency's own host tooling leaking into the // is read-only, or replaced so that a hard link to it goes stale; and inside
// consumer's, and `lint`, `run` or `test --list`, which promise not to touch // AGENTS.md, the template's text changed or the section misplaced, a write
// the project, writing it anyway. // when nothing changed (an editor reloading), notes from a test's dependency
// or a dependency's own host tooling leaking into the consumer's, and `lint`,
// `run` or `test --list`, which promise not to touch the project, writing it
// anyway.
namespace { namespace {
std::int32_t Failures = 0; std::int32_t Failures = 0;
@ -84,6 +87,7 @@ namespace {
constexpr std::string_view BeginMarker = "<!-- crafter-build: dependency notes begin -->"; constexpr std::string_view BeginMarker = "<!-- crafter-build: dependency notes begin -->";
constexpr std::string_view EndMarker = "<!-- crafter-build: dependency notes end -->"; constexpr std::string_view EndMarker = "<!-- crafter-build: dependency notes end -->";
constexpr std::string_view GeneratedLine = "<!-- Written by crafter-build from AGENTS.template.md, and rewritten on every build. Edit that file, not this one. -->";
} }
int main() { int main() {
@ -187,12 +191,13 @@ int main() {
fs::copy(fixture, scratch, fs::copy_options::recursive); fs::copy(fixture, scratch, fs::copy_options::recursive);
const fs::path app = scratch / "app"; const fs::path app = scratch / "app";
const fs::path agents = app / "AGENTS.md"; const fs::path agents = app / "AGENTS.md";
const fs::path templateFile = app / "AGENTS.template.md";
const fs::path projectFile = app / "project.cpp"; const fs::path projectFile = app / "project.cpp";
const fs::path libNotes = scratch / "lib" / "AGENTS.consumer.md"; const fs::path libNotes = scratch / "lib" / "AGENTS.consumer.md";
// Checked in under another name: an AGENTS.md in this repository's tree // Checked in under another name, so that this repository's tree holds no
// would read as instructions for the agents working on it. // template a build could ever pick up.
const std::string agentsOriginal = Read(app / "AGENTS.md.in"); const std::string templateText = Read(app / "AGENTS.template.md.in");
Write(agents, agentsOriginal); Write(templateFile, templateText);
// LocalProject resolves against the working directory, and app's paths // LocalProject resolves against the working directory, and app's paths
// are written for `cd app && crafter-build`. // are written for `cd app && crafter-build`.
fs::current_path(app); fs::current_path(app);
@ -210,10 +215,15 @@ int main() {
const std::string libNote = "<!-- from lib -->\n## lib\n\nCall lib through its module, never through its headers.\n"; const std::string libNote = "<!-- from lib -->\n## lib\n\nCall lib through its module, never through its headers.\n";
// base's file opens and ends with blank lines, which the section drops. // base's file opens and ends with blank lines, which the section drops.
const std::string baseNote = "<!-- from base -->\n## base\n\nbase counts from zero.\n"; const std::string baseNote = "<!-- from base -->\n## base\n\nbase counts from zero.\n";
// How every AGENTS.md written from templateText starts.
const std::string generated = std::format("{}\n{}", GeneratedLine, templateText);
Check(UpdateAgentsMd(cfg, projectFile), "the first update writes AGENTS.md"); Check(!fs::exists(agents) && UpdateAgentsMd(cfg, projectFile), "the first update creates AGENTS.md");
// Every case after this one reads or rewrites that file.
if (!fs::exists(agents)) return 1;
std::string text = Read(agents); std::string text = Read(agents);
Check(text.starts_with(std::format("{}\n{}\n", agentsOriginal, BeginMarker)), "the section follows the consumer's own text, which is untouched"); Check(text.starts_with(std::format("{}\n{}\n", generated, BeginMarker)), "AGENTS.md is the line saying a build wrote it, the template's text untouched, then the section");
Check(Read(templateFile) == templateText, "the template is never written");
const std::size_t tool = text.find(toolNote); const std::size_t tool = text.find(toolNote);
const std::size_t lib = text.find(libNote); const std::size_t lib = text.find(libNote);
const std::size_t base = text.find(baseNote); const std::size_t base = text.find(baseNote);
@ -228,7 +238,7 @@ int main() {
Check(Read(agents) == text && fs::last_write_time(agents) == written, "the bytes and the mtime are left alone when nothing changed"); Check(Read(agents) == text && fs::last_write_time(agents) == written, "the bytes and the mtime are left alone when nothing changed");
cfg.dependencyNotes = DependencyNotes::Direct; cfg.dependencyNotes = DependencyNotes::Direct;
Check(UpdateAgentsMd(cfg, projectFile), "switching to Direct rewrites the section"); Check(UpdateAgentsMd(cfg, projectFile), "switching to Direct rewrites AGENTS.md");
text = Read(agents); text = Read(agents);
Check(text.contains(toolNote) && text.contains(libNote) && !text.contains("## base"), "Direct keeps what app names and drops what only lib does"); Check(text.contains(toolNote) && text.contains(libNote) && !text.contains("## base"), "Direct keeps what app names and drops what only lib does");
@ -238,6 +248,18 @@ int main() {
text = Read(agents); text = Read(agents);
Check(text.contains("lib was rewritten.") && !text.contains("never through its headers") && Count(text, BeginMarker) == 1, "edited notes replace the old ones, in the one section"); Check(text.contains("lib was rewritten.") && !text.contains("never through its headers") && Count(text, BeginMarker) == 1, "edited notes replace the old ones, in the one section");
// AGENTS.md follows the template: an edit made there shows up here, and
// the template's marker lines say where the notes go.
Write(templateFile, std::format("{}\nA paragraph added to the template.\n", templateText));
Check(UpdateAgentsMd(cfg, projectFile), "an edited template is picked up");
Check(Read(agents).starts_with(std::format("{}\nA paragraph added to the template.\n\n{}\n", generated, BeginMarker)), "the template's new text goes in ahead of the section");
Write(templateFile, std::format("# app\n\n{}\n{}\n\n## After\n\nText after the notes.\n", BeginMarker, EndMarker));
Check(UpdateAgentsMd(cfg, projectFile), "a template that places the section is picked up");
text = Read(agents);
Check(text.starts_with(std::format("{}\n# app\n\n{}\n", GeneratedLine, BeginMarker)) && text.contains(toolNote) && text.ends_with(std::format("{}\n\n## After\n\nText after the notes.\n", EndMarker)), "the section goes where the template's markers are");
Write(templateFile, templateText);
Check(UpdateAgentsMd(cfg, projectFile) && Read(agents).starts_with(generated), "AGENTS.md follows the template back");
// A CLAUDE.md hard-linked to AGENTS.md has to keep reading the same file. // A CLAUDE.md hard-linked to AGENTS.md has to keep reading the same file.
fs::create_hard_link(agents, app / "CLAUDE.md"); fs::create_hard_link(agents, app / "CLAUDE.md");
Write(libNotes, "## lib\n\nlib, through a link.\n"); Write(libNotes, "## lib\n\nlib, through a link.\n");
@ -255,37 +277,157 @@ int main() {
} }
fs::permissions(agents, fs::perms::owner_write, fs::perm_options::add); fs::permissions(agents, fs::perms::owner_write, fs::perm_options::add);
// A build's own AGENTS.md is output, an edit made in it included; any
// other text in its place is someone's, and only an empty file is not.
(void)UpdateAgentsMd(cfg, projectFile);
const std::string settled = Read(agents);
Write(agents, std::format("{}\nAn edit made in AGENTS.md itself.\n", GeneratedLine));
Check(UpdateAgentsMd(cfg, projectFile) && Read(agents) == settled, "an edit made in AGENTS.md is replaced by the next build");
const std::string handWritten = "# app\n\nAn AGENTS.md committed before the template was.\n";
Write(agents, handWritten);
Check(!UpdateAgentsMd(cfg, projectFile) && Read(agents) == handWritten, "an AGENTS.md no build wrote is never replaced");
Write(agents, "");
Check(UpdateAgentsMd(cfg, projectFile) && Read(agents) == settled, "an empty AGENTS.md, all a write cut short leaves of a new one, is replaced");
cfg.dependencyNotes = DependencyNotes::None; cfg.dependencyNotes = DependencyNotes::None;
Check(UpdateAgentsMd(cfg, projectFile), "None removes the section"); Check(UpdateAgentsMd(cfg, projectFile), "None rewrites AGENTS.md");
Check(Read(agents) == agentsOriginal, "removing the section gives AGENTS.md its own bytes back"); Check(Read(agents) == generated, "under None, AGENTS.md holds the template's text alone");
cfg.dependencyNotes = DependencyNotes::Transitive; cfg.dependencyNotes = DependencyNotes::Transitive;
fs::remove(agents);
Check(!UpdateAgentsMd(cfg, projectFile) && !fs::exists(agents), "a project without an AGENTS.md does not get one");
// A common layout keeps the file elsewhere and links it, which a write // A project file that returns several configurations: each one's setting
// that replaced the link with a copy would quietly undo. // selects among what that one is built against, and the notes are
fs::create_directories(app / "docs"); // merged. `second` stands in for a second configuration of app's project
Write(app / "docs" / "agents.md", agentsOriginal); // file, and outer is a project that builds against lib, and so against
fs::create_symlink("docs/agents.md", agents); // base one ring further out.
Check(UpdateAgentsMd(cfg, projectFile), "an AGENTS.md that is a symlink is updated"); {
Check(fs::is_symlink(agents) && Read(app / "docs" / "agents.md").contains(toolNote), "the update goes through the link, which stays a link"); Configuration* outer = nullptr;
try {
outer = LocalProject({ .projectFile = scratch / "outer" / "project.cpp" });
} catch (const std::exception& e) {
std::println(std::cerr, "FAIL: loading outer threw: {}", e.what());
return 1;
}
Configuration* const baseProject = cfg.dependencies[0]->dependencies[0];
Configuration second;
std::array<const Configuration*, 2> both = { &cfg, &second };
// The projects the section names, in its order, once AGENTS.md is
// written for `configurations`.
const auto named = [&](std::span<const Configuration* const> configurations) {
(void)UpdateAgentsMd(configurations, projectFile);
const std::string now = Read(agents);
constexpr std::string_view from = "<!-- from ";
std::vector<std::string> names;
for (std::size_t pos = now.find(from); pos != std::string::npos; pos = now.find(from, pos + 1)) {
names.push_back(now.substr(pos + from.size(), now.find(" -->", pos) - pos - from.size()));
}
return names;
};
using Names = std::vector<std::string>;
cfg.dependencyNotes = DependencyNotes::Direct;
second.dependencies = { outer };
second.dependencyNotes = DependencyNotes::Direct;
Check(named(both) == Names{"tool", "lib", "outer"}, std::format("two Direct configurations give what each of them names (got {})", named(both)));
// lib is in the first ring through app, which asks for no more. The
// second configuration reaches it through outer and asks for
// everything, so what lib builds against is in.
second.dependencyNotes = DependencyNotes::Transitive;
Check(named(both) == Names{"tool", "lib", "outer", "base"}, std::format("a project a Direct configuration names is followed when a Transitive one leads to it (got {})", named(both)));
cfg.dependencyNotes = DependencyNotes::None;
second.dependencies = { baseProject };
Check(named(both) == Names{"tool", "base"}, std::format("a configuration under None keeps out what only it is built against (got {})", named(both)));
second.dependencyNotes = DependencyNotes::None;
Check(named(both).empty() && Read(agents) == generated, "with every configuration under None, AGENTS.md holds the template's text alone");
// A configuration the file loaded from another project and returns
// is one of the projects it is built against, and its own setting
// counts for nothing here: it goes by the widest of the others.
std::array<const Configuration*, 2> withOuter = { &cfg, outer };
cfg.dependencyNotes = DependencyNotes::Direct;
Check(named(withOuter) == Names{"tool", "lib", "outer"}, std::format("a returned configuration of another project is in the first ring, and under Direct no more of it (got {})", named(withOuter)));
cfg.dependencyNotes = DependencyNotes::Transitive;
Check(named(withOuter) == Names{"tool", "lib", "outer", "base"}, std::format("under Transitive what it builds against follows (got {})", named(withOuter)));
std::array<const Configuration*, 1> onlyOuter = { outer };
Check(named(onlyOuter) == Names{"tool", "outer", "lib", "base"}, std::format("a file that made no configuration itself gets everything (got {})", named(onlyOuter)));
// The same Configuration, for outer's own AGENTS.md: outer's project
// file made it, so here its setting is the one that selects, though
// a loader holds it. Told apart by being held, it was another
// project's configuration to its own file, and got everything.
const fs::path outerFile = scratch / "outer" / "project.cpp";
const fs::path outerAgents = scratch / "outer" / "AGENTS.md";
Write(scratch / "outer" / "AGENTS.template.md", templateText);
const auto outerNamed = [&](DependencyNotes setting) {
outer->dependencyNotes = setting;
(void)UpdateAgentsMd(*outer, outerFile);
const std::string now = Read(outerAgents);
constexpr std::string_view from = "<!-- from ";
Names names;
for (std::size_t pos = now.find(from); pos != std::string::npos; pos = now.find(from, pos + 1)) {
names.push_back(now.substr(pos + from.size(), now.find(" -->", pos) - pos - from.size()));
}
return names;
};
Check(outerNamed(DependencyNotes::Direct) == Names{"lib"}, std::format("a project loaded by another gets what its own Direct selects in its own AGENTS.md (got {})", outerNamed(DependencyNotes::Direct)));
Check(outerNamed(DependencyNotes::Transitive) == Names{"lib", "base"}, std::format("and what its Transitive does (got {})", outerNamed(DependencyNotes::Transitive)));
Check(outerNamed(DependencyNotes::None).empty() && Read(outerAgents) == generated, "and under None the template's text alone");
outer->dependencyNotes = DependencyNotes::Transitive;
}
// Linked to the template, AGENTS.md would have every build write the
// file that is committed.
fs::remove(agents); fs::remove(agents);
fs::create_symlink("AGENTS.template.md", agents);
Check(!UpdateAgentsMd(cfg, projectFile) && Read(templateFile) == templateText, "an AGENTS.md that links to the template is not written");
fs::remove(agents);
// A template the notes cannot be placed in leaves no AGENTS.md behind,
// not even an empty one.
Write(templateFile, std::format("# app\n\n{}\n", BeginMarker));
Check(!UpdateAgentsMd(cfg, projectFile) && !fs::exists(agents), "a template with a begin marker and no end marker writes no AGENTS.md");
// A CRLF template makes a CRLF AGENTS.md, the line a build adds included.
Write(templateFile, "# app\r\n\r\nText.\r\n");
Check(UpdateAgentsMd(cfg, projectFile), "a CRLF template is written");
text = Read(agents);
Check(text.starts_with(std::format("{}\r\n# app\r\n", GeneratedLine)) && Count(text, "\n") == Count(text, "\r\n"), "AGENTS.md from a CRLF template ends every line in CRLF");
Write(templateFile, templateText);
fs::remove(agents);
// A layout that keeps the file elsewhere and links it, which a write that
// replaced the link with a copy would quietly undo.
fs::create_directories(app / "docs");
Write(app / "docs" / "agents.md", "");
fs::create_symlink("docs/agents.md", agents);
Check(UpdateAgentsMd(cfg, projectFile), "an AGENTS.md that is a symlink is written");
Check(fs::is_symlink(agents) && Read(app / "docs" / "agents.md").contains(toolNote), "the write goes through the link, which stays a link");
fs::remove(agents);
// Without a template, AGENTS.md is someone's own: never created, and
// never written, not even to take out a section an earlier crafter-build
// kept in it, which only gets a warning.
fs::remove(templateFile);
Check(!UpdateAgentsMd(cfg, projectFile) && !fs::exists(agents), "a project without a template gets no AGENTS.md");
const std::vector<DependencyNote> oldNotes = { { .name = "lib", .text = "## lib\n\nNotes a committed AGENTS.md still holds." } };
const std::string committed = Merge(templateText, oldNotes);
Write(agents, committed);
Check(!UpdateAgentsMd(cfg, projectFile) && Read(agents) == committed, "without a template, an AGENTS.md holding a section is left alone");
fs::remove(agents);
Write(templateFile, templateText);
// The CLI: only a build or a test run writes it. // The CLI: only a build or a test run writes it.
Write(agents, agentsOriginal);
(void)RunWith({"crafter-build", "-q", "lint"}); (void)RunWith({"crafter-build", "-q", "lint"});
Check(Read(agents) == agentsOriginal, "lint leaves AGENTS.md alone"); Check(!fs::exists(agents), "lint writes no AGENTS.md");
(void)RunWith({"crafter-build", "-q", "run"}); (void)RunWith({"crafter-build", "-q", "run"});
Check(Read(agents) == agentsOriginal, "run leaves AGENTS.md alone"); Check(!fs::exists(agents), "run writes no AGENTS.md");
(void)RunWith({"crafter-build", "-q", "test", "--list"}); (void)RunWith({"crafter-build", "-q", "test", "--list"});
Check(Read(agents) == agentsOriginal, "test --list leaves AGENTS.md alone"); Check(!fs::exists(agents), "test --list writes no AGENTS.md");
(void)RunWith({"crafter-build", "-q", "test"}); (void)RunWith({"crafter-build", "-q", "test"});
Check(Read(agents).contains(toolNote), "a test run refreshes AGENTS.md"); Check(Read(agents).contains(toolNote), "a test run writes AGENTS.md");
// app has no sources, so this build fails at the link, after the update. // app has no sources, so this build fails at the link, after the update.
Write(agents, agentsOriginal); fs::remove(agents);
(void)RunWith({"crafter-build", "-q"}); (void)RunWith({"crafter-build", "-q"});
Check(Read(agents).contains(toolNote), "a build refreshes AGENTS.md before compiling, so one that fails still does"); Check(Read(agents).contains(toolNote), "a build writes AGENTS.md before compiling, so one that fails still does");
// The builds above leave a std PCM per configuration in a tmpfs; a run // The builds above leave a std PCM per configuration in a tmpfs; a run
// that failed keeps them for a look. // that failed keeps them for a look.

View file

@ -8,13 +8,16 @@ using namespace Crafter;
// Loads M itself and through A, which passes on all of its args. With // Loads M itself and through A, which passes on all of its args. With
// --split, the list P gives M leaves --wide out, as a filter meant for one // --split, the list P gives M leaves --wide out, as a filter meant for one
// sibling would, and the two paths load M with two different lists. // sibling would, and the two paths load M with two different lists. With
// --reorder, P gives M its args in the other order: the same list, which
// the loader still takes for another.
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) { extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
const bool split = std::ranges::contains(args, std::string_view("--split")); const bool split = std::ranges::contains(args, std::string_view("--split"));
std::vector<std::string> mArgs; std::vector<std::string> mArgs;
for (std::string_view arg : args) { for (std::string_view arg : args) {
if (!split || arg != "--wide") mArgs.emplace_back(arg); if (!split || arg != "--wide") mArgs.emplace_back(arg);
} }
if (std::ranges::contains(args, std::string_view("--reorder"))) std::ranges::reverse(mArgs);
Configuration* m = LocalProject({ .projectFile = "../m/project.cpp", .args = mArgs }); Configuration* m = LocalProject({ .projectFile = "../m/project.cpp", .args = mArgs });
Configuration* a = LocalProject({ .projectFile = "../a/project.cpp" }); Configuration* a = LocalProject({ .projectFile = "../a/project.cpp" });

View file

@ -8,13 +8,14 @@ using namespace Crafter;
// A program can hold one module of each name, so Build() refuses a graph in // A program can hold one module of each name, so Build() refuses a graph in
// which two configurations export the same module: the same project loaded // which two configurations export the same module: the same project loaded
// along two paths with two arg lists, say. It used to build both and put // along two paths with two arg lists, say. It used to build both and compile
// both on the consumer's module path. Clang took the first for every import // the consumer with both on its module path. Clang took the first for every
// of the module, the ones inside the other build's consumers included, and // import of the module, the ones inside the other build's consumers
// the program linked code compiled against two layouts of one struct: it // included, and the program linked code compiled against two layouts of one
// built cleanly, then read garbage or crashed (issue #41). The fixture is // struct: it built cleanly, then read garbage or crashed (issue #41). The
// P -> M and P -> A -> M. With --split, P gives M its args without --wide, // fixture is P -> M and P -> A -> M. With --split, P gives M its args
// which changes what M declares, while A passes them on whole. // without --wide, which changes what M declares, while A passes them on
// whole.
namespace { namespace {
std::int32_t Failures = 0; std::int32_t Failures = 0;
@ -53,7 +54,9 @@ int main() {
const fs::path cwd = fs::current_path(); const fs::path cwd = fs::current_path();
fs::current_path(scratch / "p"); fs::current_path(scratch / "p");
try { try {
// Two lists for M: refused before anything is built. // Two lists for M: refused before P compiles anything of its own.
// The modules of a configuration are known once it is built, so M is
// built twice, and A on one of the two, before P can tell.
{ {
std::array<std::string_view, 2> args = { "--wide", "--split" }; std::array<std::string_view, 2> args = { "--wide", "--split" };
Configuration cfg = LoadProject("project.cpp", args); Configuration cfg = LoadProject("project.cpp", args);
@ -61,7 +64,73 @@ int main() {
Check(!built.result.empty(), "a graph with two builds of one module fails to build"); Check(!built.result.empty(), "a graph with two builds of one module fails to build");
Check(built.result.contains("module M is built twice for P"), std::format("the error names the module and the program (got: {})", built.result)); Check(built.result.contains("module M is built twice for P"), std::format("the error names the module and the program (got: {})", built.result));
Check(built.result.contains("P -> M (") && built.result.contains("P -> A -> M ("), std::format("the error names the path to each build (got: {})", built.result)); Check(built.result.contains("P -> M (") && built.result.contains("P -> A -> M ("), std::format("the error names the path to each build (got: {})", built.result));
Check(!fs::exists(scratch / "m" / "bin") && !fs::exists(scratch / "a" / "bin") && !fs::exists(scratch / "p" / "bin"), "nothing was built"); Check(!fs::exists(ObjectPath(cfg, scratch / "p" / "main.cpp")) && !fs::exists(ExpectedOutput(cfg)), "P compiled and linked nothing");
}
// The same list for M along both paths, in two orders. The loader
// makes a configuration of M for each order, and VariantId, which
// takes the args sorted, gives both one directory, which a pass
// builds once, on whichever of the two asks first. That build's
// modules stand for both: P's import of M and A's have their edge to
// the module it read, and the graph is not taken for one with two
// builds of M. A second pass builds the other configuration on
// purpose, while the first still holds the modules it read: then
// both have modules, and they are still one build.
{
std::array<std::string_view, 2> args = { "--wide", "--reorder" };
Configuration cfg = LoadProject("project.cpp", args);
const bool twoM = cfg.dependencies.size() == 2 && cfg.dependencies[1]->dependencies.size() == 1 && cfg.dependencies[0] != cfg.dependencies[1]->dependencies[0];
Check(twoM, "the two orders load two configurations of M");
if (twoM) {
Configuration& a = *cfg.dependencies[1];
Configuration& mOfP = *cfg.dependencies[0];
Configuration& mOfA = *a.dependencies[0];
Check(mOfP.PcmDir() == mOfA.PcmDir(), "which are built into one directory");
// The module M as a build of `m` read it; nullptr where no
// build of `m` has.
const auto moduleOf = [](const Configuration& m) -> const Module* {
return m.interfaces.size() == 1 ? m.interfaces[0].get() : nullptr;
};
// The module a unit's edge to M leads to; nullptr without one.
const auto edgeToM = [](const auto& unit) -> const Module* {
for (const auto& [imported, bmi] : unit.externalModuleDependencies) {
if (imported->name == "M") return imported;
}
return nullptr;
};
// P's main.cpp and A's interface lead to the module of `built`.
const auto checkEdges = [&](const Configuration& built, std::string_view pass) {
const Module* m = moduleOf(built);
Check(m != nullptr, std::format("{}: the configuration of M built has its module", pass));
Check(cfg.implementations.size() == 1 && edgeToM(cfg.implementations[0]) == m, std::format("{}: P's main.cpp has its edge to that module", pass));
Check(a.interfaces.size() == 1 && edgeToM(*a.interfaces[0]) == m, std::format("{}: A's interface has its edge to that module", pass));
};
// Pass 1, with a record of its own.
BuildResult built = BuildPass(cfg);
Check(built.result.empty(), std::format("pass 1: the graph with one M in two configurations builds (got: {})", built.result));
if (built.result.empty()) {
Configuration& first = moduleOf(mOfP) != nullptr ? mOfP : mOfA;
Configuration& other = &first == &mOfP ? mOfA : mOfP;
Check(moduleOf(other) == nullptr, "pass 1: one of the two is built, and the other has no modules");
checkEdges(first, "pass 1");
// Pass 2: the other one is built first and recorded for
// the directory, as BuildAll records a configuration it
// builds, and the graph after it, which finds that build.
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
std::promise<BuildResult> otherBuilt;
otherBuilt.set_value(Build(other, depResults, depMutex));
depResults.insert_or_assign(other.PcmDir(), otherBuilt.get_future().share());
built = Build(cfg, depResults, depMutex);
Check(built.result.empty(), std::format("pass 2: the graph builds with the other configuration of M built, and the first one holding the module it read in pass 1 (got: {})", built.result));
if (built.result.empty()) {
Check(moduleOf(first) != nullptr, "pass 2: the first one still holds the module it read in pass 1");
checkEdges(other, "pass 2");
}
}
}
} }
// One list along both paths: one M, and the build goes through. // One list along both paths: one M, and the build goes through.

View file

@ -0,0 +1,97 @@
// 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;
// A CMake dependency configured with other inputs than this build's (another
// compiler or --sysroot, the flags crafter-build injects, which it records in
// <build>/.crafter-options) has to be built again from nothing. It was
// reconfigured in place, and CMake does not recompile what a changed
// --sysroot compiled (the Makefiles generator writes it into build.make,
// which make does not compare) and keeps the check results of the old
// configure. A mingw dependency built by a release that gave clang the
// host's /usr as the sysroot (issue #43) kept its objects reading
// __libc_single_threaded after the update.
//
// The dependency is a local repository with a one-file C library. A file
// planted in its build directory stands for what the old configure left,
// and the recorded inputs are rewritten the way another crafter-build would
// have left them. Everything is local; XDG_CACHE_HOME keeps the clone out of
// the real cache.
extern "C" int setenv(const char* name, const char* value, int overwrite);
namespace {
std::int32_t failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++failures;
}
}
void Git(const fs::path& dir, std::string_view args) {
const std::string command = std::format("git -C {} {}", ShellQuote(dir.string()), args);
auto result = RunCommandWithTimeout(command, std::chrono::seconds(60));
if (result.exitCode != 0) throw std::runtime_error(std::format("{} failed: {}", command, result.output));
}
void Write(const fs::path& file, std::string_view text) {
std::ofstream(file, std::ios::binary | std::ios::trunc) << text;
}
}
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-external-reconfigure";
fs::remove_all(scratch);
fs::create_directories(scratch);
setenv("XDG_CACHE_HOME", (scratch / "cache").c_str(), 1);
setenv("GIT_CONFIG_NOSYSTEM", "1", 1);
setenv("GIT_CONFIG_GLOBAL", "/dev/null", 1);
for (const char* name : { "GIT_AUTHOR_NAME", "GIT_COMMITTER_NAME" }) setenv(name, "crafter-build test", 1);
for (const char* name : { "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_EMAIL" }) setenv(name, "test@example.invalid", 1);
const fs::path repo = scratch / "reconf";
fs::create_directories(repo);
Write(repo / "lib.c", "int Reconfigured(void) { return 1; }\n");
Write(repo / "CMakeLists.txt",
"cmake_minimum_required(VERSION 3.16)\n"
"project(reconf C)\n"
"add_library(reconf STATIC lib.c)\n");
Git(repo, "init -q -b main");
Git(repo, "add .");
Git(repo, "commit -q -m reconf");
ExternalDependency dep;
dep.name = "reconf";
dep.source.url = std::format("file://{}", repo.string());
dep.builder = ExternalBuilder::CMake;
dep.libs = { "reconf" };
std::string error = BuildExternal(dep, HostTarget());
Check(error.empty(), std::format("the dependency builds: {}", error));
const fs::path build = ExternalBuildDir(dep, HostTarget());
const fs::path leftover = build / "left-by-the-old-configure";
Write(leftover, "");
error = BuildExternal(dep, HostTarget());
Check(error.empty(), std::format("and builds again: {}", error));
Check(fs::exists(leftover), "with the same inputs its build directory is kept");
Write(build / ".crafter-options", " -DCMAKE_SYSROOT=/usr\n");
error = BuildExternal(dep, HostTarget());
Check(error.empty(), std::format("configured with other inputs, it builds: {}", error));
Check(!fs::exists(leftover), "from an empty build directory");
Check(fs::exists(build / "libreconf.a"), "and the library is built again");
std::error_code ec;
fs::remove_all(scratch, ec);
if (failures > 0) {
std::println(std::cerr, "{} assertions failed", failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("bundled");
return 0;
}

View file

@ -0,0 +1,135 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <fcntl.h>
#include <stdlib.h>
#include <sys/file.h>
#include <unistd.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
std::string ReadFile(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
// Every file under `root` with its size and mtime.
std::map<fs::path, std::pair<std::uintmax_t, fs::file_time_type>> Snapshot(const fs::path& root) {
std::map<fs::path, std::pair<std::uintmax_t, fs::file_time_type>> files;
for (const fs::directory_entry& entry : fs::recursive_directory_iterator(root)) {
if (entry.is_regular_file()) files.emplace(entry.path(), std::pair{entry.file_size(), entry.last_write_time()});
}
return files;
}
}
// `crafter-build bundle` turns the Flatpak a project was built as into one
// file that `flatpak install --user` takes on another machine: the host's
// flatpak build-finish finishes the files/ the build laid out, linked into
// a build directory of the app's, flatpak build-export puts that into the
// project's repo, and the bundle is written from there, next to the bin
// dir under the same variant name. build-finish exports the desktop entry
// and the icon files/share holds, and the build's own files/ is left as it
// was, linked rather than copied. Bundling again with nothing changed works
// as the first time did, and a bundle waits while another export holds the
// repo, which every variant of the app shares. It needs the host's flatpak
// and skips without it, which is the case in flatpak-builder's build
// sandbox, where CI runs the suite.
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-bundle";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::create_directories(scratch);
const fs::path info = scratch / "flatpak-info";
std::ofstream(info) << "[Application]\nname=net.catcrafts.CrafterBuild\nruntime=runtime/org.freedesktop.Sdk/x86_64/26.08\n";
setenv("CRAFTER_BUILD_FLATPAK_INFO", info.string().c_str(), 1);
const fs::path fixture = fs::current_path() / "tests" / "FlatpakBundle" / "fixture";
if (const std::string why = HostFlatpakUnavailable(fixture); !why.empty()) {
std::println(std::cerr, "SKIP: {}", why);
return 77;
}
if (NormalizeTarget(GetToolchain().hostTriple) != "x86_64-linux-gnu") {
std::println(std::cerr, "SKIP: the staged runtime is x86_64 and the host is {}", GetToolchain().hostTriple);
return 77;
}
if (!GetToolchain().libcxxDir.empty()) {
std::println(std::cerr, "SKIP: CRAFTER_BUILD_LIBCXX_DIR is set, and a build against it is no Flatpak");
return 77;
}
fs::remove_all(fixture / "bin", ec);
fs::remove_all(fixture / "build", ec);
Configuration app;
app.path = fixture;
app.name = "bundle-app";
app.outputName = "bundled";
app.target = HostTarget();
app.packaging = Packaging::Flatpak;
app.flatpak.appId = "net.example.Bundled";
std::ofstream(scratch / "app.desktop") << "[Desktop Entry]\nType=Application\nName=Bundled\nExec=bundled\nIcon=net.example.Bundled\nCategories=Utility;\n";
std::ofstream(scratch / "icon.svg") << "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\"><rect width=\"16\" height=\"16\"/></svg>\n";
app.flatpak.desktopFile = scratch / "app.desktop";
app.flatpak.icons = { scratch / "icon.svg" };
{
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
}
{
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
if (const BuildResult r = Build(app, depResults, depMutex); !r.result.empty()) {
std::println(std::cerr, "FAIL: build failed: {}", r.result);
return 1;
}
}
const auto built = Snapshot(app.BinDir() / "files");
const std::string first = BundleFlatpakApp(app);
Check(first.empty(), std::format("the bundle is written: {}", first));
const fs::path finished = FlatpakAppDir(app) / "build-dir";
const fs::path exported = finished / "export" / "share";
Check(fs::exists(exported / "applications" / "net.example.Bundled.desktop") && fs::exists(exported / "icons" / "hicolor" / "scalable" / "apps" / "net.example.Bundled.svg"), "build-finish exports the desktop entry and the icon");
Check(ReadFile(finished / "metadata").contains("\ncommand=bundled\n"), std::format("and makes the program the app's command:\n{}", ReadFile(finished / "metadata")));
Check(fs::equivalent(finished / "files" / "bin" / "bundled", ExpectedOutput(app), ec), "files/ is linked into the build directory, not copied");
Check(Snapshot(app.BinDir() / "files") == built && !fs::exists(app.BinDir() / "metadata") && !fs::exists(app.BinDir() / "export"), "and the build's own files/ is left as it was");
const fs::path bundle = FlatpakBundlePath(app);
Check(bundle.parent_path() == app.BinDir().parent_path() && bundle.filename() == std::format("{}.flatpak", app.VariantId()), std::format("it is named after the variant, next to its bin dir: {}", bundle.string()));
Check(fs::is_regular_file(bundle) && fs::file_size(bundle, ec) > 0, "the bundle exists");
Check(fs::exists(FlatpakAppDir(app) / "repo" / "config"), "the app went into the project's repo");
const std::string second = BundleFlatpakApp(app);
Check(second.empty(), std::format("bundling again with nothing changed works: {}", second));
// While another export holds the app's repo, every variant's being one,
// a bundle waits for it rather than bundle what that one exported, and
// is written once it is free. Held here as another crafter-build would.
{
const std::int32_t held = open((FlatpakAppDir(app) / ".lock").c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
Check(held >= 0 && flock(held, LOCK_EX) == 0, "the test holds the app's repo");
std::future<std::string> third = std::async(std::launch::async, [&app] { return BundleFlatpakApp(app); });
Check(third.wait_for(std::chrono::seconds(5)) == std::future_status::timeout, "a bundle waits while another export holds the app's repo");
if (held >= 0) close(held);
const std::string waited = third.get();
Check(waited.empty(), std::format("and is written once the repo is free: {}", waited));
}
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,23 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// The project crafter-build is pointed at: an executable, with two sibling
// projects whose executables it depends on, loaded with this file's args.
// The second packages its own as a Flatpak.
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
Configuration* tool = LocalProject({ .projectFile = "../tool/project.cpp" });
Configuration* packaged = LocalProject({ .projectFile = "../packaged/project.cpp" });
Configuration cfg;
cfg.path = "./";
cfg.name = "app";
cfg.outputName = "app";
cfg.type = ConfigurationType::Executable;
ApplyStandardArgs(cfg, args);
cfg.dependencies = { tool, packaged };
return cfg;
}

View file

@ -0,0 +1 @@
the packaged sibling's own note

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("packaged");
return 0;
}

View file

@ -0,0 +1,10 @@
{
"name": "extra",
"buildsystem": "simple",
"build-commands": [
"install -Dm644 extra.txt /app/share/extra/extra.txt"
],
"sources": [
{ "type": "file", "path": "extra.txt" }
]
}

View file

@ -0,0 +1 @@
installed by a module of the project's own

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16"/></svg>

After

Width:  |  Height:  |  Size: 100 B

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<component type="desktop-application">
<id>net.example.Packaged</id>
<name>Packaged</name>
<summary>A fixture for crafter-build's tests</summary>
<metadata_license>CC0-1.0</metadata_license>
</component>

View file

@ -0,0 +1,29 @@
// 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;
// A sibling that packages its own executable as a Flatpak, in its own
// project.cpp, naming the files it is installed with relative to its own
// directory, as it would its cfg.files.
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
Configuration cfg;
cfg.path = "./";
cfg.name = "packaged";
cfg.outputName = "packaged";
cfg.type = ConfigurationType::Executable;
ApplyStandardArgs(cfg, args);
cfg.packaging = Packaging::Flatpak;
cfg.flatpak.appId = "net.example.Packaged";
cfg.flatpak.metainfo = "packaging/packaged.metainfo.xml";
cfg.flatpak.icons = { "packaging/icon.svg" };
cfg.flatpak.modules = { "packaging/extra.json" };
cfg.flatpak.share = { { "data/note.txt", "packaged/note.txt" } };
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
cfg.GetInterfacesAndImplementations(ifaces, impls);
return cfg;
}

View file

@ -0,0 +1,18 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// A sibling's executable, which its consumers run by path, loaded with the
// consumer's args.
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
Configuration cfg;
cfg.path = "./";
cfg.name = "tool";
cfg.outputName = "tool";
cfg.type = ConfigurationType::Executable;
ApplyStandardArgs(cfg, args);
return cfg;
}

View file

@ -0,0 +1,105 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// --packaging=flatpak packages the executable of the project crafter-build
// was pointed at, and no other. The args reach every sibling project the
// project loads (a GitProject's or LocalProject's args default to them),
// and a sibling's executable is run by path by its consumers, as
// Crafter.Debug's client is: packaged, it would move into files/bin and
// out of their reach. A sibling that packages its own executable in its
// own project.cpp gets a Flatpak, with the files it is installed with
// found in its own directory, as its cfg.files are, wherever the consumer
// builds it from: before the loader rebased them, they resolved against the
// consumer's directory, so it shipped the consumer's file of that name or
// failed for want of one. The fixture is an app with two executable
// siblings loaded with its args, of which the second packages itself.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
std::string ReadFile(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
}
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-dependency-executable";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::create_directories(scratch);
const fs::path info = scratch / "flatpak-info";
std::ofstream(info) << "[Application]\nname=net.catcrafts.CrafterBuild\nruntime=runtime/org.freedesktop.Sdk/x86_64/26.08\n";
setenv("CRAFTER_BUILD_FLATPAK_INFO", info.string().c_str(), 1);
const fs::path installedHome = GetCrafterBuildHome();
if (!fs::exists(installedHome / "Crafter.Build.cppm")) {
std::println(std::cerr, "SKIP: no module sources at {}", installedHome.string());
return 77;
}
// Staged because LoadProject drops a build/ tree next to every project
// file it compiles.
const fs::path fixture = fs::current_path() / "tests" / "FlatpakDependencyExecutable" / "fixture";
fs::copy(fixture, scratch, fs::copy_options::recursive);
// From the project's own directory, as crafter-build runs it: the
// fixture's LocalProject paths are relative to the working directory.
const fs::path cwd = fs::current_path();
fs::current_path(scratch / "app");
try {
std::array<std::string_view, 1> args = { "--packaging=flatpak" };
const Configuration cfg = LoadProject("project.cpp", args);
Check(cfg.packaging == Packaging::Flatpak, "the executable of the project crafter-build was pointed at is packaged");
Check(cfg.dependencies.size() == 2, std::format("the app declared its siblings (got {})", cfg.dependencies.size()));
if (cfg.dependencies.size() == 2) {
const Configuration& tool = *cfg.dependencies[0];
Check(tool.name == "tool", std::format("the first sibling is the fixture's tool (got '{}')", tool.name));
Check(tool.packaging == Packaging::Default && tool.ResolvedPackaging() == Packaging::None, "the sibling's executable stays as linked");
Check(tool.ProgramDir() == tool.BinDir(), "and lands in its bin dir, where its consumers look");
Check(tool.projectArgs.empty(), std::format("the sibling took --packaging= as a standard arg, not one of its own (projectArgs {})", tool.projectArgs));
// Built from the consumer's directory, as the consumer's build
// builds it.
Configuration& packaged = *cfg.dependencies[1];
Check(packaged.packaging == Packaging::Flatpak, "the sibling that packages itself is a Flatpak");
// The loader takes a project file where its links lead, as
// fs::canonical does, whatever the temp directory goes through.
const std::string module = std::format("\"{}\"", (fs::canonical(scratch) / "packaged" / "packaging" / "extra.json").string());
Check(FlatpakManifest(packaged).contains(module), std::format("its manifest names its own module file, {}", module));
if (NormalizeTarget(GetToolchain().hostTriple) == "x86_64-linux-gnu" && GetToolchain().libcxxDir.empty()) {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult built = Build(packaged, depResults, depMutex);
Check(built.result.empty(), std::format("it builds from the consumer's directory: {}", built.result));
const fs::path share = packaged.BinDir() / "files" / "share";
const fs::path own = scratch / "packaged" / "packaging";
Check(ReadFile(share / "metainfo" / "net.example.Packaged.metainfo.xml") == ReadFile(own / "packaged.metainfo.xml"), "its metainfo is its own");
Check(ReadFile(share / "icons" / "hicolor" / "scalable" / "apps" / "net.example.Packaged.svg") == ReadFile(own / "icon.svg"), "and so is its icon");
Check(ReadFile(share / "packaged" / "note.txt") == ReadFile(scratch / "packaged" / "data" / "note.txt"), "and so is the data it installs under /app/share");
}
}
} catch (const std::exception& e) {
Check(false, std::format("LoadProject threw: {}", e.what()));
}
fs::current_path(cwd);
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,6 @@
[Desktop Entry]
Type=Application
Name=Desktop
Exec=desktop
Icon=net.example.Desktop
Categories=Utility;

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<component type="desktop-application">
<id>net.example.Desktop</id>
<name>Desktop</name>
<summary>A fixture for crafter-build's tests</summary>
<metadata_license>CC0-1.0</metadata_license>
</component>

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16"/></svg>

After

Width:  |  Height:  |  Size: 100 B

View file

@ -0,0 +1,5 @@
[Desktop Entry]
Type=Bogus
Name=Desktop
Exec=desktop
Icon=net.example.Desktop

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("desktop");
return 0;
}

View file

@ -0,0 +1,6 @@
[Desktop Entry]
Type=Application
Name=Desktop
Exec=desktop
Icon=desktop
Categories=Utility;

View file

@ -0,0 +1,157 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
std::string ReadFile(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
std::string BuildIt(Configuration& cfg) {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
return Build(cfg, depResults, depMutex).result;
}
// A PNG's signature and IHDR, which is all the size is read from.
void WritePng(const fs::path& path, std::uint32_t width, std::uint32_t height) {
std::string bytes = "\x89PNG\r\n\x1a\n";
const auto bigEndian = [&](std::uint32_t value) {
for (std::int32_t shift = 24; shift >= 0; shift -= 8) bytes.push_back(static_cast<char>((value >> shift) & 0xff));
};
bigEndian(13);
bytes += "IHDR";
bigEndian(width);
bigEndian(height);
bytes += std::string("\x08\x06\x00\x00\x00", 5);
std::ofstream(path, std::ios::binary) << bytes;
}
}
// A desktop entry, AppStream metainfo and icons are installed under the
// app-id in files/share, where flatpak build-finish finds them to export
// to the host: the entry as share/applications/<app-id>.desktop, the
// metainfo as share/metainfo/<app-id>.metainfo.xml, an .svg as the
// scalable icon and a .png in the directory of its own size. What would
// make the app fail to install, or show no icon, is refused at build time:
// an Icon= other than the app-id, spelled with spaces around '=' or not, a
// png that is not square, an icon that is neither format, an entry
// desktop-file-validate rejects (where it exists), on the write after a
// failed one as well, an app-id flatpak does not accept. A project that
// names no app-id gets local.crafterbuild.<name>.
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-desktop";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::create_directories(scratch);
const fs::path info = scratch / "flatpak-info";
std::ofstream(info) << "[Application]\nname=net.catcrafts.CrafterBuild\nruntime=runtime/org.freedesktop.Sdk/x86_64/26.08\n";
setenv("CRAFTER_BUILD_FLATPAK_INFO", info.string().c_str(), 1);
Check(DefaultFlatpakAppId("hello") == "local.crafterbuild.hello", "the default app-id");
Check(DefaultFlatpakAppId("my-app") == "local.crafterbuild.my-app", "a dash may stay in the last segment");
Check(DefaultFlatpakAppId("3d.viewer") == "local.crafterbuild._3d_viewer", std::format("a dot and a leading digit are made safe: {}", DefaultFlatpakAppId("3d.viewer")));
Check(FlatpakAppIdError(DefaultFlatpakAppId("3d.viewer")).empty(), "and the result is valid");
Check(FlatpakAppIdError("org.example.My-App").empty(), "a valid app-id");
for (const std::string_view bad : {"org.example", "org.3d.App", "org.my-company.App", "org..App", "org.example.App!", ""}) {
Check(!FlatpakAppIdError(bad).empty(), std::format("'{}' is refused", bad));
}
Check(!FlatpakAppIdError(std::format("org.example.{}", std::string(250, 'a'))).empty(), "an app-id over 255 characters is refused");
if (NormalizeTarget(GetToolchain().hostTriple) != "x86_64-linux-gnu") {
// A skip must never cover for a failure above.
if (Failures > 0) return 1;
std::println(std::cerr, "SKIP: the staged runtime is x86_64 and the host is {}", GetToolchain().hostTriple);
return 77;
}
if (!GetToolchain().libcxxDir.empty()) {
// A skip must never cover for a failure above.
if (Failures > 0) return 1;
std::println(std::cerr, "SKIP: CRAFTER_BUILD_LIBCXX_DIR is set, and a build against it is no Flatpak");
return 77;
}
const fs::path fixture = fs::current_path() / "tests" / "FlatpakDesktop" / "fixture";
fs::remove_all(fixture / "bin", ec);
fs::remove_all(fixture / "build", ec);
WritePng(scratch / "icon-512.png", 512, 512);
WritePng(scratch / "wide.png", 512, 256);
Configuration app;
app.path = fixture;
app.name = "desktop-app";
app.outputName = "desktop";
app.target = HostTarget();
app.packaging = Packaging::Flatpak;
app.flatpak.appId = "net.example.Desktop";
app.flatpak.desktopFile = fixture / "app.desktop";
app.flatpak.metainfo = fixture / "app.metainfo.xml";
app.flatpak.icons = { fixture / "icon.svg", scratch / "icon-512.png" };
{
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
}
if (const std::string failed = BuildIt(app); !failed.empty()) {
std::println(std::cerr, "FAIL: build failed: {}", failed);
return 1;
}
const fs::path root = app.BinDir();
const fs::path share = root / "files" / "share";
Check(ReadFile(share / "applications" / "net.example.Desktop.desktop") == ReadFile(fixture / "app.desktop"), "the desktop entry is installed under the app-id");
Check(ReadFile(share / "metainfo" / "net.example.Desktop.metainfo.xml") == ReadFile(fixture / "app.metainfo.xml"), "the metainfo is installed under the app-id");
Check(fs::exists(share / "icons" / "hicolor" / "scalable" / "apps" / "net.example.Desktop.svg"), "an .svg is the scalable icon");
Check(fs::exists(share / "icons" / "hicolor" / "512x512" / "apps" / "net.example.Desktop.png"), "a .png goes under its own size");
app.flatpak.desktopFile = fixture / "wrong-icon.desktop";
Check(BuildIt(app).contains("has to be the app-id"), "an Icon= other than the app-id is refused");
// Spelled with spaces around '=', which the Desktop Entry spec allows and
// every reader of the entry ignores.
std::ofstream(scratch / "spaced-icon.desktop") << "[Desktop Entry]\nType=Application\nName=Desktop\nExec=desktop\nIcon = desktop\n";
app.flatpak.desktopFile = scratch / "spaced-icon.desktop";
Check(BuildIt(app).contains("has to be the app-id"), "so is one spelled 'Icon = desktop'");
app.flatpak.desktopFile = fixture / "app.desktop";
app.flatpak.icons = { scratch / "wide.png" };
Check(BuildIt(app).contains("has to be square"), "a png that is not square is refused");
app.flatpak.icons = { fixture / "app.desktop" };
Check(BuildIt(app).contains("has to be an .svg or a .png"), "an icon that is neither is refused");
app.flatpak.icons = { fixture / "icon.svg" };
if (std::system("command -v desktop-file-validate > /dev/null 2>&1") == 0) {
app.flatpak.desktopFile = fixture / "invalid.desktop";
Check(BuildIt(app).contains("does not pass desktop-file-validate"), "an entry desktop-file-validate rejects is refused");
// A write that copies the entry and then fails, here for a metainfo
// that does not exist, leaves it in files/share unchanged for the
// next write, which copies nothing and has to check it all the same.
app.flatpak.metainfo = scratch / "missing.metainfo.xml";
Check(BuildIt(app).contains("missing.metainfo.xml"), "a write that copies the entry and then fails is refused for what failed");
app.flatpak.metainfo = fixture / "app.metainfo.xml";
Check(BuildIt(app).contains("does not pass desktop-file-validate"), "and the next build refuses the entry it left unchecked");
app.flatpak.desktopFile = fixture / "app.desktop";
}
app.flatpak.appId = "Desktop";
Check(BuildIt(app).contains("is not a Flatpak application ID"), "an invalid app-id is refused");
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,5 @@
[Desktop Entry]
Type=Application
Name=Incremental
Exec=incremental
Categories=Utility;

View file

@ -0,0 +1 @@
dropped later

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16"/></svg>

After

Width:  |  Height:  |  Size: 100 B

View file

@ -0,0 +1 @@
kept

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("incremental");
return 0;
}

View file

@ -0,0 +1,162 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
std::string ReadFile(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
std::string BuildIt(Configuration& cfg) {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
return Build(cfg, depResults, depMutex).result;
}
}
// What a Flatpak's files/ holds is what the build puts there, and it is
// kept so without rewriting what did not change. A cfg.files entry
// dropped since goes from files/bin, which ships; a file the program wrote
// there itself stays, since the build cannot know what it is (the build
// reports it instead). A renamed app-id leaves no desktop entry or icon
// under the old name behind in files/share. What a directory
// written with a trailing separator or as "dir/." held, which the build
// copies flat, goes with the entry, and so does a program renamed in place,
// under its old name: neither may stay, taken for files the program wrote,
// nor may what a build that then failed copied there. And a library is
// copied again when its copy no longer matches the source, whatever the
// mtimes say: every file of an ostree deployment, the Flatpak's /app among
// them, has mtime 0, so a newer libc++ never looks newer than its copy.
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-incremental";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::create_directories(scratch);
const fs::path info = scratch / "flatpak-info";
std::ofstream(info) << "[Application]\nname=net.catcrafts.CrafterBuild\nruntime=runtime/org.freedesktop.Sdk/x86_64/26.08\n";
setenv("CRAFTER_BUILD_FLATPAK_INFO", info.string().c_str(), 1);
if (NormalizeTarget(GetToolchain().hostTriple) != "x86_64-linux-gnu") {
std::println(std::cerr, "SKIP: the staged runtime is x86_64 and the host is {}", GetToolchain().hostTriple);
return 77;
}
if (!GetToolchain().libcxxDir.empty()) {
std::println(std::cerr, "SKIP: CRAFTER_BUILD_LIBCXX_DIR is set, and a build against it is no Flatpak");
return 77;
}
const fs::path fixture = fs::current_path() / "tests" / "FlatpakIncremental" / "fixture";
fs::remove_all(fixture / "bin", ec);
fs::remove_all(fixture / "build", ec);
Configuration app;
app.path = fixture;
app.name = "incremental-app";
app.outputName = "incremental";
app.target = HostTarget();
app.packaging = Packaging::Flatpak;
app.files = { fixture / "kept.txt", fixture / "dropped.txt" };
app.flatpak.appId = "net.example.Incremental";
app.flatpak.desktopFile = fixture / "app.desktop";
app.flatpak.icons = { fixture / "icon.svg" };
{
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
}
if (const std::string failed = BuildIt(app); !failed.empty()) {
std::println(std::cerr, "FAIL: build failed: {}", failed);
return 1;
}
const fs::path root = app.BinDir();
const fs::path bin = root / "files" / "bin";
Check(fs::exists(bin / "kept.txt") && fs::exists(bin / "dropped.txt"), "both files are placed");
app.files = { fixture / "kept.txt" };
Check(BuildIt(app).empty(), "the build without dropped.txt succeeds");
Check(!fs::exists(bin / "dropped.txt"), "a dropped cfg.files entry goes from files/bin");
Check(fs::exists(bin / "kept.txt") && fs::exists(bin / "incremental"), "what is still placed stays");
std::ofstream(bin / "written.bin") << "written by the program";
Check(BuildIt(app).empty(), "the build after the program wrote a file succeeds");
Check(fs::exists(bin / "written.bin"), "a file the program wrote stays");
app.flatpak.appId = "net.example.Renamed";
Check(BuildIt(app).empty(), "the build under the new app-id succeeds");
const fs::path share = root / "files" / "share";
Check(fs::exists(share / "applications" / "net.example.Renamed.desktop") && !fs::exists(share / "applications" / "net.example.Incremental.desktop"), "the desktop entry is renamed");
Check(fs::exists(share / "icons" / "hicolor" / "scalable" / "apps" / "net.example.Renamed.svg") && !fs::exists(share / "icons" / "hicolor" / "scalable" / "apps" / "net.example.Incremental.svg"), "the icon is renamed");
// A directory written with a trailing separator, "flat/", or as
// "flat/.", has no filename() of its own, and the build copies what it
// holds straight into files/bin, an asset directory's files as they
// are: those are the names it placed, and once the entries are dropped
// they go, rather than stay as files the program wrote.
const fs::path flat = scratch / "flat";
fs::create_directories(flat / "inner");
std::ofstream(flat / "flat.txt") << "flat\n";
std::ofstream(flat / "inner" / "nested.txt") << "nested\n";
const fs::path flatAssets = scratch / "flat-assets";
fs::create_directories(flatAssets);
std::ofstream(flatAssets / "mod.json") << "{}\n";
for (const fs::path& spelling : { fs::path(""), fs::path(".") }) {
app.files = { fixture / "kept.txt", flat / spelling };
app.assets = { flatAssets / spelling };
const std::string written = (flat / spelling).string();
Check(BuildIt(app).empty(), std::format("the build with directories written as {} succeeds", written));
Check(fs::exists(bin / "flat.txt") && fs::exists(bin / "inner" / "nested.txt") && fs::exists(bin / "mod.json"), std::format("what they hold is placed straight in files/bin, written as {}", written));
app.files = { fixture / "kept.txt" };
app.assets = {};
Check(BuildIt(app).empty(), "the build without them succeeds");
Check(!fs::exists(bin / "flat.txt") && !fs::exists(bin / "inner") && !fs::exists(bin / "mod.json"), std::format("and what they placed goes, written as {}", written));
}
// A program renamed in place: outputName is not in VariantId(), so the
// bin dir stays, and the old program goes as one the last build
// placed, rather than stay as a file the program wrote.
app.outputName = "renamed";
Check(BuildIt(app).empty(), "the build of the renamed program succeeds");
Check(fs::exists(bin / "renamed") && !fs::exists(bin / "incremental"), "files/bin holds the program under its new name, and not under the old");
// A build that fails after copying into files/bin, here at its link,
// placed what it copied all the same: once a build places it no more, it
// goes, rather than stay as a file the program wrote.
std::ofstream(scratch / "failed.txt") << "failed\n";
app.files = { fixture / "kept.txt", scratch / "failed.txt" };
app.linkFlags = { "-lcrafter-build-missing" };
Check(!BuildIt(app).empty(), "a build whose link fails fails");
Check(fs::exists(bin / "failed.txt"), "after copying its files into files/bin");
app.files = { fixture / "kept.txt" };
app.linkFlags = {};
Check(BuildIt(app).empty(), "the build after it succeeds");
Check(!fs::exists(bin / "failed.txt"), "and what the failed build placed goes");
// A copy that no longer matches its source, under the mtime it had.
const fs::path copy = root / "files" / "lib" / "libc++.so.1";
const std::string good = ReadFile(copy);
const fs::file_time_type stamp = fs::last_write_time(copy);
std::ofstream(copy, std::ios::binary | std::ios::trunc) << std::string(good.size(), 'x');
fs::last_write_time(copy, stamp);
Check(BuildIt(app).empty(), "the build after the copy went stale succeeds");
Check(ReadFile(copy) == good, "a library whose copy differs from its source is copied again, mtimes unchanged or not");
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("installed");
return 0;
}

View file

@ -0,0 +1,124 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <fcntl.h>
#include <stdlib.h>
#include <sys/file.h>
#include <unistd.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
}
// `crafter-build install` installs the Flatpak a project was built as for
// this user: from the project's repo, through a user remote named after the
// app-id, updating what an earlier install put there, and waiting while
// another install holds that remote. The test installs into a private user
// installation under the fixture's build/ by way of FLATPAK_USER_DIR, which
// the host helper passes on from the sandbox too, so the user's own
// installation is never touched; the runtime comes from the system
// installation, so a machine without Platform 26.08 there skips, as one
// without the host's flatpak does. The app is not run: that would make
// ~/.var/app/<app-id> in the real home.
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-install";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::create_directories(scratch);
const fs::path info = scratch / "flatpak-info";
std::ofstream(info) << "[Application]\nname=net.catcrafts.CrafterBuild\nruntime=runtime/org.freedesktop.Sdk/x86_64/26.08\n";
setenv("CRAFTER_BUILD_FLATPAK_INFO", info.string().c_str(), 1);
const fs::path fixture = fs::current_path() / "tests" / "FlatpakInstall" / "fixture";
if (const std::string why = HostFlatpakUnavailable(fixture); !why.empty()) {
std::println(std::cerr, "SKIP: {}", why);
return 77;
}
if (NormalizeTarget(GetToolchain().hostTriple) != "x86_64-linux-gnu") {
std::println(std::cerr, "SKIP: the staged runtime is x86_64 and the host is {}", GetToolchain().hostTriple);
return 77;
}
if (!GetToolchain().libcxxDir.empty()) {
std::println(std::cerr, "SKIP: CRAFTER_BUILD_LIBCXX_DIR is set, and a build against it is no Flatpak");
return 77;
}
if (RunHostFlatpak("info --system --show-ref org.freedesktop.Platform//26.08") != 0) {
std::println(std::cerr, "SKIP: the system installation has no org.freedesktop.Platform//26.08 for a private user installation to use");
return 77;
}
fs::remove_all(fixture / "bin", ec);
fs::remove_all(fixture / "build", ec);
const fs::path installation = fixture / "build" / "user-installation";
fs::create_directories(installation);
setenv("FLATPAK_USER_DIR", installation.string().c_str(), 1);
Configuration app;
app.path = fixture;
app.name = "install-app";
app.outputName = "installed";
app.target = HostTarget();
app.packaging = Packaging::Flatpak;
app.flatpak.appId = "net.example.Installed";
{
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
}
{
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
if (const BuildResult r = Build(app, depResults, depMutex); !r.result.empty()) {
std::println(std::cerr, "FAIL: build failed: {}", r.result);
return 1;
}
}
const std::string installed = InstallFlatpakApp(app);
Check(installed.empty(), std::format("the app is installed: {}", installed));
Check(RunHostFlatpak("info --user --show-ref net.example.Installed") == 0, "the user installation has the app");
// On disk as well, where the private installation keeps it: a check
// through flatpak alone would pass with the app in the real one.
Check(fs::exists(installation / "app" / "net.example.Installed"), "and it is the private installation");
const std::string again = InstallFlatpakApp(app);
Check(again.empty(), std::format("installing again updates it: {}", again));
// The remote is the installation's, every checkout's that builds this
// app-id, so an install waits while another holds it, rather than install
// from the repo that one pointed it at, and installs once it is free. The
// lock follows the installation, the private one here, and not
// crafter-build's cache: another crafter-build runs with an XDG_CACHE_HOME
// of its own, natively or in the Flatpak, so this one's is moved into the
// scratch directory first, and the install still waits.
{
setenv("XDG_CACHE_HOME", (scratch / "cache").string().c_str(), 1);
const fs::path remotes = installation / "crafter.build" / "flatpak-remotes";
fs::create_directories(remotes, ec);
const std::int32_t held = open((remotes / "crafter-build-net.example.Installed.lock").c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
Check(held >= 0 && flock(held, LOCK_EX) == 0, "the test holds the app's remote");
std::future<std::string> third = std::async(std::launch::async, [&app] { return InstallFlatpakApp(app); });
Check(third.wait_for(std::chrono::seconds(5)) == std::future_status::timeout, "an install waits while another holds the app's remote");
if (held >= 0) close(held);
const std::string waited = third.get();
Check(waited.empty(), std::format("and installs once it is free: {}", waited));
}
RunHostFlatpak("uninstall --user --noninteractive net.example.Installed");
fs::remove_all(installation, ec);
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
int main() {
std::println("native");
return 0;
}

View file

@ -0,0 +1,72 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
}
// A build against CRAFTER_BUILD_LIBCXX_DIR is refused as a Flatpak, before
// anything is built, saying why. Such a build compiles and links against
// that libc++, while the Flatpak's files/lib carries the toolchain's own,
// which is built against the runtime's glibc, so the app would load a
// libc++ it was not built against; bundling the other one instead would
// carry a library nothing says the runtime can load. The override is read
// once per process, so this test is a process of its own; its libc++
// directory is empty, since nothing is compiled against it.
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-libcxx-dir";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::create_directories(scratch / "libcxx");
const fs::path info = scratch / "flatpak-info";
std::ofstream(info) << "[Application]\nname=net.catcrafts.CrafterBuild\nruntime=runtime/org.freedesktop.Sdk/x86_64/26.08\n";
setenv("CRAFTER_BUILD_FLATPAK_INFO", info.string().c_str(), 1);
setenv("CRAFTER_BUILD_LIBCXX_DIR", (scratch / "libcxx").string().c_str(), 1);
Check(GetToolchain().libcxxDir == scratch / "libcxx", std::format("the override is read: '{}'", GetToolchain().libcxxDir.string()));
if (NormalizeTarget(GetToolchain().hostTriple) != "x86_64-linux-gnu") {
// A skip must never cover for a failure above.
if (Failures > 0) return 1;
std::println(std::cerr, "SKIP: the staged runtime is x86_64 and the host is {}", GetToolchain().hostTriple);
return 77;
}
const fs::path fixture = fs::current_path() / "tests" / "FlatpakLibcxxDir" / "fixture";
fs::remove_all(fixture / "bin", ec);
fs::remove_all(fixture / "build", ec);
Configuration app;
app.path = fixture;
app.name = "libcxx-app";
app.outputName = "libcxx";
app.target = HostTarget();
app.packaging = Packaging::Flatpak;
{
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
}
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
const BuildResult r = Build(app, depResults, depMutex);
Check(r.result.contains("CRAFTER_BUILD_LIBCXX_DIR") && r.result.contains("libcxx-app") && r.result.contains((scratch / "libcxx").string()), std::format("the Flatpak is refused, naming the override, its directory and the configuration: {}", r.result));
Check(!fs::exists(app.BinDir()) && !fs::exists(app.BuildDir()), "refusing it leaves nothing behind");
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -0,0 +1,88 @@
// 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;
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// Compiles C `source`, written to `dir`/`name`, with the toolchain's
// clang and `arguments`; empty when it compiled, else what clang said.
std::string Cc(const fs::path& dir, std::string_view name, std::string_view source, std::string_view arguments) {
std::ofstream(dir / name) << source;
const fs::path log = dir / std::format("{}.log", name);
const std::string command = std::format("{} {} {} > {} 2>&1", ShellQuote(GetToolchain().clang.string()), ShellQuote((dir / name).string()), arguments, ShellQuote(log.string()));
if (std::system(command.c_str()) == 0) return "";
std::ifstream in(log);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
}
// A packaged program carries in files/lib the shared libraries it needs that
// the runtime does not have, worked out from its NEEDED entries and theirs.
// A library replaced in place can need another, as a toolchain update can
// bring, while the program stays as it was: the writer once reused what it
// had worked out for that program, so the new library's contents were
// copied and the library it needs was left out, and -r still ran the
// program, in crafter-build's sandbox, while the installed app did not
// start. It works the libraries out on every write now. A program built on
// libA.so is written, then libA.so is built again on libB.so, the program
// left as it was, and the next write has to carry libB.so as well. The
// writer is called directly, with the libraries' directory as the one it
// takes libraries from.
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-library-change";
std::error_code ec;
fs::remove_all(scratch, ec);
const fs::path libs = scratch / "libs";
const fs::path bin = scratch / "app" / "files" / "bin";
fs::create_directories(libs);
fs::create_directories(bin);
fs::create_directories(scratch / "build");
const std::string quoted = ShellQuote(libs.string());
std::string failed = Cc(scratch, "a1.c", "int a(void) { return 1; }\n", std::format("-shared -fPIC -o {}/libA.so", quoted));
Check(failed.empty(), std::format("libA.so builds: {}", failed));
failed = Cc(scratch, "main.c", "int a(void);\nint main(void) { return a(); }\n", std::format("-o {} -L{} -lA", ShellQuote((bin / "needs").string()), quoted));
Check(failed.empty(), std::format("the program builds on it: {}", failed));
if (Failures > 0) return 1;
const Toolchain& tc = GetToolchain();
FlatpakFiles d;
d.root = scratch / "app";
d.record = scratch / "build" / "flatpak-record";
d.appId = "net.example.LibraryChange";
d.command = "needs";
d.clangxx = tc.clangxx;
d.readelf = tc.llvmReadelf;
d.libraryDirs = {libs};
d.programEntries = {"needs"};
const fs::path lib = d.root / "files" / "lib";
const std::string first = WriteFlatpakFiles(d);
Check(first.empty() && fs::is_regular_file(lib / "libA.so") && !fs::exists(lib / "libB.so"), std::format("the program's library is carried, and nothing else of the directory: {}", first));
failed = Cc(scratch, "b.c", "int b(void) { return 2; }\n", std::format("-shared -fPIC -o {}/libB.so", quoted));
Check(failed.empty(), std::format("libB.so builds: {}", failed));
failed = Cc(scratch, "a2.c", "int b(void);\nint a(void) { return b(); }\n", std::format("-shared -fPIC -o {}/libA.so -L{} -lB", quoted, quoted));
Check(failed.empty(), std::format("libA.so is built again, on libB.so: {}", failed));
const std::string second = WriteFlatpakFiles(d);
Check(second.empty() && fs::is_regular_file(lib / "libA.so") && fs::is_regular_file(lib / "libB.so"), std::format("the next write carries the library the new libA.so needs: {}", second));
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

Some files were not shown because too many files have changed in this diff Show more