diff --git a/Directory.Build.targets b/Directory.Build.targets index 3aa08a0e8..22509ad87 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -30,4 +30,56 @@ $(ForkBaseVersion).$(ForkRevision) $(ForkBaseVersion).$(ForkRevision) + + + + true + + + + + + + + + + + + + $([System.Text.RegularExpressions.Regex]::Match('$(ForkGitShaRaw)', '[0-9a-fA-F]{40,64}').Value) + $(ForkGitBranchRaw.Trim()) + + + + + + diff --git a/scripts/fork-dev-update.ps1 b/scripts/fork-dev-update.ps1 index b261d92fe..617c13322 100644 --- a/scripts/fork-dev-update.ps1 +++ b/scripts/fork-dev-update.ps1 @@ -1,34 +1,72 @@ # GOXF fork:拉取最新测试代码,本地编译并运行 DeskBox(Debug) # 用法:在仓库根目录右键「使用 PowerShell 运行」,或: # powershell -ExecutionPolicy Bypass -File .\scripts\fork-dev-update.ps1 [-Branch dev] -param([string]$Branch = "dev") +# DeskBox 本地测试版的「更新并重启」也会调用本脚本(带 -GraceSeconds,先等 DeskBox 自己退出)。 +# 出错时窗口不会自动关闭,按回车后关闭。 +param( + [string]$Branch = "dev", + [int]$GraceSeconds = 0 +) $ErrorActionPreference = "Stop" -Set-Location (Split-Path $PSScriptRoot -Parent) -Write-Host "==> 关闭正在运行的 DeskBox" -ForegroundColor Cyan -Get-Process DeskBox -ErrorAction SilentlyContinue | Stop-Process -Force -Start-Sleep -Seconds 1 +try { + Set-Location (Split-Path $PSScriptRoot -Parent) -Write-Host "==> 拉取 origin/$Branch" -ForegroundColor Cyan -git fetch origin $Branch -git checkout -B $Branch "origin/$Branch" -git log -1 --format="当前提交:%h %s (%cr)" + Write-Host "==> 关闭正在运行的 DeskBox" -ForegroundColor Cyan + if ($GraceSeconds -gt 0) { + Wait-Process -Name DeskBox -Timeout $GraceSeconds -ErrorAction SilentlyContinue + } + Get-Process DeskBox -ErrorAction SilentlyContinue | Stop-Process -Force + Start-Sleep -Seconds 1 -$props = @("-p:Platform=x64", "-p:RuntimeIdentifier=win-x64", "-p:WindowsAppSDKSelfContained=true") + Write-Host "==> 拉取 origin/$Branch" -ForegroundColor Cyan + git fetch origin $Branch + if ($LASTEXITCODE -ne 0) { throw "git fetch 失败" } + git checkout -B $Branch "origin/$Branch" + if ($LASTEXITCODE -ne 0) { throw "git checkout 失败(本地是否有未提交的改动?)" } + git log -1 --format="当前提交:%h %s (%cr)" -if (-not (dotnet nuget list source | Select-String "nuget.org")) { - Write-Host "==> 添加 nuget.org 包源" -ForegroundColor Cyan - dotnet nuget add source "https://api.nuget.org/v3/index.json" -n nuget.org + $props = @("-p:Platform=x64", "-p:RuntimeIdentifier=win-x64", "-p:WindowsAppSDKSelfContained=true") + + if (-not (dotnet nuget list source | Select-String "nuget.org")) { + Write-Host "==> 添加 nuget.org 包源" -ForegroundColor Cyan + dotnet nuget add source "https://api.nuget.org/v3/index.json" -n nuget.org + } + Write-Host "==> 还原依赖" -ForegroundColor Cyan + dotnet restore .\DeskBox.sln @props + if ($LASTEXITCODE -ne 0) { throw "restore 失败" } + + Write-Host "==> 编译 Debug" -ForegroundColor Cyan + dotnet build .\src\DeskBox\DeskBox.csproj -c Debug --no-restore @props -v:minimal + if ($LASTEXITCODE -ne 0) { throw "编译失败" } + + $exe = Get-ChildItem .\src\DeskBox\bin -Recurse -Filter DeskBox.exe | Sort-Object LastWriteTime -Descending | Select-Object -First 1 + if (-not $exe) { throw "没找到 DeskBox.exe" } + + # 桌面快捷方式「DeskBox 开发版.lnk」→ 刚编译的 DeskBox.exe(失败不影响启动) + try { + $desktop = [Environment]::GetFolderPath('Desktop') + $lnkPath = Join-Path $desktop "DeskBox 开发版.lnk" + $shell = New-Object -ComObject WScript.Shell + $lnk = $shell.CreateShortcut($lnkPath) + $lnk.TargetPath = $exe.FullName + $lnk.WorkingDirectory = $exe.DirectoryName + $lnk.IconLocation = "$($exe.FullName),0" + $lnk.Description = "DeskBox 本地开发版(dev 分支 Debug 构建)" + $lnk.Save() + Write-Host "==> 已更新桌面快捷方式:$lnkPath" -ForegroundColor Cyan + } + catch { + Write-Host "!! 创建桌面快捷方式失败(不影响运行):$($_.Exception.Message)" -ForegroundColor Yellow + } + + Write-Host "==> 启动 $($exe.FullName)" -ForegroundColor Green + Start-Process $exe.FullName +} +catch { + Write-Host "" + Write-Host "!! 更新失败:$($_.Exception.Message)" -ForegroundColor Red + Write-Host " 修复后可重新运行:powershell -ExecutionPolicy Bypass -File .\scripts\fork-dev-update.ps1" -ForegroundColor Yellow + Read-Host "按回车关闭窗口" + exit 1 } -Write-Host "==> 还原依赖" -ForegroundColor Cyan -dotnet restore .\DeskBox.sln @props -if ($LASTEXITCODE -ne 0) { throw "restore 失败" } - -Write-Host "==> 编译 Debug" -ForegroundColor Cyan -dotnet build .\src\DeskBox\DeskBox.csproj -c Debug --no-restore @props -v:minimal -if ($LASTEXITCODE -ne 0) { throw "编译失败" } - -$exe = Get-ChildItem .\src\DeskBox\bin -Recurse -Filter DeskBox.exe | Sort-Object LastWriteTime -Descending | Select-Object -First 1 -if (-not $exe) { throw "没找到 DeskBox.exe" } -Write-Host "==> 启动 $($exe.FullName)" -ForegroundColor Green -Start-Process $exe.FullName diff --git a/src/DeskBox/App.ForkDevUpdate.cs b/src/DeskBox/App.ForkDevUpdate.cs new file mode 100644 index 000000000..07b73a4cc --- /dev/null +++ b/src/DeskBox/App.ForkDevUpdate.cs @@ -0,0 +1,114 @@ +using DeskBox.Services; +using H.NotifyIcon.Core; + +namespace DeskBox; + +/// +/// GOXF/DeskBox fork: background loop of the local-test-build update channel. +/// Only runs for a local dev build (): +/// shortly after startup and then every 30 minutes it asks GitHub for the tip +/// of GOXF/DeskBox's dev branch and, once per new commit, shows the same +/// style of update toast (tray balloon as fallback) the regular updater +/// uses. Clicking it opens About, where "update and restart" lives. +/// +public partial class App +{ + private string? _forkDevUpdateNotifiedSha; + + private void ScheduleForkDevUpdateCheck() + { + ForkDevBuild? build = ForkDevBuildInfo.Current; + if (build is null) + { + return; + } + + Log($"[DevUpdate] Local dev build {build.ShortSha} ({build.Branch}) at {build.RepositoryRoot}"); + _ = Task.Run(() => ForkDevUpdateLoopAsync(IsStartupMode ? TimeSpan.FromSeconds(60) : TimeSpan.FromSeconds(15))); + } + + private async Task ForkDevUpdateLoopAsync(TimeSpan initialDelay) + { + DateTimeOffset nextCheckAt = DateTimeOffset.Now + initialDelay; + while (!IsShuttingDown) + { + // Wall-clock deadline, re-evaluated after every wake (timers + // pause during sleep), same as the regular update loop. + TimeSpan remaining = nextCheckAt - DateTimeOffset.Now; + if (remaining > TimeSpan.Zero) + { + await Task.Delay(remaining < TimeSpan.FromMinutes(5) ? remaining : TimeSpan.FromMinutes(5)); + continue; + } + + try + { + ForkDevUpdateInfo? info = await ForkDevUpdateService.CheckAsync(); + if (info is { HasUpdate: true } && !IsShuttingDown) + { + Log($"[DevUpdate] dev has {info.RemoteShortSha} (local {info.LocalShortSha})"); + UiDispatcherQueue?.TryEnqueue(() => ShowForkDevUpdateNotification(info)); + } + } + catch (Exception ex) + { + Log($"[DevUpdate] Background check crashed: {ex.GetType().Name}"); + } + + nextCheckAt = DateTimeOffset.Now + ForkDevUpdateService.CheckInterval; + } + } + + private void ShowForkDevUpdateNotification(ForkDevUpdateInfo info) + { + if (IsShuttingDown || + string.Equals(_forkDevUpdateNotifiedSha, info.RemoteSha, StringComparison.Ordinal) || + !SettingsService.Settings.Core.ShowUpdateToastNotification) + { + return; + } + + (string title, string message) = ForkDevUpdateService.FormatNotification(LocalizationService.CurrentCultureName, info); + // {type=update} without an action opens Settings → About, where the + // "update and restart" button is. + var openAboutArguments = new Dictionary + { + ["type"] = "update" + }; + if (_nativeNotificationService?.TryShow( + title, + message, + openAboutArguments, + options: new NativeAppNotificationOptions( + Tag: "dev-update-available", + Group: "update")) == true) + { + _forkDevUpdateNotifiedSha = info.RemoteSha; + return; + } + + if (_trayIcon is null) + { + return; + } + + try + { + _trayIcon.ShowNotification( + title, + message, + NotificationIcon.Info, + customIconHandle: null, + largeIcon: true, + sound: false, + respectQuietTime: true, + realtime: false, + timeout: TimeSpan.FromSeconds(8)); + _forkDevUpdateNotifiedSha = info.RemoteSha; + } + catch (Exception ex) + { + Log($"[DevUpdate] Tray notification failed: {ex.Message}"); + } + } +} diff --git a/src/DeskBox/App.xaml.cs b/src/DeskBox/App.xaml.cs index dc973b810..723f45f6b 100644 --- a/src/DeskBox/App.xaml.cs +++ b/src/DeskBox/App.xaml.cs @@ -1769,6 +1769,7 @@ await RunOptionalStartupStepAsync( () => ShowReleaseNotesAfterUpdateOnce()); RunOptionalStartupStep("background-update-check", ScheduleBackgroundUpdateCheck); + RunOptionalStartupStep("fork-dev-update-check", ScheduleForkDevUpdateCheck); // GOXF fork: local dev builds only RunOptionalStartupStep( "update-installer-prune", // Interface-typed property: pruning only exists on the diff --git a/src/DeskBox/Services/ForkDevBuildInfo.cs b/src/DeskBox/Services/ForkDevBuildInfo.cs new file mode 100644 index 000000000..9b7e4fa42 --- /dev/null +++ b/src/DeskBox/Services/ForkDevBuildInfo.cs @@ -0,0 +1,265 @@ +using System.Reflection; +using System.Text.RegularExpressions; + +namespace DeskBox.Services; + +/// +/// GOXF/DeskBox fork: identifies a *local development build* — a DeskBox.exe +/// compiled inside a git clone of the fork by scripts/fork-dev-update.ps1 — +/// and the git commit it was built from. Installed builds (Program Files, +/// %LOCALAPPDATA%\Programs, …) never sit inside such a clone, so every +/// local-test-channel feature stays off for them. +/// +/// The commit sha / branch are embedded at build time by +/// Directory.Build.targets (AssemblyMetadata "ForkGitSha" / "ForkGitBranch", +/// Debug builds only). When they are missing the sha is read from the +/// clone's .git directory at runtime. +/// +public sealed record ForkDevBuild(string RepositoryRoot, string LocalSha, string Branch) +{ + public string ScriptPath => Path.Combine(RepositoryRoot, ForkDevBuildInfo.ScriptRelativePath); + public string ShortSha => ForkDevBuildInfo.ShortSha(LocalSha); +} + +public static partial class ForkDevBuildInfo +{ + public static readonly string ScriptRelativePath = Path.Combine("scripts", "fork-dev-update.ps1"); + public const string DevBranch = "dev"; + public const string ShaMetadataKey = "ForkGitSha"; + public const string BranchMetadataKey = "ForkGitBranch"; + + private static readonly Lazy s_current = new(DetectCurrent); + + /// The running process' local dev build, or null for every installed build. + public static ForkDevBuild? Current => s_current.Value; + + public static bool IsLocalDevBuild => Current is not null; + + private static ForkDevBuild? DetectCurrent() + { + try + { + return Detect(AppContext.BaseDirectory, typeof(ForkDevBuildInfo).Assembly); + } + catch (Exception ex) + { + App.Log($"[DevUpdate] Local build detection failed: {ex.GetType().Name}"); + return null; + } + } + + internal static ForkDevBuild? Detect(string? executableDirectory, Assembly? assembly) + { + string? root = FindRepositoryRoot(executableDirectory); + if (root is null) + { + return null; + } + + string? sha = NormalizeSha(GetAssemblyMetadata(assembly, ShaMetadataKey)); + string? branch = GetAssemblyMetadata(assembly, BranchMetadataKey); + if (sha is null) + { + (sha, string? headBranch) = ReadHeadFromGitDirectory(root); + branch ??= headBranch; + } + + return sha is null + ? null + : new ForkDevBuild(root, sha, string.IsNullOrWhiteSpace(branch) ? string.Empty : branch.Trim()); + } + + /// + /// Walks up from (the exe folder) to the + /// first directory that holds BOTH a ".git" entry (directory, or file for + /// worktrees) and scripts/fork-dev-update.ps1. Null when none exists. + /// + public static string? FindRepositoryRoot(string? startDirectory) + { + if (string.IsNullOrWhiteSpace(startDirectory)) + { + return null; + } + + DirectoryInfo? current; + try + { + current = new DirectoryInfo(Path.GetFullPath(startDirectory)); + } + catch (Exception) + { + return null; + } + + for (int depth = 0; current is not null && depth < 32; depth++, current = current.Parent) + { + string gitPath = Path.Combine(current.FullName, ".git"); + if ((Directory.Exists(gitPath) || File.Exists(gitPath)) && + File.Exists(Path.Combine(current.FullName, ScriptRelativePath))) + { + return current.FullName; + } + } + + return null; + } + + private static string? GetAssemblyMetadata(Assembly? assembly, string key) + { + if (assembly is null) + { + return null; + } + + foreach (AssemblyMetadataAttribute attribute in assembly.GetCustomAttributes()) + { + if (string.Equals(attribute.Key, key, StringComparison.Ordinal) && + !string.IsNullOrWhiteSpace(attribute.Value)) + { + return attribute.Value.Trim(); + } + } + + return null; + } + + /// + /// Reads HEAD from the clone: "ref: refs/heads/x" → loose ref file or + /// packed-refs; a detached HEAD is the sha itself. Handles a ".git" file + /// ("gitdir: …") for worktrees, where refs live in the common dir. + /// + internal static (string? Sha, string? Branch) ReadHeadFromGitDirectory(string repositoryRoot) + { + try + { + string? gitDir = ResolveGitDirectory(repositoryRoot); + if (gitDir is null) + { + return (null, null); + } + + string headPath = Path.Combine(gitDir, "HEAD"); + if (!File.Exists(headPath)) + { + return (null, null); + } + + string head = File.ReadAllText(headPath).Trim(); + if (!head.StartsWith("ref:", StringComparison.Ordinal)) + { + return (NormalizeSha(head), null); + } + + string refName = head[4..].Trim(); + string? branch = refName.StartsWith("refs/heads/", StringComparison.Ordinal) + ? refName["refs/heads/".Length..] + : null; + + string commonDir = gitDir; + string commonDirFile = Path.Combine(gitDir, "commondir"); + if (File.Exists(commonDirFile)) + { + string relative = File.ReadAllText(commonDirFile).Trim(); + commonDir = Path.GetFullPath(Path.Combine(gitDir, relative)); + } + + foreach (string dir in new[] { gitDir, commonDir }) + { + string loose = Path.Combine(dir, refName.Replace('/', Path.DirectorySeparatorChar)); + if (File.Exists(loose)) + { + string? looseSha = NormalizeSha(File.ReadAllText(loose)); + if (looseSha is not null) + { + return (looseSha, branch); + } + } + } + + string packed = Path.Combine(commonDir, "packed-refs"); + if (File.Exists(packed)) + { + foreach (string line in File.ReadLines(packed)) + { + int space = line.IndexOf(' '); + if (space > 0 && string.Equals(line[(space + 1)..].Trim(), refName, StringComparison.Ordinal)) + { + return (NormalizeSha(line[..space]), branch); + } + } + } + + return (null, branch); + } + catch (Exception) + { + return (null, null); + } + } + + private static string? ResolveGitDirectory(string repositoryRoot) + { + string gitPath = Path.Combine(repositoryRoot, ".git"); + if (Directory.Exists(gitPath)) + { + return gitPath; + } + + if (File.Exists(gitPath)) + { + string content = File.ReadAllText(gitPath).Trim(); + if (content.StartsWith("gitdir:", StringComparison.OrdinalIgnoreCase)) + { + string target = content["gitdir:".Length..].Trim(); + string full = Path.GetFullPath(Path.IsPathRooted(target) ? target : Path.Combine(repositoryRoot, target)); + return Directory.Exists(full) ? full : null; + } + } + + return null; + } + + [GeneratedRegex("^[0-9a-f]{7,64}$")] + private static partial Regex ShaPattern(); + + /// Lower-cased hex sha (7–64 chars), or null when the text is not one. + public static string? NormalizeSha(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + string trimmed = value.Trim().ToLowerInvariant(); + return ShaPattern().IsMatch(trimmed) ? trimmed : null; + } + + public static string ShortSha(string? sha) + { + string? normalized = NormalizeSha(sha); + if (normalized is null) + { + return string.Empty; + } + + return normalized.Length > 7 ? normalized[..7] : normalized; + } + + /// + /// True when the remote tip differs from the local build's commit. A + /// short local sha (prefix) that matches the remote counts as the same + /// commit. Unknown / malformed shas never report an update. + /// + public static bool IsRemoteNewer(string? localSha, string? remoteSha) + { + string? local = NormalizeSha(localSha); + string? remote = NormalizeSha(remoteSha); + if (local is null || remote is null) + { + return false; + } + + return !(remote.StartsWith(local, StringComparison.Ordinal) || + local.StartsWith(remote, StringComparison.Ordinal)); + } +} diff --git a/src/DeskBox/Services/ForkDevUpdateService.cs b/src/DeskBox/Services/ForkDevUpdateService.cs new file mode 100644 index 000000000..da9c53917 --- /dev/null +++ b/src/DeskBox/Services/ForkDevUpdateService.cs @@ -0,0 +1,239 @@ +using System.Diagnostics; +using System.Text.Json; + +namespace DeskBox.Services; + +/// Latest dev-branch commit compared against the local dev build. +public sealed record ForkDevUpdateInfo( + string LocalSha, + string RemoteSha, + string RemoteTitle, + bool HasUpdate) +{ + public string LocalShortSha => ForkDevBuildInfo.ShortSha(LocalSha); + public string RemoteShortSha => ForkDevBuildInfo.ShortSha(RemoteSha); +} + +/// +/// GOXF/DeskBox fork: "local test build" update channel. Only active for a +/// local dev build; asks GitHub +/// (anonymous) for the tip of GOXF/DeskBox's dev branch and, on request, +/// hands over to scripts/fork-dev-update.ps1 (pull → Debug build → relaunch). +/// Every network failure yields null: this channel never surfaces errors. +/// +public static class ForkDevUpdateService +{ + public const string DevBranchCommitApiUrl = "https://api.github.com/repos/GOXF/DeskBox/commits/dev"; + public static readonly TimeSpan CheckInterval = TimeSpan.FromMinutes(30); + + private static readonly HttpClient s_httpClient = CreateHttpClient(); + + private static HttpClient CreateHttpClient() + { + var client = new HttpClient + { + Timeout = TimeSpan.FromSeconds(10) + }; + client.DefaultRequestHeaders.UserAgent.ParseAdd($"DeskBox-dev/{AppUpdateService.GetCurrentAppVersion()}"); + client.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json"); + return client; + } + + /// Null when this is not a local dev build or the check failed. + public static Task CheckAsync(CancellationToken cancellationToken = default) + { + ForkDevBuild? build = ForkDevBuildInfo.Current; + return build is null + ? Task.FromResult(null) + : CheckAsync(build.LocalSha, s_httpClient, DevBranchCommitApiUrl, cancellationToken); + } + + internal static async Task CheckAsync( + string localSha, + HttpClient httpClient, + string commitApiUrl, + CancellationToken cancellationToken) + { + try + { + using var response = await httpClient.GetAsync(commitApiUrl, cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + return null; + } + + string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + return ParseCommit(localSha, json); + } + catch (Exception ex) + { + App.Log($"[DevUpdate] dev branch check skipped: {ex.GetType().Name}"); + return null; + } + } + + /// Parses GET /repos/{o}/{r}/commits/{ref}: "sha" + first line of "commit.message". + internal static ForkDevUpdateInfo? ParseCommit(string localSha, string json) + { + try + { + using var document = JsonDocument.Parse(json); + JsonElement root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("sha", out JsonElement shaElement) || + shaElement.ValueKind != JsonValueKind.String) + { + return null; + } + + string? remoteSha = ForkDevBuildInfo.NormalizeSha(shaElement.GetString()); + string? local = ForkDevBuildInfo.NormalizeSha(localSha); + if (remoteSha is null || local is null) + { + return null; + } + + string title = string.Empty; + if (root.TryGetProperty("commit", out JsonElement commit) && + commit.ValueKind == JsonValueKind.Object && + commit.TryGetProperty("message", out JsonElement message) && + message.ValueKind == JsonValueKind.String) + { + title = FirstLine(message.GetString()); + } + + return new ForkDevUpdateInfo(local, remoteSha, title, ForkDevBuildInfo.IsRemoteNewer(local, remoteSha)); + } + catch (JsonException) + { + return null; + } + } + + private static string FirstLine(string? text) + { + if (string.IsNullOrEmpty(text)) + { + return string.Empty; + } + + int newline = text.IndexOfAny(['\r', '\n']); + string line = (newline >= 0 ? text[..newline] : text).Trim(); + return line.Length > 120 ? line[..119] + "…" : line; + } + + /// + /// powershell.exe arguments for the update script. -GraceSeconds lets + /// DeskBox finish its own clean shutdown before the script force-kills + /// whatever is left. + /// + internal static ProcessStartInfo BuildScriptStartInfo(ForkDevBuild build) + { + var startInfo = new ProcessStartInfo + { + FileName = "powershell.exe", + // Shell-execute => its own visible console window, independent of + // DeskBox's lifetime, so the build progress stays on screen. + UseShellExecute = true, + WorkingDirectory = build.RepositoryRoot, + Arguments = $"-NoProfile -ExecutionPolicy Bypass -File \"{build.ScriptPath}\" -Branch {ForkDevBuildInfo.DevBranch} -GraceSeconds 15", + }; + return startInfo; + } + + /// Starts the update script in its own window. The caller then exits DeskBox. + public static bool TryStartUpdateScript(out string? error) + { + error = null; + ForkDevBuild? build = ForkDevBuildInfo.Current; + if (build is null) + { + error = "not a local dev build"; + return false; + } + + if (!File.Exists(build.ScriptPath)) + { + error = $"missing {build.ScriptPath}"; + return false; + } + + try + { + using Process? process = Process.Start(BuildScriptStartInfo(build)); + if (process is null) + { + error = "powershell.exe did not start"; + return false; + } + + App.Log($"[DevUpdate] Update script started (pid {process.Id}) from {build.RepositoryRoot}"); + return true; + } + catch (Exception ex) + { + error = ex.Message; + App.Log($"[DevUpdate] Update script failed to start: {ex}"); + return false; + } + } + + internal static string FormatStatus(string? cultureName, ForkDevUpdateInfo info) + { + bool zhHans = cultureName == LocalizationService.LanguageChinese; + bool zhHant = cultureName == LocalizationService.LanguageChineseTraditional; + string title = string.IsNullOrWhiteSpace(info.RemoteTitle) ? string.Empty : " " + info.RemoteTitle; + if (info.HasUpdate) + { + return zhHans + ? $"本地测试版:当前 {info.LocalShortSha},有新提交 {info.RemoteShortSha}{title}" + : zhHant + ? $"本地測試版:目前 {info.LocalShortSha},有新提交 {info.RemoteShortSha}{title}" + : $"Local test build: current {info.LocalShortSha}, new commit {info.RemoteShortSha}{title}"; + } + + return zhHans + ? $"本地测试版:当前 {info.LocalShortSha},已是 dev 最新提交" + : zhHant + ? $"本地測試版:目前 {info.LocalShortSha},已是 dev 最新提交" + : $"Local test build: current {info.LocalShortSha}, up to date with dev"; + } + + internal static string FormatLocalOnlyStatus(string? cultureName, string localShortSha) + { + return cultureName switch + { + LocalizationService.LanguageChinese => $"本地测试版:当前 {localShortSha}(暂未取到 dev 最新提交)", + LocalizationService.LanguageChineseTraditional => $"本地測試版:目前 {localShortSha}(暫未取得 dev 最新提交)", + _ => $"Local test build: current {localShortSha} (dev tip not fetched yet)", + }; + } + + internal static string FormatUpdateButton(string? cultureName) => cultureName switch + { + LocalizationService.LanguageChinese => "更新并重启", + LocalizationService.LanguageChineseTraditional => "更新並重新啟動", + _ => "Update and restart", + }; + + internal static (string Title, string Message) FormatNotification(string? cultureName, ForkDevUpdateInfo info) + { + string title = string.IsNullOrWhiteSpace(info.RemoteTitle) ? string.Empty : " " + info.RemoteTitle; + return cultureName switch + { + LocalizationService.LanguageChinese => + ("DeskBox 本地测试版有新提交", $"dev 有新提交 {info.RemoteShortSha}{title}(当前 {info.LocalShortSha})。在 设置 → 关于 → 更新详情 点「更新并重启」。"), + LocalizationService.LanguageChineseTraditional => + ("DeskBox 本地測試版有新提交", $"dev 有新提交 {info.RemoteShortSha}{title}(目前 {info.LocalShortSha})。在 設定 → 關於 → 更新詳情 點「更新並重新啟動」。"), + _ => + ("DeskBox local test build: new commit", $"dev has {info.RemoteShortSha}{title} (current {info.LocalShortSha}). Settings → About → Update details → Update and restart."), + }; + } + + internal static string FormatStartFailed(string? cultureName, string? error) => cultureName switch + { + LocalizationService.LanguageChinese => $"无法启动更新脚本:{error}", + LocalizationService.LanguageChineseTraditional => $"無法啟動更新腳本:{error}", + _ => $"Could not start the update script: {error}", + }; +} diff --git a/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs b/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs index e24fab359..b70996b6f 100644 --- a/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs +++ b/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs @@ -312,6 +312,7 @@ public async Task CheckForUpdatesAsync() _updateOperationCts?.Cancel(); _updateOperationCts = new CancellationTokenSource(); StartUpstreamReleaseCheck(); // GOXF fork: informational, never awaited + StartForkDevUpdateCheck(); // GOXF fork: local dev builds only, never awaited IsCheckingForUpdates = true; UpdateStatusText = _localizationService.T("Settings.Update.Status.Checking"); UpdateDetailText = _localizationService.T("Settings.Update.Detail.Checking"); diff --git a/src/DeskBox/ViewModels/SettingsViewModel.ForkDevUpdate.cs b/src/DeskBox/ViewModels/SettingsViewModel.ForkDevUpdate.cs new file mode 100644 index 000000000..15d23afd9 --- /dev/null +++ b/src/DeskBox/ViewModels/SettingsViewModel.ForkDevUpdate.cs @@ -0,0 +1,111 @@ +using DeskBox.Services; +using Microsoft.UI.Xaml; + +namespace DeskBox.ViewModels; + +/// +/// GOXF/DeskBox fork: "local test build" line + "update and restart" button +/// under About → Update details. Visible only for a local dev build (exe +/// inside a clone that has scripts/fork-dev-update.ps1); installed builds +/// never show it. Bound with x:Bind, so the AOT bindable-property list +/// (pinned by upstream tests) is untouched. Text lives in code for the same +/// merge-conflict reason as SettingsViewModel.ForkUpstream.cs. +/// +public partial class SettingsViewModel +{ + private ForkDevUpdateInfo? _forkDevUpdateInfo; + private int _forkDevUpdateCheckInFlight; + private int _forkDevUpdateCheckStarted; + + public Visibility ForkDevUpdateVisibility + { + get + { + // First render of the About section starts one check; the + // explicit "check for updates" path re-runs it. + if (ForkDevBuildInfo.IsLocalDevBuild && + Interlocked.Exchange(ref _forkDevUpdateCheckStarted, 1) == 0) + { + StartForkDevUpdateCheck(); + } + + return ForkDevBuildInfo.IsLocalDevBuild ? Visibility.Visible : Visibility.Collapsed; + } + } + + public string ForkDevUpdateStatusText + { + get + { + ForkDevBuild? build = ForkDevBuildInfo.Current; + if (build is null) + { + return string.Empty; + } + + return _forkDevUpdateInfo is { } info + ? ForkDevUpdateService.FormatStatus(_localizationService.CurrentCultureName, info) + : ForkDevUpdateService.FormatLocalOnlyStatus(_localizationService.CurrentCultureName, build.ShortSha); + } + } + + public Visibility ForkDevUpdateButtonVisibility => + _forkDevUpdateInfo is { HasUpdate: true } ? Visibility.Visible : Visibility.Collapsed; + + public string ForkDevUpdateButtonText => + ForkDevUpdateService.FormatUpdateButton(_localizationService.CurrentCultureName); + + /// Fire-and-forget; never awaited by the regular update flow. + private void StartForkDevUpdateCheck() + { + if (!ForkDevBuildInfo.IsLocalDevBuild || + Interlocked.Exchange(ref _forkDevUpdateCheckInFlight, 1) == 1) + { + return; + } + + Interlocked.Exchange(ref _forkDevUpdateCheckStarted, 1); + _ = RunForkDevUpdateCheckAsync(); + } + + private async Task RunForkDevUpdateCheckAsync() + { + try + { + ForkDevUpdateInfo? info = await ForkDevUpdateService.CheckAsync().ConfigureAwait(false); + if (info is not null) + { + SetForkDevUpdateInfo(info); + } + } + catch (Exception ex) + { + App.Log($"[DevUpdate] Settings check failed: {ex.GetType().Name}"); + } + finally + { + Volatile.Write(ref _forkDevUpdateCheckInFlight, 0); + } + } + + private void SetForkDevUpdateInfo(ForkDevUpdateInfo info) + { + if (_uiDispatcherQueue is { } queue && !queue.HasThreadAccess) + { + queue.TryEnqueue(() => SetForkDevUpdateInfo(info)); + return; + } + + _forkDevUpdateInfo = info; + OnPropertyChanged(nameof(ForkDevUpdateStatusText)); + OnPropertyChanged(nameof(ForkDevUpdateButtonVisibility)); + } + + /// Starts scripts/fork-dev-update.ps1; the window then shuts DeskBox down. + public bool StartForkDevUpdateScript(out string message) + { + bool started = ForkDevUpdateService.TryStartUpdateScript(out string? error); + message = started ? string.Empty : ForkDevUpdateService.FormatStartFailed(_localizationService.CurrentCultureName, error); + return started; + } +} diff --git a/src/DeskBox/Views/SettingsWindow.ForkDevUpdate.cs b/src/DeskBox/Views/SettingsWindow.ForkDevUpdate.cs new file mode 100644 index 000000000..907f492ab --- /dev/null +++ b/src/DeskBox/Views/SettingsWindow.ForkDevUpdate.cs @@ -0,0 +1,34 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; + +namespace DeskBox.Views; + +/// +/// GOXF/DeskBox fork: "update and restart" for a local dev build. Starts +/// scripts/fork-dev-update.ps1 in its own visible window (pull dev → Debug +/// build → relaunch), then shuts DeskBox down the same way an installer +/// update does so the script can replace the binaries. +/// +public sealed partial class SettingsWindow +{ + private async void ForkDevUpdateButton_Click(object sender, RoutedEventArgs e) + { + if (sender is Button button) + { + button.IsEnabled = false; + } + + if (!ViewModel.StartForkDevUpdateScript(out string message)) + { + if (sender is Button failedButton) + { + failedButton.IsEnabled = true; + } + + await ShowInfoDialogAsync(ViewModel.ForkDevUpdateButtonText, message); + return; + } + + await _appActions.ShutdownForUpdateAsync(); + } +} diff --git a/src/DeskBox/Views/SettingsWindow.xaml b/src/DeskBox/Views/SettingsWindow.xaml index 640c87550..6f676fbf3 100644 --- a/src/DeskBox/Views/SettingsWindow.xaml +++ b/src/DeskBox/Views/SettingsWindow.xaml @@ -3409,6 +3409,23 @@ Text="DeskBox" /> Text="{x:Bind UpstreamReleaseNoticeText, Mode=OneWay}" Visibility="{x:Bind UpstreamReleaseNoticeVisibility, Mode=OneWay}" TextWrapping="Wrap" /> + + + + + +/// GOXF/DeskBox fork: local-test-build update channel. Only a DeskBox.exe +/// built inside a clone (".git" + scripts/fork-dev-update.ps1 above the exe +/// folder) enables it; it compares the build's commit with the tip of dev. +/// +public sealed class ForkDevUpdateTests : IDisposable +{ + private const string LocalSha = "1111111aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private const string RemoteSha = "2222222bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + + private readonly string _tempRoot = Path.Combine(Path.GetTempPath(), "DeskBox.Tests", "dev-update-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + try + { + if (Directory.Exists(_tempRoot)) + { + Directory.Delete(_tempRoot, recursive: true); + } + } + catch (IOException) + { + } + } + + private string CreateClone(string name, bool gitAsFile = false, bool withScript = true) + { + string root = Path.Combine(_tempRoot, name); + Directory.CreateDirectory(root); + if (gitAsFile) + { + string worktreeGitDir = Path.Combine(_tempRoot, name + "-gitdir"); + Directory.CreateDirectory(worktreeGitDir); + File.WriteAllText(Path.Combine(root, ".git"), "gitdir: " + worktreeGitDir); + } + else + { + Directory.CreateDirectory(Path.Combine(root, ".git")); + } + + if (withScript) + { + Directory.CreateDirectory(Path.Combine(root, "scripts")); + File.WriteAllText(Path.Combine(root, "scripts", "fork-dev-update.ps1"), "# test"); + } + + return root; + } + + private static string CreateBinDirectory(string root) + { + string bin = Path.Combine(root, "src", "DeskBox", "bin", "x64", "Debug", "net10.0-windows10.0.22621.0", "win-x64"); + Directory.CreateDirectory(bin); + return bin; + } + + [Fact] + public void FindRepositoryRoot_WalksUpFromTheExeFolderToTheClone() + { + string root = CreateClone("clone"); + string bin = CreateBinDirectory(root); + + Assert.Equal(Path.GetFullPath(root), ForkDevBuildInfo.FindRepositoryRoot(bin)); + } + + [Fact] + public void FindRepositoryRoot_AcceptsAWorktreeGitFile() + { + string root = CreateClone("worktree", gitAsFile: true); + + Assert.Equal(Path.GetFullPath(root), ForkDevBuildInfo.FindRepositoryRoot(CreateBinDirectory(root))); + } + + [Fact] + public void FindRepositoryRoot_RequiresBothGitAndTheUpdateScript() + { + string noScript = CreateClone("no-script", withScript: false); + Assert.Null(ForkDevBuildInfo.FindRepositoryRoot(CreateBinDirectory(noScript))); + + string noGit = Path.Combine(_tempRoot, "no-git"); + Directory.CreateDirectory(Path.Combine(noGit, "scripts")); + File.WriteAllText(Path.Combine(noGit, "scripts", "fork-dev-update.ps1"), "# test"); + Assert.Null(ForkDevBuildInfo.FindRepositoryRoot(CreateBinDirectory(noGit))); + } + + [Fact] + public void InstalledBuild_IsNotALocalDevBuild() + { + string installDir = Path.Combine(_tempRoot, "Program Files", "DeskBox"); + Directory.CreateDirectory(installDir); + File.WriteAllText(Path.Combine(installDir, "DeskBox.exe"), string.Empty); + + Assert.Null(ForkDevBuildInfo.FindRepositoryRoot(installDir)); + Assert.Null(ForkDevBuildInfo.Detect(installDir, typeof(ForkDevBuildInfo).Assembly)); + Assert.Null(ForkDevBuildInfo.FindRepositoryRoot(null)); + Assert.Null(ForkDevBuildInfo.FindRepositoryRoot(" ")); + } + + [Fact] + public void Detect_FallsBackToTheGitHeadWhenNothingIsEmbedded() + { + string root = CreateClone("loose-ref"); + File.WriteAllText(Path.Combine(root, ".git", "HEAD"), "ref: refs/heads/dev\n"); + Directory.CreateDirectory(Path.Combine(root, ".git", "refs", "heads")); + File.WriteAllText(Path.Combine(root, ".git", "refs", "heads", "dev"), LocalSha.ToUpperInvariant() + "\n"); + + ForkDevBuild? build = ForkDevBuildInfo.Detect(CreateBinDirectory(root), assembly: null); + + Assert.NotNull(build); + Assert.Equal(Path.GetFullPath(root), build!.RepositoryRoot); + Assert.Equal(LocalSha, build.LocalSha); + Assert.Equal("dev", build.Branch); + Assert.Equal("1111111", build.ShortSha); + Assert.Equal(Path.Combine(Path.GetFullPath(root), "scripts", "fork-dev-update.ps1"), build.ScriptPath); + } + + [Fact] + public void ReadHeadFromGitDirectory_ReadsPackedRefsAndDetachedHead() + { + string packed = CreateClone("packed"); + File.WriteAllText(Path.Combine(packed, ".git", "HEAD"), "ref: refs/heads/dev\n"); + File.WriteAllText( + Path.Combine(packed, ".git", "packed-refs"), + "# pack-refs with: peeled fully-peeled sorted\n" + + RemoteSha + " refs/heads/custom\n" + + LocalSha + " refs/heads/dev\n"); + Assert.Equal((LocalSha, "dev"), ForkDevBuildInfo.ReadHeadFromGitDirectory(packed)); + + string detached = CreateClone("detached"); + File.WriteAllText(Path.Combine(detached, ".git", "HEAD"), RemoteSha + "\n"); + Assert.Equal((RemoteSha, (string?)null), ForkDevBuildInfo.ReadHeadFromGitDirectory(detached)); + + string empty = CreateClone("empty"); + Assert.Null(ForkDevBuildInfo.ReadHeadFromGitDirectory(empty).Sha); + } + + [Theory] + [InlineData(LocalSha, RemoteSha, true)] + [InlineData(LocalSha, LocalSha, false)] + [InlineData("1111111", LocalSha, false)] + [InlineData("1111111AAAA", LocalSha, false)] + [InlineData(LocalSha, "1111111", false)] + [InlineData(null, RemoteSha, false)] + [InlineData(LocalSha, null, false)] + [InlineData("not-a-sha", RemoteSha, false)] + [InlineData(LocalSha, "zzzzzzzz", false)] + public void IsRemoteNewer_ComparesShasSafely(string? local, string? remote, bool expected) + { + Assert.Equal(expected, ForkDevBuildInfo.IsRemoteNewer(local, remote)); + } + + [Fact] + public void ParseCommit_ReadsShaAndFirstMessageLine() + { + string json = $$""" + { + "sha": "{{RemoteSha}}", + "commit": { "message": "feat: 本地测试版更新通道\n\n详细说明" } + } + """; + + ForkDevUpdateInfo? info = ForkDevUpdateService.ParseCommit(LocalSha, json); + + Assert.NotNull(info); + Assert.True(info!.HasUpdate); + Assert.Equal("2222222", info.RemoteShortSha); + Assert.Equal("1111111", info.LocalShortSha); + Assert.Equal("feat: 本地测试版更新通道", info.RemoteTitle); + Assert.Equal( + "本地测试版:当前 1111111,有新提交 2222222 feat: 本地测试版更新通道", + ForkDevUpdateService.FormatStatus(LocalizationService.LanguageChinese, info)); + } + + [Fact] + public void ParseCommit_SameShaIsUpToDateAndMalformedIsNull() + { + ForkDevUpdateInfo? same = ForkDevUpdateService.ParseCommit(LocalSha, $$"""{ "sha": "{{LocalSha}}" }"""); + Assert.NotNull(same); + Assert.False(same!.HasUpdate); + Assert.Contains("已是 dev 最新提交", ForkDevUpdateService.FormatStatus(LocalizationService.LanguageChinese, same)); + + Assert.Null(ForkDevUpdateService.ParseCommit(LocalSha, "not json")); + Assert.Null(ForkDevUpdateService.ParseCommit(LocalSha, "[]")); + Assert.Null(ForkDevUpdateService.ParseCommit(LocalSha, """{ "message": "Not Found" }""")); + Assert.Null(ForkDevUpdateService.ParseCommit("", $$"""{ "sha": "{{RemoteSha}}" }""")); + } + + [Fact] + public async Task CheckAsync_QueriesTheDevBranchAndFailsSilently() + { + var requested = new List(); + using var ok = new HttpClient(new StubHandler(request => + { + requested.Add(request.RequestUri!.ToString()); + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent($$"""{ "sha": "{{RemoteSha}}", "commit": { "message": "fix: x" } }""", Encoding.UTF8, "application/json") + }; + })); + ForkDevUpdateInfo? info = await ForkDevUpdateService.CheckAsync(LocalSha, ok, ForkDevUpdateService.DevBranchCommitApiUrl, CancellationToken.None); + Assert.Equal(new[] { "https://api.github.com/repos/GOXF/DeskBox/commits/dev" }, requested); + Assert.True(info!.HasUpdate); + + using var rateLimited = new HttpClient(new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.Forbidden))); + Assert.Null(await ForkDevUpdateService.CheckAsync(LocalSha, rateLimited, ForkDevUpdateService.DevBranchCommitApiUrl, CancellationToken.None)); + + using var offline = new HttpClient(new StubHandler(_ => throw new HttpRequestException("offline"))); + Assert.Null(await ForkDevUpdateService.CheckAsync(LocalSha, offline, ForkDevUpdateService.DevBranchCommitApiUrl, CancellationToken.None)); + } + + [Fact] + public void BuildScriptStartInfo_RunsTheRepoScriptInAVisibleWindow() + { + string root = CreateClone("script"); + var build = new ForkDevBuild(Path.GetFullPath(root), LocalSha, "dev"); + + var startInfo = ForkDevUpdateService.BuildScriptStartInfo(build); + + Assert.Equal("powershell.exe", startInfo.FileName); + Assert.True(startInfo.UseShellExecute); + Assert.Equal(build.RepositoryRoot, startInfo.WorkingDirectory); + Assert.Contains("-ExecutionPolicy Bypass", startInfo.Arguments, StringComparison.Ordinal); + Assert.Contains($"-File \"{build.ScriptPath}\"", startInfo.Arguments, StringComparison.Ordinal); + Assert.Contains("-Branch dev", startInfo.Arguments, StringComparison.Ordinal); + } + + private sealed class StubHandler(Func handler) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + return Task.FromResult(handler(request)); + } + } +}