feat: install and bundle a Flatpak through the host's flatpak

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

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

The host's flatpak and flatpak-builder are reached only through
HostCommand in :Platform, which builds the command lines of
RunHostFlatpak, RunHostFlatpakBuilder and HostFlatpakUnavailable's
probes: flatpak-spawn --host --watch-bus inside crafter-build's Flatpak,
started in the host's / and passing FLATPAK_USER_DIR on, and the command
itself natively. flatpak-spawn would otherwise start a command in
crafter-build's own working directory, which the host need not have, and
from /app, say, every host command would fail. HostFlatpakUnavailable
says why the host cannot be reached: no org.freedesktop.Flatpak
permission, no session bus (CI's build sandbox has neither), a host that
does not see the project's bin/ and build/ where crafter-build does, as
it does not in the sandbox's own /tmp, /var, /usr, /etc and /app or
where a link leads into one, or no flatpak natively. That, and an
executable that is not packaged as a Flatpak, install and bundle refuse
as soon as the project is loaded, before anything is built;
FlatpakVerbRefusal shows the second. The host is asked rather than the
sandbox's paths modelled, which an override sharing a directory inside
the sandbox's own would defeat: its flatpak is started in a directory
just made in each of bin/ and build/ under a name no other has, which it
enters only where it sees that very directory, and the directory is
removed again. --help gets a section on both, and its Clean section says
the repo an install points at goes with build/. FlatpakModules runs
flatpak-builder only with a flatpak-builder program on the host,
crafter-build falling back to the org.flatpak.Builder app, whose
`flatpak run` would write ~/.var/app in the real home, and with the
Platform and Sdk it builds the app with. The library's install function
is InstallFlatpakApp because project.cpp files define an InstallFlatpak
script of their own under `using namespace Crafter`, this repository's
included, and a library InstallFlatpak would make the name an overload
set, which the scripts table's std::function cannot be built from;
BundleFlatpakApp is named to match. JsonQuote writes the manifest's
strings, and variants.json's, which escaped quotes and backslashes only.
FlatpakExport, FlatpakManifestText, ExportFlatpak and FlatpakPermission,
which only :Clang uses, stay out of the API a project.cpp compiles
against, as RecordFlatpakPlaced does, so their names cannot meet a
project's own under `using namespace Crafter`; ExportFlatpak's comment
names the app's lock, which its callers hold, beside
HostFlatpakUnavailable.
This commit is contained in:
Jorijn van der Graaf 2026-11-02 19:38:30 +01:00
commit eff250abb7
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
30 changed files with 1436 additions and 24 deletions

View file

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

View file

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

View file

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

View file

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

View file

@ -20,6 +20,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.flatpak.appId = "net.example.Packaged";
cfg.flatpak.metainfo = "packaging/packaged.metainfo.xml";
cfg.flatpak.icons = { "packaging/icon.svg" };
cfg.flatpak.modules = { "packaging/extra.json" };
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
cfg.GetInterfacesAndImplementations(ifaces, impls);

View file

@ -75,6 +75,10 @@ int main() {
// builds it.
Configuration& packaged = *cfg.dependencies[1];
Check(packaged.packaging == Packaging::Flatpak, "the sibling that packages itself is a Flatpak");
// The loader takes a project file where its links lead, as
// fs::canonical does, whatever the temp directory goes through.
const std::string module = std::format("\"{}\"", (fs::canonical(scratch) / "packaged" / "packaging" / "extra.json").string());
Check(FlatpakManifest(packaged).contains(module), std::format("its manifest names its own module file, {}", module));
if (NormalizeTarget(GetToolchain().hostTriple) == "x86_64-linux-gnu" && GetToolchain().libcxxDir.empty()) {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,118 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
}
// With cfg.flatpak.modules, flatpak-builder makes the app from a manifest
// crafter-build writes: the app-id, the runtime at crafter-build's branch,
// the command and the finish-args, from the fields an app without modules
// is finished with; translations kept in the app, where a bundle carries
// them, rather than split off into a .Locale extension; the project's
// module files, by absolute path; and last a module that copies the
// build's files/, so the program crafter-build linked is what ships and
// nothing is compiled twice. The manifest is checked everywhere; where the host has a
// flatpak-builder program, the app it builds holds what the extra module
// installs as well as the program.
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-modules";
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" / "FlatpakModules" / "fixture";
fs::remove_all(fixture / "bin", ec);
fs::remove_all(fixture / "build", ec);
Configuration app;
app.path = fixture;
app.name = "modules-app";
app.outputName = "modules";
app.target = HostTarget();
app.packaging = Packaging::Flatpak;
app.flatpak.appId = "net.example.Modules";
app.flatpak.permissions = { "--share=network" };
app.flatpak.modules = { fixture / "extra.json" };
{
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
}
{
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
if (const BuildResult r = Build(app, depResults, depMutex); !r.result.empty()) {
std::println(std::cerr, "FAIL: build failed: {}", r.result);
return 1;
}
}
const std::string manifest = FlatpakManifest(app);
for (const std::string& part : {
std::string("\"app-id\": \"net.example.Modules\""),
std::string("\"runtime\": \"org.freedesktop.Platform\""),
std::string("\"runtime-version\": \"26.08\""),
std::string("\"sdk\": \"org.freedesktop.Sdk\""),
std::string("\"command\": \"modules\""),
std::string("\"separate-locales\": false"),
std::string("\"--share=network\""),
std::format("\"{}\"", (fixture / "extra.json").string()),
std::string("\"cp -a . /app/\""),
std::format("\"{}\"", fs::absolute(app.BinDir() / "files").lexically_normal().string()),
}) {
Check(manifest.contains(part), std::format("the manifest has {}:\n{}", part, manifest));
}
Check(manifest.find("extra.json") < manifest.find("cp -a . /app/"), "the project's modules come before the program's");
// Only with a flatpak-builder program on the host. Where there is none,
// crafter-build runs the org.flatpak.Builder app instead, and `flatpak
// run` writes ~/.var/app/org.flatpak.Builder in the real home, which a
// test must not touch. Inside crafter-build's Flatpak this looks in the
// sandbox, which has none, so that half is left to the native run. And
// only where the host has the Platform and the Sdk of the branch, which
// flatpak-builder makes the app with: without them it fails, which says
// nothing about the manifest.
const std::string why = HostFlatpakUnavailable(fixture);
const bool builder = why.empty() && std::system("command -v flatpak-builder > /dev/null 2>&1") == 0;
const bool runtimes = builder && RunHostFlatpak("info --show-ref org.freedesktop.Platform//26.08") == 0 && RunHostFlatpak("info --show-ref org.freedesktop.Sdk//26.08") == 0;
if (runtimes) {
const std::string bundled = BundleFlatpakApp(app);
Check(bundled.empty(), std::format("flatpak-builder makes the app: {}", bundled));
const fs::path built = FlatpakAppDir(app) / "build-dir" / "files";
Check(fs::is_regular_file(built / "share" / "extra" / "extra.txt"), "the app holds what the extra module installs");
Check(fs::is_regular_file(built / "bin" / "modules") && fs::is_regular_file(built / "lib" / "libc++.so.1"), "and the program with its libraries");
} else {
std::println("only the manifest is checked: {}", !why.empty() ? why : !builder ? "the host has no flatpak-builder program, and the org.flatpak.Builder app would be run with flatpak run" : "the host lacks org.freedesktop.Platform//26.08 or org.freedesktop.Sdk//26.08");
}
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

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

View file

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

View file

@ -0,0 +1,158 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
std::string ReadFile(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
// The elements of a list key of `metadata`'s [Context], in any order:
// build-finish writes them in an order of its own.
std::set<std::string> ContextList(const std::string& metadata, std::string_view key) {
std::set<std::string> elements;
bool inContext = false;
std::istringstream lines(metadata);
for (std::string line; std::getline(lines, line);) {
if (line.starts_with("[")) {
inContext = line == "[Context]";
continue;
}
if (!inContext || !line.starts_with(std::format("{}=", key))) continue;
std::istringstream values(line.substr(key.size() + 1));
for (std::string element; std::getline(values, element, ';');) {
if (!element.empty()) elements.insert(element);
}
}
return elements;
}
}
// The sandbox's permissions are finish-args, as a project spells them, and
// flatpak build-finish is what reads them. `crafter-build install` and
// `bundle` hand it those of the executable's dependencies first and the
// executable's own last, so it can take one back, in the manifest
// flatpak-builder takes for an app with modules as for one without. The
// build itself does not read them: changing them links nothing and writes
// no metadata. Where the host's flatpak can be run, a bundle's metadata
// holds what build-finish made of them, and a permission it does not know
// fails the bundle rather than install the app without a word; elsewhere,
// as in flatpak-builder's build sandbox, where CI runs the suite, that half
// is left out.
int main() {
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-permissions";
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" / "FlatpakPermissions" / "fixture";
fs::remove_all(fixture / "bin", ec);
fs::remove_all(fixture / "build", ec);
fs::remove_all(fixture / "lib" / "bin", ec);
fs::remove_all(fixture / "lib" / "build", ec);
auto lib = std::make_unique<Configuration>();
lib->path = fixture / "lib";
lib->name = "perm-lib";
lib->outputName = "perm";
lib->target = HostTarget();
lib->type = ConfigurationType::LibraryStatic;
lib->flatpak.permissions = {"--socket=wayland", "--socket=x11", "--device=dri"};
{
std::array<fs::path, 1> ifaces = { "Perm" };
std::array<fs::path, 0> impls = {};
lib->GetInterfacesAndImplementations(ifaces, impls);
}
Configuration app;
app.path = fixture;
app.name = "perm-app";
app.outputName = "perm-app";
app.target = HostTarget();
app.packaging = Packaging::Flatpak;
app.dependencies = { lib.get() };
app.flatpak.appId = "net.example.Permissions";
app.flatpak.permissions = {"--nosocket=x11", "--share=network"};
{
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
app.GetInterfacesAndImplementations(ifaces, impls);
}
const auto build = [&]() {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
return Build(app, depResults, depMutex).result;
};
if (const std::string failed = build(); !failed.empty()) {
std::println(std::cerr, "FAIL: build failed: {}", failed);
return 1;
}
// In the order build-finish gets them, the library's before the app's.
const std::string manifest = FlatpakManifest(app);
std::size_t at = 0;
for (const std::string_view argument : {"--socket=wayland", "--socket=x11", "--device=dri", "--nosocket=x11", "--share=network"}) {
const std::size_t found = manifest.find(std::format("\"{}\"", argument), at);
Check(found != std::string::npos, std::format("{} is handed on, after what comes before it:\n{}", argument, manifest));
if (found != std::string::npos) at = found;
}
const std::string variant = app.VariantId();
const fs::path program = ExpectedOutput(app);
const fs::file_time_type linked = fs::last_write_time(program);
app.flatpak.permissions.push_back("--socket=pulseaudio");
if (const std::string failed = build(); !failed.empty()) {
std::println(std::cerr, "FAIL: the second build failed: {}", failed);
return 1;
}
Check(app.VariantId() == variant, "changing a permission does not move the build to another directory");
Check(fs::last_write_time(program) == linked, "and links nothing");
Check(!fs::exists(app.BinDir() / "metadata"), "and the build writes no metadata, which build-finish does");
Check(FlatpakManifest(app).contains("\"--socket=pulseaudio\""), "a permission added since is handed on");
if (const std::string why = HostFlatpakUnavailable(fixture); !why.empty()) {
std::println("what build-finish makes of them is left out: {}", why);
} else {
const std::string bundled = BundleFlatpakApp(app);
Check(bundled.empty(), std::format("the app is bundled: {}", bundled));
const std::string metadata = ReadFile(FlatpakAppDir(app) / "build-dir" / "metadata");
Check(ContextList(metadata, "sockets") == std::set<std::string>{"wayland", "!x11", "pulseaudio"}, std::format("the library's sockets reach the app, which takes x11 back:\n{}", metadata));
Check(ContextList(metadata, "devices") == std::set<std::string>{"dri"} && ContextList(metadata, "shared") == std::set<std::string>{"network"}, std::format("and its device and share:\n{}", metadata));
Check(metadata.contains("\ncommand=perm-app\n"), std::format("the program is the command:\n{}", metadata));
app.flatpak.permissions.push_back("--socket=sound");
const std::string refused = BundleFlatpakApp(app);
Check(refused.contains("flatpak build-finish failed") && refused.contains("listed above"), std::format("a socket build-finish does not know fails the bundle: {}", refused));
}
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

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

View file

@ -0,0 +1,21 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
using namespace Crafter;
// An executable that is not packaged as a Flatpak, which a build would
// compile as linked.
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
Configuration cfg;
cfg.path = "./";
cfg.name = "raw-app";
cfg.outputName = "raw-app";
cfg.type = ConfigurationType::Executable;
ApplyStandardArgs(cfg, args);
std::array<std::filesystem::path, 0> interfaces = {};
std::array<std::filesystem::path, 1> implementations = { "main" };
cfg.GetInterfacesAndImplementations(interfaces, implementations);
return cfg;
}

View file

@ -0,0 +1,65 @@
// 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;
}
}
}
// `crafter-build install` and `bundle` refuse what they cannot export before
// anything is built: whether the project's executable is packaged as a
// Flatpak, and whether the host's flatpak can be reached, is known once the
// project is loaded. Refused after the build, the likely first try,
// `install` in a project that sets no packaging, would compile the whole
// project into a directory nothing exports, and the retry with
// --packaging=flatpak into another. The fixture is an executable that is
// not packaged: Run() refuses both verbs, saying why, and no bin/ appears.
int main() {
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 the project
// file it compiles.
const fs::path scratch = fs::temp_directory_path() / "crafter-build-flatpak-verb-refusal";
std::error_code ec;
fs::remove_all(scratch, ec);
fs::copy(fs::current_path() / "tests" / "FlatpakVerbRefusal" / "fixture", scratch, fs::copy_options::recursive);
// From the project's own directory, as crafter-build runs it.
const fs::path cwd = fs::current_path();
fs::current_path(scratch);
for (const std::string_view verb : {"install", "bundle"}) {
std::string tool = "crafter-build";
std::string word(verb);
std::array<char*, 2> argv = { tool.data(), word.data() };
std::ostringstream err;
std::streambuf* const saved = std::cerr.rdbuf(err.rdbuf());
const std::int32_t status = Run(static_cast<std::int32_t>(argv.size()), argv.data());
std::cerr.rdbuf(saved);
Check(status == 1, std::format("{} refuses (exit {}): {}", verb, status, err.str()));
Check(err.str().contains("is not packaged as a Flatpak"), std::format("{} says why: {}", verb, err.str()));
Check(!fs::exists(scratch / "bin"), std::format("{} refuses before anything is built: there is no bin/", verb));
}
fs::current_path(cwd);
fs::remove_all(scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

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

140
tests/HostFlatpak/main.cpp Normal file
View file

@ -0,0 +1,140 @@
// 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;
}
}
std::string ReadFile(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
}
// crafter-build reaches the host's flatpak through one helper, and says why
// when it cannot. Inside its Flatpak that needs the org.freedesktop.Flatpak
// permission and a session bus, which flatpak-builder's build sandbox, where
// CI runs this suite, has neither of; and a host that sees the project's
// bin/ and build/ where crafter-build does, which the host is asked: it sees
// the fixture, in the home, and not a project in the sandbox's own /tmp, nor
// one a link in the home leads there. Every host command starts in the
// host's /: one started in crafter-build's working directory failed
// wherever the host has none such, /app for one. Natively the flatpak on
// PATH is the host's. Installing or bundling an executable that is not
// packaged as a Flatpak is refused, naming what to set, before the host is
// involved.
int main() {
const fs::path fixture = fs::current_path() / "tests" / "HostFlatpak" / "fixture";
// Whatever the question makes in the fixture, it removes again.
const auto probesLeft = [&] {
std::error_code ec;
for (const std::string_view sub : {"bin", "build"}) {
if (!fs::is_directory(fixture / sub, ec)) continue;
for (const fs::directory_entry& entry : fs::directory_iterator(fixture / sub)) {
if (entry.path().filename().string().starts_with(".crafter-build-host-probe-")) return true;
}
}
return false;
};
std::error_code ec;
fs::remove_all(fixture / "bin", ec);
fs::remove_all(fixture / "build", ec);
const std::string why = HostFlatpakUnavailable(fixture);
if (fs::exists("/.flatpak-info")) {
const std::string info = ReadFile("/.flatpak-info");
const bool permitted = info.contains("org.freedesktop.Flatpak=talk");
if (!permitted) {
Check(why.contains("org.freedesktop.Flatpak"), std::format("without the permission, the reason names it: {}", why));
} else {
Check(why.empty(), std::format("the host sees the fixture, in the home, where crafter-build does: {}", why));
Check(!fs::exists(fixture / "bin") && !fs::exists(fixture / "build"), "and asking leaves nothing in the fixture, which had no bin/ or build/");
}
// A project in the sandbox's own /tmp, a tmpfs nothing outside the
// sandbox sees, which goes with it; and one reached through a link
// in the fixture's build/, in the home, that leads there, which the
// host follows to its own /tmp. Both are made for the question and
// removed again. Where an override shares the host's /tmp with the
// sandbox, the host sees both, so they are left out.
bool tmpShared = false;
for (std::size_t at = info.find("filesystems="); at != std::string::npos && !tmpShared;) {
const std::size_t end = info.find('\n', at);
const std::string line = info.substr(at, end == std::string::npos ? std::string::npos : end - at);
for (std::size_t begin = std::string_view("filesystems=").size(); begin < line.size();) {
std::size_t next = line.find(';', begin);
if (next == std::string::npos) next = line.size();
const std::string entry = line.substr(begin, next - begin);
if (entry == "/tmp" || entry.starts_with("/tmp:")) tmpShared = true;
begin = next + 1;
}
at = info.find("filesystems=", at + 1);
}
const fs::path link = fixture / "build" / "to-tmp";
fs::create_directories(link.parent_path(), ec);
fs::remove(link, ec);
fs::create_directory_symlink("/tmp", link, ec);
const std::array<fs::path, 2> unseen = {"/tmp/crafter-build-host-flatpak", link / "crafter-build-host-flatpak-linked"};
for (const fs::path& project : unseen) {
if (tmpShared) {
std::println("an override shares the host's /tmp with the sandbox, so the host sees {}: left out", project.string());
continue;
}
if (!permitted) {
const std::string refused = HostFlatpakUnavailable(project);
Check(refused.contains("org.freedesktop.Flatpak"), std::format("and so is one at {}, for the same reason: {}", project.string(), refused));
continue;
}
fs::create_directories(project, ec);
const std::string refused = HostFlatpakUnavailable(project);
Check(refused.contains("the host does not see") && refused.contains((project / "bin").string()), std::format("inside the Flatpak, a project at {} is refused, saying why: {}", project.string(), refused));
Check(fs::is_empty(project, ec), std::format("and asking leaves nothing in {}", project.string()));
fs::remove_all(fs::weakly_canonical(project, ec), ec);
}
// From a working directory only the sandbox has, the host is reached
// all the same, and sees the fixture.
if (permitted) {
const fs::path before = fs::current_path();
fs::current_path("/app");
const std::string fromApp = HostFlatpakUnavailable(fixture);
Check(fromApp.empty(), std::format("from /app, which only the sandbox has, the host sees the fixture: {}", fromApp));
Check(RunHostFlatpak("--version") == 0, "and the host's flatpak runs from there");
fs::current_path(before);
}
Check(!probesLeft(), "asking leaves no directory of its own in the fixture's bin/ or build/");
} else if (std::system("command -v flatpak > /dev/null 2>&1") == 0) {
Check(why.empty(), std::format("natively, the flatpak on PATH is reachable: {}", why));
Check(RunHostFlatpak("--version") == 0, "and runs");
} else {
Check(why.contains("flatpak"), std::format("without flatpak, the reason says so: {}", why));
}
Configuration raw;
raw.path = fixture;
raw.name = "raw-app";
raw.outputName = "raw";
raw.target = HostTarget();
raw.packaging = Packaging::None;
{
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
raw.GetInterfacesAndImplementations(ifaces, impls);
}
Check(InstallFlatpakApp(raw).contains("cfg.packaging = Packaging::Flatpak"), std::format("installing an executable that is no Flatpak says what to set: {}", InstallFlatpakApp(raw)));
Check(BundleFlatpakApp(raw).contains("cfg.packaging = Packaging::Flatpak"), std::format("bundling one says the same: {}", BundleFlatpakApp(raw)));
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}

View file

@ -51,7 +51,8 @@ int main() {
// 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.
// files/share and what install and bundle make of it, never what is
// compiled.
Configuration plain = MakeBase();
Configuration none = MakeBase();
none.packaging = Packaging::None;
@ -62,6 +63,9 @@ int main() {
described.flatpak.appId = "net.example.Described";
described.flatpak.desktopFile = "app.desktop";
described.flatpak.icons = {"icon.svg"};
described.flatpak.runtime = FlatpakRuntime::Sdk;
described.flatpak.permissions = {"--socket=wayland"};
described.flatpak.modules = {"packaging/extra.json"};
Configuration library = MakeBase();
library.type = ConfigurationType::LibraryStatic;
Configuration flatpakLibrary = MakeBase();
@ -69,7 +73,7 @@ int main() {
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(flatpak.VariantId() == described.VariantId(), "the app-id, desktop entry, icons, runtime, permissions and modules 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");
}