From 37e6161ccc73c0b0bfd117699e69d1da2735582e Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Mon, 23 Nov 2026 09:46:12 +0100 Subject: [PATCH] Added a build command for local Flatpak builds (#1220) --- .github/workflows/build-and-release.yml | 2 + app/Build/Commands/FlatpakArchitecture.cs | 12 + .../Commands/FlatpakArchitectureExtensions.cs | 53 ++ app/Build/Commands/FlatpakCommand.cs | 817 ++++++++++++++++++ app/Build/Commands/FlatpakSource.cs | 13 + app/Build/Commands/FlatpakSourceExtensions.cs | 44 + app/Build/Flatpak/build-in-container.sh | 256 ++++++ app/Build/Program.cs | 12 +- app/Build/Tools/CapturedOutput.cs | 12 + app/Build/Tools/CommandRunner.cs | 116 ++- documentation/Build.md | 24 + 11 files changed, 1353 insertions(+), 8 deletions(-) create mode 100644 app/Build/Commands/FlatpakArchitecture.cs create mode 100644 app/Build/Commands/FlatpakArchitectureExtensions.cs create mode 100644 app/Build/Commands/FlatpakCommand.cs create mode 100644 app/Build/Commands/FlatpakSource.cs create mode 100644 app/Build/Commands/FlatpakSourceExtensions.cs create mode 100644 app/Build/Flatpak/build-in-container.sh create mode 100644 app/Build/Tools/CapturedOutput.cs diff --git a/.github/workflows/build-and-release.yml b/.github/workflows/build-and-release.yml index 02aaed872..51253bb5d 100644 --- a/.github/workflows/build-and-release.yml +++ b/.github/workflows/build-and-release.yml @@ -362,6 +362,8 @@ jobs: "$tools_dir/uv" --version "$tools_dir/yq" --version + # The build command "flatpak" of app/Build repeats this step for local test builds, in + # app/Build/Flatpak/build-in-container.sh. Whoever changes one of them changes the other one as well. - name: Update Flatpak release sources working-directory: flatpak env: diff --git a/app/Build/Commands/FlatpakArchitecture.cs b/app/Build/Commands/FlatpakArchitecture.cs new file mode 100644 index 000000000..b3e91ad70 --- /dev/null +++ b/app/Build/Commands/FlatpakArchitecture.cs @@ -0,0 +1,12 @@ +namespace Build.Commands; + +/// +/// The CPU architectures for which the Flatpak of AI Studio is built. +/// +public enum FlatpakArchitecture +{ + NONE, + + AARCH64, + X86_64, +} \ No newline at end of file diff --git a/app/Build/Commands/FlatpakArchitectureExtensions.cs b/app/Build/Commands/FlatpakArchitectureExtensions.cs new file mode 100644 index 000000000..9143b91b5 --- /dev/null +++ b/app/Build/Commands/FlatpakArchitectureExtensions.cs @@ -0,0 +1,53 @@ +namespace Build.Commands; + +public static class FlatpakArchitectureExtensions +{ + /// The CPU architecture of the Flatpak. + extension(FlatpakArchitecture architecture) + { + /// + /// The name of the architecture in Flatpak and on Linux, as uname -m reports it. + /// + public string FlatpakName => architecture switch + { + FlatpakArchitecture.AARCH64 => "aarch64", + FlatpakArchitecture.X86_64 => "x86_64", + + _ => string.Empty, + }; + + /// + /// The platform of a Docker image which runs on this architecture. + /// + public string DockerPlatform => architecture switch + { + FlatpakArchitecture.AARCH64 => "linux/arm64", + FlatpakArchitecture.X86_64 => "linux/amd64", + + _ => string.Empty, + }; + + /// + /// The file name of the bundle of AI Studio, the same as the CI of the Flatpak repository gives it. + /// + public string AppBundleName => $"MindWork AI Studio_{architecture.FlatpakName}.flatpak"; + + /// + /// The file name of the bundle of the Pandoc plugin, the same as the CI of the Flatpak repository gives it. + /// + public string PandocBundleName => $"MindWork AI Studio Plugin Pandoc_{architecture.FlatpakName}.flatpak"; + + /// + /// Finds the architecture for a name, as Flatpak, Linux, or Docker write it. + /// + /// The name, e.g., aarch64, arm64, x86_64, or amd64. + /// The architecture, or NONE for an unknown name. + public static FlatpakArchitecture FromName(string name) => name.Trim().ToLowerInvariant() switch + { + "aarch64" or "arm64" => FlatpakArchitecture.AARCH64, + "x86_64" or "amd64" => FlatpakArchitecture.X86_64, + + _ => FlatpakArchitecture.NONE, + }; + } +} \ No newline at end of file diff --git a/app/Build/Commands/FlatpakCommand.cs b/app/Build/Commands/FlatpakCommand.cs new file mode 100644 index 000000000..35f254b40 --- /dev/null +++ b/app/Build/Commands/FlatpakCommand.cs @@ -0,0 +1,817 @@ +using System.Diagnostics; +using System.Formats.Tar; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.RegularExpressions; + +using Build.Tools; + +namespace Build.Commands; + +/// +/// Builds the Flatpak of AI Studio and its Pandoc plugin in Docker, the way the CI of the Flatpak repository does. +/// +/// +/// Neither macOS nor Windows has flatpak-builder. Docker brings the CI image of the Flatpak repository instead, so the +/// build runs alike on every host with Docker, be it Docker Desktop, OrbStack, or Docker on Linux. Files go in and out +/// by docker cp only, never through a bind mount, whose paths and file permissions differ between these hosts. The +/// build lives in a container and a volume of its own, which the command removes at the end, also after a failure or +/// Ctrl+C. The script Flatpak/build-in-container.sh does the work inside the container. +/// +public sealed partial class FlatpakCommand +{ + private const string AI_STUDIO_REPOSITORY = "https://github.com/MindWorkAI/AI-Studio"; + private const string FLATPAK_REPOSITORY = "https://github.com/MindWorkAI/Flatpak"; + private const string MAIN_BRANCH = "refs/heads/main"; + private const string DOCKER_LABEL = "org.mindworkai.build=flatpak"; + private const string CONTAINER_SCRIPT_DIRECTORY = "Flatpak"; + private const string CONTAINER_SCRIPT_NAME = "build-in-container.sh"; + private const string CONTAINER_INPUT_DIRECTORY = "input"; + private const string CONTAINER_CHECKOUT_DIRECTORY = "ai-studio"; + private const string CONTAINER_BUILD_DIRECTORY = "/build"; + private const string CONTAINER_OUTPUT_DIRECTORY = "/out"; + + /// + /// The exit code after Ctrl+C, as shells report a process which SIGINT ended. + /// + private const int CANCELLED_EXIT_CODE = 130; + + private const UnixFileMode EXECUTABLE_MODE =UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute; + private static readonly TimeSpan CONNECT_TIMEOUT = TimeSpan.FromSeconds(30); + private static readonly TimeSpan REQUEST_TIMEOUT = TimeSpan.FromSeconds(60); + + // + // Without a handler of its own, HttpClient waits for a connection without any limit, see Pdfium.cs: + // + private static readonly HttpClient CLIENT = new(new SocketsHttpHandler { ConnectTimeout = CONNECT_TIMEOUT }) + { + Timeout = REQUEST_TIMEOUT + }; + + private readonly Lock cancellationLock = new(); + + private bool isCancelled; + private bool isContainerStarted; + private string containerName = string.Empty; + private string volumeName = string.Empty; + + [GeneratedRegex(@"^\s*image:\s*(\S+)\s*$", RegexOptions.Multiline)] + private static partial Regex WorkflowImageRegex(); + + [GeneratedRegex("^[0-9a-f]{40}$")] + private static partial Regex CommitHashRegex(); + + /// + /// Defines the command "flatpak". + /// + public static Command CreateCommand() + { + var output = new Option("--output", "-o") + { + Description = "The folder for the bundles of AI Studio and its Pandoc plugin, outside the repository, e.g., ~/Downloads/flatpak. The command creates it when it does not exist", + Required = true, + }; + + var source = new Option("--source", "-s") { Description = $"Which state of AI Studio goes into the Flatpak: {string.Join("; ", FlatpakSource.All.Select(candidate => $"{candidate.Name}, {candidate.Description}"))}" }; + source.AcceptOnlyFromAmong([.. FlatpakSource.All.Select(candidate => candidate.Name)]); + + var pullRequest = new Option("--pr", "-p") { Description = "The number of the pull request to build, e.g., 1219; implies --source pr" }; + + var architecture = new Option("--arch", "-a") { Description = "The CPU architecture of the Flatpak, aarch64 or x86_64. Defaults to the one of the Docker host; the other one needs an emulation such as Rosetta and takes much longer" }; + architecture.AcceptOnlyFromAmong(FlatpakArchitecture.AARCH64.FlatpakName, FlatpakArchitecture.X86_64.FlatpakName); + + var command = new Command("flatpak", "Build the Flatpak of AI Studio and its Pandoc plugin in Docker, the way a release builds them. Without --source or --pr, the command asks what to build") { output, source, pullRequest, architecture }; + command.SetAction((parseResult, _) => new FlatpakCommand().BuildFlatpak(parseResult.GetRequiredValue(output), parseResult.GetValue(source), parseResult.GetValue(pullRequest), parseResult.GetValue(architecture))); + return command; + } + + public async Task BuildFlatpak(string output, string? sourceName, int? pullRequestOption, string? architectureName) + { + if (!Environment.IsWorkingDirectoryValid()) + return 1; + + var outputDirectory = PrepareOutputDirectory(output); + if (outputDirectory is null) + return 1; + + Console.WriteLine("=============================="); + Console.WriteLine("- Building the Flatpak of AI Studio in Docker ..."); + + var workingDirectory = Directory.GetCurrentDirectory(); + var dockerVersion = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["version", "--format", "{{.Server.Version}}"]); + if (dockerVersion.ExitCode is CommandRunner.COULD_NOT_START) + return 1; + + if (dockerVersion.ExitCode is not 0) + { + Console.WriteLine("- Error: Docker does not answer. Start Docker, e.g., Docker Desktop or OrbStack, and try again."); + return 1; + } + + // + // The questions come before the command handles Ctrl+C itself: up to here, nothing needs to be cleaned + // up, so Ctrl+C may end the command at once, also while it waits for an answer. + // + var source = DetermineSource(sourceName, pullRequestOption); + if (source is FlatpakSource.NONE) + return 1; + + int? pullRequestNumber = null; + if (source is FlatpakSource.PULL_REQUEST) + { + pullRequestNumber = pullRequestOption ?? AskForPullRequestNumber(); + if (pullRequestNumber is null) + return 1; + + if (pullRequestNumber <= 0) + { + Console.WriteLine($"- Error: {pullRequestNumber} is not the number of a pull request."); + return 1; + } + } + + Console.CancelKeyPress += this.OnCancelKeyPress; + try + { + return await this.BuildInDockerAsync(workingDirectory, dockerVersion.Text.Trim(), outputDirectory, source, pullRequestNumber, architectureName); + } + finally + { + Console.CancelKeyPress -= this.OnCancelKeyPress; + } + } + + private async Task BuildInDockerAsync(string workingDirectory, string dockerVersion, string outputDirectory, FlatpakSource source, int? pullRequestNumber, string? architectureName) + { + var stopwatch = Stopwatch.StartNew(); + var architecture = await DetermineArchitectureAsync(workingDirectory, architectureName); + if (architecture is FlatpakArchitecture.NONE || this.IsCancelled) + return this.ExitCodeAfterFailure; + + string? aiStudioCommit; + var aiStudioDescription = source.Description; + IReadOnlyList localFiles = []; + var repositoryDirectory = Environment.GetRepositoryDirectory(); + switch (source) + { + case FlatpakSource.PULL_REQUEST when pullRequestNumber is { } number: + aiStudioCommit = await ResolveRemoteCommitAsync(workingDirectory, AI_STUDIO_REPOSITORY, $"refs/pull/{number}/head", $"no pull request #{number}"); + if (aiStudioCommit is not null) + aiStudioDescription = await DescribePullRequestAsync(number); + + break; + + case FlatpakSource.LOCAL: + aiStudioCommit = await ReadLocalHeadAsync(repositoryDirectory); + var files = await ListLocalFilesAsync(repositoryDirectory); + if (files is null) + return 1; + + localFiles = files; + aiStudioDescription = await DescribeLocalCheckoutAsync(repositoryDirectory); + break; + + default: + aiStudioCommit = await ResolveRemoteCommitAsync(workingDirectory, AI_STUDIO_REPOSITORY, MAIN_BRANCH, "no branch main"); + break; + } + + if (aiStudioCommit is null || this.IsCancelled) + return this.ExitCodeAfterFailure; + + var flatpakCommit = await ResolveRemoteCommitAsync(workingDirectory, FLATPAK_REPOSITORY, MAIN_BRANCH, "no branch main"); + if (flatpakCommit is null || this.IsCancelled) + return this.ExitCodeAfterFailure; + + var image = await ReadCiImageAsync(flatpakCommit); + if (image is null || this.IsCancelled) + return this.ExitCodeAfterFailure; + + Console.WriteLine($"- Docker {dockerVersion} builds the Flatpak for {architecture.FlatpakName}:"); + Console.WriteLine($" - AI Studio: {aiStudioDescription}, commit {aiStudioCommit}"); + Console.WriteLine($" - Flatpak repository: main of MindWorkAI/Flatpak, commit {flatpakCommit}"); + Console.WriteLine($" - Image: {image}"); + Console.WriteLine($" - Output: {outputDirectory}"); + + await ReportLeftoversAsync(workingDirectory); + + if (await CommandRunner.RunAsync(workingDirectory, "docker", ["pull", "--platform", architecture.DockerPlatform, image]) is not 0 || this.IsCancelled) + { + if (!this.IsCancelled) + Console.WriteLine($"- Error: Docker could not pull the image {image} for {architecture.DockerPlatform}."); + + return this.ExitCodeAfterFailure; + } + + var environment = new Dictionary + { + ["ARCH"] = architecture.FlatpakName, + ["SOURCE"] = source.Name, + ["FLATPAK_URL"] = FLATPAK_REPOSITORY, + ["FLATPAK_COMMIT"] = flatpakCommit, + ["APP_BUNDLE"] = architecture.AppBundleName, + ["PANDOC_BUNDLE"] = architecture.PandocBundleName, + ["BUILD_DIRECTORY"] = CONTAINER_BUILD_DIRECTORY, + ["OUT_DIRECTORY"] = CONTAINER_OUTPUT_DIRECTORY, + }; + + // + // The local checkout has no commit which the container could fetch. The script commits the copied files in + // a repository of its own instead and builds from there: + // + if (source is FlatpakSource.LOCAL) + environment["LOCAL_CHECKOUT"] = $"/{CONTAINER_INPUT_DIRECTORY}/{CONTAINER_CHECKOUT_DIRECTORY}"; + else + { + environment["AI_STUDIO_URL"] = AI_STUDIO_REPOSITORY; + environment["AI_STUDIO_COMMIT"] = aiStudioCommit; + } + + var name = $"aistudio-flatpak-{architecture.FlatpakName}-{DateTime.UtcNow:yyyyMMdd-HHmmss}"; + try + { + var exitCode = await this.BuildInContainerAsync(workingDirectory, name, image, architecture, environment, repositoryDirectory, localFiles, outputDirectory); + if (exitCode is 0) + Console.WriteLine($"- Done after {(int)stopwatch.Elapsed.TotalMinutes} min {stopwatch.Elapsed.Seconds} s."); + + return exitCode; + } + finally + { + await this.RemoveContainerAndVolumeAsync(workingDirectory); + } + } + + private async Task BuildInContainerAsync(string workingDirectory, string name, string image, FlatpakArchitecture architecture, IReadOnlyDictionary environment, string repositoryDirectory, IReadOnlyList localFiles, string outputDirectory) + { + var volume = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["volume", "create", "--label", DOCKER_LABEL, name]); + if (volume.ExitCode is not 0) + { + Console.WriteLine($"- Error: Docker could not create the volume {name}."); + return 1; + } + + lock (this.cancellationLock) + this.volumeName = name; + + List arguments = ["create", "--name", name, "--label", DOCKER_LABEL, "--init", "--privileged", "--platform", architecture.DockerPlatform, "--volume", $"{name}:{CONTAINER_BUILD_DIRECTORY}"]; + foreach (var (key, value) in environment) + arguments.AddRange(["--env", $"{key}={value}"]); + + arguments.AddRange([image, "bash", $"/{CONTAINER_INPUT_DIRECTORY}/{CONTAINER_SCRIPT_NAME}"]); + + var container = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", arguments); + if (container.ExitCode is not 0) + { + Console.WriteLine($"- Error: Docker could not create the container {name}."); + return 1; + } + + lock (this.cancellationLock) + this.containerName = name; + + Console.WriteLine($"- Created the container and the volume {name}."); + var script = await ReadContainerScriptAsync(); + if (await CommandRunner.RunAsync(workingDirectory, "docker", ["cp", "-", $"{name}:/"], stream => WriteScriptArchiveAsync(stream, script)) is not 0) + { + Console.WriteLine($"- Error: Docker could not copy the build script into the container {name}."); + return 1; + } + + if (localFiles.Count > 0) + { + var megabytes = localFiles.Sum(file => new FileInfo(Path.Join(repositoryDirectory, file)).Length) / 1024 / 1024; + Console.WriteLine($"- Copying {localFiles.Count} files ({megabytes} MB) of the local checkout into the container ..."); + if (await CommandRunner.RunAsync(workingDirectory, "docker", ["cp", "-", $"{name}:/"], stream => WriteCheckoutArchiveAsync(stream, repositoryDirectory, localFiles)) is not 0 || this.IsCancelled) + { + if (!this.IsCancelled) + Console.WriteLine($"- Error: Docker could not copy the local checkout into the container {name}."); + + return this.ExitCodeAfterFailure; + } + } + + lock (this.cancellationLock) + { + if (this.isCancelled) + return CANCELLED_EXIT_CODE; + + this.isContainerStarted = true; + } + + // + // docker start returns early when it gets a signal of its own, such as the Ctrl+C of the terminal, and the + // container may still be running then. Only the state of the container tells whether the build ended, and how: + // + var startExitCode = await CommandRunner.RunAsync(workingDirectory, "docker", ["start", "--attach", name]); + var buildExitCode = this.IsCancelled ? null : await ReadBuildExitCodeAsync(workingDirectory, name); + if (this.IsCancelled) + { + Console.WriteLine("- The build was cancelled."); + return CANCELLED_EXIT_CODE; + } + + if (buildExitCode is null) + { + Console.WriteLine($"- Error: The container {name} did not finish its build; docker start ended with exit code {startExitCode}."); + return 1; + } + + if (buildExitCode is not 0) + { + Console.WriteLine($"- Error: The build in the container failed with exit code {buildExitCode}. Its output above says why."); + return 1; + } + + // + // Bundles of an earlier build would otherwise pass for those of this one, should the container + // not deliver one of them: + // + foreach (var bundleName in new[] { architecture.AppBundleName, architecture.PandocBundleName }) + File.Delete(Path.Join(outputDirectory, bundleName)); + + if (await CommandRunner.RunAsync(workingDirectory, "docker", ["cp", $"{name}:{CONTAINER_OUTPUT_DIRECTORY}/.", outputDirectory]) is not 0) + { + Console.WriteLine($"- Error: Docker could not copy the bundles out of the container {name}."); + return 1; + } + + return await ReportBundlesAsync(outputDirectory, architecture) ? 0 : 1; + } + + /// + /// Reads how the build in the container ended. + /// + /// The exit code of the build script, or null when the container has not run to its end. + private static async Task ReadBuildExitCodeAsync(string workingDirectory, string name) + { + var state = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["inspect", "--format", "{{.State.Status}} {{.State.ExitCode}}", name]); + var parts = state.Text.Trim().Split(' '); + if (state.ExitCode is not 0 || parts.Length is not 2 || parts[0] is not "exited" || !int.TryParse(parts[1], out var exitCode)) + return null; + + return exitCode; + } + + private bool IsCancelled + { + get + { + lock (this.cancellationLock) + return this.isCancelled; + } + } + + private int ExitCodeAfterFailure => this.IsCancelled ? CANCELLED_EXIT_CODE : 1; + + /// + /// Stops the build at the first Ctrl+C, so that the command can still remove its container and volume. + /// + /// + /// The shell inside the container waits for flatpak-builder and passes the signal on only after that, so the + /// container gets killed instead. A second Ctrl+C ends the command at once and names what it leaves behind. + /// + private void OnCancelKeyPress(object? sender, ConsoleCancelEventArgs eventArgs) + { + string container; + bool isStarted; + lock (this.cancellationLock) + { + if (this.isCancelled) + { + Console.WriteLine("- Quitting at once."); + WriteRemovalCommands(this.containerName, this.volumeName); + return; + } + + this.isCancelled = true; + container = this.containerName; + isStarted = this.isContainerStarted; + } + + eventArgs.Cancel = true; + Console.WriteLine("- Cancelling: the build stops, and the command removes its container and volume. Press Ctrl+C again to quit at once."); + if (isStarted) + _ = CommandRunner.ReadOutputAsync(Directory.GetCurrentDirectory(), "docker", ["kill", container]); + } + + private async Task RemoveContainerAndVolumeAsync(string workingDirectory) + { + string container; + string volume; + lock (this.cancellationLock) + { + container = this.containerName; + volume = this.volumeName; + } + + var leftContainer = string.Empty; + if (!string.IsNullOrWhiteSpace(container) && (await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["rm", "--force", container])).ExitCode is not 0) + leftContainer = container; + + var leftVolume = string.Empty; + if (!string.IsNullOrWhiteSpace(volume) && (await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["volume", "rm", volume])).ExitCode is not 0) + leftVolume = volume; + + if (string.IsNullOrWhiteSpace(leftContainer) && string.IsNullOrWhiteSpace(leftVolume)) + { + if (!string.IsNullOrWhiteSpace(volume)) + Console.WriteLine($"- Removed the container and the volume {volume}."); + + return; + } + + Console.WriteLine("- Error: Docker could not remove everything this build created."); + WriteRemovalCommands(leftContainer, leftVolume); + } + + private static void WriteRemovalCommands(string container, string volume) + { + if (string.IsNullOrWhiteSpace(container) && string.IsNullOrWhiteSpace(volume)) + return; + + Console.WriteLine(" Remove what is left with:"); + if (!string.IsNullOrWhiteSpace(container)) + Console.WriteLine($" docker rm --force {container}"); + + if (!string.IsNullOrWhiteSpace(volume)) + Console.WriteLine($" docker volume rm {volume}"); + } + + /// + /// Resolves the output folder and creates it when it does not exist. + /// + /// + /// A folder inside the repository is refused: the bundles would show up in git status, and a build of the local + /// checkout would copy them into the container. + /// + /// The folder as the user gave it; a leading ~ stands for the home folder. + /// The absolute path of the folder, or null when it cannot be used. + private static string? PrepareOutputDirectory(string output) + { + var outputDirectory = Path.GetFullPath(ExpandHomeDirectory(output)); + var repositoryDirectory = Environment.GetRepositoryDirectory(); + var relativePath = Path.GetRelativePath(repositoryDirectory, outputDirectory); + var isOutsideRepository = Path.IsPathRooted(relativePath) || relativePath == ".." || relativePath.StartsWith($"..{Path.DirectorySeparatorChar}", StringComparison.Ordinal); + if (!isOutsideRepository) + { + Console.WriteLine($"- Error: The output folder '{outputDirectory}' lies inside the repository. The bundles would show up in git status, and a build of the local checkout would copy them into the container."); + Console.WriteLine($" Choose a folder outside of '{repositoryDirectory}', e.g., --output ~/Downloads/flatpak."); + return null; + } + + try + { + Directory.CreateDirectory(outputDirectory); + return outputDirectory; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + Console.WriteLine($"- Error: Could not create the output folder '{outputDirectory}': {exception.Message}"); + return null; + } + } + + private static string ExpandHomeDirectory(string path) + { + var homeDirectory = global::System.Environment.GetFolderPath(global::System.Environment.SpecialFolder.UserProfile); + if (path == "~") + return homeDirectory; + + if (path.StartsWith("~/", StringComparison.Ordinal) || path.StartsWith(@"~\", StringComparison.Ordinal)) + return Path.Join(homeDirectory, path[2..]); + + return path; + } + + private static async Task DetermineArchitectureAsync(string workingDirectory, string? architectureName) + { + if (!string.IsNullOrWhiteSpace(architectureName)) + return FlatpakArchitecture.FromName(architectureName); + + var dockerInfo = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["info", "--format", "{{.Architecture}}"]); + if (dockerInfo.ExitCode is not 0) + { + Console.WriteLine("- Error: Docker did not name the architecture of its host. Choose one with --arch aarch64 or --arch x86_64."); + return FlatpakArchitecture.NONE; + } + + var architecture = FlatpakArchitecture.FromName(dockerInfo.Text); + if (architecture is FlatpakArchitecture.NONE) + Console.WriteLine($"- Error: The Docker host runs on '{dockerInfo.Text.Trim()}', for which there is no Flatpak. Choose one with --arch aarch64 or --arch x86_64."); + + return architecture; + } + + /// + /// Asks a repository on GitHub which commit a reference points to. + /// + /// + /// The command fixes every commit before the build starts. A push during the build therefore cannot mix two + /// states, and the output names exactly what the Flatpak contains. + /// + /// Where git should run. + /// The URL of the repository. + /// The full name of the reference, e.g., refs/heads/main. + /// What the repository lacks when the reference does not exist, e.g., "no branch main". + /// The hash of the commit, or null when the repository has no such reference. + private static async Task ResolveRemoteCommitAsync(string workingDirectory, string repository, string reference, string whatIsMissing) + { + var references = await CommandRunner.ReadOutputAsync(workingDirectory, "git", ["ls-remote", repository, reference]); + if (references.ExitCode is not 0) + { + Console.WriteLine($"- Error: Could not ask {repository} for '{reference}'."); + return null; + } + + foreach (var line in references.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var parts = line.Split('\t'); + if (parts.Length is 2 && parts[1] == reference && CommitHashRegex().IsMatch(parts[0])) + return parts[0]; + } + + Console.WriteLine($"- Error: {repository} has {whatIsMissing}."); + return null; + } + + /// + /// Decides which state of AI Studio goes into the Flatpak, and asks when the options leave it open. + /// + /// The source, or NONE when the options contradict each other or nobody answered. + private static FlatpakSource DetermineSource(string? sourceName, int? pullRequestOption) + { + var source = string.IsNullOrWhiteSpace(sourceName) ? FlatpakSource.NONE : FlatpakSource.FromName(sourceName); + if (pullRequestOption is not null) + { + if (source is FlatpakSource.NONE or FlatpakSource.PULL_REQUEST) + return FlatpakSource.PULL_REQUEST; + + Console.WriteLine($"- Error: --pr builds a pull request, while --source {source.Name} builds something else. Leave out one of them."); + return FlatpakSource.NONE; + } + + return source is FlatpakSource.NONE ? AskForSource() : source; + } + + private static FlatpakSource AskForSource() + { + var sources = FlatpakSource.All; + Console.WriteLine("- Which state of AI Studio should go into the Flatpak?"); + for (var index = 0; index < sources.Count; index++) + Console.WriteLine($" {index + 1}) {sources[index].Description}"); + + while (true) + { + Console.Write($"- Your choice (1-{sources.Count}): "); + var answer = Console.ReadLine(); + if (answer is null) + { + Console.WriteLine(); + Console.WriteLine($"- Error: No answer arrived. Choose with --source {string.Join(", --source ", sources.Select(candidate => candidate.Name))}, or with --pr ."); + return FlatpakSource.NONE; + } + + if (int.TryParse(answer.Trim(), out var choice) && choice >= 1 && choice <= sources.Count) + return sources[choice - 1]; + + Console.WriteLine($" Please enter a number from 1 to {sources.Count}."); + } + } + + private static int? AskForPullRequestNumber() + { + while (true) + { + Console.Write("- Number of the pull request: "); + var answer = Console.ReadLine(); + if (answer is null) + { + Console.WriteLine(); + Console.WriteLine("- Error: No answer arrived. Pass the number with --pr ."); + return null; + } + + if (int.TryParse(answer.Trim().TrimStart('#'), out var number) && number > 0) + return number; + + Console.WriteLine(" Please enter the number of a pull request, e.g., 1219."); + } + } + + /// + /// Describes a pull request with its title and state, so that a mistyped number stands out before the build. + /// + /// + /// The commit comes from git, which needs no token and knows no rate limit. The title is a courtesy on top: when + /// the GitHub API refuses to answer, e.g., after too many requests without a token, the build goes on without it. + /// + private static async Task DescribePullRequestAsync(int number) + { + var description = $"pull request #{number} of MindWorkAI/AI-Studio"; + try + { + using var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.github.com/repos/MindWorkAI/AI-Studio/pulls/{number}"); + request.Headers.UserAgent.ParseAdd("MindWork-AI-Studio-Build-Script"); + request.Headers.Accept.ParseAdd("application/vnd.github+json"); + + using var response = await CLIENT.SendAsync(request); + if (!response.IsSuccessStatusCode) + return $"{description} (GitHub did not tell its title: {(int)response.StatusCode} {response.ReasonPhrase})"; + + await using var stream = await response.Content.ReadAsStreamAsync(); + using var json = await JsonDocument.ParseAsync(stream); + var root = json.RootElement; + var title = root.GetProperty("title").GetString(); + var state = root.GetProperty("merged").GetBoolean() ? "merged" : root.GetProperty("state").GetString() switch + { + "open" => "open", + _ => "closed without merging", + }; + + return $"{description}, \"{title}\" ({state})"; + } + catch (Exception exception) when (exception is HttpRequestException or TaskCanceledException or JsonException or KeyNotFoundException or InvalidOperationException) + { + return $"{description} (GitHub did not tell its title: {exception.Message})"; + } + } + + /// + /// Reads which container image the CI of the Flatpak repository builds with. + /// + /// + /// The image carries the GNOME runtime the manifest builds against. Reading it from the workflow keeps the local + /// build in step with the CI, e.g., when the Flatpak moves on to a newer GNOME runtime. + /// + /// The commit of the Flatpak repository whose workflow counts. + /// The image, or null when the workflow cannot be read or names more or less than one image. + private static async Task ReadCiImageAsync(string flatpakCommit) + { + var url = $"https://raw.githubusercontent.com/MindWorkAI/Flatpak/{flatpakCommit}/.github/workflows/flatpak.yml"; + string workflow; + try + { + workflow = await CLIENT.GetStringAsync(url); + } + catch (Exception exception) when (exception is HttpRequestException or TaskCanceledException) + { + Console.WriteLine($"- Error: Could not read the CI workflow of the Flatpak repository from {url}: {exception.Message}"); + return null; + } + + var images = WorkflowImageRegex().Matches(workflow).Select(match => match.Groups[1].Value).Distinct().ToList(); + if (images.Count is 1) + return images[0]; + + Console.WriteLine($"- Error: The CI workflow of the Flatpak repository names {images.Count} container images instead of one: {url}"); + return null; + } + + /// + /// Names the containers and volumes which earlier builds left behind, e.g., after the terminal was closed. + /// + /// + /// They may also belong to a build which is still running in another terminal. Hence, the command only names + /// them and leaves the removal to the user. + /// + private static async Task ReportLeftoversAsync(string workingDirectory) + { + var containers = await ReadNamesAsync(workingDirectory, ["ps", "--all", "--filter", $"label={DOCKER_LABEL}", "--format", "{{.Names}}"]); + var volumes = await ReadNamesAsync(workingDirectory, ["volume", "ls", "--filter", $"label={DOCKER_LABEL}", "--format", "{{.Name}}"]); + if (containers.Count is 0 && volumes.Count is 0) + return; + + Console.WriteLine("- Note: Docker still holds containers or volumes of earlier builds. They may belong to a build which is still running, so the command leaves them alone. Once no other build runs, remove them with:"); + foreach (var container in containers) + Console.WriteLine($" docker rm --force {container}"); + + foreach (var volume in volumes) + Console.WriteLine($" docker volume rm {volume}"); + } + + private static async Task> ReadNamesAsync(string workingDirectory, IReadOnlyList arguments) + { + var names = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", arguments); + return names.ExitCode is 0 ? names.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) : []; + } + + /// + /// Reads the script which builds inside the container, with LF line endings. + /// + /// + /// Git on Windows may check the script out with CR LF, which bash refuses. + /// + private static async Task ReadContainerScriptAsync() + { + var path = Path.Join(Directory.GetCurrentDirectory(), CONTAINER_SCRIPT_DIRECTORY, CONTAINER_SCRIPT_NAME); + var script = await File.ReadAllTextAsync(path, Encoding.UTF8); + return Environment.UTF8_NO_BOM.GetBytes(script.ReplaceLineEndings("\n")); + } + + /// + /// Writes the build script as a tar archive, which docker cp unpacks into the container. + /// + /// + /// docker cp copies a single file only into a folder which already exists, so the archive brings its folder along. + /// + private static async Task WriteScriptArchiveAsync(Stream stream, byte[] script) + { + await using var writer = new TarWriter(stream, TarEntryFormat.Pax, leaveOpen: true); + await writer.WriteEntryAsync(new PaxTarEntry(TarEntryType.Directory, $"{CONTAINER_INPUT_DIRECTORY}/") { Mode = EXECUTABLE_MODE }); + + using var data = new MemoryStream(script); + await writer.WriteEntryAsync(new PaxTarEntry(TarEntryType.RegularFile, $"{CONTAINER_INPUT_DIRECTORY}/{CONTAINER_SCRIPT_NAME}") { Mode = EXECUTABLE_MODE, DataStream = data }); + } + + /// + /// Writes the files of the local checkout as a tar archive, which docker cp unpacks into the container. + /// + /// + /// The archive reads one file after the other straight into the stream, so even a large checkout never sits in + /// memory as a whole. + /// + private static async Task WriteCheckoutArchiveAsync(Stream stream, string repositoryDirectory, IReadOnlyList files) + { + var checkoutDirectory = $"{CONTAINER_INPUT_DIRECTORY}/{CONTAINER_CHECKOUT_DIRECTORY}"; + await using var writer = new TarWriter(stream, TarEntryFormat.Pax, leaveOpen: true); + await writer.WriteEntryAsync(new PaxTarEntry(TarEntryType.Directory, $"{checkoutDirectory}/") { Mode = EXECUTABLE_MODE }); + foreach (var file in files) + await writer.WriteEntryAsync(Path.Join(repositoryDirectory, file), $"{checkoutDirectory}/{file}"); + } + + /// + /// Reads the commit the local checkout stands on, which the summary names before the build. + /// + /// The hash of the commit, or null when the checkout has none. + private static async Task ReadLocalHeadAsync(string repositoryDirectory) + { + var head = await CommandRunner.ReadOutputAsync(repositoryDirectory, "git", ["rev-parse", "HEAD"]); + if (head.ExitCode is 0 && CommitHashRegex().IsMatch(head.Text.Trim())) + return head.Text.Trim(); + + Console.WriteLine($"- Error: The local checkout in '{repositoryDirectory}' has no commit to start from."); + return null; + } + + /// + /// Lists the files of the local checkout which go into the Flatpak. + /// + /// + /// These are the files git knows plus the new ones which no ignore rule covers, the same files a commit of + /// everything would hold. Build outputs such as bin, obj, or target stay behind, and so do deleted files. + /// + /// The paths relative to the repository, with forward slashes, or null when git fails. + private static async Task?> ListLocalFilesAsync(string repositoryDirectory) + { + var listing = await CommandRunner.ReadOutputAsync(repositoryDirectory, "git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"]); + if (listing.ExitCode is not 0) + { + Console.WriteLine($"- Error: git could not list the files of the local checkout in '{repositoryDirectory}'."); + return null; + } + + return listing.Text.Split('\0', StringSplitOptions.RemoveEmptyEntries).Distinct().Where(file => File.Exists(Path.Join(repositoryDirectory, file))).ToList(); + } + + /// + /// Describes the local checkout with its branch and the number of files which differ from its commit. + /// + /// + /// git status refreshes the index by default, which is a change to the repository. Without optional locks, it + /// only reads. + /// + private static async Task DescribeLocalCheckoutAsync(string repositoryDirectory) + { + var branch = await CommandRunner.ReadOutputAsync(repositoryDirectory, "git", ["rev-parse", "--abbrev-ref", "HEAD"]); + var status = await CommandRunner.ReadOutputAsync(repositoryDirectory, "git", ["--no-optional-locks", "status", "--porcelain", "--untracked-files=all"]); + var changedFiles = status.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries).Length; + var changes = changedFiles is 0 ? "without uncommitted changes" : $"with {changedFiles} changed or new files"; + return $"the local checkout on {branch.Text.Trim()}, {changes}"; + } + + /// + /// Names the bundles in the output folder, with their sizes and SHA-256 hashes. + /// + /// True, when both bundles are there. + private static async Task ReportBundlesAsync(string outputDirectory, FlatpakArchitecture architecture) + { + Console.WriteLine("- The bundles:"); + foreach (var bundleName in new[] { architecture.AppBundleName, architecture.PandocBundleName }) + { + var path = Path.Join(outputDirectory, bundleName); + if (!File.Exists(path)) + { + Console.WriteLine($"- Error: The container did not deliver '{bundleName}'."); + return false; + } + + await using var bundle = File.OpenRead(path); + var hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(bundle)); + Console.WriteLine($" - {path}"); + Console.WriteLine($" {bundle.Length / 1024 / 1024} MB, SHA-256 {hash}"); + } + + return true; + } +} \ No newline at end of file diff --git a/app/Build/Commands/FlatpakSource.cs b/app/Build/Commands/FlatpakSource.cs new file mode 100644 index 000000000..3726104eb --- /dev/null +++ b/app/Build/Commands/FlatpakSource.cs @@ -0,0 +1,13 @@ +namespace Build.Commands; + +/// +/// Which state of AI Studio goes into a Flatpak which the build command "flatpak" builds. +/// +public enum FlatpakSource +{ + NONE, + + MAIN, + PULL_REQUEST, + LOCAL, +} \ No newline at end of file diff --git a/app/Build/Commands/FlatpakSourceExtensions.cs b/app/Build/Commands/FlatpakSourceExtensions.cs new file mode 100644 index 000000000..a414e24a2 --- /dev/null +++ b/app/Build/Commands/FlatpakSourceExtensions.cs @@ -0,0 +1,44 @@ +namespace Build.Commands; + +public static class FlatpakSourceExtensions +{ + /// The state of AI Studio which goes into the Flatpak. + extension(FlatpakSource source) + { + /// + /// The name of the source for the option --source. + /// + public string Name => source switch + { + FlatpakSource.MAIN => "main", + FlatpakSource.PULL_REQUEST => "pr", + FlatpakSource.LOCAL => "local", + + _ => string.Empty, + }; + + /// + /// What the source builds, and what for. + /// + public string Description => source switch + { + FlatpakSource.MAIN => "main of MindWorkAI/AI-Studio, to simulate a pre-release", + FlatpakSource.PULL_REQUEST => "a pull request of MindWorkAI/AI-Studio, to test its changes early", + FlatpakSource.LOCAL => "this local checkout with its uncommitted changes, to test work before there is a pull request", + + _ => string.Empty, + }; + + /// + /// All sources the command offers, in the order of its menu. + /// + public static IReadOnlyList All => [FlatpakSource.MAIN, FlatpakSource.PULL_REQUEST, FlatpakSource.LOCAL]; + + /// + /// Finds the source for its name. + /// + /// The name of the source, as the option --source takes it. + /// The source, or NONE for an unknown name. + public static FlatpakSource FromName(string name) => FlatpakSource.All.FirstOrDefault(candidate => string.Equals(candidate.Name, name.Trim(), StringComparison.OrdinalIgnoreCase)); + } +} \ No newline at end of file diff --git a/app/Build/Flatpak/build-in-container.sh b/app/Build/Flatpak/build-in-container.sh new file mode 100644 index 000000000..bd7d49b73 --- /dev/null +++ b/app/Build/Flatpak/build-in-container.sh @@ -0,0 +1,256 @@ +#!/usr/bin/env bash +# +# Builds the Flatpak of AI Studio and its Pandoc plugin. The build command "flatpak" of app/Build, see +# Commands/FlatpakCommand.cs, runs this script inside the CI image of the Flatpak repository and copies the +# bundles out of the output folder afterward. +# +# The sync below simulates the job "sync_flatpak_repo" of .github/workflows/build-and-release.yml, which +# prepares the Flatpak repository for a release. Whoever changes one of them changes the other one as well. +# On purpose, the script differs from the job in three points: +# +# - It removes the tag of AI Studio. flatpak-builder checks a tag against the commit, and the commit of a +# test build has none. +# - It skips update-metainfo.py --check. The metainfo gets the entry of a release from the release command +# only, so a test build lacks it. +# - It sets the URL of AI Studio as well. For the source "local", it points to a repository inside the +# container, which holds the copied files of the local checkout in a single commit. +# +set -euo pipefail + +: "${ARCH:?}" "${SOURCE:?}" "${FLATPAK_URL:?}" "${FLATPAK_COMMIT:?}" +: "${APP_BUNDLE:?}" "${PANDOC_BUNDLE:?}" "${BUILD_DIRECTORY:?}" "${OUT_DIRECTORY:?}" +if [ "$SOURCE" = "local" ]; then + : "${LOCAL_CHECKOUT:?}" +else + : "${AI_STUDIO_URL:?}" "${AI_STUDIO_COMMIT:?}" +fi + +# The same version of yq as the pipeline uses, see FLATPAK_YQ_VERSION and FLATPAK_YQ_SHA256 there: +YQ_VERSION="4.44.6" +YQ_SHA256_X86_64="0c2b24e645b57d8e7c0566d18643a6d4f5580feeea3878127354a46f2a1e4598" +YQ_SHA256_AARCH64="9477ac3cc447b6c083986129e35af8122eb2b938fe55c9c3e40436fb966e5813" + +FLATHUB_REPO_URL="https://flathub.org/repo/flathub.flatpakrepo" +APP_MANIFEST="org.mindworkai.AIStudio.yml" +PANDOC_MANIFEST="plugins/pandoc/org.mindworkai.AIStudio.plugin.pandoc.yml" + +stage() { + printf '\n===== %s: %s =====\n' "$(date -u '+%H:%M:%S')" "$*" +} + +fail() { + echo >&2 "error: $*" + exit 1 +} + +# Fetches a single commit of a repository into a new folder, without its history. +fetch_commit() { + local url="$1" commit="$2" directory="$3" + shift 3 + git init --quiet "$directory" + git -C "$directory" remote add origin "$url" + git -C "$directory" fetch --quiet --depth 1 "$@" origin "$commit" +} + +# Installs the given refs from Flathub, unless they are installed already. The image brings some runtimes +# in a lower layer of its file system, where updating them fails with "Invalid cross-device link". Hence, +# the script never updates them, and flatpak-builder runs without --install-deps-from. +install_missing() { + local missing=() + local ref + for ref in "$@"; do + if flatpak info --system "$ref" > /dev/null 2>&1; then + echo "Already installed: $ref" + else + missing+=("$ref") + fi + done + + if [ "${#missing[@]}" -gt 0 ]; then + flatpak install --system --noninteractive -y flathub "${missing[@]}" + fi +} + +# Prints the branch of an SDK extension: the version of the extension point which the SDK declares, e.g., +# 25.08 for org.freedesktop.Sdk.Extension.rust-stable in org.gnome.Sdk//50. +extension_branch() { + local sdk_ref="$1" extension="$2" + flatpak info --system --show-metadata "$sdk_ref" | awk -v section="[Extension ${extension%.*}]" ' + $0 == section { inside = 1; next } + /^\[/ { inside = 0 } + inside && $1 == "version" { sub(/^[^=]*=[[:space:]]*/, ""); print; exit } + ' +} + +stage "Checking the container" +test "$(uname -m)" = "$ARCH" || fail "the container runs on $(uname -m) instead of $ARCH" +for tool in curl flatpak flatpak-builder git jq python3 sha256sum uv; do + hash "$tool" 2> /dev/null || fail "the image lacks $tool" +done +echo "Building the source '$SOURCE' for $ARCH" + +stage "Preparing yq ${YQ_VERSION}" +case "$ARCH" in + aarch64) + yq_asset="yq_linux_arm64" + yq_sha256="$YQ_SHA256_AARCH64" + ;; + x86_64) + yq_asset="yq_linux_amd64" + yq_sha256="$YQ_SHA256_X86_64" + ;; + *) + fail "there is no Flatpak for $ARCH" + ;; +esac + +mkdir -p "$BUILD_DIRECTORY/tools" "$OUT_DIRECTORY" +curl -fsSL -o "$BUILD_DIRECTORY/tools/yq" "https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/${yq_asset}" +echo "${yq_sha256} $BUILD_DIRECTORY/tools/yq" | sha256sum --check --strict +chmod 755 "$BUILD_DIRECTORY/tools/yq" +export PATH="$BUILD_DIRECTORY/tools:$PATH" + +if [ "$SOURCE" = "local" ]; then + stage "Committing the local checkout in a repository of its own" + + # The files arrive with the owner of the checkout, and git refuses to work in a repository of another user: + chown -R root:root "$LOCAL_CHECKOUT" + git init --quiet "$LOCAL_CHECKOUT" + + # A checkout on Windows may hold CR LF line endings, which a commit there would turn into LF. The fetches by + # commit, from update-dependencies and flatpak-builder alike, need the two uploadpack settings: + git -C "$LOCAL_CHECKOUT" config core.autocrlf input + git -C "$LOCAL_CHECKOUT" config core.safecrlf false + git -C "$LOCAL_CHECKOUT" config uploadpack.allowAnySHA1InWant true + git -C "$LOCAL_CHECKOUT" config uploadpack.allowFilter true + git -C "$LOCAL_CHECKOUT" add --all + git -C "$LOCAL_CHECKOUT" -c user.name="AI Studio build" -c user.email="build@localhost" commit --quiet --no-verify -m "Local checkout" + + AI_STUDIO_URL="file://$LOCAL_CHECKOUT" + AI_STUDIO_COMMIT=$(git -C "$LOCAL_CHECKOUT" rev-parse HEAD) + echo "Committed $(git -C "$LOCAL_CHECKOUT" ls-files | wc -l) files as ${AI_STUDIO_COMMIT}" +fi + +stage "Fetching the Flatpak repository at ${FLATPAK_COMMIT}" +fetch_commit "$FLATPAK_URL" "$FLATPAK_COMMIT" "$BUILD_DIRECTORY/flatpak" +cd "$BUILD_DIRECTORY/flatpak" +git checkout --quiet FETCH_HEAD + +stage "Installing the runtimes and SDKs" +runtime_version=$(yq -r '."runtime-version"' "$APP_MANIFEST") +sdk_ref="$(yq -r '.sdk' "$APP_MANIFEST")//${runtime_version}" +install_missing "$(yq -r '.runtime' "$APP_MANIFEST")//${runtime_version}" "$sdk_ref" + +refs=() +while IFS= read -r extension; do + branch=$(extension_branch "$sdk_ref" "$extension") + [ -n "$branch" ] || fail "$sdk_ref declares no extension point for $extension" + refs+=("${extension}//${branch}") +done < <(yq -r '."sdk-extensions"[]' "$APP_MANIFEST") + +# update-dependencies restores the .NET projects inside the Freedesktop SDK and its .NET extension, in the +# versions it passes to flatpak-dotnet-generator.py: +generator_call=$(grep -E 'flatpak-dotnet-generator\.py' update-dependencies) +freedesktop_version=$(grep -oE -e '-f [0-9]+\.[0-9]+' <<< "$generator_call" | cut -d' ' -f2) +dotnet_major=$(grep -oE -e '-d [0-9]+' <<< "$generator_call" | cut -d' ' -f2) +[ -n "$freedesktop_version" ] && [ -n "$dotnet_major" ] || fail "update-dependencies calls flatpak-dotnet-generator.py without -f and -d" +refs+=("org.freedesktop.Sdk//${freedesktop_version}" "org.freedesktop.Sdk.Extension.dotnet${dotnet_major}//${freedesktop_version}") + +pandoc_sdk=$(yq -r '.sdk' "$PANDOC_MANIFEST") +[[ "$pandoc_sdk" == *//* ]] || fail "the Pandoc plugin names its SDK without a branch: $pandoc_sdk" +refs+=("$pandoc_sdk") +install_missing "${refs[@]}" + +stage "Reading metadata.txt of AI Studio ${AI_STUDIO_COMMIT}" +fetch_commit "$AI_STUDIO_URL" "$AI_STUDIO_COMMIT" "$BUILD_DIRECTORY/ai-studio-metadata" --filter=blob:none +metadata=$(git -C "$BUILD_DIRECTORY/ai-studio-metadata" show FETCH_HEAD:metadata.txt | tr -d '\r') +app_version=$(sed -n '1p' <<< "$metadata") +pdfium_full_version=$(sed -n '10p' <<< "$metadata") +pdfium_chromium_revision=$(cut -d'.' -f3 <<< "$pdfium_full_version") +[[ "$pdfium_chromium_revision" =~ ^[0-9]+$ ]] || fail "line 10 of metadata.txt names no PDFium version: $pdfium_full_version" +echo "AI Studio ${app_version} with PDFium ${pdfium_full_version}" + +stage "Syncing the Flatpak repository like the release pipeline" +pdfium_base_url="https://github.com/bblanchon/pdfium-binaries/releases/download/chromium%2F${pdfium_chromium_revision}" +export AI_STUDIO_URL AI_STUDIO_COMMIT +export PDFIUM_X64_URL="${pdfium_base_url}/pdfium-linux-x64.tgz" +export PDFIUM_ARM64_URL="${pdfium_base_url}/pdfium-linux-arm64.tgz" +curl -fsSL -o "$BUILD_DIRECTORY/pdfium-linux-x64.tgz" "$PDFIUM_X64_URL" +curl -fsSL -o "$BUILD_DIRECTORY/pdfium-linux-arm64.tgz" "$PDFIUM_ARM64_URL" + +export PDFIUM_X64_SHA256 +export PDFIUM_ARM64_SHA256 +PDFIUM_X64_SHA256=$(sha256sum "$BUILD_DIRECTORY/pdfium-linux-x64.tgz" | awk '{print $1}') +PDFIUM_ARM64_SHA256=$(sha256sum "$BUILD_DIRECTORY/pdfium-linux-arm64.tgz" | awk '{print $1}') + +yq -i ' + (.modules[] | select(.name == "mind-work-ai-studio").sources[0].url) = strenv(AI_STUDIO_URL) | + (.modules[] | select(.name == "mind-work-ai-studio").sources[0].commit) = strenv(AI_STUDIO_COMMIT) | + del(.modules[] | select(.name == "mind-work-ai-studio").sources[0].tag) | + (.modules[] | select(.name == "mind-work-ai-studio").sources[] | select(.type == "archive" and .only-arches[0] == "x86_64").url) = strenv(PDFIUM_X64_URL) | + (.modules[] | select(.name == "mind-work-ai-studio").sources[] | select(.type == "archive" and .only-arches[0] == "x86_64").sha256) = strenv(PDFIUM_X64_SHA256) | + (.modules[] | select(.name == "mind-work-ai-studio").sources[] | select(.type == "archive" and .only-arches[0] == "aarch64").url) = strenv(PDFIUM_ARM64_URL) | + (.modules[] | select(.name == "mind-work-ai-studio").sources[] | select(.type == "archive" and .only-arches[0] == "aarch64").sha256) = strenv(PDFIUM_ARM64_SHA256) +' "$APP_MANIFEST" + +./update-dependencies + +test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[0].url' "$APP_MANIFEST")" = "$AI_STUDIO_URL" +test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[0].commit' "$APP_MANIFEST")" = "$AI_STUDIO_COMMIT" +test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[0].tag' "$APP_MANIFEST")" = "null" +test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[] | select(.type == "archive" and .only-arches[0] == "x86_64").url' "$APP_MANIFEST")" = "$PDFIUM_X64_URL" +test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[] | select(.type == "archive" and .only-arches[0] == "x86_64").sha256' "$APP_MANIFEST")" = "$PDFIUM_X64_SHA256" +test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[] | select(.type == "archive" and .only-arches[0] == "aarch64").url' "$APP_MANIFEST")" = "$PDFIUM_ARM64_URL" +test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[] | select(.type == "archive" and .only-arches[0] == "aarch64").sha256' "$APP_MANIFEST")" = "$PDFIUM_ARM64_SHA256" + +for generated_source in cargo-sources.json dotnet-sources.json tauri-cli-sources.json; do + test -s "$generated_source" + jq -e 'type == "array" and length > 0' "$generated_source" > /dev/null +done + +git diff --check +git diff --stat + +stage "Building the Flatpak of AI Studio" +app_id=$(yq -r '.id' "$APP_MANIFEST") +flatpak-builder \ + --arch="$ARCH" \ + --repo="$BUILD_DIRECTORY/repo" \ + --state-dir="$BUILD_DIRECTORY/state" \ + --disable-rofiles-fuse \ + --force-clean \ + --default-branch=stable \ + "$BUILD_DIRECTORY/build-app" \ + "$APP_MANIFEST" + +flatpak build-bundle \ + --arch="$ARCH" \ + --runtime-repo="$FLATHUB_REPO_URL" \ + "$BUILD_DIRECTORY/repo" \ + "$OUT_DIRECTORY/$APP_BUNDLE" \ + "$app_id" \ + stable + +stage "Building the Pandoc plugin" + +# Like the CI, the plugin builds against the app it extends, so the bundle of the app gets installed first: +flatpak install --system --noninteractive -y --bundle "$OUT_DIRECTORY/$APP_BUNDLE" +flatpak-builder \ + --arch="$ARCH" \ + --repo="$BUILD_DIRECTORY/repo" \ + --state-dir="$BUILD_DIRECTORY/state" \ + --disable-rofiles-fuse \ + --force-clean \ + "$BUILD_DIRECTORY/build-pandoc" \ + "$PANDOC_MANIFEST" + +flatpak build-bundle \ + --arch="$ARCH" \ + --runtime \ + "$BUILD_DIRECTORY/repo" \ + "$OUT_DIRECTORY/$PANDOC_BUNDLE" \ + "$(yq -r '.id' "$PANDOC_MANIFEST")" \ + "$(yq -r '.branch' "$PANDOC_MANIFEST")" + +stage "Done" +ls -l "$OUT_DIRECTORY" \ No newline at end of file diff --git a/app/Build/Program.cs b/app/Build/Program.cs index 82fb48bed..5ba6328e7 100644 --- a/app/Build/Program.cs +++ b/app/Build/Program.cs @@ -23,17 +23,23 @@ var rootCommand = new Command("build-script", "Build, check, and release MindWor CollectI18NKeysCommand.CreateCommand(), AssistantPluginHashCommand.CreateCommand(), VerifyModelsCommand.CreateCommand(), - VerifyCommand.CreateCommand() + VerifyCommand.CreateCommand(), + FlatpakCommand.CreateCommand() }; // // A command which fails deep inside, e.g., the build within a release, ends the whole script through // a CommandExitedException, once it has said why. System.CommandLine would print that exception with -// its stack trace, so we handle the exceptions ourselves and print only those nobody expected: +// its stack trace, so we handle the exceptions ourselves and print only those nobody expected. +// +// System.CommandLine would also answer Ctrl+C by cancelling a token and ending the script two seconds +// later, whether the command has finished or not. No command reads that token, and the command flatpak +// needs longer to remove its container and volume. Without the timeout, Ctrl+C ends a command at once, +// unless the command handles Ctrl+C itself, as flatpak does: // try { - return await rootCommand.Parse(args).InvokeAsync(new InvocationConfiguration { EnableDefaultExceptionHandler = false }); + return await rootCommand.Parse(args).InvokeAsync(new InvocationConfiguration { EnableDefaultExceptionHandler = false, ProcessTerminationTimeout = null }); } catch (CommandExitedException exception) { diff --git a/app/Build/Tools/CapturedOutput.cs b/app/Build/Tools/CapturedOutput.cs new file mode 100644 index 000000000..583ef783a --- /dev/null +++ b/app/Build/Tools/CapturedOutput.cs @@ -0,0 +1,12 @@ +namespace Build.Tools; + +/// +/// What an external tool wrote to its standard output, and how it ended. +/// +/// +/// The standard error of the tool went straight to the terminal. A tool which fails says why it failed there, so +/// whoever reads the terminal learns the reason from the tool itself. +/// +/// Everything the tool wrote to its standard output. +/// The exit code of the tool, where anything but zero is a failure. +public readonly record struct CapturedOutput(string Text, int ExitCode); \ No newline at end of file diff --git a/app/Build/Tools/CommandRunner.cs b/app/Build/Tools/CommandRunner.cs index 51092a11d..133be7c8b 100644 --- a/app/Build/Tools/CommandRunner.cs +++ b/app/Build/Tools/CommandRunner.cs @@ -44,9 +44,55 @@ public static class CommandRunner { using var process = Process.Start(startInfo); if (process is null) + return ReportNotStarted(fileName); + + await process.WaitForExitAsync(); + return process.ExitCode; + } + catch (Win32Exception exception) + { + return ReportCouldNotStart(fileName, exception); + } + } + + /// + /// Runs a tool with a list of arguments and waits for it. + /// + /// + /// Each argument reaches the tool unchanged, also when it contains spaces or quotes, because the system quotes + /// it as the platform needs it. Paths which a user chose, such as an output folder, therefore need no quoting. + /// + /// Where the tool should run. + /// The tool, as it is called on the PATH. + /// What to pass it, one argument per entry. + /// Writes the standard input of the tool, or null when the tool reads none. The input ends once the callback returns. + /// The exit code of the tool, or COULD_NOT_START when it never ran. + public static async Task RunAsync(string workingDirectory, string fileName, IReadOnlyList arguments, Func? writeInput = null) + { + Console.WriteLine($"- Running '{fileName} {DescribeArguments(arguments)}' in '{workingDirectory}' ..."); + var startInfo = CreateStartInfo(workingDirectory, fileName, arguments); + startInfo.RedirectStandardInput = writeInput is not null; + + try + { + using var process = Process.Start(startInfo); + if (process is null) + return ReportNotStarted(fileName); + + if (writeInput is not null) { - Console.WriteLine($"- Error: '{fileName}' did not start, and the system did not say why."); - return COULD_NOT_START; + try + { + await using var input = process.StandardInput.BaseStream; + await writeInput(input); + } + catch (IOException) + { + // + // The tool closed its input early, which it does when it fails. Its exit code + // and what it wrote to the terminal tell more than the broken pipe could: + // + } } await process.WaitForExitAsync(); @@ -54,9 +100,69 @@ public static class CommandRunner } catch (Win32Exception exception) { - Console.WriteLine($"- Error: '{fileName}' could not be started: {exception.Message}"); - Console.WriteLine($" Is '{fileName}' installed and on the PATH?"); - return COULD_NOT_START; + return ReportCouldNotStart(fileName, exception); } } + + /// + /// Runs a tool with a list of arguments and collects what it writes to its standard output. + /// + /// + /// Its standard error still goes to the terminal, so a failing tool explains itself there. The standard output + /// stays clean for reading answers such as a commit hash, which a warning on the same stream would spoil. + /// + /// Where the tool should run. + /// The tool, as it is called on the PATH. + /// What to pass it, one argument per entry. + /// The standard output and the exit code of the tool; the exit code is COULD_NOT_START when it never ran. + public static async Task ReadOutputAsync(string workingDirectory, string fileName, IReadOnlyList arguments) + { + var startInfo = CreateStartInfo(workingDirectory, fileName, arguments); + startInfo.RedirectStandardOutput = true; + + try + { + using var process = Process.Start(startInfo); + if (process is null) + return new(string.Empty, ReportNotStarted(fileName)); + + var text = await process.StandardOutput.ReadToEndAsync(); + await process.WaitForExitAsync(); + return new(text, process.ExitCode); + } + catch (Win32Exception exception) + { + return new(string.Empty, ReportCouldNotStart(fileName, exception)); + } + } + + private static ProcessStartInfo CreateStartInfo(string workingDirectory, string fileName, IReadOnlyList arguments) + { + var startInfo = new ProcessStartInfo + { + FileName = fileName, + WorkingDirectory = workingDirectory, + UseShellExecute = false, + }; + + foreach (var argument in arguments) + startInfo.ArgumentList.Add(argument); + + return startInfo; + } + + private static string DescribeArguments(IReadOnlyList arguments) => string.Join(' ', arguments.Select(argument => argument.Contains(' ') ? $"\"{argument}\"" : argument)); + + private static int ReportNotStarted(string fileName) + { + Console.WriteLine($"- Error: '{fileName}' did not start, and the system did not say why."); + return COULD_NOT_START; + } + + private static int ReportCouldNotStart(string fileName, Win32Exception exception) + { + Console.WriteLine($"- Error: '{fileName}' could not be started: {exception.Message}"); + Console.WriteLine($" Is '{fileName}' installed and on the PATH?"); + return COULD_NOT_START; + } } \ No newline at end of file diff --git a/documentation/Build.md b/documentation/Build.md index 83f1f4daa..f918cb516 100644 --- a/documentation/Build.md +++ b/documentation/Build.md @@ -78,6 +78,30 @@ When a maintainer wants signed test builds for their own work, they push the bra Changes which touch only the documentation, such as the README or the files in `documentation/`, start no build at all: neither in a pull request, not even with the `run-pipeline` label, nor after the merge into `main`. The workflow lists these files under `paths-ignore`. Release tags always build. +## Build the Flatpak locally +Neither macOS nor Windows can build a Flatpak, and on Linux it takes the right Flatpak tools and runtimes. The build script therefore builds the Flatpak and its Pandoc plugin in Docker, with the container image of the CI of our [Flatpak repository](https://github.com/MindWorkAI/Flatpak), the same way a release does. All you need is Docker which allows privileged containers, such as Docker Desktop, OrbStack, or Docker on Linux. Podman has not been tested. + +1. Open a terminal. +2. Navigate to the `/app/Build` directory within the repository. +3. Run `dotnet run flatpak --output `, e.g., `dotnet run flatpak --output ~/Downloads/flatpak`. The folder has to lie outside the repository; the command creates it when it does not exist. + +The command asks which state of AI Studio goes into the Flatpak. You may also choose it right away: + +- `--source main` builds `main` of this repository, to simulate a pre-release. +- `--pr ` builds a pull request, e.g., `--pr 1219`, to test its changes early. Pull requests from forks work as well. +- `--source local` builds your local checkout with all its uncommitted changes, to test your work before there is a pull request. It takes the files git knows plus your new files which no ignore rule covers, and it changes nothing in your repository. + +The Flatpak repository always comes from its `main` branch. Before the build starts, the command fixes every commit and names it, together with the container image. + +At the end, the output folder holds `MindWork AI Studio_.flatpak` and `MindWork AI Studio Plugin Pandoc_.flatpak`, the same bundles our Flatpak workflow produces. Copy them to a Linux machine, e.g., a virtual machine, and install them there with `flatpak install --bundle `, the app first. + +Some notes: +- **Architecture:** The Flatpak is built for the architecture of the Docker host. `--arch x86_64` or `--arch aarch64` chooses the other one, which needs an emulation such as Rosetta, available in OrbStack and in Docker Desktop on Apple silicon, and takes considerably longer. +- **Duration and disk space:** Every build downloads the SDKs and runtimes anew, several gigabytes, before it builds the Tauri CLI, the Rust runtime, and the .NET app. On a fast machine, a build takes between half an hour and 45 minutes, depending on the connection; under an emulation, it takes about twice as long. While the build runs, the container and its volume need about 15 GB of free space. The container image needs about 6 GB more, once for each architecture you build for. +- **Firewalls:** The container fetches from GitHub (`github.com`, `ghcr.io`, `*.githubusercontent.com`), Flathub (`flathub.org`), PyPI, crates.io, and NuGet. A firewall on your machine, such as Little Snitch, may have to allow these connections for the processes of Docker. +- **Cleaning up:** The command removes its container and volume at the end, also after a failure or when you press Ctrl+C. Pressing Ctrl+C a second time quits at once and prints the commands which remove what is left. A build which ends otherwise, e.g., because the terminal was closed, leaves both behind; the next build names them. The container image stays, so that the next build does not download it again. +- **Differences from a release:** The script `app/Build/Flatpak/build-in-container.sh` prepares the Flatpak repository the way the job `sync_flatpak_repo` of our GitHub workflow does for a release. Whoever changes one of them changes the other one as well. On purpose, the script leaves out the tag of AI Studio, which flatpak-builder would check against the commit, and the check of the release entry in the metainfo, which only the release command writes. + ## Create a release In order to create a release: 1. To create a new release, you need to be a maintainer of the repository—see step 8.