From 27031ed8e31f54fee75febf25b21c3af86fd121b Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 1 Nov 2026 19:20:55 +0100 Subject: [PATCH] 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. --- AGENTS.template.md | 10 +- build.sh | 2 +- implementations/Crafter.Build-Clang.cpp | 221 +++++++--- implementations/Crafter.Build-External.cpp | 6 + implementations/Crafter.Build-Flatpak.cpp | 380 ++++++++++++++++++ implementations/Crafter.Build-Lint.cpp | 3 + implementations/Crafter.Build-Platform.cpp | 3 +- implementations/Crafter.Build-Test.cpp | 5 + implementations/Crafter.Build-Toolchain.cpp | 66 ++- interfaces/Crafter.Build-Clang.cppm | 51 ++- interfaces/Crafter.Build-Flatpak.cppm | 98 +++++ interfaces/Crafter.Build-Test.cppm | 11 + interfaces/Crafter.Build-Toolchain.cppm | 23 ++ interfaces/Crafter.Build.cppm | 1 + project.cpp | 17 +- .../fixture/app/project.cpp | 23 ++ .../fixture/packaged/main.cpp | 9 + .../fixture/packaged/packaging/icon.svg | 1 + .../packaged/packaging/packaged.metainfo.xml | 7 + .../fixture/packaged/project.cpp | 27 ++ .../fixture/tool/project.cpp | 18 + tests/FlatpakDependencyExecutable/main.cpp | 100 +++++ tests/FlatpakDesktop/fixture/app.desktop | 6 + tests/FlatpakDesktop/fixture/app.metainfo.xml | 7 + tests/FlatpakDesktop/fixture/icon.svg | 1 + tests/FlatpakDesktop/fixture/invalid.desktop | 5 + tests/FlatpakDesktop/fixture/main.cpp | 9 + .../FlatpakDesktop/fixture/wrong-icon.desktop | 6 + tests/FlatpakDesktop/main.cpp | 157 ++++++++ tests/FlatpakIncremental/fixture/app.desktop | 5 + tests/FlatpakIncremental/fixture/dropped.txt | 1 + tests/FlatpakIncremental/fixture/icon.svg | 1 + tests/FlatpakIncremental/fixture/kept.txt | 1 + tests/FlatpakIncremental/fixture/main.cpp | 9 + tests/FlatpakIncremental/main.cpp | 162 ++++++++ tests/FlatpakLibcxxDir/fixture/main.cpp | 9 + tests/FlatpakLibcxxDir/main.cpp | 72 ++++ tests/FlatpakLibraryChange/main.cpp | 88 ++++ tests/FlatpakNative/fixture/main.cpp | 9 + tests/FlatpakNative/main.cpp | 76 ++++ tests/FlatpakOutput/fixture/main.cpp | 9 + tests/FlatpakOutput/fixture/message.txt | 1 + tests/FlatpakOutput/main.cpp | 181 +++++++++ .../FlatpakRefusals/fixture/lib/Refused.cppm | 9 + tests/FlatpakRefusals/fixture/main.cpp | 9 + tests/FlatpakRefusals/main.cpp | 107 +++++ .../fixture/tests/hello/Hello.cppm | 9 + .../fixture/tests/hello/main.cpp | 10 + tests/FlatpakTestsRaw/main.cpp | 78 ++++ .../FlatpakToolchainLibrary/fixture/main.cpp | 14 + tests/FlatpakToolchainLibrary/main.cpp | 125 ++++++ tests/SharedLibraryRuns/main.cpp | 34 +- tests/StandardArgs/main.cpp | 23 ++ tests/ToolchainResolve/main.cpp | 27 ++ tests/VariantId/main.cpp | 27 ++ tests/WasiBrowserRuntime/main.cpp | 19 + 56 files changed, 2314 insertions(+), 74 deletions(-) create mode 100644 implementations/Crafter.Build-Flatpak.cpp create mode 100644 interfaces/Crafter.Build-Flatpak.cppm create mode 100644 tests/FlatpakDependencyExecutable/fixture/app/project.cpp create mode 100644 tests/FlatpakDependencyExecutable/fixture/packaged/main.cpp create mode 100644 tests/FlatpakDependencyExecutable/fixture/packaged/packaging/icon.svg create mode 100644 tests/FlatpakDependencyExecutable/fixture/packaged/packaging/packaged.metainfo.xml create mode 100644 tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp create mode 100644 tests/FlatpakDependencyExecutable/fixture/tool/project.cpp create mode 100644 tests/FlatpakDependencyExecutable/main.cpp create mode 100644 tests/FlatpakDesktop/fixture/app.desktop create mode 100644 tests/FlatpakDesktop/fixture/app.metainfo.xml create mode 100644 tests/FlatpakDesktop/fixture/icon.svg create mode 100644 tests/FlatpakDesktop/fixture/invalid.desktop create mode 100644 tests/FlatpakDesktop/fixture/main.cpp create mode 100644 tests/FlatpakDesktop/fixture/wrong-icon.desktop create mode 100644 tests/FlatpakDesktop/main.cpp create mode 100644 tests/FlatpakIncremental/fixture/app.desktop create mode 100644 tests/FlatpakIncremental/fixture/dropped.txt create mode 100644 tests/FlatpakIncremental/fixture/icon.svg create mode 100644 tests/FlatpakIncremental/fixture/kept.txt create mode 100644 tests/FlatpakIncremental/fixture/main.cpp create mode 100644 tests/FlatpakIncremental/main.cpp create mode 100644 tests/FlatpakLibcxxDir/fixture/main.cpp create mode 100644 tests/FlatpakLibcxxDir/main.cpp create mode 100644 tests/FlatpakLibraryChange/main.cpp create mode 100644 tests/FlatpakNative/fixture/main.cpp create mode 100644 tests/FlatpakNative/main.cpp create mode 100644 tests/FlatpakOutput/fixture/main.cpp create mode 100644 tests/FlatpakOutput/fixture/message.txt create mode 100644 tests/FlatpakOutput/main.cpp create mode 100644 tests/FlatpakRefusals/fixture/lib/Refused.cppm create mode 100644 tests/FlatpakRefusals/fixture/main.cpp create mode 100644 tests/FlatpakRefusals/main.cpp create mode 100644 tests/FlatpakTestsRaw/fixture/tests/hello/Hello.cppm create mode 100644 tests/FlatpakTestsRaw/fixture/tests/hello/main.cpp create mode 100644 tests/FlatpakTestsRaw/main.cpp create mode 100644 tests/FlatpakToolchainLibrary/fixture/main.cpp create mode 100644 tests/FlatpakToolchainLibrary/main.cpp diff --git a/AGENTS.template.md b/AGENTS.template.md index 3fe95de..f6fd70e 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -23,7 +23,7 @@ crafter-build is a C++26 modules build system. A project is described by a `proj 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. `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. +- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, 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. `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 `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. @@ -33,12 +33,13 @@ Partitions and what they own: - `: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` 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 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. +- `:Flatpak` is an executable packaged as a Flatpak: `FlatpakApp` (app-id, desktop file, metainfo, icons) and the writer of its `files/`, which becomes `/app` in the app's sandbox. It works on plain data; `Build()` in `:Clang` gathers it from the Configuration: the writer's input after the link, and the names its copies placed on every way out of `Build()`. ## 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. +Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime), `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/ @@ -91,6 +92,7 @@ Conventions the existing tests follow: - Fixtures under `tests//fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-"` 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 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. @@ -119,7 +121,7 @@ Beyond the rules: - 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()`, `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 at run time land, and the directory `-r` runs a host executable in and serves a browser build from; `ExpectedOutput()` names the executable in it. -- 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 and the toolchain (`Toolchain::Key()`). +- 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()`) 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 never what is compiled. ## Design rules @@ -196,7 +198,7 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary: - `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache. - 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 (`/.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. Changing asset extensions means updating two maps in `Crafter.Build-Clang.cpp`: `assetOutput` and the transitive copy loop. +- 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. - 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//`, one `libcxx--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`. diff --git a/build.sh b/build.sh index dcb8696..e72ead1 100755 --- a/build.sh +++ b/build.sh @@ -47,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 # 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 Interface Implementation External Agents Clang Test Lint Script Progress Asset" cp interfaces/Crafter.Build.cppm share/crafter-build/ for p in $PARTITIONS; do diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index 6ff9c6a..6a56310 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -16,6 +16,7 @@ import :Script; import :Agents; import :Progress; import :Asset; +import :Flatpak; namespace fs = std::filesystem; using namespace Crafter; @@ -579,6 +580,85 @@ namespace { } return ""; } + + // Why `config` cannot be the Flatpak it asks for; empty when it can be, + // or does not ask. Checked before anything is built, like WasmBuildError: + // each of these would otherwise surface as an app that does not start + // once installed, or not at all on the machine it was meant for. + std::string FlatpakBuildError(const Configuration& config) { + if (config.ResolvedPackaging() != Packaging::Flatpak) return ""; + if (config.target == "x86_64-w64-mingw32") return std::format("{}: a Windows executable is not packaged as a Flatpak; it stays an .exe", config.name); + if (config.target.starts_with("wasm32")) return std::format("{}: a wasm build is not packaged as a Flatpak; it stays a .wasm", config.name); + const Toolchain& tc = GetToolchain(); + if (tc.flatpakBranch.empty()) { + return std::format("{}: only the Flatpak crafter-build packages a Flatpak: a native one links the program against the host's glibc and libc++, which no Flatpak runtime matches", config.name); + } + if (!config.sysroot.empty()) { + return std::format("{}: a build against a sysroot ({}) links that sysroot's libraries, its C library among them, and not those of the runtime the app runs on", config.name, config.sysroot); + } + if (NormalizeTarget(config.target) != std::format("{}-linux-gnu", tc.flatpakArch)) { + if (config.target.ends_with("-linux-musl")) return std::format("{}: {} links musl, which no Flatpak runtime provides", config.name, config.target); + return std::format("{}: {} is not packaged as a Flatpak: the runtime crafter-build runs on, and the libc++ it would bundle, are {}", config.name, config.target, tc.flatpakArch); + } + // The libc++ a Flatpak carries is the toolchain's own, built against + // the runtime's glibc. One from CRAFTER_BUILD_LIBCXX_DIR is what the + // program would be compiled and linked against instead, and nothing + // says which glibc it needs: bundled, it may not load on the + // runtime; not bundled, the program loads a libc++ it was not built + // against. + if (!tc.libcxxDir.empty()) { + return std::format("{}: a build against CRAFTER_BUILD_LIBCXX_DIR ({}) links that libc++, and a Flatpak carries the toolchain's own, built against the runtime's glibc: unset it to package a Flatpak", config.name, tc.libcxxDir.string()); + } + return ""; + } + + // What an asset is compressed to, by the extension Crafter.Asset reads: + // the formats stb_image loads (behind TextureAsset::LoadPNG) to .ctex, + // .obj to .cmesh; nullopt for anything else. The one rule for an + // executable's own assets and the ones its dependencies forward to it. + std::optional CompressedAssetName(const fs::path& src) { + std::string ext = src.extension().string(); + for (char& c : ext) c = static_cast(std::tolower(static_cast(c))); + if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") { + return fs::path(src.filename()).replace_extension(".ctex"); + } + if (ext == ".obj") return fs::path(src.filename()).replace_extension(".cmesh"); + return std::nullopt; + } + + // The writer's record: one per bin dir, as there is one bin dir per + // BuildDir(). VariantId() does not hold outputName, and under a name of + // its own the record of a program renamed in place was not found, so + // the old program stayed in files/bin as one it wrote. + fs::path FlatpakRecordPath(const Configuration& config) { + return config.BuildDir() / "flatpak-record"; + } + + // Gathers what WriteFlatpakFiles needs from `config`, the link that just + // ran and the top-level names Build()'s copies placed in files/bin, and + // has it lay out files/. + std::string WriteFlatpak(const Configuration& config, const BuildResult& linked, const std::set& placed) { + const Toolchain& tc = GetToolchain(); + FlatpakFiles d; + d.root = config.BinDir(); + d.record = FlatpakRecordPath(config); + d.appId = config.flatpak.appId.empty() ? DefaultFlatpakAppId(config.outputName) : config.flatpak.appId; + d.command = ExpectedOutput(config).filename().string(); + d.desktopFile = config.flatpak.desktopFile; + d.metainfo = config.flatpak.metainfo; + d.icons = config.flatpak.icons; + d.clangxx = tc.clangxx; + d.readelf = tc.llvmReadelf; + for (const std::string& dir : linked.runPaths) d.libraryDirs.emplace_back(dir); + // Last, the toolchain's own lib dir, which the link searches as well + // (LibcxxSearchFlags): a library it takes from there, libclang or + // libedit of crafter-build's /app/lib, is no runtime's. -r would not + // show it missing, since crafter-build's sandbox has /app/lib on the + // loader's path, but the installed app would not start. + if (const fs::path toolchainLib = tc.LibcxxLibDir(); !toolchainLib.empty()) d.libraryDirs.push_back(toolchainLib); + d.programEntries = placed; + return WriteFlatpakFiles(d); + } } BuildResult Crafter::Build(Configuration& config, std::unordered_map>& depResults, std::mutex& depMutex) { @@ -641,6 +721,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map placed = {ExpectedOutput(config).filename().string()}; + const auto withoutSeparator = [](fs::path path) { + path = fs::absolute(path).lexically_normal(); + return path.has_filename() ? path : path.parent_path(); + }; + const fs::path outputRoot = withoutSeparator(outputDir); + const auto place = [&](const fs::path& destination, const fs::path& source) { + const fs::path normal = withoutSeparator(destination); + if (normal != outputRoot) { + placed.insert(normal.lexically_relative(outputRoot).begin()->string()); + return; + } + std::error_code ec; + for (const fs::directory_entry& child : fs::directory_iterator(source, ec)) placed.insert(child.path().filename().string()); + }; + // A build that fails has copied into files/bin all the same, so what it + // placed joins the writer's record on every way out of Build(): the next + // write removes what no build places any more, rather than take it for + // a file the program wrote. After a write, the record holds these names + // already. + struct PlacedOnExit { + const Configuration& config; + const std::set& names; + ~PlacedOnExit() { + if (config.ResolvedPackaging() == Packaging::Flatpak) RecordFlatpakPlaced(FlatpakRecordPath(config), names); + } + }; + const PlacedOnExit placedOnExit{config, placed}; if (!fs::exists(buildDir)) { fs::create_directories(buildDir); @@ -705,6 +823,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map std::optional { - std::string ext = src.extension().string(); - for (char& c : ext) c = static_cast(std::tolower(static_cast(c))); - // stb_image (used by CompressAsset → TextureAsset::LoadPNG) handles - // png/tga/jpg/bmp; all map to .ctex. - if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") { - return fs::path(src.filename()).replace_extension(".ctex"); - } - if (ext == ".obj") return fs::path(src.filename()).replace_extension(".cmesh"); - return std::nullopt; - }; auto submitCompress = [&](fs::path sourcePath, fs::path outRelative) { + place(outputDir / outRelative, {}); fs::path out = outputDir / outRelative; if (fs::exists(out) && fs::exists(sourcePath) && fs::last_write_time(sourcePath) <= fs::last_write_time(out)) return; threads.emplace_back([sourcePath = std::move(sourcePath), out = std::move(out), &buildError, &buildCancelled]() { @@ -766,14 +875,15 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map compName = compressedName(entry.path())) { + if (std::optional compName = CompressedAssetName(entry.path())) { submitCompress(entry.path(), topName / rel.parent_path() / *compName); } else { + place(outputDir / topName / rel, {}); assetPassthroughs.emplace_back(entry.path(), topName / rel); } } } else { - std::optional outName = compressedName(asset); + std::optional outName = CompressedAssetName(asset); if (!outName) { buildCancelled.store(true); buildError = std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string()); @@ -805,6 +915,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mapshaders) { fs::path src = depBinDir / shader.OutputName(); if (!fs::exists(src)) continue; + place(outputDir / src.filename(), src); copyTree(src, outputDir / src.filename()); } for (const fs::path& additionalFile : dep->files) { fs::path src = depBinDir / additionalFile.filename(); if (!fs::exists(src)) continue; + place(outputDir / additionalFile.filename(), src); copyTree(src, outputDir / additionalFile.filename()); } for (const fs::path& asset : dep->assets) { @@ -1100,22 +1213,16 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map(std::tolower(static_cast(c))); - fs::path srcName = asset.filename(); - if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") { - srcName.replace_extension(".ctex"); - } else if (ext == ".obj") { - srcName.replace_extension(".cmesh"); - } else { - continue; - } - fs::path src = depBinDir / srcName; + const std::optional srcName = CompressedAssetName(asset); + if (!srcName) continue; + fs::path src = depBinDir / *srcName; if (!fs::exists(src)) continue; - copyTree(src, outputDir / srcName); + place(outputDir / *srcName, src); + copyTree(src, outputDir / *srcName); } for (Configuration* sub : dep->dependencies) forwardDepArtifacts(sub); }; @@ -1219,18 +1326,29 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map std::optional { - std::string ext = src.extension().string(); - for (char& c : ext) c = static_cast(std::tolower(static_cast(c))); - if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") { - return std::string(".ctex"); - } - if (ext == ".obj") return std::string(".cmesh"); - return std::nullopt; - }; - auto compressedRel = [&](const fs::path& rel) -> fs::path { - if (auto ext = compressedExt(rel)) { - fs::path out = rel; - out.replace_extension(*ext); - return out; - } + // The name Build() writes an asset under, by the rule its own copy uses, + // so the manifest cannot list a file the build never wrote. + auto compressedRel = [](const fs::path& rel) -> fs::path { + if (const std::optional name = CompressedAssetName(rel)) return rel.parent_path() / *name; return rel; }; std::vector assetFiles; @@ -1581,8 +1695,9 @@ void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) { } // cfg.assets — mirror the bin-dir layout the build emits: a // directory entry becomes /, single - // files land flat at the bin root. .png/.obj are compressed in - // place; everything else passes through under its original name. + // files land flat at the bin root. What CompressedAssetName maps + // is compressed in place; everything else passes through under its + // original name. for (const fs::path& a : c->assets) { if (fs::is_directory(a)) { const fs::path topName = a.filename(); @@ -1747,6 +1862,14 @@ ArgQuery Crafter::ApplyStandardArgs(Configuration& cfg, std::span= '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 Split(std::string_view s, char separator) { + std::vector 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(in), std::istreambuf_iterator()); + } + + // 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 x(Block); + std::vector y(Block); + while (left && right) { + left.read(x.data(), static_cast(Block)); + right.read(y.data(), static_cast(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(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 SyncOwned(const fs::path& dir, const std::map& wanted) { + std::set copied; + std::error_code ec; + if (fs::exists(dir, ec)) { + std::vector files; + std::vector 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; + } + + // 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(std::tolower(static_cast(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(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 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> 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 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 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 Libraries(const FlatpakFiles& d, const fs::path& program) { + std::vector libraries; + std::set seen; + std::deque 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 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 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& 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 libraries; + for (const fs::path& library : Libraries(d, program)) libraries.emplace(library.filename(), library); + SyncOwned(files / "lib", libraries); + + std::map 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 icon = DesktopIcon(d.desktopFile); !icon.empty() && icon != d.appId) { + return std::format("{}: its Icon= is {}, and has to be the app-id, {}, which its icons are installed as", d.desktopFile.string(), icon, d.appId); + } + share.emplace(desktopEntry, d.desktopFile); + } + if (!d.metainfo.empty()) { + const fs::path metainfo = fs::path("metainfo") / std::format("{}.metainfo.xml", d.appId); + share.emplace(metainfo, d.metainfo); + } + for (const fs::path& icon : d.icons) { + const fs::path relative = IconPath(icon, d.appId); + if (share.contains(relative)) return std::format("{}: two icons go to {}", d.appId, relative.string()); + share.emplace(relative, icon); + } + 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 (share.contains(desktopEntry) && 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{}", d.desktopFile.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 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 ""; +} diff --git a/implementations/Crafter.Build-Lint.cpp b/implementations/Crafter.Build-Lint.cpp index 39e4be0..d1b1258 100644 --- a/implementations/Crafter.Build-Lint.cpp +++ b/implementations/Crafter.Build-Lint.cpp @@ -8,6 +8,7 @@ export module Crafter.Build:Lint_impl; import std; import :Lint; import :Clang; +import :Test; import :Platform; import :Toolchain; import :Progress; @@ -1084,6 +1085,8 @@ LintSummary Crafter::RunLint(Configuration& projectCfg, const RunLintOptions& op : opts.projectFile.parent_path(); std::vector localConfigs = CollectLocalConfigs(projectCfg, 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). std::vector rules; diff --git a/implementations/Crafter.Build-Platform.cpp b/implementations/Crafter.Build-Platform.cpp index 1aae592..6e3fa61 100644 --- a/implementations/Crafter.Build-Platform.cpp +++ b/implementations/Crafter.Build-Platform.cpp @@ -878,10 +878,11 @@ std::string Crafter::GetBaseCommand(const Configuration& config) { } namespace { - constexpr std::array CrafterBuildModules = { + constexpr std::array CrafterBuildModules = { "Crafter.Build-Toolchain", "Crafter.Build-Shader", "Crafter.Build-Platform", + "Crafter.Build-Flatpak", "Crafter.Build-Interface", "Crafter.Build-Implementation", "Crafter.Build-External", diff --git a/implementations/Crafter.Build-Test.cpp b/implementations/Crafter.Build-Test.cpp index 3d68fa2..7ba19e9 100644 --- a/implementations/Crafter.Build-Test.cpp +++ b/implementations/Crafter.Build-Test.cpp @@ -442,7 +442,12 @@ TestBuilder& TestBuilder::Dependencies(std::vector d) { 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; } +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 projectArgs) { + UnpackageTests(projectCfg); // Multi-target sweep: when no --target= was given, the run covers every // distinct target declared across projectCfg.tests plus the host target. // Lets a bare `crafter-build test` exercise cross-arch tests without the diff --git a/implementations/Crafter.Build-Toolchain.cpp b/implementations/Crafter.Build-Toolchain.cpp index 84a1de3..1167f8c 100644 --- a/implementations/Crafter.Build-Toolchain.cpp +++ b/implementations/Crafter.Build-Toolchain.cpp @@ -21,9 +21,40 @@ namespace { "CRAFTER_BUILD_LIBCXX_DIR", "CRAFTER_BUILD_LIBCLANG", "CRAFTER_BUILD_WASI_SYSROOT", + "CRAFTER_BUILD_FLATPAK_INFO", "CRAFTER_MINGW_DIR", }; + // The arch and branch of the runtime=runtime/// line + // in the [Application] group of a .flatpak-info; empty when it has none. + std::pair 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 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) { auto it = in.env.find(name); return it == in.env.end() ? std::string_view{} : std::string_view(it->second); @@ -81,20 +112,27 @@ std::string Toolchain::LibcxxCompileFlags() const { return std::format(" -nostdinc++ -isystem {}", (libcxxDir / "include" / "c++" / "v1").string()); } +// clang searches its per-target runtime directory and the system library +// paths for -lc++, not /lib, so a toolchain outside /usr with the +// classic layout needs the search path as well as the run-time path. +fs::path Toolchain::LibcxxLibDir() const { + if (!libcxxDir.empty()) return libcxxDir / "lib"; + if (!prefix.empty() && prefix != "/usr") return prefix / "lib"; + return {}; +} + std::string Toolchain::LibcxxLinkFlags() const { - // clang searches its per-target runtime directory and the system library - // paths for -lc++, not /lib, so a toolchain outside /usr with the - // classic layout needs the search path as well as the run-time path. - fs::path lib; - if (!libcxxDir.empty()) { - lib = libcxxDir / "lib"; - } else if (!prefix.empty() && prefix != "/usr") { - lib = prefix / "lib"; - } + const fs::path lib = LibcxxLibDir(); if (lib.empty()) return {}; 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 identity; for (const std::string& part : {clangxx.string(), clangVersion, libcxxDir.string(), stdCppm.string()}) { @@ -124,10 +162,12 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) { tc.clangxx = "clang++"; tc.clang = "clang"; tc.llvmAr = "llvm-ar"; + tc.llvmReadelf = "llvm-readelf"; } else { tc.clangxx = tc.prefix / "bin" / "clang++"; tc.clang = tc.prefix / "bin" / "clang"; tc.llvmAr = tc.prefix / "bin" / "llvm-ar"; + tc.llvmReadelf = tc.prefix / "bin" / "llvm-readelf"; if (tc.prefix != "/usr" && fs::exists(tc.prefix / "include" / "clang-c" / "Index.h")) { tc.llvmIncludeDir = tc.prefix / "include"; } @@ -181,6 +221,7 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) { tc.mingwPrefix = PrefixPath(in.hostRoot / "usr"); tc.mingwPrefixIsSystem = true; } + std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo); return tc; } @@ -198,6 +239,13 @@ const Toolchain& Crafter::GetToolchain() { in.crafterPrefix = GetCrafterBuildHome().parent_path().parent_path(); } catch (const std::exception&) {} if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host"; + { + 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(file), std::istreambuf_iterator()); + } + } Toolchain tc = ResolveToolchain(in); if (!tc.error.empty()) return tc; diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index 7499e63..a70e42a 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -9,6 +9,7 @@ import :Implementation; import :External; import :Toolchain; import :Agents; +import :Flatpak; namespace fs = std::filesystem; namespace Crafter { @@ -57,7 +58,9 @@ export namespace Crafter { // 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. + // 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 runPaths; }; @@ -89,6 +92,25 @@ export namespace Crafter { 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 TestRunner { @@ -471,6 +493,11 @@ export namespace Crafter { std::string sysroot; bool debug = false; 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. + FlatpakApp flatpak; std::vector> interfaces; std::vector implementations; std::vector cFiles; @@ -661,6 +688,10 @@ export namespace Crafter { } compileKey += "|T:"; compileKey += toolchain.Key(); + // 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{}(compileKey); return std::format("{}-{}-{}-{}-{:08x}", name, target, march, mtune, configHash); } @@ -669,9 +700,16 @@ export namespace Crafter { // 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. For now that is the bin - // dir of every configuration. - fs::path ProgramDir() const { return BinDir(); } + // 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; + } fs::path PcmDir() const { return type == ConfigurationType::Executable ? BuildDir() : BinDir(); } @@ -806,6 +844,11 @@ export namespace Crafter { // --mtune= cfg.mtune = // --lib cfg.type promoted Executable → LibraryStatic // --shared cfg.type promoted LibraryStatic → LibraryDynamic + // --packaging= 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 // 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 diff --git a/interfaces/Crafter.Build-Flatpak.cppm b/interfaces/Crafter.Build-Flatpak.cppm new file mode 100644 index 0000000..55f6748 --- /dev/null +++ b/interfaces/Crafter.Build-Flatpak.cppm @@ -0,0 +1,98 @@ +// 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, and +// the files/ Build() lays out for it, which becomes /app in the app's +// sandbox. Everything here works on plain data; Build() gathers it from the +// Configuration, so this partition knows nothing of one. +export namespace Crafter { + // What an executable packaged as a Flatpak is installed as. Read for an + // executable whose Configuration::packaging makes it one. + struct FlatpakApp { + // The application ID, reverse-DNS. Empty means + // DefaultFlatpakAppId(outputName). + std::string appId; + // A desktop entry, installed as .desktop. Its Icon= has to be + // the app-id. Empty: none, and the app gets no menu entry. + fs::path desktopFile; + // AppStream metadata, installed as .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 icons; + }; + + // local.crafterbuild.: 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 icons; + // 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 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 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 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& names); +} diff --git a/interfaces/Crafter.Build-Test.cppm b/interfaces/Crafter.Build-Test.cppm index 0b69256..52f1d1c 100644 --- a/interfaces/Crafter.Build-Test.cppm +++ b/interfaces/Crafter.Build-Test.cppm @@ -95,3 +95,14 @@ export namespace Crafter { void SetParentProject(Configuration* parent); 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); +} diff --git a/interfaces/Crafter.Build-Toolchain.cppm b/interfaces/Crafter.Build-Toolchain.cppm index 6f1b68c..84c0194 100644 --- a/interfaces/Crafter.Build-Toolchain.cppm +++ b/interfaces/Crafter.Build-Toolchain.cppm @@ -18,6 +18,8 @@ export namespace Crafter { fs::path clangxx; fs::path clang; fs::path llvmAr; + // What a packaged program's shared libraries are read with. + fs::path llvmReadelf; // Where clang-c/Index.h lives when it is not on the default include // path; empty otherwise. fs::path llvmIncludeDir; @@ -53,6 +55,15 @@ export namespace Crafter { // 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 Flatpak runtime crafter-build runs on, from the + // runtime=runtime/// 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++ --version`; both empty when clang++ could not be run. std::string hostTriple; @@ -62,6 +73,12 @@ export namespace Crafter { // Flags for compiling against libcxxDir; empty without one. std::string LibcxxCompileFlags() const; + // Where libc++.so.1 is when clang would not find it itself: an + // explicit libcxxDir's lib, or /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 // and an rpath for /lib when the prefix is not the system one // (clang searches only its per-target runtime directory and the @@ -69,6 +86,9 @@ export namespace Crafter { // the linker's nor the loader's default path), or for an explicit // libcxxDir. 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 // followed by a hash of what decides which headers and libraries a // PCM is built against. Two toolchains with different keys never @@ -85,6 +105,9 @@ export namespace Crafter { // Where the host's root shows inside a sandbox (/run/host in a // Flatpak); empty outside one. fs::path hostRoot; + // What /.flatpak-info holds, or the file CRAFTER_BUILD_FLATPAK_INFO + // names; empty outside a Flatpak. + std::string flatpakInfo; }; // Pure path resolution: an env override wins, then a toolchain installed // beside crafter-build (/bin/clang++), then bare names on diff --git a/interfaces/Crafter.Build.cppm b/interfaces/Crafter.Build.cppm index ce4535c..03fbe44 100644 --- a/interfaces/Crafter.Build.cppm +++ b/interfaces/Crafter.Build.cppm @@ -3,6 +3,7 @@ export module Crafter.Build; export import :Toolchain; +export import :Flatpak; export import :Clang; export import :Platform; export import :Implementation; diff --git a/project.cpp b/project.cpp index e17a42c..dc636e7 100644 --- a/project.cpp +++ b/project.cpp @@ -173,11 +173,12 @@ extern "C" Configuration CrafterBuildProject(std::span a // it reaches clang, which must still see a string literal. CrafterBuildLib->defines.push_back({"CRAFTER_BUILD_VERSION", std::format("\\\"{}\\\"", version)}); { - std::array interfaces = { + std::array interfaces = { "interfaces/Crafter.Build", "interfaces/Crafter.Build-Toolchain", "interfaces/Crafter.Build-Shader", "interfaces/Crafter.Build-Platform", + "interfaces/Crafter.Build-Flatpak", "interfaces/Crafter.Build-Interface", "interfaces/Crafter.Build-Implementation", "interfaces/Crafter.Build-External", @@ -189,10 +190,11 @@ extern "C" Configuration CrafterBuildProject(std::span a "interfaces/Crafter.Build-Progress", "interfaces/Crafter.Build-Asset", }; - std::array implementations = { + std::array implementations = { "implementations/Crafter.Build-Toolchain", "implementations/Crafter.Build-Shader", "implementations/Crafter.Build-Platform", + "implementations/Crafter.Build-Flatpak", "implementations/Crafter.Build-Interface", "implementations/Crafter.Build-Implementation", "implementations/Crafter.Build-External", @@ -276,6 +278,17 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("WasmVariants").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("WasmExceptions").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasiSysrootWithoutExceptions").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() }); diff --git a/tests/FlatpakDependencyExecutable/fixture/app/project.cpp b/tests/FlatpakDependencyExecutable/fixture/app/project.cpp new file mode 100644 index 0000000..ce08f80 --- /dev/null +++ b/tests/FlatpakDependencyExecutable/fixture/app/project.cpp @@ -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 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; +} diff --git a/tests/FlatpakDependencyExecutable/fixture/packaged/main.cpp b/tests/FlatpakDependencyExecutable/fixture/packaged/main.cpp new file mode 100644 index 0000000..75e6b0c --- /dev/null +++ b/tests/FlatpakDependencyExecutable/fixture/packaged/main.cpp @@ -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; +} diff --git a/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/icon.svg b/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/icon.svg new file mode 100644 index 0000000..81ef5d3 --- /dev/null +++ b/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/icon.svg @@ -0,0 +1 @@ + diff --git a/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/packaged.metainfo.xml b/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/packaged.metainfo.xml new file mode 100644 index 0000000..e5e8dc1 --- /dev/null +++ b/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/packaged.metainfo.xml @@ -0,0 +1,7 @@ + + + net.example.Packaged + Packaged + A fixture for crafter-build's tests + CC0-1.0 + diff --git a/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp b/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp new file mode 100644 index 0000000..8fe7748 --- /dev/null +++ b/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp @@ -0,0 +1,27 @@ +// 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 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" }; + std::array ifaces = {}; + std::array impls = { "main" }; + cfg.GetInterfacesAndImplementations(ifaces, impls); + return cfg; +} diff --git a/tests/FlatpakDependencyExecutable/fixture/tool/project.cpp b/tests/FlatpakDependencyExecutable/fixture/tool/project.cpp new file mode 100644 index 0000000..a823bde --- /dev/null +++ b/tests/FlatpakDependencyExecutable/fixture/tool/project.cpp @@ -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 args) { + Configuration cfg; + cfg.path = "./"; + cfg.name = "tool"; + cfg.outputName = "tool"; + cfg.type = ConfigurationType::Executable; + ApplyStandardArgs(cfg, args); + return cfg; +} diff --git a/tests/FlatpakDependencyExecutable/main.cpp b/tests/FlatpakDependencyExecutable/main.cpp new file mode 100644 index 0000000..94c04e3 --- /dev/null +++ b/tests/FlatpakDependencyExecutable/main.cpp @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +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(in), std::istreambuf_iterator()); + } +} + +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 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"); + if (NormalizeTarget(GetToolchain().hostTriple) == "x86_64-linux-gnu" && GetToolchain().libcxxDir.empty()) { + std::unordered_map> 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"); + } + } + } 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; +} diff --git a/tests/FlatpakDesktop/fixture/app.desktop b/tests/FlatpakDesktop/fixture/app.desktop new file mode 100644 index 0000000..057aa14 --- /dev/null +++ b/tests/FlatpakDesktop/fixture/app.desktop @@ -0,0 +1,6 @@ +[Desktop Entry] +Type=Application +Name=Desktop +Exec=desktop +Icon=net.example.Desktop +Categories=Utility; diff --git a/tests/FlatpakDesktop/fixture/app.metainfo.xml b/tests/FlatpakDesktop/fixture/app.metainfo.xml new file mode 100644 index 0000000..f5770f7 --- /dev/null +++ b/tests/FlatpakDesktop/fixture/app.metainfo.xml @@ -0,0 +1,7 @@ + + + net.example.Desktop + Desktop + A fixture for crafter-build's tests + CC0-1.0 + diff --git a/tests/FlatpakDesktop/fixture/icon.svg b/tests/FlatpakDesktop/fixture/icon.svg new file mode 100644 index 0000000..81ef5d3 --- /dev/null +++ b/tests/FlatpakDesktop/fixture/icon.svg @@ -0,0 +1 @@ + diff --git a/tests/FlatpakDesktop/fixture/invalid.desktop b/tests/FlatpakDesktop/fixture/invalid.desktop new file mode 100644 index 0000000..2f84b12 --- /dev/null +++ b/tests/FlatpakDesktop/fixture/invalid.desktop @@ -0,0 +1,5 @@ +[Desktop Entry] +Type=Bogus +Name=Desktop +Exec=desktop +Icon=net.example.Desktop diff --git a/tests/FlatpakDesktop/fixture/main.cpp b/tests/FlatpakDesktop/fixture/main.cpp new file mode 100644 index 0000000..f2e1509 --- /dev/null +++ b/tests/FlatpakDesktop/fixture/main.cpp @@ -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; +} diff --git a/tests/FlatpakDesktop/fixture/wrong-icon.desktop b/tests/FlatpakDesktop/fixture/wrong-icon.desktop new file mode 100644 index 0000000..3af2ce8 --- /dev/null +++ b/tests/FlatpakDesktop/fixture/wrong-icon.desktop @@ -0,0 +1,6 @@ +[Desktop Entry] +Type=Application +Name=Desktop +Exec=desktop +Icon=desktop +Categories=Utility; diff --git a/tests/FlatpakDesktop/main.cpp b/tests/FlatpakDesktop/main.cpp new file mode 100644 index 0000000..ec01cc3 --- /dev/null +++ b/tests/FlatpakDesktop/main.cpp @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +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(in), std::istreambuf_iterator()); + } + + std::string BuildIt(Configuration& cfg) { + std::unordered_map> 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((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/.desktop, the +// metainfo as share/metainfo/.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.. +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 ifaces = {}; + std::array 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; +} diff --git a/tests/FlatpakIncremental/fixture/app.desktop b/tests/FlatpakIncremental/fixture/app.desktop new file mode 100644 index 0000000..d3064e8 --- /dev/null +++ b/tests/FlatpakIncremental/fixture/app.desktop @@ -0,0 +1,5 @@ +[Desktop Entry] +Type=Application +Name=Incremental +Exec=incremental +Categories=Utility; diff --git a/tests/FlatpakIncremental/fixture/dropped.txt b/tests/FlatpakIncremental/fixture/dropped.txt new file mode 100644 index 0000000..14dcb55 --- /dev/null +++ b/tests/FlatpakIncremental/fixture/dropped.txt @@ -0,0 +1 @@ +dropped later diff --git a/tests/FlatpakIncremental/fixture/icon.svg b/tests/FlatpakIncremental/fixture/icon.svg new file mode 100644 index 0000000..81ef5d3 --- /dev/null +++ b/tests/FlatpakIncremental/fixture/icon.svg @@ -0,0 +1 @@ + diff --git a/tests/FlatpakIncremental/fixture/kept.txt b/tests/FlatpakIncremental/fixture/kept.txt new file mode 100644 index 0000000..bd93009 --- /dev/null +++ b/tests/FlatpakIncremental/fixture/kept.txt @@ -0,0 +1 @@ +kept diff --git a/tests/FlatpakIncremental/fixture/main.cpp b/tests/FlatpakIncremental/fixture/main.cpp new file mode 100644 index 0000000..427cc04 --- /dev/null +++ b/tests/FlatpakIncremental/fixture/main.cpp @@ -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; +} diff --git a/tests/FlatpakIncremental/main.cpp b/tests/FlatpakIncremental/main.cpp new file mode 100644 index 0000000..12ad63f --- /dev/null +++ b/tests/FlatpakIncremental/main.cpp @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +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(in), std::istreambuf_iterator()); + } + + std::string BuildIt(Configuration& cfg) { + std::unordered_map> 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 ifaces = {}; + std::array 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; +} diff --git a/tests/FlatpakLibcxxDir/fixture/main.cpp b/tests/FlatpakLibcxxDir/fixture/main.cpp new file mode 100644 index 0000000..10869e3 --- /dev/null +++ b/tests/FlatpakLibcxxDir/fixture/main.cpp @@ -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; +} diff --git a/tests/FlatpakLibcxxDir/main.cpp b/tests/FlatpakLibcxxDir/main.cpp new file mode 100644 index 0000000..05dc762 --- /dev/null +++ b/tests/FlatpakLibcxxDir/main.cpp @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +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 ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + } + std::unordered_map> 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; +} diff --git a/tests/FlatpakLibraryChange/main.cpp b/tests/FlatpakLibraryChange/main.cpp new file mode 100644 index 0000000..b0d971d --- /dev/null +++ b/tests/FlatpakLibraryChange/main.cpp @@ -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(in), std::istreambuf_iterator()); + } +} + +// 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; +} diff --git a/tests/FlatpakNative/fixture/main.cpp b/tests/FlatpakNative/fixture/main.cpp new file mode 100644 index 0000000..10869e3 --- /dev/null +++ b/tests/FlatpakNative/fixture/main.cpp @@ -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; +} diff --git a/tests/FlatpakNative/main.cpp b/tests/FlatpakNative/main.cpp new file mode 100644 index 0000000..08e02d1 --- /dev/null +++ b/tests/FlatpakNative/main.cpp @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +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; + } + } + + BuildResult BuildIt(Configuration& cfg) { + std::unordered_map> depResults; + std::mutex depMutex; + return Build(cfg, depResults, depMutex); + } +} + +// Only crafter-build running in its Flatpak packages a Flatpak: the program +// links that sandbox's glibc, the runtime's, so the app runs on it. A native +// crafter-build links against the host's glibc and libc++, which no runtime +// matches, so asking it for a Flatpak fails saying so, and Default builds +// the executable as linked, as it always has. A .flatpak-info without a +// runtime is staged, which is what a native process has, inside the Flatpak +// as well as out of it. +int main() { + const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-native"; + std::error_code ec; + fs::remove_all(scratch, ec); + fs::create_directories(scratch); + const fs::path info = scratch / "flatpak-info"; + std::ofstream(info) << ""; + setenv("CRAFTER_BUILD_FLATPAK_INFO", info.string().c_str(), 1); + Check(GetToolchain().flatpakBranch.empty(), "without a runtime in the staged file there is none"); + + const fs::path fixture = fs::current_path() / "tests" / "FlatpakNative" / "fixture"; + fs::remove_all(fixture / "bin", ec); + fs::remove_all(fixture / "build", ec); + Configuration app; + app.path = fixture; + app.name = "native-app"; + app.outputName = "native"; + app.target = HostTarget(); + { + std::array ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + } + + app.packaging = Packaging::Flatpak; + const BuildResult refused = BuildIt(app); + Check(refused.result.contains("only the Flatpak crafter-build packages a Flatpak") && refused.result.contains("native-app"), std::format("a native build refuses to package a Flatpak, saying why: {}", refused.result)); + + app.packaging = Packaging::Default; + const BuildResult built = BuildIt(app); + Check(built.result.empty(), std::format("Default builds: {}", built.result)); + Check(ExpectedOutput(app) == app.BinDir() / "native" && fs::is_regular_file(ExpectedOutput(app)), "the executable is linked into the bin dir, as before"); + Check(!fs::exists(app.BinDir() / "files"), "and it is not packaged"); + const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(app).string()), std::chrono::seconds(30)); + Check(run.exitCode == 0 && run.output.contains("native"), std::format("it runs: {}", run.output)); + + fs::remove_all(scratch, ec); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} diff --git a/tests/FlatpakOutput/fixture/main.cpp b/tests/FlatpakOutput/fixture/main.cpp new file mode 100644 index 0000000..10c5168 --- /dev/null +++ b/tests/FlatpakOutput/fixture/main.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; + +int main() { + std::println("hello from a Flatpak"); + return 0; +} diff --git a/tests/FlatpakOutput/fixture/message.txt b/tests/FlatpakOutput/fixture/message.txt new file mode 100644 index 0000000..3d501aa --- /dev/null +++ b/tests/FlatpakOutput/fixture/message.txt @@ -0,0 +1 @@ +read beside the program diff --git a/tests/FlatpakOutput/main.cpp b/tests/FlatpakOutput/main.cpp new file mode 100644 index 0000000..4ffa7de --- /dev/null +++ b/tests/FlatpakOutput/main.cpp @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +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; + } + } + + // The NEEDED entries of an ELF file, by the toolchain's llvm-readelf. + std::set Needed(const fs::path& readelf, const fs::path& file) { + const auto r = RunCommandWithTimeout(std::format("{} --needed-libs {}", ShellQuote(readelf.string()), ShellQuote(file.string())), std::chrono::seconds(30)); + std::set names; + bool inList = false; + std::istringstream lines(r.output); + for (std::string line; std::getline(lines, line);) { + const std::size_t first = line.find_first_not_of(" \t"); + const std::string t = first == std::string::npos ? std::string() : line.substr(first); + if (!inList) { + inList = t.starts_with("NeededLibraries ["); + continue; + } + if (t == "]") break; + if (!t.empty()) names.insert(t); + } + return names; + } + + // Whether the toolchain has its own copy of an LLVM runtime library. + bool ToolchainHas(const fs::path& clangxx, std::string_view name) { + const auto r = RunCommandWithTimeout(std::format("{} -print-file-name={}", ShellQuote(clangxx.string()), name), std::chrono::seconds(30)); + std::string out = r.output; + while (!out.empty() && (out.back() == '\n' || out.back() == '\r')) out.pop_back(); + const fs::path path = out; + std::error_code ec; + return r.exitCode == 0 && path.is_absolute() && fs::exists(path, ec); + } + + std::map Mtimes(const fs::path& root) { + std::map times; + for (const fs::directory_entry& entry : fs::recursive_directory_iterator(root)) { + if (entry.is_regular_file()) times.emplace(entry.path(), entry.last_write_time()); + } + return times; + } +} + +// An executable packaged as a Flatpak comes out as the files/ of a Flatpak +// build directory, what becomes /app: the program and its files in +// files/bin, which ExpectedOutput and ProgramDir name, and in files/lib +// exactly the libraries of the toolchain the program needs, found there +// through its one run path, $ORIGIN/../lib. The Platform has no libc++, so +// an app without them would not start. The metadata and export/ are flatpak +// build-finish's to write, so the build writes neither. A second build +// changes nothing. The runtime is staged through CRAFTER_BUILD_FLATPAK_INFO, +// so the native loop packages too; inside the Flatpak the staged file wins +// over the sandbox's own. +int main() { + const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-output"; + 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"; + // Before anything asks for the toolchain, which reads it once. + setenv("CRAFTER_BUILD_FLATPAK_INFO", info.string().c_str(), 1); + + const Toolchain& tc = GetToolchain(); + if (NormalizeTarget(tc.hostTriple) != "x86_64-linux-gnu") { + std::println(std::cerr, "SKIP: the staged runtime is x86_64 and the host is {}", tc.hostTriple); + return 77; + } + if (!tc.libcxxDir.empty()) { + std::println(std::cerr, "SKIP: CRAFTER_BUILD_LIBCXX_DIR is set, and a build against it is no Flatpak"); + return 77; + } + Check(tc.flatpakArch == "x86_64" && tc.flatpakBranch == "26.08", std::format("the staged runtime is read: '{}' '{}'", tc.flatpakArch, tc.flatpakBranch)); + + const fs::path fixture = fs::current_path() / "tests" / "FlatpakOutput" / "fixture"; + fs::remove_all(fixture / "bin", ec); + fs::remove_all(fixture / "build", ec); + Configuration app; + app.path = fixture; + app.name = "flatpak-hello"; + app.outputName = "hello"; + app.target = HostTarget(); + app.packaging = Packaging::Flatpak; + app.files.push_back(fixture / "message.txt"); + { + std::array ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + } + + { + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult r = Build(app, depResults, depMutex); + if (!r.result.empty()) { + std::println(std::cerr, "FAIL: build failed: {}", r.result); + return 1; + } + } + + const fs::path root = app.BinDir(); + const fs::path program = ExpectedOutput(app); + Check(app.ProgramDir() == root / "files" / "bin", std::format("ProgramDir is files/bin: {}", app.ProgramDir().string())); + Check(program == root / "files" / "bin" / "hello", std::format("ExpectedOutput is files/bin/hello: {}", program.string())); + Check(fs::is_regular_file(program), "the program is linked into files/bin"); + Check(fs::is_regular_file(root / "files" / "bin" / "message.txt"), "cfg.files land beside the program"); + Check(!fs::exists(root / "metadata") && !fs::exists(root / "export"), "no metadata or export/, which flatpak build-finish writes"); + + // files/lib holds what the toolchain links and the program needs, and + // nothing the runtime has. + const fs::path lib = root / "files" / "lib"; + std::set bundled; + for (const fs::directory_entry& entry : fs::directory_iterator(lib, ec)) bundled.insert(entry.path().filename().string()); + std::set needed = Needed(tc.llvmReadelf, program); + for (const std::string& name : bundled) needed.merge(Needed(tc.llvmReadelf, lib / name)); + Check(bundled.contains("libc++.so.1"), "libc++.so.1 is bundled"); + for (const std::string_view name : {"libc++.so.1", "libc++abi.so.1", "libunwind.so.1"}) { + if (needed.contains(std::string(name)) && ToolchainHas(tc.clangxx, name)) Check(bundled.contains(std::string(name)), std::format("{}, which the toolchain links, is bundled", name)); + } + for (const std::string& name : bundled) Check(needed.contains(name), std::format("{} is bundled because something needs it", name)); + for (const std::string_view name : {"libc.so.6", "libm.so.6", "libgcc_s.so.1", "ld-linux-x86-64.so.2"}) { + Check(!bundled.contains(std::string(name)), std::format("{}, the runtime's, is not bundled", name)); + } + + const auto dynamic = RunCommandWithTimeout(std::format("{} -d {}", ShellQuote(tc.llvmReadelf.string()), ShellQuote(program.string())), std::chrono::seconds(30)); + Check(dynamic.output.contains("Library runpath: [$ORIGIN/../lib]"), std::format("the one run path is $ORIGIN/../lib:\n{}", dynamic.output)); + + // The loader takes libc++ from files/lib, not from wherever the + // toolchain keeps it. + if (std::system("command -v ldd > /dev/null 2>&1") == 0) { + // Without LD_LIBRARY_PATH, which flatpak-builder's build sandbox, where + // CI runs this suite, sets to /app/lib ahead of the program's run path: + // the check is what the installed app's loader does, and `flatpak run` + // sets none. + const auto ldd = RunCommandWithTimeout(std::format("env -u LD_LIBRARY_PATH ldd {}", ShellQuote(program.string())), std::chrono::seconds(30)); + std::istringstream lines(ldd.output); + bool resolved = false; + for (std::string line; std::getline(lines, line);) { + const std::size_t arrow = line.find("libc++.so.1 => "); + if (arrow == std::string::npos) continue; + const std::string rest = line.substr(arrow + std::string_view("libc++.so.1 => ").size()); + const fs::path path = rest.substr(0, rest.find(" (")); + resolved = fs::equivalent(path, lib / "libc++.so.1", ec); + } + Check(resolved, std::format("libc++.so.1 resolves to the bundled copy:\n{}", ldd.output)); + } + + const auto run = RunCommandWithTimeout(ShellQuote(program.string()), std::chrono::seconds(30)); + Check(run.exitCode == 0 && run.output.contains("hello from a Flatpak"), std::format("the program runs (exit {}): {}", run.exitCode, run.output)); + + // A build with nothing to do writes nothing. + const std::map before = Mtimes(root); + { + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult r = Build(app, depResults, depMutex); + Check(r.result.empty(), std::format("the second build succeeds: {}", r.result)); + } + Check(Mtimes(root) == before, "a second build leaves every file of the bin dir alone"); + + fs::remove_all(scratch, ec); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} diff --git a/tests/FlatpakRefusals/fixture/lib/Refused.cppm b/tests/FlatpakRefusals/fixture/lib/Refused.cppm new file mode 100644 index 0000000..c37faa9 --- /dev/null +++ b/tests/FlatpakRefusals/fixture/lib/Refused.cppm @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Refused; +import std; + +export std::int32_t Value() { + return 1; +} diff --git a/tests/FlatpakRefusals/fixture/main.cpp b/tests/FlatpakRefusals/fixture/main.cpp new file mode 100644 index 0000000..aa06d5a --- /dev/null +++ b/tests/FlatpakRefusals/fixture/main.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; + +int main() { + std::println("refused"); + return 0; +} diff --git a/tests/FlatpakRefusals/main.cpp b/tests/FlatpakRefusals/main.cpp new file mode 100644 index 0000000..dd6c2d2 --- /dev/null +++ b/tests/FlatpakRefusals/main.cpp @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +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; + } + } + + BuildResult BuildIt(Configuration& cfg) { + std::unordered_map> depResults; + std::mutex depMutex; + return Build(cfg, depResults, depMutex); + } + + struct Refusal { + std::string_view what; + std::string target; + std::string sysroot; + std::string_view reason; + }; +} + +// An executable asking to be a Flatpak where it cannot be one is refused +// before anything is built, saying why: a Windows executable and a wasm +// build have outputs of their own, a build against a sysroot links that +// sysroot's libraries and not the runtime's, one for musl links a C library +// no runtime provides, and another architecture than the runtime's has no +// libc++ crafter-build could bundle. Each would otherwise be an app built +// against something other than what it runs with. With Default or None the +// same configurations keep the output they have, and a library asked to be +// a Flatpak is built as the library it is. +int main() { + const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-refusals"; + 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" / "FlatpakRefusals" / "fixture"; + fs::remove_all(fixture / "bin", ec); + fs::remove_all(fixture / "build", ec); + + const std::array refusals = {{ + {"a Windows executable", "x86_64-w64-mingw32", "", "a Windows executable is not packaged as a Flatpak"}, + {"a wasm build", "wasm32-wasip1", "", "a wasm build is not packaged as a Flatpak"}, + {"a build against a sysroot", HostTarget(), (scratch / "sysroot").string(), "links that sysroot's libraries"}, + {"a musl build", "x86_64-alpine-linux-musl", "", "links musl"}, + {"another architecture", "aarch64-linux-gnu", "", "the libc++ it would bundle, are x86_64"}, + }}; + for (const Refusal& refusal : refusals) { + Configuration app; + app.path = fixture; + app.name = "refused-app"; + app.outputName = "refused"; + app.target = refusal.target; + app.sysroot = refusal.sysroot; + app.packaging = Packaging::Flatpak; + std::array ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + + const BuildResult r = BuildIt(app); + Check(r.result.contains(refusal.reason) && r.result.contains(app.name), std::format("{} is refused as a Flatpak, saying why and naming the configuration: {}", refusal.what, r.result)); + Check(!fs::exists(app.BinDir()) && !fs::exists(app.BuildDir()), std::format("refusing {} leaves nothing behind", refusal.what)); + for (const Packaging packaging : {Packaging::Default, Packaging::None}) { + app.packaging = packaging; + Check(app.ResolvedPackaging() == Packaging::None && app.ProgramDir() == app.BinDir(), std::format("{} keeps its own output with Default and None", refusal.what)); + } + } + + Configuration lib; + lib.path = fixture / "lib"; + lib.name = "refused-lib"; + lib.outputName = "refused"; + lib.target = HostTarget(); + lib.type = ConfigurationType::LibraryStatic; + lib.packaging = Packaging::Flatpak; + { + std::array ifaces = { "Refused" }; + std::array impls = {}; + lib.GetInterfacesAndImplementations(ifaces, impls); + } + Check(lib.ResolvedPackaging() == Packaging::None, "a library is never packaged"); + const BuildResult built = BuildIt(lib); + Check(built.result.empty(), std::format("a library asked to be a Flatpak builds as a library: {}", built.result)); + Check(fs::exists(ExpectedOutput(lib)) && !fs::exists(lib.BinDir() / "files"), "it is an archive, with no files/ beside it"); + + fs::remove_all(scratch, ec); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} diff --git a/tests/FlatpakTestsRaw/fixture/tests/hello/Hello.cppm b/tests/FlatpakTestsRaw/fixture/tests/hello/Hello.cppm new file mode 100644 index 0000000..0e3e310 --- /dev/null +++ b/tests/FlatpakTestsRaw/fixture/tests/hello/Hello.cppm @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +export module Hello; +import std; + +export std::string_view Greeting() { + return "hello from a test"; +} diff --git a/tests/FlatpakTestsRaw/fixture/tests/hello/main.cpp b/tests/FlatpakTestsRaw/fixture/tests/hello/main.cpp new file mode 100644 index 0000000..e60eceb --- /dev/null +++ b/tests/FlatpakTestsRaw/fixture/tests/hello/main.cpp @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Hello; + +int main() { + std::println("{}", Greeting()); + return 0; +} diff --git a/tests/FlatpakTestsRaw/main.cpp b/tests/FlatpakTestsRaw/main.cpp new file mode 100644 index 0000000..341873d --- /dev/null +++ b/tests/FlatpakTestsRaw/main.cpp @@ -0,0 +1,78 @@ +// 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; + } + } +} + +// A test is never packaged, whatever its Configuration asks for: the runner +// starts the binary itself. Saying so in AddTest alone would miss a test +// from AddMarchVariants, or one a project.cpp puts into cfg.tests itself: +// it would follow its own packaging, Default only while that means the +// executable as linked, and Packaging::Flatpak would be packaged, or, by a +// native crafter-build, refused. So RunTests runs every test as linked, +// and so does RunLint work out its compile command: the test's own module +// PCMs are where its VariantId puts them, and the Flatpak variant, which +// nothing builds, has none, so linting it with a rule that reads the AST +// used to fail the run for want of them, after any number of test runs. +int main() { + // AddTest resolves tests//main.cpp against the working directory, + // and the test's outputs land below it, in the fixture's own bin/ and + // build/. + fs::current_path(fs::current_path() / "tests" / "FlatpakTestsRaw" / "fixture"); + std::error_code ec; + fs::remove_all("bin", ec); + fs::remove_all("build", ec); + + Configuration project; + project.path = "./"; + project.name = "flatpak-tests-raw"; + project.outputName = "flatpak-tests-raw"; + project.target = HostTarget(); + { + std::array ifaces = { "tests/hello/Hello" }; + project.AddTest("hello", ifaces); + } + project.tests.back().config.packaging = Packaging::Flatpak; + + RunTestsOptions opts; + opts.jobs = 1; + const TestSummary summary = RunTests(project, opts); + + Check(summary.results.size() == 1, std::format("one test ran, got {}", summary.results.size())); + if (!summary.results.empty()) { + const TestResult& result = summary.results.front(); + Check(result.outcome == TestOutcome::Pass, std::format("the test passes (exit {}): {}", result.exitCode, result.output)); + Check(result.output.contains("hello from a test"), "the output is the program's own"); + } + const Configuration& test = project.tests.back().config; + Check(test.ResolvedPackaging() == Packaging::None, "the test is built as linked"); + Check(!fs::exists(test.BinDir() / "files") && fs::is_regular_file(test.BinDir() / "hello"), "its bin directory holds the program, and no Flatpak files/"); + + // As `crafter-build lint` loads the project afresh: the test asks for a + // Flatpak again, and main.cpp, which imports Hello, parses against the + // PCMs the test run built. + project.tests.back().config.packaging = Packaging::Flatpak; + std::size_t parsed = 0; + project.AddAstLintRule("parses", [&parsed](LintContext&) { ++parsed; }); + const LintSummary lint = RunLint(project, RunLintOptions{}); + Check(lint.errors == 0 && parsed == 2, std::format("lint parses the test's two files against those PCMs ({} errors, {} parsed)", lint.errors, parsed)); + + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} diff --git a/tests/FlatpakToolchainLibrary/fixture/main.cpp b/tests/FlatpakToolchainLibrary/fixture/main.cpp new file mode 100644 index 0000000..4eb5ae0 --- /dev/null +++ b/tests/FlatpakToolchainLibrary/fixture/main.cpp @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; + +// A function of libedit, called only on a path that never runs, so that the +// link records the library. +extern "C" void* history_init(); + +int main(int argc, char**) { + if (argc > 100) history_init(); + std::println("linked against libedit"); + return 0; +} diff --git a/tests/FlatpakToolchainLibrary/main.cpp b/tests/FlatpakToolchainLibrary/main.cpp new file mode 100644 index 0000000..b42724c --- /dev/null +++ b/tests/FlatpakToolchainLibrary/main.cpp @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +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; + } + } + + // The NEEDED entries of an ELF file, by the toolchain's llvm-readelf. + std::set Needed(const fs::path& readelf, const fs::path& file) { + const auto r = RunCommandWithTimeout(std::format("{} --needed-libs {}", ShellQuote(readelf.string()), ShellQuote(file.string())), std::chrono::seconds(30)); + std::set names; + bool inList = false; + std::istringstream lines(r.output); + for (std::string line; std::getline(lines, line);) { + const std::size_t first = line.find_first_not_of(" \t"); + const std::string t = first == std::string::npos ? std::string() : line.substr(first); + if (!inList) { + inList = t.starts_with("NeededLibraries ["); + continue; + } + if (t == "]") break; + if (!t.empty()) names.insert(t); + } + return names; + } +} + +// A program packaged as a Flatpak carries what its link takes from the +// toolchain's own lib dir, which the Flatpak link searches with -L. In +// crafter-build's Flatpak that is /app/lib, which holds libclang, libLLVM, +// liblldb and libedit beside the LLVM runtime libraries, none of them a +// runtime's. The writer used to look only in the directories of the shared +// libraries the program is built on and took any other name for the +// runtime's, so a program linked against one of those started under -r, +// where crafter-build's own /app/lib is on the loader's path, and failed +// once installed. The fixture links libedit. Skips where the toolchain is in +// /usr, whose lib dir is the system's, and where its lib dir has no libedit. +int main() { + const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-toolchain-library"; + 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 Toolchain& tc = GetToolchain(); + if (NormalizeTarget(tc.hostTriple) != "x86_64-linux-gnu") { + std::println(std::cerr, "SKIP: the staged runtime is x86_64 and the host is {}", tc.hostTriple); + return 77; + } + if (!tc.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 toolchainLib = tc.LibcxxLibDir(); + if (toolchainLib.empty()) { + std::println(std::cerr, "SKIP: the toolchain is in /usr, whose libraries are the system's"); + return 77; + } + if (!fs::exists(toolchainLib / "libedit.so")) { + std::println(std::cerr, "SKIP: the toolchain's lib dir, {}, has no libedit.so", toolchainLib.string()); + return 77; + } + + const fs::path fixture = fs::current_path() / "tests" / "FlatpakToolchainLibrary" / "fixture"; + fs::remove_all(fixture / "bin", ec); + fs::remove_all(fixture / "build", ec); + Configuration app; + app.path = fixture; + app.name = "toolchain-library-app"; + app.outputName = "edit"; + app.target = HostTarget(); + app.packaging = Packaging::Flatpak; + app.flatpak.appId = "net.example.ToolchainLibrary"; + app.linkFlags = { "-ledit" }; + { + std::array ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + } + { + std::unordered_map> 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 fs::path lib = app.BinDir() / "files" / "lib"; + const std::set needed = Needed(tc.llvmReadelf, ExpectedOutput(app)); + const auto edit = std::ranges::find_if(needed, [](const std::string& name) { return name.starts_with("libedit.so"); }); + Check(edit != needed.end(), std::format("the program needs libedit (NEEDED: {})", needed)); + if (edit != needed.end()) { + Check(fs::exists(toolchainLib / *edit), std::format("{} is the toolchain's, in {}", *edit, toolchainLib.string())); + Check(fs::is_regular_file(lib / *edit), std::format("{} is carried in files/lib", *edit)); + } + // Whatever the program and the libraries it carries need from the + // toolchain's lib dir is carried too. + std::set all = needed; + for (const fs::directory_entry& entry : fs::directory_iterator(lib)) all.merge(Needed(tc.llvmReadelf, entry.path())); + for (const std::string& name : all) { + if (fs::exists(toolchainLib / name)) Check(fs::exists(lib / name), std::format("{}, from the toolchain's lib dir, is carried in files/lib", name)); + } + + fs::remove_all(scratch, ec); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +} diff --git a/tests/SharedLibraryRuns/main.cpp b/tests/SharedLibraryRuns/main.cpp index 380dc9d..f935099 100644 --- a/tests/SharedLibraryRuns/main.cpp +++ b/tests/SharedLibraryRuns/main.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +#include import std; import Crafter.Build; namespace fs = std::filesystem; @@ -67,11 +68,20 @@ namespace { // An executable built on a LibraryDynamic dependency starts: the loader // finds lib.so, which the executable's link took from the library's -// bin dir, through the run path the link records for that directory. -// Before, the link took the library and recorded nowhere to find it, so the -// program failed at start with "cannot open shared object file". +// bin dir. Linked as it is, the executable records that directory as a run +// path; packaged as a Flatpak, it carries the library in files/lib, where +// its run path looks. Before, the link took the library and recorded +// nowhere to find it, so the program failed at start with "cannot open +// shared object file", raw and packaged alike. int main() { + const fs::path scratch = fs::temp_directory_path() / "crafter-build-shared-library-runs"; 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" / "SharedLibraryRuns" / "fixture"; fs::remove_all(fixture / "bin", ec); fs::remove_all(fixture / "build", ec); @@ -108,8 +118,24 @@ int main() { const std::string comma = FromCommaDirectory(fixture); Check(comma.empty(), std::format("built from a directory whose name holds a comma, it starts: {}", comma)); const auto raw = RunCommandWithTimeout(ShellQuote(ExpectedOutput(app).string()), std::chrono::seconds(30)); - Check(raw.exitCode == 0 && raw.output.contains("hello from a shared library"), std::format("the program starts (exit {}): {}", raw.exitCode, raw.output)); + Check(raw.exitCode == 0 && raw.output.contains("hello from a shared library"), std::format("linked as it is, it starts (exit {}): {}", raw.exitCode, raw.output)); + if (NormalizeTarget(GetToolchain().hostTriple) == "x86_64-linux-gnu" && GetToolchain().libcxxDir.empty()) { + app.packaging = Packaging::Flatpak; + if (const std::string failed = BuildIt(app); !failed.empty()) { + std::println(std::cerr, "FAIL: the Flatpak build failed: {}", failed); + return 1; + } + Check(fs::is_regular_file(app.BinDir() / "files" / "lib" / "libgreet.so"), "the Flatpak carries the library in files/lib"); + const auto packaged = RunCommandWithTimeout(ShellQuote(ExpectedOutput(app).string()), std::chrono::seconds(30)); + Check(packaged.exitCode == 0 && packaged.output.contains("hello from a shared library"), std::format("packaged as a Flatpak, it starts (exit {}): {}", packaged.exitCode, packaged.output)); + } else if (!GetToolchain().libcxxDir.empty()) { + std::println("the Flatpak half is left out: CRAFTER_BUILD_LIBCXX_DIR is set, and a build against it is no Flatpak"); + } else { + std::println("the Flatpak half is left out: the staged runtime is x86_64 and the host is {}", GetToolchain().hostTriple); + } + + fs::remove_all(scratch, ec); if (Failures > 0) { std::println(std::cerr, "{} assertions failed", Failures); return 1; diff --git a/tests/StandardArgs/main.cpp b/tests/StandardArgs/main.cpp index 5024908..3a21241 100644 --- a/tests/StandardArgs/main.cpp +++ b/tests/StandardArgs/main.cpp @@ -69,6 +69,29 @@ int main() { ApplyStandardArgs(cfg, raw); Check(cfg.type == ConfigurationType::Executable, "--shared alone on Executable is a no-op"); } + { + // --packaging= is standard: it sets cfg.packaging and, its effect + // showing in VariantId already, stays out of projectArgs. Outside any + // project file, as here, it counts as the top-level project's. + Configuration flatpak; + std::array raw = { "--packaging=flatpak" }; + ApplyStandardArgs(flatpak, raw); + Check(flatpak.packaging == Packaging::Flatpak, "--packaging=flatpak asks for a Flatpak"); + Check(flatpak.projectArgs.empty(), "--packaging= is not a project arg"); + Configuration none; + std::array rawNone = { "--packaging=none" }; + ApplyStandardArgs(none, rawNone); + Check(none.packaging == Packaging::None, "--packaging=none asks for the executable as linked"); + Configuration bad; + std::array rawBad = { "--packaging=snap" }; + bool threw = false; + try { + ApplyStandardArgs(bad, rawBad); + } catch (const std::invalid_argument& e) { + threw = std::string_view(e.what()).contains("expected none or flatpak"); + } + Check(threw, "an unknown --packaging= is an error naming the kinds"); + } // ArgQuery is returned over the same args span and exposes Has/Get. { diff --git a/tests/ToolchainResolve/main.cpp b/tests/ToolchainResolve/main.cpp index d92a1c8..2ef5abf 100644 --- a/tests/ToolchainResolve/main.cpp +++ b/tests/ToolchainResolve/main.cpp @@ -215,6 +215,33 @@ int main() { Check(!real.Key().starts_with("unknown-"), std::format("the real clang version parses (got '{}')", real.Key())); } + { + // The runtime crafter-build runs on is the runtime= ref in + // /.flatpak-info's [Application] group: what a packaged program + // links against, and so the runtime it is packaged for. + ToolchainInputs in; + in.flatpakInfo = "[Application]\nname=net.catcrafts.CrafterBuild\nruntime=runtime/org.freedesktop.Sdk/x86_64/26.08\n\n[Instance]\nruntime=runtime/org.example.Other/aarch64/1\n"; + const Toolchain tc = ResolveToolchain(in); + Check(tc.flatpakArch == "x86_64" && tc.flatpakBranch == "26.08", std::format("the runtime's arch and branch are read (got '{}' '{}')", tc.flatpakArch, tc.flatpakBranch)); + Check(ResolveToolchain({}).flatpakBranch.empty(), "outside a Flatpak there is no runtime"); + ToolchainInputs elsewhere; + elsewhere.flatpakInfo = "[Instance]\nruntime=runtime/org.freedesktop.Sdk/x86_64/26.08\n"; + Check(ResolveToolchain(elsewhere).flatpakBranch.empty(), "a runtime= outside [Application] is not the runtime"); + ToolchainInputs malformed; + malformed.flatpakInfo = "[Application]\nruntime=org.freedesktop.Sdk/26.08\n"; + Check(ResolveToolchain(malformed).flatpakBranch.empty(), "a runtime= that is not a runtime ref is ignored"); + + // llvm-readelf, which reads what a packaged program needs, sits + // beside the compiler like llvm-ar; LibcxxSearchFlags is the link + // flags without the rpath a Flatpak does not use. + Check(ResolveToolchain({}).llvmReadelf == "llvm-readelf", "the PATH fallback names llvm-readelf bare"); + ToolchainInputs prefixed; + prefixed.env.emplace("CRAFTER_BUILD_LLVM_DIR", full.string()); + const Toolchain withPrefix = ResolveToolchain(prefixed); + Check(withPrefix.llvmReadelf == full / "bin" / "llvm-readelf", "llvm-readelf comes from the prefix"); + Check(withPrefix.LibcxxSearchFlags() == std::format(" -L{}", (full / "lib").string()), std::format("the search flags are -L alone (got '{}')", withPrefix.LibcxxSearchFlags())); + } + fs::remove_all(scratch, ec); return Failures == 0 ? 0 : 1; } diff --git a/tests/VariantId/main.cpp b/tests/VariantId/main.cpp index 0b4472d..5293e60 100644 --- a/tests/VariantId/main.cpp +++ b/tests/VariantId/main.cpp @@ -46,6 +46,33 @@ int main() { b.type = ConfigurationType::LibraryStatic; Check(a.VariantId() != b.VariantId(), "type change perturbs VariantId"); } + { + // A Flatpak lays its bin dir out unlike the executable as linked, so + // the two get directories of their own. Only a Flatpak is keyed: + // Default and None, and a library whatever it asks for, keep the + // directory they had, and what the app is installed as changes + // files/share only, never what is compiled. + Configuration plain = MakeBase(); + Configuration none = MakeBase(); + none.packaging = Packaging::None; + Configuration flatpak = MakeBase(); + flatpak.packaging = Packaging::Flatpak; + Configuration described = MakeBase(); + described.packaging = Packaging::Flatpak; + described.flatpak.appId = "net.example.Described"; + described.flatpak.desktopFile = "app.desktop"; + described.flatpak.icons = {"icon.svg"}; + Configuration library = MakeBase(); + library.type = ConfigurationType::LibraryStatic; + Configuration flatpakLibrary = MakeBase(); + flatpakLibrary.type = ConfigurationType::LibraryStatic; + flatpakLibrary.packaging = Packaging::Flatpak; + Check(plain.VariantId() == none.VariantId(), "Default and None share a directory"); + Check(plain.VariantId() != flatpak.VariantId(), "a Flatpak gets a directory of its own"); + Check(flatpak.VariantId() == described.VariantId(), "the app-id, desktop entry and icons do not move the directory"); + Check(library.VariantId() == flatpakLibrary.VariantId(), "a library ignores packaging"); + Check(flatpak.ProgramDir() == flatpak.BinDir() / "files" / "bin" && plain.ProgramDir() == plain.BinDir(), "a Flatpak's program lives in files/bin, everything else's in the bin dir"); + } { // debug differs -> VariantId differs. Configuration a = MakeBase(); diff --git a/tests/WasiBrowserRuntime/main.cpp b/tests/WasiBrowserRuntime/main.cpp index 9f0fe27..9cc0dcb 100644 --- a/tests/WasiBrowserRuntime/main.cpp +++ b/tests/WasiBrowserRuntime/main.cpp @@ -45,6 +45,14 @@ int main() { return 77; // skipped — environmental, not a code defect } + // Assets go into files.json under the names Build() writes them as: a + // texture or mesh compressed (an upper-case extension too), a file of a + // directory entry under the directory's name, passed through as it is. + fs::create_directories(cfg.path / "maps" / "a"); + std::ofstream(cfg.path / "maps" / "a" / "b.jpg") << ""; + std::ofstream(cfg.path / "maps" / "mod.json") << "{}"; + cfg.assets = { cfg.path / "tex.PNG", cfg.path / "mesh.obj", cfg.path / "maps" }; + EnableWasiBrowserRuntime(cfg); // Three files registered: runtime.js, generated index.html, files.json. @@ -86,6 +94,17 @@ int main() { return 1; } + { + std::ifstream fin(*manifest); + const std::string fjson{std::istreambuf_iterator(fin), std::istreambuf_iterator()}; + for (const std::string_view name : {"\"tex.ctex\"", "\"mesh.cmesh\"", "\"maps/a/b.ctex\"", "\"maps/mod.json\""}) { + if (!fjson.contains(name)) { + std::println(std::cerr, "files.json lacks {}, the name the build writes the asset as: {}", name, fjson); + return 1; + } + } + } + // With no declared variants, variants.json is a single baseline entry // pointing at outputName.wasm, with only the probes for what every wasm // build needs, SIMD128 and exception handling, so that runtime.js can