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

@ -626,6 +626,26 @@ namespace {
return std::nullopt;
}
std::string AppIdOf(const Configuration& config) {
return config.flatpak.appId.empty() ? DefaultFlatpakAppId(config.outputName) : config.flatpak.appId;
}
// The sandbox's permissions as the executable gets them: a dependency's
// dependencies before it, each once, and the executable's own last, so
// it has the last word.
std::vector<FlatpakPermission> PermissionsOf(const Configuration& config) {
std::vector<FlatpakPermission> permissions;
std::unordered_set<const Configuration*> seen;
std::function<void(const Configuration*)> walk = [&](const Configuration* c) {
if (!seen.insert(c).second) return;
for (const Configuration* dep : c->dependencies) walk(dep);
for (const std::string& permission : c->flatpak.permissions) permissions.push_back({permission, c->name});
};
for (const Configuration* dep : config.dependencies) walk(dep);
for (const std::string& permission : config.flatpak.permissions) permissions.push_back({permission, config.name});
return permissions;
}
// 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
@ -642,7 +662,7 @@ namespace {
FlatpakFiles d;
d.root = config.BinDir();
d.record = FlatpakRecordPath(config);
d.appId = config.flatpak.appId.empty() ? DefaultFlatpakAppId(config.outputName) : config.flatpak.appId;
d.appId = AppIdOf(config);
d.command = ExpectedOutput(config).filename().string();
d.desktopFile = config.flatpak.desktopFile;
d.metainfo = config.flatpak.metainfo;
@ -1613,6 +1633,132 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
return buildResult;
}
namespace {
FlatpakExport ExportOf(const Configuration& config) {
FlatpakExport app;
app.files = fs::absolute(config.BinDir() / "files").lexically_normal();
app.appId = AppIdOf(config);
app.work = fs::absolute(FlatpakAppDir(config)).lexically_normal();
app.command = ExpectedOutput(config).filename().string();
app.runtime = config.flatpak.runtime;
app.arch = GetToolchain().flatpakArch;
app.branch = GetToolchain().flatpakBranch;
app.permissions = PermissionsOf(config);
for (const fs::path& module : config.flatpak.modules) app.modules.push_back(fs::absolute(module).lexically_normal());
return app;
}
// Why `verb` cannot export `config`, from the loaded Configuration and
// the host alone, so that Run() refuses before anything is built; empty
// when it can.
std::string ExportRefusal(const Configuration& config, std::string_view verb) {
if (config.ResolvedPackaging() != Packaging::Flatpak) {
return std::format("crafter-build {}: {} is not packaged as a Flatpak; set cfg.packaging = Packaging::Flatpak in project.cpp, or, where it calls ApplyStandardArgs, pass --packaging=flatpak", verb, config.name);
}
if (const std::string why = HostFlatpakUnavailable(config.path); !why.empty()) return std::format("crafter-build {}: {}", verb, why);
return "";
}
// ExportRefusal, or a build that is not there to export.
std::string CannotExport(const Configuration& config, std::string_view verb) {
if (const std::string refused = ExportRefusal(config, verb); !refused.empty()) return refused;
if (!fs::exists(ExpectedOutput(config))) return std::format("crafter-build {}: {} is not built yet", verb, config.name);
return "";
}
// A repo's path as the file:// URL of a remote: percent-encoded, since
// `remote-modify --url=` stores what it is given as it is.
std::string FileUrl(const fs::path& path) {
std::string url = "file://";
for (const char c : path.string()) {
const bool plain = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || std::string_view("/-._~").contains(c);
if (plain) url.push_back(c);
else url += std::format("%{:02X}", static_cast<std::uint8_t>(c));
}
return url;
}
// Every variant of an app exports into its one repo, FlatpakAppDir(), so
// another crafter-build exporting a variant between an export and the
// install or bundle made from it would have that install or bundle the
// other's program. Both hold this lock from the export on.
FileLock AppDirLock(const fs::path& work) {
std::error_code ec;
fs::create_directories(work, ec);
return FileLock(work / ".lock");
}
}
std::string Crafter::InstallFlatpakApp(const Configuration& config) {
if (const std::string refused = CannotExport(config, "install"); !refused.empty()) return refused;
const FlatpakExport app = ExportOf(config);
const FileLock lock = AppDirLock(app.work);
if (const std::string failed = ExportFlatpak(app); !failed.empty()) return failed;
// A remote of its own, re-pointed at this project's repo each time: the
// same app-id built in another checkout would otherwise go on updating
// from that one's, and --if-not-exists would keep it silently.
const std::string remote = std::format("crafter-build-{}", app.appId);
const std::string url = ShellQuote(FileUrl(app.work / "repo"));
// The remote is the installation's, shared by every checkout that builds
// this app-id, so re-pointing it and installing from it hold a lock of
// their own: another checkout's install would otherwise re-point it
// between this one's remote-modify and install. Every crafter-build that
// installs there has to take the same lock, native or in the Flatpak,
// with whatever XDG_CACHE_HOME it runs, so the lock follows the
// installation and not the cache: a private one, FLATPAK_USER_DIR, holds
// it, one lock for all of them where the sandbox shares that directory
// with the host, and for the user's own, which flatpak hides from
// crafter-build's sandbox behind a tmpfs of the sandbox's own, it is in
// ~/.cache by HOME.
const fs::path base = [] {
if (const char* userDir = std::getenv("FLATPAK_USER_DIR"); userDir && *userDir) return fs::path(userDir);
if (const char* home = std::getenv("HOME"); home && *home) return fs::path(home) / ".cache";
return fs::path();
}();
if (base.empty()) return "crafter-build install: neither FLATPAK_USER_DIR nor HOME is set, and the lock on the user's remote is found by one of them";
const fs::path locks = base / "crafter.build" / "flatpak-remotes";
std::error_code ec;
fs::create_directories(locks, ec);
const FileLock remoteLock(locks / std::format("{}.lock", remote));
if (RunHostFlatpak(std::format("remote-add --user --if-not-exists --no-gpg-verify {} {}", ShellQuote(remote), url)) != 0) return std::format("crafter-build install: adding the remote {} failed", remote);
if (RunHostFlatpak(std::format("remote-modify --user --url={} {}", url, ShellQuote(remote))) != 0) return std::format("crafter-build install: pointing the remote {} at the repo failed", remote);
if (RunHostFlatpak(std::format("install --user --noninteractive --or-update {} {}", ShellQuote(remote), ShellQuote(app.appId))) != 0) return std::format("crafter-build install: installing {} failed", app.appId);
if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) {
std::println("\nInstalled {0}: `flatpak run {0}` starts it.\nThe remote {1} points into build/, which `crafter-build clean` deletes; remove both with\n flatpak uninstall --user {0}\n flatpak remote-delete --user {1}", app.appId, remote);
}
return "";
}
std::string Crafter::BundleFlatpakApp(const Configuration& config) {
if (const std::string refused = CannotExport(config, "bundle"); !refused.empty()) return refused;
const FlatpakExport app = ExportOf(config);
const FileLock lock = AppDirLock(app.work);
if (const std::string failed = ExportFlatpak(app); !failed.empty()) return failed;
const fs::path bundle = fs::absolute(FlatpakBundlePath(config)).lexically_normal();
// The runtime's repository goes into the bundle, so a machine without
// the Platform fetches it from Flathub on install instead of refusing.
if (RunHostFlatpak(std::format("build-bundle --runtime-repo=https://dl.flathub.org/repo/flathub.flatpakrepo {} {} {}", ShellQuote((app.work / "repo").string()), ShellQuote(bundle.string()), ShellQuote(app.appId))) != 0) {
return std::format("crafter-build bundle: flatpak build-bundle failed for {}", app.appId);
}
if (config.march == "native") {
Progress::Diagnostic(std::format("{} is built with -march=native, so it may stop with SIGILL on a CPU older than this one; for others, build with --march=x86-64-v3", bundle.string()));
}
if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) std::println("\nBundled {} as {}: `flatpak install --user {}` installs it.", app.appId, bundle.string(), bundle.filename().string());
return "";
}
fs::path Crafter::FlatpakBundlePath(const Configuration& config) {
return config.BinDir().parent_path() / std::format("{}.flatpak", config.VariantId());
}
fs::path Crafter::FlatpakAppDir(const Configuration& config) {
return config.BuildDir().parent_path() / "flatpak-apps" / AppIdOf(config);
}
std::string Crafter::FlatpakManifest(const Configuration& config) {
return FlatpakManifestText(ExportOf(config));
}
void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) {
fs::path runtimeDir = GetCrafterBuildHome() / "wasi-runtime";
fs::path runtimeJs = runtimeDir / "runtime.js";
@ -1738,14 +1884,6 @@ void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) {
// driver); the baseline maps to outputName.wasm. Even with no declared
// variants we still emit a one-entry manifest so the runtime has a
// single, uniform code path.
auto jsonEscape = [](std::string_view s) {
std::string out;
for (char c : s) {
if (c == '"' || c == '\\') out += '\\';
out += c;
}
return out;
};
fs::path variantsPath = htmlOutDir / "variants.json";
{
std::ofstream v(variantsPath);
@ -1759,12 +1897,12 @@ void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) {
: std::format("{}.{}.wasm", cfg.outputName, label);
std::vector<std::string> probes = ownProbes;
probes.insert(probes.end(), WasmBaselineProbes.begin(), WasmBaselineProbes.end());
v << "{\"label\":\"" << jsonEscape(label) << "\""
<< ",\"url\":\"" << jsonEscape(url) << "\""
v << "{\"label\":" << JsonQuote(label)
<< ",\"url\":" << JsonQuote(url)
<< ",\"probes\":[";
for (std::size_t i = 0; i < probes.size(); ++i) {
if (i) v << ",";
v << "\"" << jsonEscape(probes[i]) << "\"";
v << JsonQuote(probes[i]);
}
v << "]}";
};
@ -1939,6 +2077,8 @@ R"(Usage:
{0} lint [lint-options] [globs...] Run the project's lint rules over its sources
{0} format [format-options] [globs...] Apply the project's transform rules (rewrites files)
{0} run [script [args...]] Run a script the project defines, or list them
{0} install [options] Build a project packaged as a Flatpak and install it for this user
{0} bundle [options] Build a project packaged as a Flatpak into a .flatpak file
{0} clean Delete the project's bin/ and build/ trees
{0} help | -h | --help Show this help
{0} --version Print the version and the compiler in use
@ -2015,10 +2155,29 @@ Run (after the `run` subcommand):
crafter-build was started from. Only the scripts of the project being run
are available, never a dependency's.
Install and bundle (after the `install` or `bundle` subcommand):
Both need the project's executable packaged as a Flatpak (cfg.packaging =
Packaging::Flatpak, or --packaging=flatpak where project.cpp calls
ApplyStandardArgs), and refuse before building when it is not, or when the
host's flatpak cannot be reached. They build the project, have the host's
flatpak build-finish make the app of its files/ with the permissions, which
it refuses where it does not know one, and export it into the project's
repo, build/flatpak-apps/<app-id>/repo, with flatpak build-export, or have
flatpak-builder do both when cfg.flatpak.modules names modules. install
installs it for this user from the remote crafter-build-<app-id>; bundle
writes it into a single .flatpak file beside its bin directory, for
`flatpak install --user`, naming Flathub's repository for the runtime. Both
run the host's flatpak, inside crafter-build's Flatpak through
flatpak-spawn --host, and refuse a project whose bin/ and build/ the host
does not see where crafter-build does, as in the sandbox's own /tmp, /var,
/usr, /etc and /app, which they ask the host before building.
Clean (after the `clean` subcommand):
Removes bin/ and build/ next to the project file. Does not load project.cpp,
so it works when the project itself no longer compiles. Every target, variant
and dependency artifact under those trees goes with it.
and dependency artifact under those trees goes with it, and so does the repo
an app from `install` is installed from: remove the app and its remote
first, as install says how.
AGENTS.md:
When an AGENTS.template.md sits beside the project file, a build and a test
@ -2064,7 +2223,8 @@ Environment:
Exit status:
0 success / all non-skipped tests passed / lint clean / format applied
1 build failure, one or more tests failed, lint findings, no rules defined,
format write errors, or `format --check` found files that would change
format write errors, `format --check` found files that would change, or
`install` or `bundle` was refused or its export, install or bundle failed
`run` exits with the status its script returned, and with 1 when there is no
such script, when the script throws, or when it returns a value outside 0..255
)", argv0);
@ -2082,7 +2242,7 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) {
// build without one. A verb word after it is an operand of that one
// (`test lint` runs the tests that match "lint", `run test` runs the
// script called test) or a project arg, never a second verb.
enum class Verb { Build, Test, Lint, Format, Clean, Run };
enum class Verb { Build, Test, Lint, Format, Clean, Run, Install, Bundle };
Verb verb = Verb::Build;
bool runAfterBuild = false;
RunTestsOptions testOpts;
@ -2142,6 +2302,10 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) {
lintOpts.mode = LintMode::Apply;
} else if (verb == Verb::Build && arg == "run") {
verb = Verb::Run;
} else if (verb == Verb::Build && arg == "install") {
verb = Verb::Install;
} else if (verb == Verb::Build && arg == "bundle") {
verb = Verb::Bundle;
} else if (verb == Verb::Run && arg == "--list") {
scriptOpts.listOnly = true;
} else if (verb == Verb::Format && arg == "--check") {
@ -2222,6 +2386,16 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) {
return lintOpts.mode == LintMode::Check && !lintSummary.changedFiles.empty() ? 1 : 0;
}
// What install and bundle cannot export they refuse here, before
// anything is built: a project that is not packaged as a Flatpak, or
// a host flatpak out of reach, is known from the loaded project.
if (verb == Verb::Install || verb == Verb::Bundle) {
if (const std::string refused = ExportRefusal(config, verb == Verb::Install ? "install" : "bundle"); !refused.empty()) {
std::println(std::cerr, "{}", refused);
return 1;
}
}
// Builds and test runs only: lint and `format --check` promise to
// write nothing, `format` rewrites the project's sources and nothing
// else, `run` is for chores and `test --list` only lists. Here,
@ -2247,6 +2421,13 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) {
Progress::Finalize();
if (verb == Verb::Install || verb == Verb::Bundle) {
const std::string failed = verb == Verb::Install ? InstallFlatpakApp(config) : BundleFlatpakApp(config);
if (failed.empty()) return 0;
std::println(std::cerr, "{}", failed);
return 1;
}
if (runAfterBuild) {
if (config.type != ConfigurationType::Executable) {
std::println(std::cerr, "-r: cannot run a library");

View file

@ -374,6 +374,7 @@ namespace {
if (!cfg.flatpak.desktopFile.empty()) cfg.flatpak.desktopFile = abs(cfg.flatpak.desktopFile);
if (!cfg.flatpak.metainfo.empty()) cfg.flatpak.metainfo = abs(cfg.flatpak.metainfo);
for (fs::path& p : cfg.flatpak.icons) p = abs(p);
for (fs::path& p : cfg.flatpak.modules) p = abs(p);
return cfg;
}

View file

@ -378,3 +378,113 @@ std::string Crafter::WriteFlatpakFiles(const FlatpakFiles& d) {
}
return "";
}
std::string Crafter::FlatpakManifestText(const FlatpakExport& app) {
std::string finishArgs;
for (const FlatpakPermission& permission : app.permissions) {
finishArgs += std::format("{}\n {}", finishArgs.empty() ? "" : ",", JsonQuote(permission.argument));
}
std::string modules;
for (const fs::path& module : app.modules) modules += std::format(" {},\n", JsonQuote(module.string()));
// The program's module is named apart from anything a project would
// call one of its own: module names are flatpak-builder's cache keys.
// "separate-locales": false keeps /app/share/locale in the app. By
// default flatpak-builder moves it into an <app-id>.Locale extension,
// which an install fetches with the app but a bundle, which holds the
// app alone, leaves out.
return std::format(
"{{\n"
" \"app-id\": {},\n"
" \"runtime\": {},\n"
" \"runtime-version\": {},\n"
" \"sdk\": \"org.freedesktop.Sdk\",\n"
" \"command\": {},\n"
" \"separate-locales\": false,\n"
" \"finish-args\": [{}{}],\n"
" \"modules\": [\n"
"{}"
" {{\n"
" \"name\": \"crafter-build-program\",\n"
" \"buildsystem\": \"simple\",\n"
" \"build-commands\": [ \"cp -a . /app/\" ],\n"
" \"sources\": [ {{ \"type\": \"dir\", \"path\": {} }} ]\n"
" }}\n"
" ]\n"
"}}\n",
JsonQuote(app.appId),
app.runtime == FlatpakRuntime::Sdk ? "\"org.freedesktop.Sdk\"" : "\"org.freedesktop.Platform\"",
JsonQuote(app.branch),
JsonQuote(app.command),
finishArgs, finishArgs.empty() ? "" : "\n ",
modules,
JsonQuote(app.files.string()));
}
namespace {
// `from` again at `to`: hard links where they can be made, copies where
// they cannot, links as links. flatpak build-finish and build-export
// read files/ and write nothing into it, so a link costs no copy of the
// app's data and leaves the build's files as they are. A link fails
// across filesystems, and on one that has none, vfat or exFAT on a USB
// stick say, with another error; whatever the reason, the copy is made
// instead, and a failure it shares, a full disk say, shows there.
void LinkOrCopyTree(const fs::path& from, const fs::path& to) {
try {
fs::copy(from, to, fs::copy_options::recursive | fs::copy_options::create_hard_links | fs::copy_options::copy_symlinks);
} catch (const fs::filesystem_error&) {
fs::remove_all(to);
fs::copy(from, to, fs::copy_options::recursive | fs::copy_options::copy_symlinks);
}
}
}
std::string Crafter::ExportFlatpak(const FlatpakExport& app) {
// On every install and bundle: the build does not read them, and
// build-finish names only the argument it refuses, not the
// configuration it came from.
if (!app.permissions.empty()) {
std::string report = std::format("{} has these Flatpak permissions:", app.appId);
for (const FlatpakPermission& permission : app.permissions) report += std::format("\n {} (from {})", permission.argument, permission.source);
Progress::Diagnostic(report);
}
try {
fs::create_directories(app.work);
const fs::path repo = app.work / "repo";
const fs::path buildDir = app.work / "build-dir";
if (app.modules.empty()) {
// Made afresh each time: build-finish refuses a directory it
// finished before, and what a finish wrote, such as the export/
// of a desktop entry the app no longer has, must not reach the
// next one.
fs::remove_all(buildDir);
fs::create_directories(buildDir);
const std::string_view runtime = app.runtime == FlatpakRuntime::Sdk ? "org.freedesktop.Sdk" : "org.freedesktop.Platform";
WriteIfDifferent(buildDir / "metadata", std::format("[Application]\nname={}\nruntime={}/{}/{}\nsdk=org.freedesktop.Sdk/{}/{}\n", app.appId, runtime, app.arch, app.branch, app.arch, app.branch));
LinkOrCopyTree(app.files, buildDir / "files");
// The permissions before --command, so the program stays the
// app's command whatever they hold.
std::string finish = "build-finish";
for (const FlatpakPermission& permission : app.permissions) finish += std::format(" {}", ShellQuote(permission.argument));
finish += std::format(" --command={} {}", ShellQuote(app.command), ShellQuote(buildDir.string()));
if (RunHostFlatpak(finish) != 0) {
return std::format("{}: flatpak build-finish failed{}", app.appId, app.permissions.empty() ? "" : "; the permissions it was given are listed above, with where each came from");
}
if (RunHostFlatpak(std::format("build-export {} {}", ShellQuote(repo.string()), ShellQuote(buildDir.string()))) != 0) {
return std::format("{}: flatpak build-export failed", app.appId);
}
return "";
}
// Written only when it changes, so flatpak-builder sees the same
// manifest, and reuses what it built from it, until it does.
const fs::path manifest = app.work / std::format("{}.json", app.appId);
WriteIfDifferent(manifest, FlatpakManifestText(app));
// --force-clean: the build directory is flatpak-builder's scratch,
// made again from its cache each time; the repo keeps what it
// exported.
const std::string arguments = std::format("--force-clean --state-dir={} --repo={} {} {}", ShellQuote((app.work / "state").string()), ShellQuote(repo.string()), ShellQuote(buildDir.string()), ShellQuote(manifest.string()));
if (RunHostFlatpakBuilder(arguments) != 0) return std::format("{}: flatpak-builder failed on {}", app.appId, manifest.string());
} catch (const std::exception& e) {
return std::format("{}: {}", app.appId, e.what());
}
return "";
}

View file

@ -698,6 +698,118 @@ CommandResult Crafter::RunCommandChecked(std::string_view cmd) {
return result;
}
std::string Crafter::JsonQuote(std::string_view s) {
std::string out = "\"";
for (const char c : s) {
if (c == '"') out += "\\\"";
else if (c == '\\') out += "\\\\";
else if (c == '\n') out += "\\n";
else if (c == '\t') out += "\\t";
else if (c == '\r') out += "\\r";
else if (static_cast<std::uint8_t>(c) < 0x20) out += std::format("\\u{:04x}", static_cast<std::uint8_t>(c));
else out.push_back(c);
}
out.push_back('"');
return out;
}
namespace {
bool InFlatpak() {
std::error_code ec;
return fs::exists("/.flatpak-info", ec);
}
// The command line that runs `program arguments` on the host: as it is
// natively, through the Flatpak session helper inside crafter-build's
// Flatpak, started there in `directory`. flatpak-spawn would start it in
// crafter-build's own working directory, which the host need not have,
// so it is / unless a caller asks for another: every host command names
// its paths absolutely. --watch-bus ends the host command when
// flatpak-spawn ends. A crafter-build killed outright leaves
// flatpak-spawn running, so the host command runs on until it finishes.
// Every host command of crafter-build's own is built here: the host's
// flatpak and flatpak-builder, for RunHostFlatpak, RunHostFlatpakBuilder
// and HostFlatpakUnavailable's probes.
std::string HostCommand(std::string_view program, std::string_view arguments, const fs::path& directory = "/") {
if (!InFlatpak()) return std::format("{} {}", program, arguments);
std::string env;
if (const char* userDir = std::getenv("FLATPAK_USER_DIR"); userDir && *userDir) {
env = std::format(" {}", ShellQuote(std::format("--env=FLATPAK_USER_DIR={}", userDir)));
}
return std::format("flatpak-spawn --host --watch-bus {}{} {} {}", ShellQuote(std::format("--directory={}", directory.string())), env, program, arguments);
}
std::int32_t RunOnHost(std::string_view program, std::string_view arguments, std::string_view shown) {
if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) std::println("$ {} {}", shown, arguments);
return RunCommandAttached(HostCommand(program, arguments));
}
}
std::string Crafter::HostFlatpakUnavailable(const fs::path& projectDir) {
if (!InFlatpak()) {
// Through the shell: `command` is one of its builtins, which the
// `timeout` RunCommandWithTimeout wraps a command in cannot run.
if (RunCommandChecked("command -v flatpak").exitCode != 0) return "flatpak is not installed";
return "";
}
std::ifstream file("/.flatpak-info", std::ios::binary);
const std::string info((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
if (!info.contains("org.freedesktop.Flatpak=talk")) {
return "crafter-build's Flatpak lacks the org.freedesktop.Flatpak permission it runs the host's flatpak with: it is older than that, or runs in a build sandbox";
}
// The program install and bundle run, built as they build theirs, in
// `directory` on the host; and what it said, for a refusal.
const auto probe = [](const fs::path& directory) { return RunCommandWithTimeout(HostCommand("flatpak", "--version", directory), std::chrono::seconds(30)); };
const auto said = [](const CommandResult& result) {
std::string_view output = result.output;
while (!output.empty() && (output.back() == '\n' || output.back() == '\r')) output.remove_suffix(1);
return std::string(output);
};
if (const CommandResult reached = probe("/"); reached.exitCode != 0) {
return std::format("the host cannot be reached through flatpak-spawn --host: {}", said(reached));
}
// install and bundle hand the host's flatpak paths in the project's bin/
// and build/, so the host has to see those where crafter-build does,
// which it does not in the sandbox's own /tmp, /var, /usr, /etc and /app,
// nor where a link leads into one. The host answers for itself, by its
// own links and by whatever the sandbox shares, overrides included: the
// same program, started in a directory just made in each of them under a
// name no other has, starts only where the host sees that very directory,
// not merely a path it has as well, as it has /tmp. What this makes is
// removed again, bin/ and build/ too where they were not there before, so
// a refusal leaves nothing behind in the project's directory, which the
// caller's project.cpp is in.
std::random_device random;
const std::string mark = std::format(".crafter-build-host-probe-{:08x}{:08x}", random(), random());
for (const std::string_view sub : {"bin", "build"}) {
const fs::path dir = fs::absolute(projectDir / sub).lexically_normal();
std::error_code ec;
const bool existed = fs::exists(fs::symlink_status(dir, ec));
fs::create_directories(dir / mark, ec);
if (ec) return std::format("{} cannot be made, to see whether the host sees it: {}", (dir / mark).string(), ec.message());
const CommandResult seen = probe(dir / mark);
fs::remove(dir / mark, ec);
if (!existed) fs::remove(dir, ec);
if (seen.exitCode != 0) {
return std::format("the host does not see {} where crafter-build does ({}): crafter-build's sandbox has /tmp, /var, /usr, /etc and /app of its own, so keep the project, its bin/ and build/ and where their links lead in a directory the sandbox shares with the host, such as your home", dir.string(), said(seen));
}
}
return "";
}
std::int32_t Crafter::RunHostFlatpak(std::string_view arguments) {
return RunOnHost("flatpak", arguments, "flatpak");
}
std::int32_t Crafter::RunHostFlatpakBuilder(std::string_view arguments) {
// flatpak-builder as a host package, else the org.flatpak.Builder app,
// as the self-host's `run flatpak` script finds it.
if (RunCommandWithTimeout(HostCommand("flatpak-builder", "--version"), std::chrono::seconds(30)).exitCode == 0) {
return RunOnHost("flatpak-builder", arguments, "flatpak-builder");
}
return RunOnHost("flatpak", std::format("run org.flatpak.Builder {}", arguments), "flatpak");
}
std::int32_t Crafter::RunCommandAttached(std::string_view cmd) {
// The child writes straight to the terminal. Anything of ours that is
// still pending — the in-place status line, buffered stdout when it is