Added a build command for local Flatpak builds (#1220)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-23 09:46:12 +01:00
1 parent 2772612c00
commit 37e6161ccc
11 files changed
+1353 -8

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
namespace Build.Commands;
/// <summary>
/// The CPU architectures for which the Flatpak of AI Studio is built.
/// </summary>
public enum FlatpakArchitecture
{
NONE,
AARCH64,
X86_64,
}
@@ -0,0 +1,53 @@
namespace Build.Commands;
public static class FlatpakArchitectureExtensions
{
/// <param name="architecture">The CPU architecture of the Flatpak.</param>
extension(FlatpakArchitecture architecture)
{
/// <summary>
/// The name of the architecture in Flatpak and on Linux, as uname -m reports it.
/// </summary>
public string FlatpakName => architecture switch
{
FlatpakArchitecture.AARCH64 => "aarch64",
FlatpakArchitecture.X86_64 => "x86_64",
_ => string.Empty,
};
/// <summary>
/// The platform of a Docker image which runs on this architecture.
/// </summary>
public string DockerPlatform => architecture switch
{
FlatpakArchitecture.AARCH64 => "linux/arm64",
FlatpakArchitecture.X86_64 => "linux/amd64",
_ => string.Empty,
};
/// <summary>
/// The file name of the bundle of AI Studio, the same as the CI of the Flatpak repository gives it.
/// </summary>
public string AppBundleName => $"MindWork AI Studio_{architecture.FlatpakName}.flatpak";
/// <summary>
/// The file name of the bundle of the Pandoc plugin, the same as the CI of the Flatpak repository gives it.
/// </summary>
public string PandocBundleName => $"MindWork AI Studio Plugin Pandoc_{architecture.FlatpakName}.flatpak";
/// <summary>
/// Finds the architecture for a name, as Flatpak, Linux, or Docker write it.
/// </summary>
/// <param name="name">The name, e.g., aarch64, arm64, x86_64, or amd64.</param>
/// <returns>The architecture, or NONE for an unknown name.</returns>
public static FlatpakArchitecture FromName(string name) => name.Trim().ToLowerInvariant() switch
{
"aarch64" or "arm64" => FlatpakArchitecture.AARCH64,
"x86_64" or "amd64" => FlatpakArchitecture.X86_64,
_ => FlatpakArchitecture.NONE,
};
}
}
+817
View File
@@ -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;
/// <summary>
/// Builds the Flatpak of AI Studio and its Pandoc plugin in Docker, the way the CI of the Flatpak repository does.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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";
/// <summary>
/// The exit code after Ctrl+C, as shells report a process which SIGINT ended.
/// </summary>
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();
/// <summary>
/// Defines the command "flatpak".
/// </summary>
public static Command CreateCommand()
{
var output = new Option<string>("--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<string>("--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<int?>("--pr", "-p") { Description = "The number of the pull request to build, e.g., 1219; implies --source pr" };
var architecture = new Option<string>("--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<int> 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<int> 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<string> 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<string, string>
{
["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<int> BuildInContainerAsync(string workingDirectory, string name, string image, FlatpakArchitecture architecture, IReadOnlyDictionary<string, string> environment, string repositoryDirectory, IReadOnlyList<string> 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<string> 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;
}
/// <summary>
/// Reads how the build in the container ended.
/// </summary>
/// <returns>The exit code of the build script, or null when the container has not run to its end.</returns>
private static async Task<int?> 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;
/// <summary>
/// Stops the build at the first Ctrl+C, so that the command can still remove its container and volume.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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}");
}
/// <summary>
/// Resolves the output folder and creates it when it does not exist.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="output">The folder as the user gave it; a leading ~ stands for the home folder.</param>
/// <returns>The absolute path of the folder, or null when it cannot be used.</returns>
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<FlatpakArchitecture> 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;
}
/// <summary>
/// Asks a repository on GitHub which commit a reference points to.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="workingDirectory">Where git should run.</param>
/// <param name="repository">The URL of the repository.</param>
/// <param name="reference">The full name of the reference, e.g., refs/heads/main.</param>
/// <param name="whatIsMissing">What the repository lacks when the reference does not exist, e.g., "no branch main".</param>
/// <returns>The hash of the commit, or null when the repository has no such reference.</returns>
private static async Task<string?> 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;
}
/// <summary>
/// Decides which state of AI Studio goes into the Flatpak, and asks when the options leave it open.
/// </summary>
/// <returns>The source, or NONE when the options contradict each other or nobody answered.</returns>
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 <number>.");
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 <number>.");
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.");
}
}
/// <summary>
/// Describes a pull request with its title and state, so that a mistyped number stands out before the build.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
private static async Task<string> 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})";
}
}
/// <summary>
/// Reads which container image the CI of the Flatpak repository builds with.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="flatpakCommit">The commit of the Flatpak repository whose workflow counts.</param>
/// <returns>The image, or null when the workflow cannot be read or names more or less than one image.</returns>
private static async Task<string?> 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;
}
/// <summary>
/// Names the containers and volumes which earlier builds left behind, e.g., after the terminal was closed.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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<IReadOnlyList<string>> ReadNamesAsync(string workingDirectory, IReadOnlyList<string> arguments)
{
var names = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", arguments);
return names.ExitCode is 0 ? names.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) : [];
}
/// <summary>
/// Reads the script which builds inside the container, with LF line endings.
/// </summary>
/// <remarks>
/// Git on Windows may check the script out with CR LF, which bash refuses.
/// </remarks>
private static async Task<byte[]> 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"));
}
/// <summary>
/// Writes the build script as a tar archive, which docker cp unpacks into the container.
/// </summary>
/// <remarks>
/// docker cp copies a single file only into a folder which already exists, so the archive brings its folder along.
/// </remarks>
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 });
}
/// <summary>
/// Writes the files of the local checkout as a tar archive, which docker cp unpacks into the container.
/// </summary>
/// <remarks>
/// The archive reads one file after the other straight into the stream, so even a large checkout never sits in
/// memory as a whole.
/// </remarks>
private static async Task WriteCheckoutArchiveAsync(Stream stream, string repositoryDirectory, IReadOnlyList<string> 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}");
}
/// <summary>
/// Reads the commit the local checkout stands on, which the summary names before the build.
/// </summary>
/// <returns>The hash of the commit, or null when the checkout has none.</returns>
private static async Task<string?> 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;
}
/// <summary>
/// Lists the files of the local checkout which go into the Flatpak.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <returns>The paths relative to the repository, with forward slashes, or null when git fails.</returns>
private static async Task<IReadOnlyList<string>?> 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();
}
/// <summary>
/// Describes the local checkout with its branch and the number of files which differ from its commit.
/// </summary>
/// <remarks>
/// git status refreshes the index by default, which is a change to the repository. Without optional locks, it
/// only reads.
/// </remarks>
private static async Task<string> 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}";
}
/// <summary>
/// Names the bundles in the output folder, with their sizes and SHA-256 hashes.
/// </summary>
/// <returns>True, when both bundles are there.</returns>
private static async Task<bool> 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;
}
}
+13
View File
@@ -0,0 +1,13 @@
namespace Build.Commands;
/// <summary>
/// Which state of AI Studio goes into a Flatpak which the build command "flatpak" builds.
/// </summary>
public enum FlatpakSource
{
NONE,
MAIN,
PULL_REQUEST,
LOCAL,
}
@@ -0,0 +1,44 @@
namespace Build.Commands;
public static class FlatpakSourceExtensions
{
/// <param name="source">The state of AI Studio which goes into the Flatpak.</param>
extension(FlatpakSource source)
{
/// <summary>
/// The name of the source for the option --source.
/// </summary>
public string Name => source switch
{
FlatpakSource.MAIN => "main",
FlatpakSource.PULL_REQUEST => "pr",
FlatpakSource.LOCAL => "local",
_ => string.Empty,
};
/// <summary>
/// What the source builds, and what for.
/// </summary>
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,
};
/// <summary>
/// All sources the command offers, in the order of its menu.
/// </summary>
public static IReadOnlyList<FlatpakSource> All => [FlatpakSource.MAIN, FlatpakSource.PULL_REQUEST, FlatpakSource.LOCAL];
/// <summary>
/// Finds the source for its name.
/// </summary>
/// <param name="name">The name of the source, as the option --source takes it.</param>
/// <returns>The source, or NONE for an unknown name.</returns>
public static FlatpakSource FromName(string name) => FlatpakSource.All.FirstOrDefault(candidate => string.Equals(candidate.Name, name.Trim(), StringComparison.OrdinalIgnoreCase));
}
}
+256
View File
@@ -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"
+9 -3
View File
@@ -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)
{
+12
View File
@@ -0,0 +1,12 @@
namespace Build.Tools;
/// <summary>
/// What an external tool wrote to its standard output, and how it ended.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="Text">Everything the tool wrote to its standard output.</param>
/// <param name="ExitCode">The exit code of the tool, where anything but zero is a failure.</param>
public readonly record struct CapturedOutput(string Text, int ExitCode);
+111 -5
View File
@@ -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);
}
}
/// <summary>
/// Runs a tool with a list of arguments and waits for it.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="workingDirectory">Where the tool should run.</param>
/// <param name="fileName">The tool, as it is called on the PATH.</param>
/// <param name="arguments">What to pass it, one argument per entry.</param>
/// <param name="writeInput">Writes the standard input of the tool, or null when the tool reads none. The input ends once the callback returns.</param>
/// <returns>The exit code of the tool, or COULD_NOT_START when it never ran.</returns>
public static async Task<int> RunAsync(string workingDirectory, string fileName, IReadOnlyList<string> arguments, Func<Stream, Task>? 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);
}
}
/// <summary>
/// Runs a tool with a list of arguments and collects what it writes to its standard output.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="workingDirectory">Where the tool should run.</param>
/// <param name="fileName">The tool, as it is called on the PATH.</param>
/// <param name="arguments">What to pass it, one argument per entry.</param>
/// <returns>The standard output and the exit code of the tool; the exit code is COULD_NOT_START when it never ran.</returns>
public static async Task<CapturedOutput> ReadOutputAsync(string workingDirectory, string fileName, IReadOnlyList<string> 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<string> 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<string> 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;
}
}