diff --git a/AGENTS.template.md b/AGENTS.template.md index f6fd70e..09e39e5 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -121,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, 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. +- 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 what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory. ## Design rules diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index eb805be..d65465e 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -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 PermissionsOf(const Configuration& config) { + std::vector permissions; + std::unordered_set seen; + std::function 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= '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(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 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//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-; 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"); diff --git a/implementations/Crafter.Build-External.cpp b/implementations/Crafter.Build-External.cpp index 89500a5..5a3d395 100644 --- a/implementations/Crafter.Build-External.cpp +++ b/implementations/Crafter.Build-External.cpp @@ -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; } diff --git a/implementations/Crafter.Build-Flatpak.cpp b/implementations/Crafter.Build-Flatpak.cpp index 7af4851..8b52ea7 100644 --- a/implementations/Crafter.Build-Flatpak.cpp +++ b/implementations/Crafter.Build-Flatpak.cpp @@ -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 .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 ""; +} diff --git a/implementations/Crafter.Build-Platform.cpp b/implementations/Crafter.Build-Platform.cpp index 6e3fa61..dc4953c 100644 --- a/implementations/Crafter.Build-Platform.cpp +++ b/implementations/Crafter.Build-Platform.cpp @@ -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(c) < 0x20) out += std::format("\\u{:04x}", static_cast(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(file)), std::istreambuf_iterator()); + 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 diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index a70e42a..19a7047 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -496,7 +496,9 @@ export namespace Crafter { // 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. + // What it is installed as when it is packaged as a Flatpak, and the + // sandbox permissions any configuration may declare for the + // executables built on it. FlatpakApp flatpak; std::vector> interfaces; std::vector implementations; @@ -743,6 +745,29 @@ export namespace Crafter { // disagree about the file name. fs::path ExpectedOutput(const Configuration& config); + // `crafter-build install`: makes the Flatpak of the files/ `config` was + // built as (see Packaging::Flatpak), with its permissions, puts it into + // the project's repo, and installs it for this user from a user remote + // named after the app-id, updating what an earlier install left. The + // host's flatpak does the work (see HostFlatpakUnavailable and + // ExportFlatpak). Returns why it could not; empty when it did. + std::string InstallFlatpakApp(const Configuration& config); + // `crafter-build bundle`: the same export, then a single-file bundle at + // FlatpakBundlePath(config) that `flatpak install --user ` takes + // on any machine, fetching the runtime from Flathub where it is missing. + std::string BundleFlatpakApp(const Configuration& config); + // bin/.flatpak, beside the bin dir it is made from. + fs::path FlatpakBundlePath(const Configuration& config); + // build/flatpak-apps/, where install and bundle keep the app's + // repo and the build directory they finish it in, and with modules the + // manifest and flatpak-builder's state. One per app rather than per + // variant: the state is flatpak-builder's cache, and under a variant's + // name every module would be built again after each compiler update. + fs::path FlatpakAppDir(const Configuration& config); + // The manifest flatpak-builder makes the app from when cfg.flatpak has + // modules (FlatpakManifestText). + std::string FlatpakManifest(const Configuration& config); + // The clang invocation every C++ translation unit in this Configuration is // compiled with, before anything that depends on work having happened // (dependency public flags, external dependency flags — Build appends diff --git a/interfaces/Crafter.Build-Flatpak.cppm b/interfaces/Crafter.Build-Flatpak.cppm index 55f6748..10faa57 100644 --- a/interfaces/Crafter.Build-Flatpak.cppm +++ b/interfaces/Crafter.Build-Flatpak.cppm @@ -5,17 +5,44 @@ 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. +// An executable packaged as a Flatpak: what a project declares about it, the +// files/ Build() lays out for it, which becomes /app in the app's sandbox, +// and what `crafter-build install` and `bundle` hand the host's flatpak to +// make the app of it. Everything here works on plain data; Build() and those +// verbs gather it from the Configuration, so this partition knows nothing of +// one. export namespace Crafter { + // The runtime an executable packaged as a Flatpak runs on. Its branch is + // always the one crafter-build itself runs on: the program is linked + // against that Sdk's glibc, which the Platform of the same branch carries + // as well, and an older runtime's glibc would not load it. + enum class FlatpakRuntime { + // org.freedesktop.Platform: what a program needs to run. + Platform, + // org.freedesktop.Sdk, for a program that runs tools at run time that + // the Platform does not have, git for one. + Sdk, + }; + // What an executable packaged as a Flatpak is installed as. Read for an - // executable whose Configuration::packaging makes it one. + // executable whose Configuration::packaging makes it one, except + // `permissions`, which every configuration may declare: a library's + // reach each executable built on it. struct FlatpakApp { // The application ID, reverse-DNS. Empty means // DefaultFlatpakAppId(outputName). std::string appId; + FlatpakRuntime runtime = FlatpakRuntime::Platform; + // The sandbox's permissions, spelled as Flatpak's finish-args are: + // "--socket=wayland", "--device=dri", "--filesystem=xdg-documents:ro". + // An executable gets those of its dependencies first and its own + // last, and flatpak takes a later one over an earlier one for the + // same socket, device, path or bus name, so "--nosocket=x11" takes + // back what a library granted. `crafter-build install` and `bundle` + // print the resulting list, naming where each came from, and hand + // it to the host's flatpak build-finish, which refuses one it does + // not know. The build itself does not read them. + std::vector permissions; // 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; @@ -24,6 +51,14 @@ export namespace Crafter { // 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; + // flatpak-builder module files, in Flatpak's own format (JSON or + // YAML), for what the app needs in /app besides the program: a + // runtime it starts, a tool it runs, data built from source. With + // any, `crafter-build install` and `bundle` have flatpak-builder make + // the app from a manifest that lists them and copies the program in + // last, so the program is not compiled again. crafter-build only + // names them; flatpak-builder reads them. + std::vector modules; }; // local.crafterbuild.: no published application uses the @@ -95,4 +130,58 @@ namespace Crafter { // 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); + + // For :Clang's install and bundle alone, kept out of the API a + // project.cpp compiles against, so that the names cannot meet one of its + // own under `using namespace Crafter`. + + // A permission and the configuration that declared it. + struct FlatpakPermission { + std::string argument; + std::string source; + }; + + // What `crafter-build install` and `bundle` hand the host's flatpak, + // gathered from the Configuration like FlatpakFiles. Paths are absolute: + // the host runs the commands from its /. + struct FlatpakExport { + // BinDir()/files, as WriteFlatpakFiles left it. + fs::path files; + // /build/flatpak-apps/: the repo, the build + // directory the app is finished in, and with modules the manifest + // and flatpak-builder's state. One per app rather than per variant, + // because the state is flatpak-builder's cache, and a variant-keyed + // path would build every module again after each compiler update. + fs::path work; + std::string appId; + std::string command; + FlatpakRuntime runtime = FlatpakRuntime::Platform; + // The arch and branch of the runtime crafter-build runs on, from its + // /.flatpak-info: the app's runtime and Sdk are at the same. + std::string arch; + std::string branch; + // The executable's dependencies' first, its own last. + std::vector permissions; + std::vector modules; + }; + // The manifest flatpak-builder makes an app with modules from: the + // app-id, runtime, sdk, command and finish-args, the project's modules, + // and last a module that copies files/ into /app as it is. + std::string FlatpakManifestText(const FlatpakExport& app); + // Makes the app on the host and puts it into work/repo. Without modules, + // the host's flatpak build-finish finishes work/build-dir, made afresh + // each time from a metadata naming the app, its runtime and the Sdk and + // a copy of files/, hard links where they can be made: it writes the + // command and the sandbox's permissions into the metadata, and export/, + // by flatpak's own rules, and refuses a permission it does not know. + // flatpak build-export then puts that into the repo. With modules, + // flatpak-builder makes the app from FlatpakManifestText, written to + // work/.json, and runs build-finish itself. Either way the + // permissions are printed first, with where each came from, so a + // refusal can be traced to the configuration that declared it. + // Returns why it could not; empty when it did. HostFlatpakUnavailable is + // the caller's to check first, and the lock on work/ that + // InstallFlatpakApp and BundleFlatpakApp take is the caller's to hold: + // every variant of the app exports into the one repo. + std::string ExportFlatpak(const FlatpakExport& app); } diff --git a/interfaces/Crafter.Build-Platform.cppm b/interfaces/Crafter.Build-Platform.cppm index 88207c4..dbdc64d 100644 --- a/interfaces/Crafter.Build-Platform.cppm +++ b/interfaces/Crafter.Build-Platform.cppm @@ -61,6 +61,37 @@ namespace Crafter { // `s` as one single-quoted sh word, safe to splice into a command line // whatever it contains: paths with spaces, arguments a user typed. export std::string ShellQuote(std::string_view s); + // `s` as a JSON string, quotes included, whatever it contains: what a + // generated manifest or variants.json writes for a path or an argument. + std::string JsonQuote(std::string_view s); + // Why crafter-build cannot run the host's flatpak for a project in + // `projectDir`; empty when it can. Natively that is the flatpak on PATH. + // Inside crafter-build's Flatpak it takes the org.freedesktop.Flatpak + // permission, a session bus to reach the host's Flatpak session helper + // over (flatpak-builder's build sandbox, where CI runs, has neither), and + // a host that sees the project's bin/ and build/ where crafter-build + // does, which it does not in the sandbox's own /tmp, /var, /usr, /etc or + // /app: the host's flatpak is started in a directory made in each for + // it, so bin/ and build/ are made where they are missing. + export std::string HostFlatpakUnavailable(const fs::path& projectDir); + // Runs `flatpak ` on the host with the terminal attached, + // after echoing it as ScriptContext::Run does, and returns its exit + // code. Inside crafter-build's Flatpak it goes through flatpak-spawn + // --host --watch-bus, so the host command ends when flatpak-spawn does, + // starts it in the host's /, whatever crafter-build's working directory, + // and passes FLATPAK_USER_DIR on when it is set. crafter-build's own code + // reaches the host only through HostCommand, the builder of host command + // lines this shares with RunHostFlatpakBuilder and HostFlatpakUnavailable's + // probes, for the host's flatpak and flatpak-builder; add no other host + // command (AGENTS.md, Security considerations). The permission is the + // sandbox's, not this function's: anything else that runs there, a + // project.cpp among them, can use it through flatpak-spawn --host + // without this. Exported for the tests. Host commands have no terminal + // of their own, so `arguments` must not need one to answer a prompt. + export std::int32_t RunHostFlatpak(std::string_view arguments); + // `flatpak-builder ` the same way: the host's flatpak-builder, + // or the org.flatpak.Builder app where the host has none. + std::int32_t RunHostFlatpakBuilder(std::string_view arguments); std::string GetBaseCommand(const Configuration& config); export Configuration LoadProject(const fs::path& projectFile, std::span args); // A dependency the project file currently running its CrafterBuildProject diff --git a/project.cpp b/project.cpp index 976d76d..fb99112 100644 --- a/project.cpp +++ b/project.cpp @@ -291,6 +291,13 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("FlatpakIncremental").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("FlatpakLibraryChange").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("FlatpakDesktop").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("HostFlatpak").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("FlatpakBundle").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("FlatpakPermissions").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("FlatpakInstall").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("FlatpakModules").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("FlatpakVerbRefusal").Dependencies({ CrafterBuildLib.get() }) + .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); cfg.AddTest("WasmExceptions").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasiSysrootWithoutExceptions").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("WasmBuildRefusals").Dependencies({ CrafterBuildLib.get() }); diff --git a/tests/FlatpakBundle/fixture/main.cpp b/tests/FlatpakBundle/fixture/main.cpp new file mode 100644 index 0000000..9ff5dc9 --- /dev/null +++ b/tests/FlatpakBundle/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("bundled"); + return 0; +} diff --git a/tests/FlatpakBundle/main.cpp b/tests/FlatpakBundle/main.cpp new file mode 100644 index 0000000..f26a089 --- /dev/null +++ b/tests/FlatpakBundle/main.cpp @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +#include +#include +#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()); + } + + // Every file under `root` with its size and mtime. + std::map> Snapshot(const fs::path& root) { + std::map> 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") << "\n"; + app.flatpak.desktopFile = scratch / "app.desktop"; + app.flatpak.icons = { scratch / "icon.svg" }; + { + 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 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 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; +} diff --git a/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/extra.json b/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/extra.json new file mode 100644 index 0000000..d51e0e7 --- /dev/null +++ b/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/extra.json @@ -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" } + ] +} diff --git a/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/extra.txt b/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/extra.txt new file mode 100644 index 0000000..3a9acc0 --- /dev/null +++ b/tests/FlatpakDependencyExecutable/fixture/packaged/packaging/extra.txt @@ -0,0 +1 @@ +installed by a module of the project's own diff --git a/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp b/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp index 8fe7748..197c3a7 100644 --- a/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp +++ b/tests/FlatpakDependencyExecutable/fixture/packaged/project.cpp @@ -20,6 +20,7 @@ extern "C" Configuration CrafterBuildProject(std::span 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 ifaces = {}; std::array impls = { "main" }; cfg.GetInterfacesAndImplementations(ifaces, impls); diff --git a/tests/FlatpakDependencyExecutable/main.cpp b/tests/FlatpakDependencyExecutable/main.cpp index 94c04e3..6449e5d 100644 --- a/tests/FlatpakDependencyExecutable/main.cpp +++ b/tests/FlatpakDependencyExecutable/main.cpp @@ -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> depResults; std::mutex depMutex; diff --git a/tests/FlatpakInstall/fixture/main.cpp b/tests/FlatpakInstall/fixture/main.cpp new file mode 100644 index 0000000..6d46c16 --- /dev/null +++ b/tests/FlatpakInstall/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("installed"); + return 0; +} diff --git a/tests/FlatpakInstall/main.cpp b/tests/FlatpakInstall/main.cpp new file mode 100644 index 0000000..2e02ab7 --- /dev/null +++ b/tests/FlatpakInstall/main.cpp @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +#include +#include +#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; + } + } +} + +// `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/ 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 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 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 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; +} diff --git a/tests/FlatpakModules/fixture/extra.json b/tests/FlatpakModules/fixture/extra.json new file mode 100644 index 0000000..d51e0e7 --- /dev/null +++ b/tests/FlatpakModules/fixture/extra.json @@ -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" } + ] +} diff --git a/tests/FlatpakModules/fixture/extra.txt b/tests/FlatpakModules/fixture/extra.txt new file mode 100644 index 0000000..3a9acc0 --- /dev/null +++ b/tests/FlatpakModules/fixture/extra.txt @@ -0,0 +1 @@ +installed by a module of the project's own diff --git a/tests/FlatpakModules/fixture/main.cpp b/tests/FlatpakModules/fixture/main.cpp new file mode 100644 index 0000000..96dd0e2 --- /dev/null +++ b/tests/FlatpakModules/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("modules"); + return 0; +} diff --git a/tests/FlatpakModules/main.cpp b/tests/FlatpakModules/main.cpp new file mode 100644 index 0000000..ae0fcd8 --- /dev/null +++ b/tests/FlatpakModules/main.cpp @@ -0,0 +1,118 @@ +// 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; + } + } +} + +// 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 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 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; +} diff --git a/tests/FlatpakPermissions/fixture/lib/Perm.cppm b/tests/FlatpakPermissions/fixture/lib/Perm.cppm new file mode 100644 index 0000000..29288c3 --- /dev/null +++ b/tests/FlatpakPermissions/fixture/lib/Perm.cppm @@ -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; +} diff --git a/tests/FlatpakPermissions/fixture/main.cpp b/tests/FlatpakPermissions/fixture/main.cpp new file mode 100644 index 0000000..bfa65ff --- /dev/null +++ b/tests/FlatpakPermissions/fixture/main.cpp @@ -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; +} diff --git a/tests/FlatpakPermissions/main.cpp b/tests/FlatpakPermissions/main.cpp new file mode 100644 index 0000000..a6ce440 --- /dev/null +++ b/tests/FlatpakPermissions/main.cpp @@ -0,0 +1,158 @@ +// 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()); + } + + // 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 ContextList(const std::string& metadata, std::string_view key) { + std::set 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(); + 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 ifaces = { "Perm" }; + std::array 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 ifaces = {}; + std::array impls = { "main" }; + app.GetInterfacesAndImplementations(ifaces, impls); + } + const auto build = [&]() { + std::unordered_map> 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{"wayland", "!x11", "pulseaudio"}, std::format("the library's sockets reach the app, which takes x11 back:\n{}", metadata)); + Check(ContextList(metadata, "devices") == std::set{"dri"} && ContextList(metadata, "shared") == std::set{"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; +} diff --git a/tests/FlatpakVerbRefusal/fixture/main.cpp b/tests/FlatpakVerbRefusal/fixture/main.cpp new file mode 100644 index 0000000..56ea1ee --- /dev/null +++ b/tests/FlatpakVerbRefusal/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("a raw app"); + return 0; +} diff --git a/tests/FlatpakVerbRefusal/fixture/project.cpp b/tests/FlatpakVerbRefusal/fixture/project.cpp new file mode 100644 index 0000000..10f3cd4 --- /dev/null +++ b/tests/FlatpakVerbRefusal/fixture/project.cpp @@ -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 args) { + Configuration cfg; + cfg.path = "./"; + cfg.name = "raw-app"; + cfg.outputName = "raw-app"; + cfg.type = ConfigurationType::Executable; + ApplyStandardArgs(cfg, args); + std::array interfaces = {}; + std::array implementations = { "main" }; + cfg.GetInterfacesAndImplementations(interfaces, implementations); + return cfg; +} diff --git a/tests/FlatpakVerbRefusal/main.cpp b/tests/FlatpakVerbRefusal/main.cpp new file mode 100644 index 0000000..69ac8ac --- /dev/null +++ b/tests/FlatpakVerbRefusal/main.cpp @@ -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 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(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; +} diff --git a/tests/HostFlatpak/fixture/main.cpp b/tests/HostFlatpak/fixture/main.cpp new file mode 100644 index 0000000..37451f7 --- /dev/null +++ b/tests/HostFlatpak/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("raw"); + return 0; +} diff --git a/tests/HostFlatpak/main.cpp b/tests/HostFlatpak/main.cpp new file mode 100644 index 0000000..7aba938 --- /dev/null +++ b/tests/HostFlatpak/main.cpp @@ -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(in), std::istreambuf_iterator()); + } +} + +// 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 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 ifaces = {}; + std::array 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; +} diff --git a/tests/VariantId/main.cpp b/tests/VariantId/main.cpp index 5293e60..f751ef2 100644 --- a/tests/VariantId/main.cpp +++ b/tests/VariantId/main.cpp @@ -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"); }