diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c34bae4..07be562 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,10 +39,11 @@ jobs: & ./scripts/build-release-notes.ps1 -Tag $ver -OutFile $tmp Write-Host "PASS CHANGELOG.md contains valid release notes for $ver ($((Get-Item -LiteralPath $tmp).Length) bytes)" - - name: Frontend build + - name: Frontend test & build shell: pwsh run: | pnpm --dir frontend install --frozen-lockfile + pnpm --dir frontend test pnpm --dir frontend build - name: Debug workspace hygiene check & self-test diff --git a/.github/workflows/dev-release.yml b/.github/workflows/dev-release.yml new file mode 100644 index 0000000..d673d9d --- /dev/null +++ b/.github/workflows/dev-release.yml @@ -0,0 +1,239 @@ +name: Dev Release (Rolling) + +on: + push: + branches: + - main + paths-ignore: + - "docs/**" + - "README.md" + - "README.en.md" + - "AGENTS.md" + - ".github/ISSUE_TEMPLATE/**" + - ".github/readme/**" + workflow_dispatch: + +permissions: + contents: write + +concurrency: + group: dev-release-${{ github.ref }} + cancel-in-progress: true + +jobs: + dev-release: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - uses: pnpm/action-setup@v4 + with: + version: 10 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + cache-dependency-path: frontend/pnpm-lock.yaml + + - name: Resolve rolling dev version + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + + function Parse-StableSemVer([string]$v) { + if ($v -match '^v([0-9]+)\.([0-9]+)\.([0-9]+)$') { + return [PSCustomObject]@{ + Tag = $v + Major = [int]$Matches[1] + Minor = [int]$Matches[2] + Patch = [int]$Matches[3] + } + } + return $null + } + + function Compare-SemVer($a, $b) { + if ($a.Major -ne $b.Major) { return [Math]::Sign($a.Major - $b.Major) } + if ($a.Minor -ne $b.Minor) { return [Math]::Sign($a.Minor - $b.Minor) } + return [Math]::Sign($a.Patch - $b.Patch) + } + + $shortSha = (git rev-parse --short=7 HEAD).Trim() + if ([string]::IsNullOrWhiteSpace($shortSha)) { + throw 'Could not resolve HEAD short commit SHA' + } + + $stableTags = @( + git tag --list 'v*' | + ForEach-Object { Parse-StableSemVer $_.Trim() } | + Where-Object { $_ -ne $null } | + Sort-Object Major, Minor, Patch -Descending + ) + $latestStable = if ($stableTags.Count -gt 0) { $stableTags[0] } else { $null } + + $codeVer = $null + $verFile = Get-Content -Raw -LiteralPath 'internal/version/version.go' + if ($verFile -match 'var\s+Version\s*=\s*"(v[0-9]+\.[0-9]+\.[0-9]+)"') { + $codeVer = Parse-StableSemVer $Matches[1] + } + + if ($latestStable) { + if ($codeVer -and (Compare-SemVer $codeVer $latestStable) -gt 0) { + $nextBase = $codeVer.Tag + } else { + $nextBase = "v$($latestStable.Major).$($latestStable.Minor).$($latestStable.Patch + 1)" + } + $baseStableTag = $latestStable.Tag + } elseif ($codeVer) { + $nextBase = $codeVer.Tag + $baseStableTag = '' + } else { + $nextBase = 'v0.0.1' + $baseStableTag = '' + } + + $devVersion = "$nextBase-dev-$shortSha" + "DEV_VERSION=$devVersion" | Out-File -FilePath $env:GITHUB_ENV -Append + "DEV_COMMIT=$shortSha" | Out-File -FilePath $env:GITHUB_ENV -Append + "BASE_STABLE_TAG=$baseStableTag" | Out-File -FilePath $env:GITHUB_ENV -Append + Write-Host "Resolved DEV_VERSION=$devVersion (commit=$shortSha, baseStable=$baseStableTag)" + + - name: Generate dev release notes + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $devVersion = $env:DEV_VERSION + $runtimeTag = '' + $runtimeTitle = '' + try { + $rels = gh release list -R $env:GITHUB_REPOSITORY --limit 100 --json tagName,name,isPrerelease,isDraft,createdAt | ConvertFrom-Json + $stable = $rels | + Where-Object { $_.tagName -like 'runtime-*' -and -not $_.isPrerelease -and -not $_.isDraft } | + Sort-Object createdAt -Descending | + Select-Object -First 1 + if ($stable) { + $runtimeTag = $stable.tagName + $runtimeTitle = if ($stable.name) { $stable.name } else { $stable.tagName } + } + } catch { + Write-Warning "Could not query latest stable runtime release: $_" + } + $notesFile = Join-Path $env:RUNNER_TEMP "release-notes-dev.md" + & ./scripts/build-release-notes.ps1 ` + -Tag $devVersion ` + -Channel dev ` + -PrevTag $env:BASE_STABLE_TAG ` + -Commit $env:DEV_COMMIT ` + -Repo $env:GITHUB_REPOSITORY ` + -StableRuntimeTag $runtimeTag ` + -StableRuntimeTitle $runtimeTitle ` + -OutFile $notesFile + "RELEASE_NOTES_FILE=$notesFile" | Out-File -FilePath $env:GITHUB_ENV -Append + Write-Host "Generated dev release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $devVersion" + + - name: Build frontend + shell: pwsh + run: | + pnpm --dir frontend install --frozen-lockfile + pnpm --dir frontend build + + - name: Go test & vet + shell: pwsh + run: | + go test ./... + go vet ./... + + - name: Install Wails CLI + shell: pwsh + run: go install github.com/wailsapp/wails/v2/cmd/wails@v2.17.1 + + - name: Build Windows x64 binary + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $ver = $env:DEV_VERSION + $dist = 'dist-release' + New-Item -ItemType Directory -Force -Path $dist | Out-Null + $verPkg = 'github.com/Nwflower/reims-go/internal/version' + $guiOut = Join-Path $dist "reims-go-$ver-windows-amd64.exe" + wails build -s -trimpath -ldflags "-s -w -X $verPkg.Version=$ver" -o "reims-go-$ver-windows-amd64.exe" + if ($LASTEXITCODE) { throw "wails build failed ($LASTEXITCODE)" } + Copy-Item (Join-Path 'build\bin' "reims-go-$ver-windows-amd64.exe") $guiOut + $zipOut = [IO.Path]::ChangeExtension($guiOut, '.zip') + Compress-Archive -LiteralPath @($guiOut, 'LICENSE', 'NOTICE.md') -DestinationPath $zipOut -CompressionLevel Optimal -Force + $lines = @(Get-Item -LiteralPath $guiOut, $zipOut | ForEach-Object { + $h = (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLowerInvariant() + "$h $($_.Name)" + }) + [IO.File]::WriteAllText((Join-Path $dist 'SHA256SUMS.txt'), ($lines -join "`n") + "`n", [Text.UTF8Encoding]::new($false)) + Get-Content (Join-Path $dist 'SHA256SUMS.txt') + + - name: Update rolling dev GitHub Release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $releaseTag = 'dev' + $ver = $env:DEV_VERSION + $notesFile = $env:RELEASE_NOTES_FILE + if (-not (Test-Path -LiteralPath $notesFile) -or (Get-Item -LiteralPath $notesFile).Length -eq 0) { + throw "Release notes file is missing or empty: $notesFile" + } + $title = "Reims-Go Dev ($ver)" + $files = @(Get-ChildItem -LiteralPath 'dist-release' -File | Select-Object -ExpandProperty FullName) + $keepNames = @($files | ForEach-Object { [IO.Path]::GetFileName($_) }) + + # Point the fixed 'dev' tag to the commit being built. + git tag -f $releaseTag $env:GITHUB_SHA + if ($LASTEXITCODE -ne 0) { throw "git tag -f $releaseTag failed ($LASTEXITCODE)" } + git push --force origin "refs/tags/$releaseTag" + if ($LASTEXITCODE -ne 0) { throw "git push --force refs/tags/$releaseTag failed ($LASTEXITCODE)" } + + $exists = $true + $existingAssets = @() + try { + $relJson = gh release view $releaseTag --json assets 2>$null + if ($LASTEXITCODE -ne 0) { + $exists = $false + } else { + $existingAssets = @(($relJson | ConvertFrom-Json).assets) + } + } catch { + $exists = $false + } + + if ($exists) { + # Upload new assets first so the release is never left empty if upload fails. + gh release upload $releaseTag @files --clobber + if ($LASTEXITCODE -ne 0) { throw "gh release upload failed ($LASTEXITCODE)" } + foreach ($asset in $existingAssets) { + if ($keepNames -notcontains $asset.name) { + Write-Host "Removing stale dev asset $($asset.name)" + gh release delete-asset $releaseTag $asset.name --yes + if ($LASTEXITCODE -ne 0) { throw "gh release delete-asset $($asset.name) failed ($LASTEXITCODE)" } + } + } + gh release edit $releaseTag ` + --target $env:GITHUB_SHA ` + --prerelease ` + --title $title ` + --notes-file $notesFile + if ($LASTEXITCODE -ne 0) { throw "gh release edit failed ($LASTEXITCODE)" } + } else { + gh release create $releaseTag @files ` + --target $env:GITHUB_SHA ` + --prerelease ` + --title $title ` + --notes-file $notesFile + if ($LASTEXITCODE -ne 0) { throw "gh release create failed ($LASTEXITCODE)" } + } diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 67fe314..0a7d774 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,7 +7,7 @@ on: workflow_dispatch: inputs: tag: - description: "Release tag to build & publish (e.g. v0.2.1)" + description: "Release tag to build & publish (e.g. v0.2.9 or v0.2.9-alpha.1)" required: true permissions: @@ -20,6 +20,7 @@ jobs: - uses: actions/checkout@v4 with: ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }} + fetch-depth: 0 - uses: actions/setup-go@v5 with: @@ -35,20 +36,31 @@ jobs: cache: pnpm cache-dependency-path: frontend/pnpm-lock.yaml - - name: Resolve version tag + - name: Resolve version tag and channel shell: pwsh run: | + $ErrorActionPreference = 'Stop' $tag = if ('${{ github.event_name }}' -eq 'workflow_dispatch') { '${{ inputs.tag }}' } else { '${{ github.ref_name }}' } - if (-not $tag.StartsWith('v')) { throw "Release tag must start with 'v', got: $tag" } + $tag = $tag.Trim() + if ($tag -match '^v[0-9]+\.[0-9]+\.[0-9]+$') { + $channel = 'stable' + } elseif ($tag -match '^v[0-9]+\.[0-9]+\.[0-9]+-alpha(?:[.-][0-9A-Za-z.-]+)?$') { + $channel = 'alpha' + } else { + throw "Release tag must be stable (vX.Y.Z) or alpha test (vX.Y.Z-alpha[.N]), got: $tag" + } "RELEASE_TAG=$tag" | Out-File -FilePath $env:GITHUB_ENV -Append + "RELEASE_CHANNEL=$channel" | Out-File -FilePath $env:GITHUB_ENV -Append + Write-Host "Resolved tag=$tag channel=$channel" - - name: Generate release notes from CHANGELOG.md + - name: Generate release notes env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} shell: pwsh run: | $ErrorActionPreference = 'Stop' $tag = $env:RELEASE_TAG + $channel = $env:RELEASE_CHANNEL $runtimeTag = '' $runtimeTitle = '' try { @@ -67,13 +79,14 @@ jobs: $notesFile = Join-Path $env:RUNNER_TEMP "release-notes-$tag.md" & ./scripts/build-release-notes.ps1 ` -Tag $tag ` + -Channel $channel ` -ChangelogPath 'CHANGELOG.md' ` -Repo $env:GITHUB_REPOSITORY ` -StableRuntimeTag $runtimeTag ` -StableRuntimeTitle $runtimeTitle ` -OutFile $notesFile "RELEASE_NOTES_FILE=$notesFile" | Out-File -FilePath $env:GITHUB_ENV -Append - Write-Host "Generated release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $tag" + Write-Host "Generated $channel release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $tag" - name: Build frontend shell: pwsh @@ -120,10 +133,12 @@ jobs: run: | $ErrorActionPreference = 'Stop' $tag = $env:RELEASE_TAG + $channel = $env:RELEASE_CHANNEL $notesFile = $env:RELEASE_NOTES_FILE if (-not (Test-Path -LiteralPath $notesFile) -or (Get-Item -LiteralPath $notesFile).Length -eq 0) { throw "Release notes file is missing or empty: $notesFile" } + $title = if ($channel -eq 'alpha') { "Reims-Go $tag (Alpha)" } else { "Reims-Go $tag" } $files = @(Get-ChildItem -LiteralPath 'dist-release' -File | Select-Object -ExpandProperty FullName) $exists = $true $existingBody = '' @@ -140,15 +155,52 @@ jobs: if ($exists) { gh release upload $tag @files --clobber if ($LASTEXITCODE -ne 0) { throw "gh release upload failed ($LASTEXITCODE)" } + $editArgs = @('release', 'edit', $tag, '--title', $title) + if ($channel -eq 'alpha') { + $editArgs += '--prerelease' + } else { + $editArgs += @('--prerelease=false', '--latest') + } # Backfill notes if the existing release body is empty or only GitHub's auto-generated compare link. $isAutoOnly = [string]::IsNullOrWhiteSpace($existingBody) -or ($existingBody -match '^\*\*Full Changelog\*\*:\s*https://\S+$') if ($isAutoOnly) { - gh release edit $tag --notes-file $notesFile - if ($LASTEXITCODE -ne 0) { throw "gh release edit failed ($LASTEXITCODE)" } + $editArgs += @('--notes-file', $notesFile) } + & gh @editArgs + if ($LASTEXITCODE -ne 0) { throw "gh release edit failed ($LASTEXITCODE)" } } else { - gh release create $tag @files ` - --title "Reims-Go $tag" ` - --notes-file $notesFile + $createArgs = @('release', 'create', $tag) + $files + @('--title', $title, '--notes-file', $notesFile) + if ($channel -eq 'alpha') { + $createArgs += '--prerelease' + } else { + $createArgs += '--latest' + } + & gh @createArgs if ($LASTEXITCODE -ne 0) { throw "gh release create failed ($LASTEXITCODE)" } } + + - name: Delete all published alpha test releases after stable release + if: env.RELEASE_CHANNEL == 'stable' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + # Only delete app alpha prereleases (vX.Y.Z-alpha*); never touch runtime-* or the rolling dev release. + $rels = gh release list -R $env:GITHUB_REPOSITORY --limit 1000 --json tagName,isPrerelease,isDraft | ConvertFrom-Json + $alphas = @($rels | Where-Object { + $_.isPrerelease -and + -not $_.isDraft -and + $_.tagName -match '^v[0-9]+\.[0-9]+\.[0-9]+-alpha(?:[.-][0-9A-Za-z.-]+)?$' + }) + if ($alphas.Count -eq 0) { + Write-Host "No published alpha test releases to clean up." + exit 0 + } + foreach ($rel in $alphas) { + Write-Host "Deleting alpha test release $($rel.tagName)" + gh release delete $rel.tagName -R $env:GITHUB_REPOSITORY --yes --cleanup-tag + if ($LASTEXITCODE -ne 0) { + throw "Failed to delete alpha test release $($rel.tagName) (exit $LASTEXITCODE)" + } + } diff --git a/cmd/i18ngen/main.go b/cmd/i18ngen/main.go new file mode 100644 index 0000000..94bb026 --- /dev/null +++ b/cmd/i18ngen/main.go @@ -0,0 +1,327 @@ +// Command i18ngen compiles and validates the canonical JSON message catalogs +// under locales/{zh-CN,en-US}/*.json, enforcing: +// - 100% key parity between zh-CN and en-US in every domain +// - valid lightweight ICU AST syntax across every entry +// - identical {var} placeholder sets between zh-CN, en-US, and optional $params +// +// Outputs: +// - internal/i18n/catalog_gen.go +// - frontend/src/i18n/keys.gen.ts +// - frontend/src/i18n/domains/{core,vm,wizard,settings,plugins}.gen.ts +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +var ( + allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"} + goDomains = []string{"native", "macos-glossary", "core"} + feEagerDomains = []string{"core", "vm"} + feLazyDomains = []string{"wizard", "settings", "plugins"} +) + +type parsedEntry struct { + Message string + Params []string + Comment string + MaxLength int +} + +func main() { + root := "." + if _, err := os.Stat("locales/zh-CN/core.json"); err != nil { + fmt.Fprintf(os.Stderr, "i18ngen: must be run from repository root: %v\n", err) + os.Exit(1) + } + + zhByDomain := make(map[string]map[string]parsedEntry) + enByDomain := make(map[string]map[string]parsedEntry) + keyOwnerDomain := make(map[string]string) + + var validationErrors []string + + for _, dom := range allDomains { + zhPath := filepath.Join(root, "locales", "zh-CN", dom+".json") + enPath := filepath.Join(root, "locales", "en-US", dom+".json") + + zhMap, err := readCatalogFile(zhPath) + if err != nil { + fmt.Fprintf(os.Stderr, "i18ngen: read %s: %v\n", zhPath, err) + os.Exit(1) + } + enMap, err := readCatalogFile(enPath) + if err != nil { + fmt.Fprintf(os.Stderr, "i18ngen: read %s: %v\n", enPath, err) + os.Exit(1) + } + + for k := range zhMap { + if prevDom, exists := keyOwnerDomain[k]; exists { + validationErrors = append(validationErrors, fmt.Sprintf("duplicate key %q across domains %q and %q", k, prevDom, dom)) + } + keyOwnerDomain[k] = dom + if _, ok := enMap[k]; !ok { + validationErrors = append(validationErrors, fmt.Sprintf("[%s] key %q exists in zh-CN but missing in en-US", dom, k)) + } + } + for k := range enMap { + if _, ok := zhMap[k]; !ok { + validationErrors = append(validationErrors, fmt.Sprintf("[%s] key %q exists in en-US but missing in zh-CN", dom, k)) + } + } + + keys := sortedKeys(zhMap) + for _, k := range keys { + ze, ok := zhMap[k] + if !ok { + continue + } + ee, ok := enMap[k] + if !ok { + continue + } + _, zhVars, zErr := i18n.ParseICU(ze.Message) + if zErr != nil { + validationErrors = append(validationErrors, fmt.Sprintf("[%s] zh-CN %q invalid ICU syntax: %v", dom, k, zErr)) + continue + } + _, enVars, eErr := i18n.ParseICU(ee.Message) + if eErr != nil { + validationErrors = append(validationErrors, fmt.Sprintf("[%s] en-US %q invalid ICU syntax: %v", dom, k, eErr)) + continue + } + if !reflect.DeepEqual(zhVars, enVars) { + validationErrors = append(validationErrors, fmt.Sprintf("[%s] placeholder mismatch for %q: zh-CN=%v vs en-US=%v", dom, k, zhVars, enVars)) + } + if len(ze.Params) > 0 { + decl := append([]string(nil), ze.Params...) + sort.Strings(decl) + if !reflect.DeepEqual(decl, zhVars) { + validationErrors = append(validationErrors, fmt.Sprintf("[%s] zh-CN $params %v does not match template vars %v for %q", dom, ze.Params, zhVars, k)) + } + } + if len(ee.Params) > 0 { + decl := append([]string(nil), ee.Params...) + sort.Strings(decl) + if !reflect.DeepEqual(decl, enVars) { + validationErrors = append(validationErrors, fmt.Sprintf("[%s] en-US $params %v does not match template vars %v for %q", dom, ee.Params, enVars, k)) + } + } + } + + zhByDomain[dom] = zhMap + enByDomain[dom] = enMap + } + + if len(validationErrors) > 0 { + for _, msg := range validationErrors { + fmt.Fprintln(os.Stderr, "ERROR:", msg) + } + os.Exit(1) + } + + if err := writeGoCatalog(root, zhByDomain, enByDomain); err != nil { + fmt.Fprintf(os.Stderr, "i18ngen: write Go catalog: %v\n", err) + os.Exit(1) + } + if err := writeFrontendCatalogs(root, zhByDomain, enByDomain); err != nil { + fmt.Fprintf(os.Stderr, "i18ngen: write frontend catalogs: %v\n", err) + os.Exit(1) + } + fmt.Println("i18ngen: OK") +} + +func readCatalogFile(path string) (map[string]parsedEntry, error) { + raw, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var rawMap map[string]json.RawMessage + if err := json.Unmarshal(raw, &rawMap); err != nil { + return nil, err + } + out := make(map[string]parsedEntry, len(rawMap)) + for k, v := range rawMap { + if strings.HasPrefix(k, "$") { + continue + } + var plain string + if err := json.Unmarshal(v, &plain); err == nil { + out[k] = parsedEntry{Message: plain} + continue + } + var meta struct { + Message string `json:"message"` + Params []string `json:"$params"` + Comment string `json:"$comment"` + MaxLength int `json:"$maxLength"` + } + if err := json.Unmarshal(v, &meta); err != nil { + return nil, fmt.Errorf("key %q: %w", k, err) + } + out[k] = parsedEntry{ + Message: meta.Message, + Params: meta.Params, + Comment: meta.Comment, + MaxLength: meta.MaxLength, + } + } + return out, nil +} + +func sortedKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +func writeGoCatalog(root string, zhByDom, enByDom map[string]map[string]parsedEntry) error { + zhMerged := make(map[string]string) + enMerged := make(map[string]string) + params := make(map[string][]string) + + for _, dom := range goDomains { + for k, e := range zhByDom[dom] { + zhMerged[k] = e.Message + if len(e.Params) > 0 { + params[k] = e.Params + } else if ee := enByDom[dom][k]; len(ee.Params) > 0 { + params[k] = ee.Params + } else { + _, vars, _ := i18n.ParseICU(e.Message) + if len(vars) > 0 { + params[k] = vars + } + } + } + for k, e := range enByDom[dom] { + enMerged[k] = e.Message + } + } + + keys := sortedKeys(zhMerged) + var b bytes.Buffer + b.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n\npackage i18n\n\n") + b.WriteString("var catalog = map[Locale]map[string]string{\n") + b.WriteString("\tZhCN: {\n") + for _, k := range keys { + fmt.Fprintf(&b, "\t\t%q: %q,\n", k, zhMerged[k]) + } + b.WriteString("\t},\n\tEnUS: {\n") + for _, k := range keys { + fmt.Fprintf(&b, "\t\t%q: %q,\n", k, enMerged[k]) + } + b.WriteString("\t},\n}\n\n") + + paramKeys := sortedKeys(params) + b.WriteString("var paramOrder = map[string][]string{\n") + for _, k := range paramKeys { + p := params[k] + quoted := make([]string, len(p)) + for i, name := range p { + quoted[i] = fmt.Sprintf("%q", name) + } + fmt.Fprintf(&b, "\t%q: {%s},\n", k, strings.Join(quoted, ", ")) + } + b.WriteString("}\n") + + return os.WriteFile(filepath.Join(root, "internal/i18n/catalog_gen.go"), b.Bytes(), 0o644) +} + +func writeFrontendCatalogs(root string, zhByDom, enByDom map[string]map[string]parsedEntry) error { + feDir := filepath.Join(root, "frontend/src/i18n") + domDir := filepath.Join(feDir, "domains") + if err := os.MkdirAll(domDir, 0o755); err != nil { + return err + } + + // Merge macos-glossary into frontend core domain as well so UI components can use official glossary keys. + feDomains := []string{"core", "vm", "wizard", "settings", "plugins"} + var allFEKeys []string + + for _, dom := range feDomains { + zhMap := make(map[string]string) + enMap := make(map[string]string) + for k, v := range zhByDom[dom] { + zhMap[k] = v.Message + } + for k, v := range enByDom[dom] { + enMap[k] = v.Message + } + if dom == "core" { + for k, v := range zhByDom["macos-glossary"] { + zhMap[k] = v.Message + } + for k, v := range enByDom["macos-glossary"] { + enMap[k] = v.Message + } + } + + keys := sortedKeys(zhMap) + allFEKeys = append(allFEKeys, keys...) + + isLazy := false + for _, ld := range feLazyDomains { + if ld == dom { + isLazy = true + break + } + } + + var b bytes.Buffer + b.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n") + if isLazy { + b.WriteString("import { registerBuiltinDomain } from '../runtime'\n\n") + } else { + b.WriteString("\n") + } + fmt.Fprintf(&b, "export const %sZh: Record = {\n", dom) + for _, k := range keys { + fmt.Fprintf(&b, " %s: %s,\n", tsQuoted(k), tsQuoted(zhMap[k])) + } + b.WriteString("}\n\n") + fmt.Fprintf(&b, "export const %sEn: Record = {\n", dom) + for _, k := range keys { + fmt.Fprintf(&b, " %s: %s,\n", tsQuoted(k), tsQuoted(enMap[k])) + } + b.WriteString("}\n") + if isLazy { + fmt.Fprintf(&b, "\nregisterBuiltinDomain(%sZh, %sEn)\n", dom, dom) + } + + if err := os.WriteFile(filepath.Join(domDir, dom+".gen.ts"), b.Bytes(), 0o644); err != nil { + return err + } + } + + sort.Strings(allFEKeys) + var kb bytes.Buffer + kb.WriteString("// Code generated by cmd/i18ngen; DO NOT EDIT.\n\n") + kb.WriteString("export type I18nKey =\n") + for i, k := range allFEKeys { + sep := "" + if i == len(allFEKeys)-1 { + sep = ";" + } + fmt.Fprintf(&kb, " | %s%s\n", tsQuoted(k), sep) + } + return os.WriteFile(filepath.Join(feDir, "keys.gen.ts"), kb.Bytes(), 0o644) +} + +func tsQuoted(s string) string { + raw, _ := json.Marshal(s) + return string(raw) +} diff --git a/docs/architecture.md b/docs/architecture.md index f7e6f63..682d9b5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -10,7 +10,7 @@ 2. **包装而非重写引擎**:通过受控子进程调用上游 `reims-ctl`、`reims-util` 与 `qemu-img`,不手写易随上游演进失效的 QEMU 启动参数拼接逻辑。 3. **GUI 与 CLI 单文件同源**:所有业务逻辑下沉在 `internal/`。无参数启动 Wails 桌面窗口,带子命令(`reims-go `)进入命令行模式,供终端、脚本与自动化工具调用。 4. **数据目录隔离**:运行时、下载缓存、虚拟机磁盘、快照与临时文件全部落在用户选定的 `` 下,不污染系统盘。 -5. **原生中英双语**:前后端内置 `zh-CN` / `en-US` 双语字典,自动跟随系统语言并支持运行时切换。 +5. **同构多语言与语言包扩展**:单一事实源分域 JSON 词表(`locales/`)在编译期同时生成 Go 与 TypeScript 类型安全字典,前后端共用轻量 ICU 消息语法与多跳区域回退链;主程序内置 `zh-CN` 与 `en-US`(默认 `auto` 跟随系统并支持热切换),其他语种通过 L1 声明式语言包插件按需扩展并覆盖桌面界面、Win32 原生浮层、系统托盘与命令行。 6. **跨平台开发友好**:所有 Windows 原生 API(WHPX、注册表、处理器拓扑、进程亲和性、系统代理、托盘)严格隔离在 `*_windows.go`,提供 `*_other.go` 桩实现,确保非 Windows 环境也能执行 `go build` 与 `go test ./...`。 --- @@ -66,7 +66,8 @@ flowchart TB | `internal/guesttools` | 本地回环鉴权 HTTP/WebDAV 服务:图文双向剪贴板、共享目录、Windows 盘符只读共享、防休眠开关与 `REIMSTOOLS` 辅助盘生成 | | `internal/opencore` | 改写 OpenCore 镜像中的 `prev-lang:kbd`,实现系统外预设 macOS 语言 | | `internal/netproxy` | 统一 HTTP Transport:优先环境变量代理,回退读取 Windows 系统代理配置 | -| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)与 Go 端双语消息/结构化错误码 | +| `locales/`、`cmd/i18ngen` | 单一事实源分域 JSON 词表(含译者上下文 `$comment` 与 Apple macOS 官方多语种词汇表)及编译期前后端字典代码生成器 | +| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)、轻量 ICU 格式化引擎、多跳语言回退链与带稳定排障码的结构化错误(`CodedError`) | | `internal/thumb`、`internal/tray`、`internal/version` | 4K 截屏行级缩放预览、Windows 系统托盘常驻、版本信息与新版本检查 | | `frontend/src` | 桌面界面:`components/`(页面与对话框)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) | | `patches/` | 上游临时补丁队列与 PR 跟踪,见 [`patches/README.md`](../patches/README.md) | diff --git a/docs/design-guidelines.md b/docs/design-guidelines.md index 84b370c..1e75b1c 100644 --- a/docs/design-guidelines.md +++ b/docs/design-guidelines.md @@ -82,7 +82,7 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台 ## 6. 视觉、图标与无障碍基线 - **样式令牌化**:所有颜色、字号、间距(4 px 网格)、圆角与阴影统一引用 [`frontend/src/styles/tokens.css`](../frontend/src/styles/tokens.css) 中的 CSS 变量,禁止在组件内联写死颜色或字号。 -- **字体**:内嵌开源 Inter Variable 作为拉丁字体,并针对 Windows DirectWrite 特性显式映射中文字体字重,避免正文过细或中英混排断层。 +- **字体与区域排印**:内嵌开源 Inter Variable 作为拉丁字体,并通过动态 `` 与 `:lang()` 选择器按区域分离东亚字体栈(简体、繁体、日文、韩文各自优先匹配对应系统 UI 字体,避免 Han Unification 异体字混用);繁体与日文正文采用 `400` 字重与更舒展的行高防止高笔画糊字,开启中西文自动盘古间距;Win32 原生引导浮层按脚本分级探测 GDI 字体并支持卡片宽度自适应与长按钮纵向堆叠。语言包插件可附带沙箱校验的 `.woff2` 字体补齐缺字宿主。 - **按钮层级**:每视图至多 1 个实底主按钮;常用操作用次按钮或图标按钮;破坏性操作仅用红字出现在菜单与确认框。 - **纯图标按钮边界**:仅当图标含义通用(启动、停止、设置、更多、新建、复制、关闭、刷新、日志)且既非主操作也非破坏性操作时才允许纯图标;所有纯图标按钮必须具备悬停 Tooltip(含快捷键)、`aria-label` 与 ≥ 28×28 px 的点击热区。领域专有操作(如「弹出安装盘」「显示 VM 窗口」「重启以应用」)必须保留文字。 - **键盘与缩放**:所有可交互项必须为原生 ` diff --git a/frontend/src/components/HostView.tsx b/frontend/src/components/HostView.tsx index 030ec44..50d780f 100644 --- a/frontend/src/components/HostView.tsx +++ b/frontend/src/components/HostView.tsx @@ -1,5 +1,7 @@ import { Cpu, HardDrive, MemoryStick, Plus, RefreshCw, ShieldCheck, Trash } from 'lucide-react' import React, { useEffect, useState } from 'react' +import '../i18n/domains/settings.gen' +import '../i18n/domains/wizard.gen' import { I18nKey, t } from '../i18n' import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format' import { AppState, Locale, StorageBreakdown, Task } from '../types' @@ -154,7 +156,7 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o
{tr('storageBreakdownTitle')} - {formatBytes(storage.total_bytes)} + {formatBytes(storage.total_bytes, locale)}