diff --git a/.gitattributes b/.gitattributes index 62a08f33..b56fc532 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,9 +2,14 @@ *.cs eol=lf *.json eol=lf *.txt eol=lf +# Shell scripts must always be LF; CRLF breaks them on Linux/macOS checkouts +*.sh eol=lf # Add any other file extensions that should use LF endings # Explicitly declare binary files to prevent line ending conversion *.exe binary *.dll binary +*.icns binary +*.ico binary +*.png binary diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..c085eaf7 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,95 @@ +name: Build and package + +on: + push: + branches: [ "master" ] + # matches both release tags (5.14.0) and pre-release tags (5.14.0-beta.1) + tags: [ "[0-9]+.[0-9]+.[0-9]+*" ] + pull_request: + branches: [ "master" ] + workflow_dispatch: + inputs: + version: + description: "Optional version override, eg 5.14.0. Leave empty to use the version derived from git tags." + required: false + type: string + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + # MinVer derives the version from tags, so the full history and tags are needed here too; without + # them every build would report 0.0.0-alpha.0 + fetch-depth: 0 + + - name: Install .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 10.0.x + + - name: Restore + run: dotnet restore + + - name: Test + run: dotnet test Tests/Tests.csproj -c Release --no-restore + + # build.sh cross-publishes every runtime, so a single host is enough. macOS is used because packaging the + # macOS bundles correctly needs ditto and codesign. + package: + needs: test + runs-on: macos-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + # MinVer needs the full history and tags to derive the version + fetch-depth: 0 + + - name: Install .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 10.0.x + + # The version comes from the git tag via MinVer, so no version file is read or written. + - name: Build + shell: bash + env: + VERSION_OVERRIDE: ${{ inputs.version }} + run: ./build.sh ${VERSION_OVERRIDE:+"$VERSION_OVERRIDE"} + + - name: Upload artifacts + uses: actions/upload-artifact@v4 + with: + name: object-editor + path: | + artifacts/*.zip + artifacts/*.tar.gz + if-no-files-found: error + retention-days: 14 + + release: + if: github.ref_type == 'tag' + needs: package + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Download artifacts + uses: actions/download-artifact@v4 + with: + path: artifacts + merge-multiple: true + + - name: Create draft release + uses: softprops/action-gh-release@v2 + with: + files: artifacts/* + draft: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/dotnet-desktop.yml b/.github/workflows/dotnet-desktop.yml deleted file mode 100644 index e745c99d..00000000 --- a/.github/workflows/dotnet-desktop.yml +++ /dev/null @@ -1,100 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -# This workflow will build, test, sign and package a WPF or Windows Forms desktop application -# built on .NET Core. -# To learn how to migrate your existing application to .NET Core, -# refer to https://docs.microsoft.com/en-us/dotnet/desktop-wpf/migration/convert-project-from-net-framework -# -# To configure this workflow: -# -# 1. Configure environment variables -# GitHub sets default environment variables for every workflow run. -# Replace the variables relative to your project in the "env" section below. -# -# 2. Signing -# Generate a signing certificate in the Windows Application -# Packaging Project or add an existing signing certificate to the project. -# Next, use PowerShell to encode the .pfx file using Base64 encoding -# by running the following Powershell script to generate the output string: -# -# $pfx_cert = Get-Content '.\SigningCertificate.pfx' -Encoding Byte -# [System.Convert]::ToBase64String($pfx_cert) | Out-File 'SigningCertificate_Encoded.txt' -# -# Open the output file, SigningCertificate_Encoded.txt, and copy the -# string inside. Then, add the string to the repo as a GitHub secret -# and name it "Base64_Encoded_Pfx." -# For more information on how to configure your signing certificate for -# this workflow, refer to https://github.com/microsoft/github-actions-for-desktop-apps#signing -# -# Finally, add the signing certificate password to the repo as a secret and name it "Pfx_Key". -# See "Build the Windows Application Packaging project" below to see how the secret is used. -# -# For more information on GitHub Actions, refer to https://github.com/features/actions -# For a complete CI/CD sample to get started with GitHub Action workflows for Desktop Applications, -# refer to https://github.com/microsoft/github-actions-for-desktop-apps - -name: .NET Core Desktop - -on: - push: - branches: [ "master" ] - pull_request: - branches: [ "master" ] - -jobs: - - build: - - strategy: - matrix: - configuration: [Release] - - runs-on: windows-latest # For a list of available runner types, refer to - # https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idruns-on - - env: - Solution_Name: OpenLocoToolGui # Replace with your solution name, i.e. MyWpfApp.sln. - # Test_Project_Path: your-test-project-path # Replace with the path to your test project, i.e. MyWpfApp.Tests\MyWpfApp.Tests.csproj - - steps: - - name: Generate Timestamp - id: timestamp - run: echo "::set-output name=timestamp::$(date +'%Y-%m-%d')" - - - name: Checkout - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - # Install the .NET workload - - name: Install .NET - uses: actions/setup-dotnet@v3 - with: - dotnet-version: 8.0.x - - # Execute all unit tests in the solution - #- name: Execute unit tests - # run: dotnet test - - - name: Restore dependencies - run: dotnet restore - - - name: Publish the application - run: dotnet publish -c Release -o ./publish - - - name: Create GitHub Release - id: create_release - uses: softprops/action-gh-release@v1 - with: - files: ./publish/* - tag_name: ${{ steps.timestamp.outputs.timestamp }} - name: Release ${{ steps.timestamp.outputs.timestamp }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - - name: Cleanup - run: rm -rf ./publish - diff --git a/Common/Common.csproj b/Common/Common.csproj index 5b501c5b..e5625bf2 100644 --- a/Common/Common.csproj +++ b/Common/Common.csproj @@ -9,7 +9,7 @@ - + diff --git a/Common/PlatformSpecific.cs b/Common/PlatformSpecific.cs index 3239aee4..6702b448 100644 --- a/Common/PlatformSpecific.cs +++ b/Common/PlatformSpecific.cs @@ -35,16 +35,46 @@ public static bool RunningAsAdmin() } public static string EditorPlatformZipName(OSPlatform platform) => - platform == OSPlatform.Windows ? "win-x64.zip" : - platform == OSPlatform.OSX ? "osx-x64.tar" : - platform == OSPlatform.Linux ? "linux-x64.tar" : - throw new PlatformNotSupportedException(); + EditorPlatformZipName(platform, RuntimeInformation.ProcessArchitecture); + + // mac: object-editor-5.3.5-osx-x64.zip / object-editor-5.3.5-osx-arm64.zip + // linux: object-editor-5.3.5-linux-x64.tar.gz + // win: object-editor-5.3.5-win-x64.zip + public static string EditorPlatformZipName(OSPlatform platform, Architecture architecture) + { + var rid = RuntimeIdentifierFor(platform, architecture); + + return platform == OSPlatform.Windows ? $"{rid}.zip" + : platform == OSPlatform.OSX ? $"{rid}.zip" + : platform == OSPlatform.Linux ? $"{rid}.tar.gz" + : throw new PlatformNotSupportedException(); + } public static string EditorPlatformBinaryName(OSPlatform platform) => - platform == OSPlatform.Windows ? $"{VersionHelpers.ObjectEditorName}.exe" : - platform == OSPlatform.OSX ? VersionHelpers.ObjectEditorName : - platform == OSPlatform.Linux ? VersionHelpers.ObjectEditorName : - throw new PlatformNotSupportedException(); + platform == OSPlatform.Windows ? $"{VersionHelpers.ObjectEditorName}.exe" + : platform == OSPlatform.OSX || platform == OSPlatform.Linux ? VersionHelpers.ObjectEditorName + : throw new PlatformNotSupportedException(); + + public static string EditorPlatformUpdaterName(OSPlatform platform) => + platform == OSPlatform.Windows ? $"{VersionHelpers.ObjectEditorUpdaterName}.exe" + : platform == OSPlatform.OSX || platform == OSPlatform.Linux ? VersionHelpers.ObjectEditorUpdaterName + : throw new PlatformNotSupportedException(); + + // the runtime identifier used by build.sh, eg win-x64, osx-arm64, linux-x64 + public static string RuntimeIdentifierFor(OSPlatform platform, Architecture architecture) + { + var arch = architecture switch + { + Architecture.X64 => "x64", + Architecture.Arm64 => "arm64", + _ => throw new PlatformNotSupportedException($"Architecture {architecture} is not supported."), + }; + + return platform == OSPlatform.Windows ? $"win-{arch}" + : platform == OSPlatform.OSX ? $"osx-{arch}" + : platform == OSPlatform.Linux ? $"linux-{arch}" + : throw new PlatformNotSupportedException(); + } public static OSPlatform GetPlatform => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? OSPlatform.Windows : diff --git a/Common/VersionHelpers.cs b/Common/VersionHelpers.cs index 68528c5b..0107c08e 100644 --- a/Common/VersionHelpers.cs +++ b/Common/VersionHelpers.cs @@ -3,8 +3,8 @@ using System.Diagnostics; using System.Net.Http.Headers; using System.Net.Http.Json; +using System.Reflection; using System.Runtime.InteropServices; -using System.Text; namespace Common; @@ -19,15 +19,15 @@ public static class VersionHelpers public static Process? OpenDownloadPage() => Process.Start(new ProcessStartInfo(GithubLatestReleaseDownloadPage) { UseShellExecute = true }); - // win: object-editor-5.3.5-win-x64.zip - // osx: object-editor-5.3.5-osx-x64.tar - // linux: object-editor-5.3.5-linux-x64.tar + // win: object-editor-5.3.5-win-x64.zip + // osx: object-editor-5.3.5-osx-arm64.zip (or -osx-x64.zip) + // linux: object-editor-5.3.5-linux-x64.tar.gz - static string DownloadFilename(SemanticVersion latestVersion, OSPlatform platform) - => $"object-editor-{latestVersion}-{PlatformSpecific.EditorPlatformZipName(platform)}"; + static string DownloadFilename(SemanticVersion latestVersion, OSPlatform platform, Architecture architecture) + => $"object-editor-{latestVersion}-{PlatformSpecific.EditorPlatformZipName(platform, architecture)}"; - public static string UrlForDownload(SemanticVersion latestVersion, OSPlatform platform) - => $"{GithubLatestReleaseDownloadPage}/download/{latestVersion}/{DownloadFilename(latestVersion, platform)}"; + public static string UrlForDownload(SemanticVersion latestVersion, OSPlatform platform, Architecture? architecture = null) + => $"{GithubLatestReleaseDownloadPage}/download/{latestVersion}/{DownloadFilename(latestVersion, platform, architecture ?? RuntimeInformation.ProcessArchitecture)}"; public static void StartAutoUpdater(ILogger logger, SemanticVersion currentVersion, SemanticVersion latestVersion) { @@ -48,17 +48,17 @@ public static void StartAutoUpdater(ILogger logger, SemanticVersion currentVersi } } - // The updater binary has no .exe suffix on Unix-like platforms. - var editorExe = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? $"{ObjectEditorUpdaterName}.exe" - : ObjectEditorUpdaterName; - if (!File.Exists(editorExe)) +var editorExe = PlatformSpecific.EditorPlatformUpdaterName(PlatformSpecific.GetPlatform); + // resolve relative to the editor's own folder: inside a macOS .app bundle the working directory + // is unrelated to where the binaries live + var editorExePath = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath) ?? ".", editorExe); + if (!File.Exists(editorExePath)) { - logger.LogError("Cannot find the auto-updater executable: {EditorExe}. You'll need to manually download the update.", editorExe); + logger.LogError("Cannot find the auto-updater executable: {EditorExePath}. You'll need to manually download the update.", editorExePath); return; } - var startInfo = new ProcessStartInfo(editorExe, + var startInfo = new ProcessStartInfo(editorExePath, [ "--pid", $"{Environment.ProcessId}", @@ -103,24 +103,17 @@ public static SemanticVersion GetCurrentAppVersion() return CachedSemanticVersion; } - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) - { - // version.txt is an embedded resource in the Definitions assembly - using var stream = assembly.GetManifestResourceStream("Definitions.version.txt") ?? assembly.GetManifestResourceStream("version.txt"); - if (stream == null) - { - continue; - } + // The version is baked into every assembly at build time by MinVer (from the git tag), so the running + // binary can never disagree with what it reports. SourceLink appends the commit hash as build metadata, + // which is not part of the version. + // Read from the assembly that defines this type rather than the entry assembly: it is always this + // product's assembly, even when the app is hosted by another process (eg a test runner or designer). + var informationalVersion = typeof(VersionHelpers).Assembly + .GetCustomAttribute()? + .InformationalVersion; - using var ms = new MemoryStream(); - stream.CopyTo(ms); - CachedSemanticVersion = GetVersionFromText(Encoding.ASCII.GetString(ms.ToArray())); - return CachedSemanticVersion; - } - - CachedSemanticVersion = UnknownVersion; + CachedSemanticVersion = GetVersionFromText(informationalVersion?.Split('+')[0]); return CachedSemanticVersion; - } // A single, process-wide HttpClient avoids socket exhaustion that comes from diff --git a/Dat/Dat.csproj b/Dat/Dat.csproj index 48e0de3f..d5a902bc 100644 --- a/Dat/Dat.csproj +++ b/Dat/Dat.csproj @@ -11,7 +11,7 @@ - + diff --git a/Definitions/Definitions.csproj b/Definitions/Definitions.csproj index 8a7053af..c4b96217 100644 --- a/Definitions/Definitions.csproj +++ b/Definitions/Definitions.csproj @@ -44,7 +44,6 @@ - Core.palette.png @@ -62,8 +61,8 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - - + + diff --git a/Definitions/version.txt b/Definitions/version.txt deleted file mode 100644 index 9f7a8aa9..00000000 --- a/Definitions/version.txt +++ /dev/null @@ -1 +0,0 @@ -5.13.1 diff --git a/Directory.Build.props b/Directory.Build.props index e4f77abf..1b234589 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -40,4 +40,16 @@ + + + + + \ No newline at end of file diff --git a/Gui/Assets/loco_icon.icns b/Gui/Assets/loco_icon.icns new file mode 100644 index 00000000..0d44b639 Binary files /dev/null and b/Gui/Assets/loco_icon.icns differ diff --git a/Gui/Gui.csproj b/Gui/Gui.csproj index a863a941..0bbd9a3b 100644 --- a/Gui/Gui.csproj +++ b/Gui/Gui.csproj @@ -11,12 +11,8 @@ true README.md https://github.com/OpenLoco/OpenLocoObjectEditor - $(Version) - $(Version) ObjectEditor $(AssemblyName) $(Version) - - 1.2.3 LeftofZen False Assets\loco_icon.ico @@ -31,6 +27,12 @@ + + + + + + @@ -51,11 +53,11 @@ - + - + diff --git a/Gui/PlatformSpecific.cs b/Gui/PlatformSpecific.cs index 20791605..6b2e8f15 100644 --- a/Gui/PlatformSpecific.cs +++ b/Gui/PlatformSpecific.cs @@ -36,18 +36,22 @@ static void FolderOpenInDesktopCore(string directory, string? filename = null) // Platform-specific command construction string command; + string arguments; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { command = "explorer.exe"; // Windows File Explorer + arguments = filename == null ? directory : $"/select, \"{Path.Combine(directory, filename)}\""; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { command = "open"; // macOS Finder + arguments = filename == null ? $"\"{directory}\"" : $"-R \"{Path.Combine(directory, filename)}\""; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { // Note: This assumes the user's desktop environment has a standard file manager command = "xdg-open"; + arguments = $"\"{directory}\""; } else { @@ -59,7 +63,7 @@ static void FolderOpenInDesktopCore(string directory, string? filename = null) var processStartInfo = new ProcessStartInfo { FileName = command, - Arguments = filename == null ? directory : $"/select, \"{Path.Combine(directory, filename)}\"", + Arguments = arguments, UseShellExecute = true // Use the shell for proper handling on each OS }; diff --git a/Gui/ViewModels/AudioViewModel.cs b/Gui/ViewModels/AudioViewModel.cs index 4101b3cb..359a69ae 100644 --- a/Gui/ViewModels/AudioViewModel.cs +++ b/Gui/ViewModels/AudioViewModel.cs @@ -143,10 +143,10 @@ public void PlaySound() return; } - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - // unfortunately NAudio is not cross-platform! this code just crashes on Linux - // so there isn't anything to do here until a cross-platform audio lib is used + // unfortunately NAudio's WaveOutEvent is Windows-only (winmm), so this code crashes on Linux and + // macOS. there isn't anything to do here until a cross-platform audio lib is used return; } diff --git a/Gui/version.txt b/Gui/version.txt deleted file mode 100644 index dd0ad7ae..00000000 --- a/Gui/version.txt +++ /dev/null @@ -1 +0,0 @@ -5.12.0 diff --git a/GuiUpdater/GuiUpdater.csproj b/GuiUpdater/GuiUpdater.csproj index 549c2a1d..26bacb98 100644 --- a/GuiUpdater/GuiUpdater.csproj +++ b/GuiUpdater/GuiUpdater.csproj @@ -7,11 +7,7 @@ README.md https://github.com/OpenLoco/OpenLocoObjectEditor ObjectEditorUpdater - $(Version) - $(Version) $(AssemblyName) $(Version) - - 1.2.3 LeftofZen False Assets\updater_icon.ico @@ -19,7 +15,7 @@ - + diff --git a/GuiUpdater/Program.cs b/GuiUpdater/Program.cs index e731ea5c..2db6e293 100644 --- a/GuiUpdater/Program.cs +++ b/GuiUpdater/Program.cs @@ -2,7 +2,9 @@ using NuGet.Versioning; using System.CommandLine; using System.Diagnostics; +using System.Formats.Tar; using System.IO.Compression; +using System.Runtime.InteropServices; var pidOption = new Option("--pid") { Description = "The process ID of the main application to wait for it to exit." }; var appPathOption = new Option("--app-path") { Description = "The path to the main application executable to restart." }; @@ -26,6 +28,7 @@ async Task UpdateEditor(ParseResult parseResult, CancellationToken cancellationT { var programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ApplicationName); var loggingFile = Path.Combine(programDataPath, LoggingFileName); +_ = Directory.CreateDirectory(programDataPath); // FileMode.Create truncates the log; File.OpenWrite would leave stale trailing text from a // previous, longer run appended after the new (shorter) contents. using var logStream = new StreamWriter(File.Create(loggingFile)); @@ -54,7 +57,7 @@ async Task UpdateEditor(ParseResult parseResult, CancellationToken cancellationT Console.WriteLine("Current version is empty"); } - // latest version +// latest version var latestVersion = await GetLatestVersionAsync(cancellationToken); if (latestVersion == null) @@ -99,10 +102,11 @@ async Task UpdateEditor(ParseResult parseResult, CancellationToken cancellationT } // actually download - var url = VersionHelpers.UrlForDownload(latestVersion, PlatformSpecific.GetPlatform); + var platform = PlatformSpecific.GetPlatform; + var url = VersionHelpers.UrlForDownload(latestVersion, platform); var filename = Path.GetFileName(url); - var tempZipPath = Path.Combine(Path.GetTempPath(), filename); - var extractionPath = Path.GetDirectoryName(appPath); + var tempArchivePath = Path.Combine(Path.GetTempPath(), filename); + var extractionPath = GetInstallRoot(appPath, platform); if (string.IsNullOrEmpty(extractionPath)) { @@ -117,16 +121,17 @@ async Task UpdateEditor(ParseResult parseResult, CancellationToken cancellationT { var response = await httpClient.GetAsync(url, cancellationToken); _ = response.EnsureSuccessStatusCode(); - await using (var fs = new FileStream(tempZipPath, FileMode.Create, FileAccess.Write, FileShare.None)) + await using (var fs = new FileStream(tempArchivePath, FileMode.Create, FileAccess.Write, FileShare.None)) { await response.Content.CopyToAsync(fs, cancellationToken); } } - Console.WriteLine($"Update downloaded to {tempZipPath}."); + Console.WriteLine($"Update downloaded to {tempArchivePath}."); Console.WriteLine($"Extracting update to {extractionPath}..."); - ZipFile.ExtractToDirectory(tempZipPath, extractionPath, true); + ExtractArchive(tempArchivePath, extractionPath); + RestoreExecutablePermissions(extractionPath, platform); Console.WriteLine("Extraction complete"); } catch (Exception ex) @@ -136,14 +141,107 @@ async Task UpdateEditor(ParseResult parseResult, CancellationToken cancellationT } finally { - if (File.Exists(tempZipPath)) + if (File.Exists(tempArchivePath)) { - File.Delete(tempZipPath); + File.Delete(tempArchivePath); } } Console.WriteLine($"Restarting editor at: {appPath}"); - _ = Process.Start(new ProcessStartInfo(appPath) { UseShellExecute = false, CreateNoWindow = true, }); + if (platform == OSPlatform.OSX) + { + // relaunch through `open` so macOS boots the bundle properly rather than the raw inner binary + var appBundlePath = GetMacAppBundlePath(appPath) ?? appPath; + _ = Process.Start(new ProcessStartInfo("open", ["-n", appBundlePath]) { UseShellExecute = false, CreateNoWindow = true, }); + } + else + { + _ = Process.Start(new ProcessStartInfo(appPath) { UseShellExecute = false, CreateNoWindow = true, }); + } +} + +// the directory the archive should be extracted into, ie the folder that holds the app/bundle +static string? GetInstallRoot(string appPath, OSPlatform platform) +{ + if (platform == OSPlatform.OSX) + { + // appPath is /ObjectEditor.app/Contents/MacOS/ObjectEditor, and the archive contains + // ObjectEditor.app/..., so extract into + var bundlePath = GetMacAppBundlePath(appPath); + return bundlePath == null ? null : Path.GetDirectoryName(bundlePath); + } + + return Path.GetDirectoryName(appPath); +} + +// eg /Applications/ObjectEditor.app/Contents/MacOS/ObjectEditor -> /Applications/ObjectEditor.app +static string? GetMacAppBundlePath(string appPath) +{ + var directory = new DirectoryInfo(Path.GetDirectoryName(appPath) ?? "."); + // walk up looking for the .app directory + for (var i = 0; i < 3 && directory != null; i++) + { + if (directory.Extension == ".app") + { + return directory.FullName; + } + + directory = directory.Parent; + } + + return null; +} + +static void ExtractArchive(string archivePath, string destination) +{ + if (archivePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) + { + ZipFile.ExtractToDirectory(archivePath, destination, true); + } + else if (archivePath.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase) || archivePath.EndsWith(".tgz", StringComparison.OrdinalIgnoreCase)) + { + using var fileStream = File.OpenRead(archivePath); + using var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress); + TarFile.ExtractToDirectory(gzipStream, destination, true); + } + else + { + throw new NotSupportedException($"Unsupported archive type: \"{Path.GetFileName(archivePath)}\""); + } +} + +// zip archives do not carry unix file modes, so the extracted binaries need their exec bit setting +static void RestoreExecutablePermissions(string installRoot, OSPlatform platform) +{ + if (OperatingSystem.IsWindows()) + { + return; + } + + const UnixFileMode executableMode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute + | UnixFileMode.GroupRead | UnixFileMode.GroupExecute + | UnixFileMode.OtherRead | UnixFileMode.OtherExecute; + + var executablePaths = platform == OSPlatform.OSX + ? new[] + { + Path.Combine(installRoot, "ObjectEditor.app", "Contents", "MacOS", VersionHelpers.ObjectEditorName), + Path.Combine(installRoot, "ObjectEditor.app", "Contents", "MacOS", VersionHelpers.ObjectEditorUpdaterName), + } + : new[] + { + Path.Combine(installRoot, VersionHelpers.ObjectEditorName), + Path.Combine(installRoot, VersionHelpers.ObjectEditorUpdaterName), + }; + + foreach (var path in executablePaths) + { + if (File.Exists(path)) + { + File.SetUnixFileMode(path, executableMode); + Console.WriteLine($"Restored executable permissions on \"{path}\""); + } + } } static async Task GetLatestVersionAsync(CancellationToken cancellationToken) diff --git a/PaletteGenerator/PaletteGenerator.csproj b/PaletteGenerator/PaletteGenerator.csproj index 49de282f..8e05ca80 100644 --- a/PaletteGenerator/PaletteGenerator.csproj +++ b/PaletteGenerator/PaletteGenerator.csproj @@ -8,7 +8,7 @@ - + diff --git a/README.md b/README.md index ddac3f7f..3be37ee1 100644 --- a/README.md +++ b/README.md @@ -159,8 +159,43 @@ A modern implementation of 'LocoTool' for Locomotion `dat` file parsing and edit - Open `ObjectEditor.sln` in Visual Studio - You'll need the `Avalonia for Visual Studio` plugin to use the visual XAML previewer, but it isn't required to actually build or run the editor +# Versioning +Versions are derived from git tags by [MinVer](https://github.com/adamralph/minver) — the standard +approach for .NET SDK projects. There is no version file to keep in sync; tagging a commit *is* the +release. + +- A commit tagged `5.14.0` builds as `5.14.0`. +- Any other commit builds as the next patch pre-release, with the number of commits since the last + tag: e.g. 19 commits after `5.13.1` builds as `5.13.2-alpha.0.19`. +- MinVer sets `AssemblyVersion`, `FileVersion`, `InformationalVersion` and `Version` for every + project, and the editor reports its version by reading the informational version from its own + assembly — so the version shown in the UI always matches the binaries and the artifact name. + # Deploying -See `build.sh` and `tag.sh` +Run `./build.sh` from the repository root. The version is taken from git tags (pass an argument such +as `./build.sh 5.14.0` to override it). It publishes a self-contained, single-file build of the +editor and the updater for every supported platform and writes the release artifacts to `artifacts/`: + +| Platform | Runtime identifier | Artifact | +| --- | --- | --- | +| Windows | `win-x64` | `object-editor--win-x64.zip` | +| Linux | `linux-x64` | `object-editor--linux-x64.tar.gz` | +| macOS (Intel) | `osx-x64` | `object-editor--osx-x64.zip` | +| macOS (Apple silicon) | `osx-arm64` | `object-editor--osx-arm64.zip` | + +- The macOS artifacts are zipped `ObjectEditor.app` bundles: unzip, then drag the app to + `/Applications`. The bundles are only ad-hoc signed, so on first launch macOS Gatekeeper may + require right-clicking the app and choosing *Open*. Distributing a fully notarised build requires + an Apple Developer ID certificate, which is applied outside this script. +- Archives are named after the runtime identifier above; the in-editor auto-updater downloads the + matching file, so these names are part of the update contract (covered by `VersioningTests`). +- `tag.sh ` publishes the current commit (pushing it and setting upstream if needed), then tags + and pushes the tag. It refuses to run if the tree is dirty, the tag already exists locally or on the + remote, or the branch has diverged from the remote. Pushing a `x.y.z` or `x.y.z-prerelease` tag runs + the `Build and package` workflow, which tests, builds all artifacts and attaches them to a draft + GitHub release. No commit is needed to bump the version. +- Release builds can also be triggered manually from the *Actions* tab, with an optional version + override. # Database Schema Migration - `dotnet ef migrations add ` diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index d95726ff..177246ec 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -13,13 +13,13 @@ - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Tests/VersioningTests.cs b/Tests/VersioningTests.cs index afb2437a..fedb83d1 100644 --- a/Tests/VersioningTests.cs +++ b/Tests/VersioningTests.cs @@ -1,6 +1,8 @@ using Common; using NuGet.Versioning; using NUnit.Framework; +using System.Diagnostics; +using System.Reflection; using System.Runtime.InteropServices; namespace Tests; @@ -8,16 +10,97 @@ namespace Tests; [TestFixture] public class VersioningTests { - static object[] TestInput => + static object[] PlatformInput => [ new object[]{ new SemanticVersion(1, 0, 0), OSPlatform.Windows }, new object[]{ new SemanticVersion(1, 0, 0), OSPlatform.Linux }, new object[]{ new SemanticVersion(1, 0, 0), OSPlatform.OSX }, ]; - [TestCaseSource(nameof(TestInput))] + static object[] PlatformAndArchitectureInput => + [ + new object[]{ OSPlatform.Windows, Architecture.X64, "win-x64.zip" }, + new object[]{ OSPlatform.Windows, Architecture.Arm64, "win-arm64.zip" }, + new object[]{ OSPlatform.Linux, Architecture.X64, "linux-x64.tar.gz" }, + new object[]{ OSPlatform.Linux, Architecture.Arm64, "linux-arm64.tar.gz" }, + new object[]{ OSPlatform.OSX, Architecture.X64, "osx-x64.zip" }, + new object[]{ OSPlatform.OSX, Architecture.Arm64, "osx-arm64.zip" }, + ]; + + static object[] UpdaterNameInput => + [ + new object[]{ OSPlatform.Windows, "ObjectEditorUpdater.exe" }, + new object[]{ OSPlatform.Linux, "ObjectEditorUpdater" }, + new object[]{ OSPlatform.OSX, "ObjectEditorUpdater" }, + ]; + + [TestCaseSource(nameof(PlatformInput))] public void TestUrlForDownload(SemanticVersion version, OSPlatform platform) { Assert.That(VersionHelpers.UrlForDownload(version, platform), Is.EqualTo($"https://github.com/OpenLoco/ObjectEditor/releases/download/{version}/object-editor-{version}-{PlatformSpecific.EditorPlatformZipName(platform)}")); } + + [TestCaseSource(nameof(PlatformAndArchitectureInput))] + public void TestEditorPlatformZipName(OSPlatform platform, Architecture architecture, string expected) + { + Assert.That(PlatformSpecific.EditorPlatformZipName(platform, architecture), Is.EqualTo(expected)); + } + + [TestCaseSource(nameof(PlatformAndArchitectureInput))] + public void TestUrlForDownloadMatchesBuildArtifact(OSPlatform platform, Architecture architecture, string expected) + { + var version = new SemanticVersion(1, 2, 3); + + // the URL the updater downloads must be the exact file name build.sh produces + Assert.That(VersionHelpers.UrlForDownload(version, platform, architecture), Is.EqualTo($"https://github.com/OpenLoco/ObjectEditor/releases/download/{version}/object-editor-{version}-{expected}")); + } + + [TestCaseSource(nameof(UpdaterNameInput))] + public void TestEditorPlatformUpdaterName(OSPlatform platform, string expected) + { + Assert.That(PlatformSpecific.EditorPlatformUpdaterName(platform), Is.EqualTo(expected)); + } + + [Test] + public void TestUnsupportedArchitectureThrows() + { + Assert.Throws(() => PlatformSpecific.EditorPlatformZipName(OSPlatform.Windows, Architecture.X86)); + } + + [Test] + public void TestCurrentAppVersionMatchesAssembly() + { + // the version is baked in by MinVer, so it must be reported from the assembly and never be the old + // hard-coded placeholder + var version = VersionHelpers.GetCurrentAppVersion(); + + Assert.That(version, Is.Not.EqualTo(VersionHelpers.UnknownVersion)); + + var informationalVersion = typeof(VersionHelpers).Assembly + .GetCustomAttribute()? + .InformationalVersion? + .Split('+')[0]; + + Assert.That(version.ToString(), Is.EqualTo(informationalVersion)); + Assert.That(version.ToString(), Is.Not.EqualTo("1.2.3"), "the version should come from the build, not a placeholder"); + + // 0.0.0-alpha.0 is MinVer's no-tag fallback; only tolerate it in a tagless checkout (eg a shallow CI clone) + var hasVersionTag = new ProcessStartInfo("git", "describe --tags") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + + using var process = Process.Start(hasVersionTag); + _ = process?.StandardOutput.ReadToEnd(); + _ = process?.StandardError.ReadToEnd(); + process?.WaitForExit(); + + if (process?.ExitCode == 0) + { + Assert.That(version, Is.Not.EqualTo(new SemanticVersion(0, 0, 0, "alpha.0")), + "a tag was available, so the version must not be MinVer's no-tag fallback"); + } + } } diff --git a/build.sh b/build.sh index 955af6a3..60078a27 100644 --- a/build.sh +++ b/build.sh @@ -4,85 +4,272 @@ # ./build.sh 1.2.3 # immediately abort script on error -set -e +set -euo pipefail -# Define color variables for readability -FG_BLUE=$(tput setaf 39) -BG_BLUE=$(tput setab 39) -FG_GREEN=$(tput setaf 46) -BG_GREEN=$(tput setab 46) -RESET=$(tput sgr0) +# Define color variables for readability. tput fails when there is no terminal (eg CI), so fall back to no color. +if command -v tput > /dev/null 2>&1 && [ -n "${TERM:-}" ]; then + FG_BLUE=$(tput setaf 39 2> /dev/null || true) + FG_GREEN=$(tput setaf 46 2> /dev/null || true) + RESET=$(tput sgr0 2> /dev/null || true) +else + FG_BLUE="" + FG_GREEN="" + RESET="" +fi +# Always operate from the repository root, regardless of where the script is invoked from +cd "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# 1. Get the version from the first command-line argument -if [ -z "$1" ]; then - echo "Error: Please provide the version as the first argument." - exit 1 +# 1. Restore first: the MinVer target is provided by a NuGet package, so it does not exist until packages +# have been restored. Doing this up front also means a clean checkout works. +echo "Restoring packages" +dotnet restore Gui/Gui.csproj +dotnet restore GuiUpdater/GuiUpdater.csproj + +# 2. Determine the version. MinVer (see Directory.Build.props) derives it from the git tag, so the version is +# normally whatever `git describe` resolves to. An explicit argument overrides it, which is useful for CI or +# for producing a build for a tag before it exists. +version="${1:-}" + +if [ -n "$version" ]; then + if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]]; then + echo "Error: \"$version\" is not a valid semantic version (expected eg 1.2.3 or 1.2.3-beta.1)." + exit 1 + fi + min_ver_override=(-p:MinVerVersionOverride="$version") +else + # ask MSBuild for the version MinVer will bake into the assemblies, so the artifact names always match the + # version reported by the running app + version=$(dotnet msbuild Gui/Gui.csproj -t:MinVer -getProperty:Version -nologo 2> /dev/null | tr -d '[:space:]') + + if [ -z "$version" ]; then + echo "Error: Unable to determine the version. Please provide it as the first argument, eg ./build.sh 1.2.3" + exit 1 + fi + + # MinVer falls back to 0.0.0-alpha.0 when no version tag is reachable, which means the checkout is + # shallow or has no tags. Refuse to ship an artifact with a meaningless version. + case "$version" in + 0.0.0*) + echo "Error: No version tag was found, so the version resolved to \"$version\"." + echo " Fetch the full history and tags (git fetch --tags --unshallow), or pass the version explicitly." + exit 1 + ;; + esac + + min_ver_override=() fi -version="$1" +# Apple's CFBundleShortVersionString/CFBundleVersion only accept digits and dots +base_version="${version%%-*}" +base_version="${base_version%%+*}" + +# read .net version from csproj file +framework=$(grep -m1 '' Gui/Gui.csproj | sed 's/.*\(.*\)<\/TargetFramework>.*/\1/') + +if [ -z "$framework" ]; then + echo "Error: Unable to determine the target framework from Gui/Gui.csproj." + exit 1 +fi echo "=== Building Object Editor v${FG_BLUE}$version${RESET} for ${FG_BLUE}$framework${RESET} ===" -# read .net version from csproj file -framework=$(grep '' Gui/Gui.csproj | sed 's/.*\(.*\)<\/TargetFramework>.*/\1/') - -# 2. Write the version to version.txt. This is read by the UI to know the current version. -echo "$version" > Definitions/version.txt - -# 3. Build the editor for different platforms -echo "Building the ${FG_BLUE}Editor${RESET}" -dotnet publish Gui/Gui.csproj -c Release -p:WarningLevel=0 -p:PublishSingleFile=true -p:Version=$version --self-contained --runtime win-x64 -dotnet publish Gui/Gui.csproj -c Release -p:WarningLevel=0 -p:PublishSingleFile=true -p:Version=$version --self-contained --runtime linux-x64 -dotnet publish Gui/Gui.csproj -c Release -p:WarningLevel=0 -p:PublishSingleFile=true -p:Version=$version --self-contained --runtime osx-x64 - -echo "Building the ${FG_BLUE}Updater${RESET}" -dotnet publish GuiUpdater/GuiUpdater.csproj -c Release -p:PublishSingleFile=true -p:Version=$version --self-contained --runtime win-x64 -dotnet publish GuiUpdater/GuiUpdater.csproj -c Release -p:PublishSingleFile=true -p:Version=$version --self-contained --runtime linux-x64 -dotnet publish GuiUpdater/GuiUpdater.csproj -c Release -p:PublishSingleFile=true -p:Version=$version --self-contained --runtime osx-x64 - -# 4. Copy updater into release folders -echo "Copying ${FG_BLUE}Updater${RESET} files into ${FG_BLUE}Gui${RESET} folders" -cp GuiUpdater/bin/Release/$framework/win-x64/publish/* Gui/bin/Release/$framework/win-x64/publish -cp GuiUpdater/bin/Release/$framework/linux-x64/publish/* Gui/bin/Release/$framework/linux-x64/publish -cp GuiUpdater/bin/Release/$framework/osx-x64/publish/* Gui/bin/Release/$framework/osx-x64/publish - -# 4.5 Remove debug symbol (.pdb) files from the publish folders before archiving. -# These are not needed by end users but otherwise inflate the release archives by -# ~100MB on Windows (native libSkiaSharp.pdb / libHarfBuzzSharp.pdb are the big ones). -echo "Deleting debug symbol (.pdb) files from the publish folders" -find Gui/bin/Release/$framework/win-x64/publish -name '*.pdb' -delete -find Gui/bin/Release/$framework/linux-x64/publish -name '*.pdb' -delete -find Gui/bin/Release/$framework/osx-x64/publish -name '*.pdb' -delete - -# 5. Create the zip and tar archives -pushd "Gui/bin/Release/$framework/" - -echo "Zipping ${FG_BLUE}win-x64${RESET}" -pushd "win-x64/publish" -zip -r "object-editor-$version-win-x64.zip" . -mv "object-editor-$version-win-x64.zip" ../../.. -popd - -echo "Zipping ${FG_BLUE}linux-x64${RESET}" -pushd "linux-x64/publish" -chmod +x "./ObjectEditor" -chmod +x "./ObjectEditorUpdater" -# error happens if you make tar file inside the dir its zipping. hack is to touch it first then exclude it -touch "object-editor-$version-linux-x64.tar" -tar --exclude="object-editor-$version-linux-x64.tar" -jcf "object-editor-$version-linux-x64.tar" . -mv "object-editor-$version-linux-x64.tar" ../../.. -popd - -echo "Zipping ${FG_BLUE}osx-x64${RESET}" -pushd "osx-x64/publish" -chmod +x "./ObjectEditor" -chmod +x "./ObjectEditorUpdater" -# error happens if you make tar file inside the dir its zipping. hack is to touch it first then exclude it -touch "object-editor-$version-osx-x64.tar" -tar --exclude="object-editor-$version-osx-x64.tar" -jcf "object-editor-$version-osx-x64.tar" . -mv "object-editor-$version-osx-x64.tar" ../../.. -popd - -popd -echo "=== Build and packaging ${FG_GREEN}complete${RESET}! ===" +app_name="ObjectEditor" +updater_name="ObjectEditorUpdater" +mac_bundle_id="com.openloco.objecteditor" +mac_min_os="15.0" +mac_icon="Gui/Assets/loco_icon.icns" + +artifacts_dir="artifacts" +# archives are created from inside a staging directory, so the output path must be absolute +artifacts_root="$(pwd)/$artifacts_dir" +publish_root="$artifacts_root/publish" +rm -rf "$artifacts_root" +mkdir -p "$publish_root" + +# Publish both the editor and the updater into a single staging folder for the given runtime identifier. +# The restore is intentionally left to `dotnet publish` (ie no --no-restore): a restore performed without a +# runtime identifier does not produce the rid-specific assets that publish needs (NETSDK1047). +publish_rid() { + local rid="$1" + local out="$publish_root/$rid" + + rm -rf "$out" + mkdir -p "$out" + + echo "Publishing ${FG_BLUE}Editor${RESET} ($rid)" + dotnet publish Gui/Gui.csproj -c Release -p:WarningLevel=0 -p:PublishSingleFile=true "${min_ver_override[@]}" --self-contained -r "$rid" -o "$out" + + echo "Publishing ${FG_BLUE}Updater${RESET} ($rid)" + dotnet publish GuiUpdater/GuiUpdater.csproj -c Release -p:PublishSingleFile=true "${min_ver_override[@]}" --self-contained -r "$rid" -o "$out" + + # Debug symbols are not needed by end users but inflate the archives by ~100MB + find "$out" -name '*.pdb' -delete +} + +zip_dir() { + local dir="$1" + local archive="$2" + rm -f "$archive" + (cd "$dir" && zip -r $ZIP_SYMLINK_OPTS "$archive" .) +} + +# -y stores symlinks as symlinks instead of following them, which macOS app bundles rely on. +# Some Info-ZIP builds (eg the one bundled with git on Windows) do not support it, so probe for real. +detect_zip_symlink_support() { + local probe_dir + probe_dir=$(mktemp -d) + if (cd "$probe_dir" && echo probe > file.txt && zip -q -y probe.zip file.txt > /dev/null 2>&1); then + ZIP_SYMLINK_OPTS="-y" + else + ZIP_SYMLINK_OPTS="" + fi + rm -rf "$probe_dir" +} +detect_zip_symlink_support + +# GNU tar can force file modes from the command line, which is needed when building on Windows where +# chmod records nothing. macOS ships bsdtar, which has no --mode, so probe for it. +detect_tar_mode_support() { + local probe_dir + probe_dir=$(mktemp -d) + if (cd "$probe_dir" && echo probe > file.txt && tar -cf probe.tar --mode='u+rwx,go+rx' file.txt > /dev/null 2>&1); then + TAR_MODE_OPTS="--mode=u+rwx,go+rx" + else + TAR_MODE_OPTS="" + fi + rm -rf "$probe_dir" +} +detect_tar_mode_support + +build_windows() { + local rid="win-x64" + local out="$publish_root/$rid" + local archive="$artifacts_root/object-editor-$version-$rid.zip" + + publish_rid "$rid" + + echo "Zipping ${FG_BLUE}$rid${RESET}" + zip_dir "$out" "$archive" + # free the staging copy immediately; a self-contained publish is several hundred MB per rid + rm -rf "$out" +} + +build_linux() { + local rid="linux-x64" + local out="$publish_root/$rid" + local archive="$artifacts_root/object-editor-$version-$rid.tar.gz" + local tar_file="$artifacts_root/object-editor-$version-$rid.tar" + + publish_rid "$rid" + + echo "Creating gzip tarball for ${FG_BLUE}$rid${RESET}" + rm -f "$archive" "$tar_file" + # The binaries get explicit exec bits rather than relying on chmod, which records nothing on Windows hosts. + # The archive lives outside $out, so it can never include itself. + tar -cf "$tar_file" -C "$out" --exclude="./$app_name" --exclude="./$updater_name" . + if [ -n "$TAR_MODE_OPTS" ]; then + tar -rf "$tar_file" -C "$out" $TAR_MODE_OPTS ./$app_name ./$updater_name + else + # bsdtar/macOS: commit the bit on disk first, then add the entry + chmod +x "$out/$app_name" "$out/$updater_name" + tar -rf "$tar_file" -C "$out" ./$app_name ./$updater_name + fi + gzip -n -f "$tar_file" + rm -rf "$out" +} + +write_info_plist() { + local destination="$1" + + cat > "$destination" < + + + + CFBundleName + $app_name + CFBundleDisplayName + $app_name + CFBundleExecutable + $app_name + CFBundleIdentifier + $mac_bundle_id + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + APPL + CFBundleShortVersionString + $base_version + CFBundleVersion + $base_version + CFBundleIconFile + loco_icon + LSMinimumSystemVersion + $mac_min_os + NSHighResolutionCapable + + + +EOF +} + +build_macos() { + local rid="$1" + local out="$publish_root/$rid" + local bundle_root="$publish_root/macos/$rid" + local bundle_dir="$bundle_root/$app_name.app" + local archive="$artifacts_root/object-editor-$version-$rid.zip" + + publish_rid "$rid" + + echo "Creating ${FG_BLUE}macOS .app bundle ($rid)${RESET}" + # the bundle is assembled outside the publish folder so publishing output never gets copied into itself + rm -rf "$bundle_root" + mkdir -p "$bundle_dir/Contents/MacOS" "$bundle_dir/Contents/Resources" + + cp -R "$out"/. "$bundle_dir/Contents/MacOS/" + chmod +x "$bundle_dir/Contents/MacOS/$app_name" "$bundle_dir/Contents/MacOS/$updater_name" + + printf 'APPL????' > "$bundle_dir/Contents/PkgInfo" + + if [ ! -f "$mac_icon" ]; then + echo "Error: macOS icon \"$mac_icon\" is missing." + exit 1 + fi + cp "$mac_icon" "$bundle_dir/Contents/Resources/loco_icon.icns" + + write_info_plist "$bundle_dir/Contents/Info.plist" + + # ad-hoc sign so Gatekeeper lets a locally-built bundle launch. Developer ID signing/notarisation + # requires certificates and is done outside this script. + if command -v codesign > /dev/null 2>&1; then + echo "Ad-hoc signing ${FG_BLUE}$app_name.app${RESET}" + codesign --force --deep --sign - "$bundle_dir" + fi + + echo "Zipping ${FG_BLUE}$rid${RESET}" + rm -f "$archive" + if command -v ditto > /dev/null 2>&1; then + # ditto preserves permissions and extended attributes, which macOS app bundles rely on + ditto -c -k --sequesterRsrc --keepParent "$bundle_dir" "$archive" + else + # fallback for building macOS artifacts on non-macOS hosts. this zip does not carry unix file modes, + # so the extracted binaries are not executable until the in-app updater fixes them. + echo "Warning: ditto is unavailable; the macOS zip will not record executable permissions." + (cd "$bundle_root" && zip -r $ZIP_SYMLINK_OPTS "$archive" "$app_name.app") + fi + + # free the staging copies immediately; a self-contained publish is several hundred MB per rid + rm -rf "$bundle_root" "$out" +} + +# 2. Build the editor for each platform. These run sequentially because the publishes share the projects' +# obj/ folders, so running them concurrently would race. +build_windows +build_linux +build_macos "osx-x64" +build_macos "osx-arm64" + +echo "=== Build and packaging ${FG_GREEN}complete${RESET}! Artifacts are in ${FG_BLUE}$artifacts_dir${RESET} ===" +ls -1 "$artifacts_root"/*.zip "$artifacts_root"/*.tar.gz 2> /dev/null || true diff --git a/tag.sh b/tag.sh index ab9be535..bde054d1 100644 --- a/tag.sh +++ b/tag.sh @@ -3,25 +3,85 @@ # example usage: # ./tag.sh 1.2.3 +# immediately abort script on error +set -euo pipefail + +# Always operate from the repository root, regardless of where the script is invoked from +cd "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + # 1. Get the version from the first command-line argument -if [ -z "$1" ]; then +if [ -z "${1:-}" ]; then echo "Error: Please provide the version as the first argument." exit 1 fi version="$1" -echo "Building version $version" +if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]]; then + echo "Error: \"$version\" is not a valid semantic version (expected eg 1.2.3 or 1.2.3-beta.1)." + exit 1 +fi -# 2. Write the version to version.txt. This is purely to generate a commit on master for new version -echo "$version" > Definitions/version.txt +if [ -n "$(git status --porcelain)" ]; then + echo "Error: The working tree has uncommitted changes. Commit or stash them before tagging a release." + exit 1 +fi -# 3. Make a release commit -git add Definitions/version.txt -git commit -m "prepare $version" -git push +if git rev-parse -q --verify "refs/tags/$version" > /dev/null; then + echo "Error: Tag \"$version\" already exists." + exit 1 +fi + +# 2. Work out which remote/branch this commit should be published to +branch=$(git branch --show-current) +if [ -z "$branch" ]; then + echo "Error: HEAD is detached. Check out the branch you want to release before tagging." + exit 1 +fi -## 4. Make a tag +if upstream=$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2> /dev/null); then + remote="${upstream%%/*}" + remote_branch="${upstream#*/}" +else + remote="origin" + remote_branch="$branch" + echo "No upstream is configured for \"$branch\"; assuming \"$remote/$remote_branch\"." +fi + +remote_ref="$remote/$remote_branch" + +if git ls-remote --exit-code --tags "$remote" "refs/tags/$version" > /dev/null 2>&1; then + echo "Error: Tag \"$version\" already exists on \"$remote\"." + exit 1 +fi + +# 3. Make sure the commit being tagged is on the remote. CI builds the tag from a fresh checkout, so if the +# commit has not been pushed the tag would point at something the remote does not have. +if ! git ls-remote --exit-code --heads "$remote" "$remote_branch" > /dev/null 2>&1; then + echo "\"$remote/$remote_branch\" does not exist yet; pushing \"$branch\" and setting it as upstream" + git push --set-upstream "$remote" "$branch:$remote_branch" +else + # refresh the remote-tracking ref so the comparison below reflects the actual remote state + git fetch --quiet "$remote" "+refs/heads/$remote_branch:refs/remotes/$remote_ref" + + if git merge-base --is-ancestor HEAD "$remote_ref"; then + echo "Commit $(git rev-parse --short HEAD) is already pushed to \"$remote_ref\"." + elif git merge-base --is-ancestor "$remote_ref" HEAD; then + echo "Pushing \"$branch\" to \"$remote_ref\"" + git push "$remote" "$branch:$remote_branch" + else + echo "Error: \"$branch\" has diverged from \"$remote_ref\" (both have commits the other does not)." + echo " Rebase or merge before tagging a release so the tagged commit is a normal fast-forward." + exit 1 + fi +fi + +# 4. Tag the current commit. The version comes from this tag via MinVer (see Directory.Build.props), so there +# is no version file to commit first. +echo "Tagging $version" git tag -a "$version" -m "tag $version" -git push --tags -echo "Tagging complete!" +# 5. Push the tag. This triggers the release workflow, which builds and attaches the artifacts. +echo "Pushing tag $version" +git push "$remote" "$version" + +echo "Tagging complete!" \ No newline at end of file