diff --git a/.gitea/workflows/quality-gates.yml b/.gitea/workflows/quality-gates.yml index 2786f9d4..eb245167 100644 --- a/.gitea/workflows/quality-gates.yml +++ b/.gitea/workflows/quality-gates.yml @@ -238,11 +238,21 @@ jobs: env: GITEA_TOKEN: ${{ gitea.token }} run: node scripts/ci/main-push-reuse.ts --job "merge / browser tests" --github-output "$GITHUB_OUTPUT" + - name: Restore and save the visual-test fonts cache + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && gitea.ref == 'refs/heads/main' }} + uses: https://github.com/actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 + with: + path: ${{ runner.temp }}/visual-test-fonts + key: fe-visual-fonts-baed2032d533-7231f2b318ec + - name: Restore the visual-test fonts cache + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && gitea.ref != 'refs/heads/main' }} + uses: https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 + with: + path: ${{ runner.temp }}/visual-test-fonts + key: fe-visual-fonts-baed2032d533-7231f2b318ec - name: Install visual-test fonts if: ${{ steps.main-push-reuse.outputs.reuse != 'true' }} - run: | - $(command -v sudo || true) apt-get update - $(command -v sudo || true) apt-get install -y fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation + run: bash scripts/ci/install-visual-test-fonts.sh "$RUNNER_TEMP/visual-test-fonts" fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation - name: "FE-GATE-008 / e2e" if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-008 diff --git a/CHANGELOG.md b/CHANGELOG.md index 89686523..0ef66e0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -187,6 +187,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지 | [계약] | merge static job이 게이트 뒤에 `scripts/tests` 시험(`.claude/` 지침, 편집 훅, `scripts/verify.sh`)을 `python3 -I -m unittest discover -s scripts/tests`로 돈다. 계약에 step 종류 `run-script-tests`를 더하고 `merge_static`에만 둔다. 자기 runner job 이미지에 python3가 있어야 한다 | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/generate-ci-workflow.ts`, `tests/unit/ci-workflow-generation.test.ts` | `91c03b49` | | [계약] | `refs/heads/main` push의 merge job 셋(`merge_static`·`merge_test`·`merge_browser`)이 `Frozen install` 다음 `main-push-reuse` step에서 직전 PR 실행을 재사용할 수 있는지 본다. checkout이 `fetch-depth: 2`로 부모 둘을 받고, 여섯 조건(main push, 부모 둘 병합 커밋·`tree(HEAD)==tree(HEAD^2)`, `.nvmrc`·`pnpm-lock.yaml` 무변경, `HEAD^2` 최신 PR run의 같은 job `success`, 그 job 로그에 `건너뜀:` 없음, Gitea API 읽기 성공)이 모두 참이면 뒤 step(글꼴·게이트·`scripts/tests`·증거 업로드)을 건너뛰고 `건너뜀:` 한 줄로 성공 종료한다. 하나라도 모르거나 읽지 못하면 전부 돈다. `main_gate`(FE-GATE-029·020·030)와 release·tag run은 늘 돈다 (CI-FE-0004) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/generate-ci-workflow.ts`, `.gitea/workflows/quality-gates.yml`, `scripts/lib/main-push-reuse.ts`, `scripts/ci/main-push-reuse.ts`, `tests/unit/main-push-reuse.test.ts`, `tests/unit/ci-workflow-generation.test.ts`, `docs/operations/ci-quality-gates.md`, `docs/work/reference/decisions.md` | `b2b92dc6` | | [계약] | 기능·scaffold 제거 드릴 FE-GATE-020을 `merge` 단계(`merge_test`, `MERGE_READY`)에서 `main` 단계(`main_gate`, `MAIN_READY`)로 옮긴다. PR 경로표 `config/ci/pr-gate-selection.json`의 `accessibility-records`·`scaffold` 줄에서 FE-GATE-020을 빼고(`scaffold` 줄은 되돌림과 계약 시험을 위해 유지), `scripts/lib/feature-scaffold-drill.ts`는 되돌림 시 재귀를 막으려 자기 스크립트(`test:sample-removal`·`test:feature-scaffold`)를 제외 목록에 남기되 merge 밖 stale 거절에서 면제한다. release·tag run과 `RELEASE_READY`는 FE-GATE-020을 요구하지 않는다. 위 "먼저 할 일" (CI-FE-0005) | `config/ci/gates.json`, `config/ci/pr-gate-selection.json`, `scripts/contracts/ci-gates.ts`, `scripts/lib/promotion-readiness.ts`, `scripts/lib/feature-scaffold-drill.ts`, `.gitea/workflows/quality-gates.yml`, `tests/unit/ci-workflow-generation.test.ts`, `tests/unit/promotion-readiness.test.ts`, `tests/unit/feature-scaffold-drill.test.ts`, `tests/unit/pr-gate-selection.test.ts`, `docs/operations/ci-quality-gates.md`, `docs/work/reference/decisions.md`, `docs/work/reference/gates.md`, `docs/work/reference/structure.md`, `docs/work/new-feature.md` | `94f8434f` | +| [계약] | `merge_browser` job이 visual 시험 글꼴 `.deb` 패키지를 `${{ runner.temp }}/visual-test-fonts`에 캐시하고 `scripts/ci/install-visual-test-fonts.sh`로 설치한다. 키는 Playwright 이미지 digest 앞자리와 `VISUAL_TEST_FONT_PACKAGES` 해시로 정확히 맞추며(`restore-keys` 없음), `refs/heads/main`에서만 저장하고 PR과 다른 브랜치는 복원만 한다. hit이면 `apt-get` 없이 `dpkg -i`로 설치하고, miss이면 `--download-only`로 받은 뒤 설치한다 (CI-FE-0003) | `scripts/lib/visual-test-fonts.ts`, `scripts/ci/install-visual-test-fonts.sh`, `scripts/generate-ci-workflow.ts`, `.gitea/workflows/quality-gates.yml`, `tests/unit/ci-browser-image.test.ts`, `tests/unit/install-visual-test-fonts.test.ts`, `tests/unit/ci-workflow-generation.test.ts`, `docs/operations/ci-quality-gates.md` | `2db8b90e` | ### 그 밖의 변경 diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index cc1ba7a7..b4f763da 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -14,7 +14,12 @@ repo 훅·검사기·`.claude/` 지침 시험(`python3 -I -m unittest discover - 게이트가 실패해도 돌고, PR의 게이트 고르기와 상관없이 늘 돈다. `merge_browser` 컨테이너는 `/dev/shm`을 2 GB로 연다(`--shm-size=2g`). Firefox 시험 프로필을 RAM에 두기 위해서다 (`tests/support/browser/browser-test.ts`). Docker 기본값 64 MB면 프로필이 runner 디스크에 남아 -Firefox의 첫 localStorage 접근이 수 초씩 기다렸다. +Firefox의 첫 localStorage 접근이 수 초씩 기다렸다. `merge_browser`의 visual 시험 글꼴 패키지 +(`scripts/lib/visual-test-fonts.ts`)는 `.deb` 파일을 `${{ runner.temp }}/visual-test-fonts`에 +캐시해 설치한다(`scripts/ci/install-visual-test-fonts.sh`). 키는 이미지 digest 앞자리와 패키지 목록 +해시로 정확히 맞추고 `restore-keys`는 두지 않는다. 의존성 캐시와 같이 `refs/heads/main`에서만 저장하고 +PR과 다른 브랜치는 복원만 한다. 캐시가 맞으면 `apt-get` 없이 `dpkg -i`로 설치하고, 비어 있으면 +`apt-get install -y --download-only`로 내려받은 뒤 설치한다. PR run(`pull_request`)은 merge 게이트를 바뀐 파일로 고른다(소유자 결정 2026-11-13). 경로표는 `config/ci/pr-gate-selection.json`이다. 파일마다 `rules`를 위에서부터 보고 처음 맞는 줄의 게이트를 `always`(FE-GATE-001·002·003·010)에 더한다. 문서만 바뀌면 FE-GATE-005까지, 접근성 기록은 diff --git a/scripts/ci/install-visual-test-fonts.sh b/scripts/ci/install-visual-test-fonts.sh new file mode 100755 index 00000000..6f45706f --- /dev/null +++ b/scripts/ci/install-visual-test-fonts.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# FE-3 (2) (CI-FE-0003). Installs the visual goldens' font packages from the +# cached .deb archives in $1; on a cache miss downloads them there first with +# apt-get and drops apt's partial/lock metadata so actions/cache archives only +# the .deb files. Package names follow $1. +set -euo pipefail + +dir=${1:?cache directory is required} +shift +if (($# == 0)); then + echo "install-visual-test-fonts: at least one package name is required" >&2 + exit 2 +fi + +sudo_cmd=$(command -v sudo || true) +run_privileged() { + if [ -n "$sudo_cmd" ]; then + "$sudo_cmd" "$@" + else + "$@" + fi +} + +shopt -s nullglob +debs=("$dir"/*.deb) +if ((${#debs[@]} == 0)); then + mkdir -p "$dir/partial" + run_privileged env DEBIAN_FRONTEND=noninteractive apt-get update + run_privileged env DEBIAN_FRONTEND=noninteractive apt-get install -y --download-only -o Dir::Cache::archives="$dir" "$@" + run_privileged rm -rf "$dir/partial" "$dir/lock" + debs=("$dir"/*.deb) +fi + +if ((${#debs[@]} > 0)); then + run_privileged env DEBIAN_FRONTEND=noninteractive dpkg -i "${debs[@]}" + exit 0 +fi + +for pkg in "$@"; do + if ! dpkg-query -W -f='${Status}\n' "$pkg" 2>/dev/null | grep -qx 'install ok installed'; then + echo "install-visual-test-fonts: no .deb archive downloaded and package not installed: $pkg" >&2 + exit 1 + fi +done diff --git a/scripts/generate-ci-workflow.ts b/scripts/generate-ci-workflow.ts index e9197dc4..8608978e 100644 --- a/scripts/generate-ci-workflow.ts +++ b/scripts/generate-ci-workflow.ts @@ -16,6 +16,7 @@ import { indexCiGateContract, loadCiGateContract, MAIN_PUSH_REUSE, + resolveCiActionUses, resolveCiStepActionUses, resolveCiSubActionUses, type CiGateContract, @@ -29,7 +30,12 @@ import { ensureSafePublishDirectory, } from "./lib/ci-gate-log.ts"; import { isEntryModule } from "./lib/entry-module.ts"; -import { VISUAL_TEST_FONT_INSTALL_ARGUMENTS } from "./lib/visual-test-fonts.ts"; +import { + VISUAL_TEST_FONT_CACHE, + VISUAL_TEST_FONT_INSTALL_ARGUMENTS, + VISUAL_TEST_FONT_PACKAGES, + visualTestFontCacheKey, +} from "./lib/visual-test-fonts.ts"; export type GenerateCiWorkflowOptions = Readonly<{ root: string; @@ -332,6 +338,26 @@ function notMainPushReused(): string { return `steps.${MAIN_PUSH_REUSE.stepId}.outputs.reuse != 'true'`; } +function visualFontCacheSteps(job: CiWorkflowJob, image: string): string[] { + const key = visualTestFontCacheKey(image); + const reuseGuard = hasMainPushReuse(job) ? `${notMainPushReused()} && ` : ""; + const cacheWith = [ + " with:", + ` path: ${VISUAL_TEST_FONT_CACHE.directory}`, + ` key: ${key}`, + ]; + return [ + " - name: Restore and save the visual-test fonts cache", + ` if: \${{ ${reuseGuard}gitea.ref == 'refs/heads/main' }}`, + ` uses: ${resolveCiActionUses("cache")}`, + ...cacheWith, + " - name: Restore the visual-test fonts cache", + ` if: \${{ ${reuseGuard}gitea.ref != 'refs/heads/main' }}`, + ` uses: ${resolveCiSubActionUses("cache", "restore")}`, + ...cacheWith, + ]; +} + function renderStep( job: CiWorkflowJob, step: CiWorkflowStep, @@ -399,14 +425,15 @@ function renderStep( ]; case "browser-install": if (step.image) { - // The job image holds the browsers and their OS libraries; the goldens' - // faces are still OS packages it lacks, and it ships no package lists. + // FE-3 (2) (CI-FE-0003). The job image holds the browsers and their OS + // libraries; the visual goldens' font .deb archives are cached like the + // dependencies (main saves, non-main restores) and installed via dpkg + // on a hit without calling apt-get. return [ + ...visualFontCacheSteps(job, step.image), " - name: Install visual-test fonts", ...(hasMainPushReuse(job) ? [` if: \${{ ${notMainPushReused()} }}`] : []), - " run: |", - " $(command -v sudo || true) apt-get update", - ` $(command -v sudo || true) ${VISUAL_TEST_FONT_INSTALL_ARGUMENTS}`, + ` run: bash ${VISUAL_TEST_FONT_CACHE.installScript} ${VISUAL_TEST_FONT_CACHE.shellDirectory} ${VISUAL_TEST_FONT_PACKAGES.join(" ")}`, ]; } return [ diff --git a/scripts/lib/visual-test-fonts.ts b/scripts/lib/visual-test-fonts.ts index f689f3fa..d39cc4e0 100644 --- a/scripts/lib/visual-test-fonts.ts +++ b/scripts/lib/visual-test-fonts.ts @@ -1,3 +1,5 @@ +import { createHash } from "node:crypto"; + /** * 1103/11-02. The Debian/Ubuntu packages that hold the four faces the visual * goldens were captured with. `tests/visual/fonts.conf` shows Chromium only @@ -14,3 +16,30 @@ export const VISUAL_TEST_FONT_PACKAGES = Object.freeze([ ] as const); export const VISUAL_TEST_FONT_INSTALL_ARGUMENTS = `apt-get install -y ${VISUAL_TEST_FONT_PACKAGES.join(" ")}`; + +/** + * FE-3 (2) (CI-FE-0003). Caches the downloaded `.deb` archives for the visual + * goldens' font packages outside the checkout so cache hits install via + * `dpkg -i` without calling `apt-get update` or re-downloading ~220 MB. + */ +export const VISUAL_TEST_FONT_CACHE = Object.freeze({ + keyPrefix: "fe-visual-fonts-", + directory: "${{ runner.temp }}/visual-test-fonts", + shellDirectory: '"$RUNNER_TEMP/visual-test-fonts"', + installScript: "scripts/ci/install-visual-test-fonts.sh", +}); + +const IMAGE_SHA256_PATTERN = /@sha256:([0-9a-f]{64})$/u; + +export function visualTestFontCacheKey( + image: string, + packages: readonly string[] = VISUAL_TEST_FONT_PACKAGES, +): string { + const match = IMAGE_SHA256_PATTERN.exec(image); + if (!match) { + throw new TypeError(`visual-test font cache requires an image pinned by sha256 digest: ${image}`); + } + const imageDigestPrefix = match[1]!.slice(0, 12); + const packagesHash = createHash("sha256").update(packages.join("\n")).digest("hex").slice(0, 12); + return `${VISUAL_TEST_FONT_CACHE.keyPrefix}${imageDigestPrefix}-${packagesHash}`; +} diff --git a/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap b/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap index 8c3de860..a7f7654e 100644 --- a/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap +++ b/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap @@ -241,11 +241,21 @@ jobs: env: GITEA_TOKEN: \${{ gitea.token }} run: node scripts/ci/main-push-reuse.ts --job "merge / browser tests" --github-output "$GITHUB_OUTPUT" + - name: Restore and save the visual-test fonts cache + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && gitea.ref == 'refs/heads/main' }} + uses: https://github.com/actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 + with: + path: \${{ runner.temp }}/visual-test-fonts + key: fe-visual-fonts-baed2032d533-7231f2b318ec + - name: Restore the visual-test fonts cache + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && gitea.ref != 'refs/heads/main' }} + uses: https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 + with: + path: \${{ runner.temp }}/visual-test-fonts + key: fe-visual-fonts-baed2032d533-7231f2b318ec - name: Install visual-test fonts if: \${{ steps.main-push-reuse.outputs.reuse != 'true' }} - run: | - $(command -v sudo || true) apt-get update - $(command -v sudo || true) apt-get install -y fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation + run: bash scripts/ci/install-visual-test-fonts.sh "$RUNNER_TEMP/visual-test-fonts" fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation - name: "FE-GATE-008 / e2e" if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-008 diff --git a/tests/unit/ci-browser-image.test.ts b/tests/unit/ci-browser-image.test.ts index 6cadc273..14263465 100644 --- a/tests/unit/ci-browser-image.test.ts +++ b/tests/unit/ci-browser-image.test.ts @@ -2,8 +2,14 @@ import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; -import { loadCiGateContract, PLAYWRIGHT_JOB_IMAGE_PATTERN } from "../../scripts/contracts/ci-gates.ts"; +import { + loadCiGateContract, + PLAYWRIGHT_JOB_IMAGE_PATTERN, + resolveCiActionUses, + resolveCiSubActionUses, +} from "../../scripts/contracts/ci-gates.ts"; import { BROWSER_JOB_SHARED_MEMORY, renderCiWorkflow } from "../../scripts/generate-ci-workflow.ts"; +import { VISUAL_TEST_FONT_PACKAGES } from "../../scripts/lib/visual-test-fonts.ts"; /** * merge_browser runs in Playwright's own image so it does not download the @@ -51,4 +57,42 @@ describe("browser job image", () => { expect(PLAYWRIGHT_JOB_IMAGE_PATTERN.test(image), image).toBe(false); } }); + + // FE-3 (2) (CI-FE-0003): merge_browser caches visual-test font .deb archives + // (main saves, non-main only restores, exact key only without restore-keys) + // and passes VISUAL_TEST_FONT_PACKAGES verbatim to the install script. + it("caches visual-test font .deb archives (restore-only on non-main) and installs VISUAL_TEST_FONT_PACKAGES", async () => { + const contract = await loadCiGateContract(process.cwd()); + const workflow = renderCiWorkflow(contract); + const job = workflow.slice(workflow.indexOf(" merge_browser:\n"), workflow.indexOf(" release_gate:\n")); + const steps = job.split("\n - "); + + const saveStep = steps.find((step) => step.startsWith("name: Restore and save the visual-test fonts cache")); + const restoreStep = steps.find((step) => step.startsWith("name: Restore the visual-test fonts cache")); + const installStep = steps.find((step) => step.startsWith("name: Install visual-test fonts")); + + expect(saveStep).toBeDefined(); + expect(restoreStep).toBeDefined(); + expect(installStep).toBeDefined(); + + // Only main saves; PR / non-main jobs must use actions/cache/restore only. + expect(saveStep).toContain("gitea.ref == 'refs/heads/main'"); + expect(saveStep).toContain(`uses: ${resolveCiActionUses("cache")}`); + expect(saveStep).not.toContain("restore-keys:"); + + expect(restoreStep).toContain("gitea.ref != 'refs/heads/main'"); + expect(restoreStep).toContain(`uses: ${resolveCiSubActionUses("cache", "restore")}`); + expect(restoreStep).not.toContain(`uses: ${resolveCiActionUses("cache")}\n`); + expect(restoreStep).not.toContain("restore-keys:"); + + const saveKey = /^\s+key: (fe-visual-fonts-[0-9a-f]{12}-[0-9a-f]{12})$/mu.exec(saveStep!)?.[1]; + const restoreKey = /^\s+key: (fe-visual-fonts-[0-9a-f]{12}-[0-9a-f]{12})$/mu.exec(restoreStep!)?.[1]; + expect(saveKey).toBeDefined(); + expect(restoreKey).toBe(saveKey); + + expect(installStep).toContain( + `run: bash scripts/ci/install-visual-test-fonts.sh "$RUNNER_TEMP/visual-test-fonts" ${VISUAL_TEST_FONT_PACKAGES.join(" ")}`, + ); + expect(installStep).not.toContain("apt-get"); + }); }); diff --git a/tests/unit/ci-workflow-generation.test.ts b/tests/unit/ci-workflow-generation.test.ts index 031fb239..1be6f154 100644 --- a/tests/unit/ci-workflow-generation.test.ts +++ b/tests/unit/ci-workflow-generation.test.ts @@ -1734,7 +1734,7 @@ describe("CI workflow generation", () => { 'if [ -n "$PROMOTION_STAGING_ROOT" ] && [ -n "$PROMOTION_CLEANUP_TOKEN" ] && [ -n "$PROMOTION_RUNNER_TEMP_DEV" ] && [ -n "$PROMOTION_RUNNER_TEMP_INO" ] && [ -n "$PROMOTION_STAGING_DEV" ] && [ -n "$PROMOTION_STAGING_INO" ]; then', ); const actionUses = [...first.matchAll(/^\s+-?\s*uses: (.+)$/gmu)].map((match) => match[1]); - expect(actionUses).toHaveLength(51); + expect(actionUses).toHaveLength(53); expect(new Set(actionUses)).toEqual( new Set([ "https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5", @@ -1770,9 +1770,10 @@ describe("CI workflow generation", () => { } for (const step of imaged) { expect(step).not.toContain("playwright install"); - const update = step.indexOf("apt-get update"); - expect(update).toBeGreaterThan(0); - expect(step.indexOf(fontsInstall)).toBeGreaterThan(update); + expect(step).not.toContain("apt-get update"); + expect(step).toContain( + `bash scripts/ci/install-visual-test-fonts.sh "$RUNNER_TEMP/visual-test-fonts" ${VISUAL_TEST_FONT_PACKAGES.join(" ")}`, + ); } expect(VISUAL_TEST_FONT_PACKAGES).toEqual([ "fonts-noto-core", @@ -1918,11 +1919,23 @@ describe("CI workflow generation", () => { const steps = workflow.split("\n - "); const saving = steps.filter((step) => step.includes(`uses: ${save}`)); const restoring = steps.filter((step) => step.includes(`uses: ${restore}`)); - expect(saving).toHaveLength(DEPENDENCY_CACHE.jobIds.length); - expect(restoring).toHaveLength(DEPENDENCY_CACHE.jobIds.length); + // 4 dependency caches (merge_* + main_gate) + 1 visual-test fonts cache (merge_browser). + const cachePairs = DEPENDENCY_CACHE.jobIds.length + 1; + expect(saving).toHaveLength(cachePairs); + expect(restoring).toHaveLength(cachePairs); const condition = (step: string) => /\n {8}if: (.+)\n/u.exec(step)?.[1]; - expect(new Set(saving.map(condition))).toEqual(new Set(["${{ gitea.ref == 'refs/heads/main' }}"])); - expect(new Set(restoring.map(condition))).toEqual(new Set(["${{ gitea.ref != 'refs/heads/main' }}"])); + expect(new Set(saving.map(condition))).toEqual( + new Set([ + "${{ gitea.ref == 'refs/heads/main' }}", + "${{ steps.main-push-reuse.outputs.reuse != 'true' && gitea.ref == 'refs/heads/main' }}", + ]), + ); + expect(new Set(restoring.map(condition))).toEqual( + new Set([ + "${{ gitea.ref != 'refs/heads/main' }}", + "${{ steps.main-push-reuse.outputs.reuse != 'true' && gitea.ref != 'refs/heads/main' }}", + ]), + ); // The restore-only action has no post step, so nothing it runs writes the cache. expect(restore).toMatch(/^https:\/\/github\.com\/actions\/cache\/restore@[0-9a-f]{40}$/u); const withBlock = (step: string) => step.slice(step.indexOf(" with:\n")); @@ -1946,7 +1959,9 @@ describe("CI workflow generation", () => { expect(job, jobId).not.toContain("actions/cache"); expect(job, jobId).not.toMatch(/PNPM_CONFIG_|COREPACK_HOME|fe-dependency-cache/u); } - expect(workflow.match(/uses: https:\/\/github\.com\/actions\/cache/gu)).toHaveLength(2 * DEPENDENCY_CACHE.jobIds.length); + expect(workflow.match(/uses: https:\/\/github\.com\/actions\/cache/gu)).toHaveLength( + 2 * DEPENDENCY_CACHE.jobIds.length + 2, + ); }); it.each([ diff --git a/tests/unit/install-visual-test-fonts.test.ts b/tests/unit/install-visual-test-fonts.test.ts new file mode 100644 index 00000000..96a34132 --- /dev/null +++ b/tests/unit/install-visual-test-fonts.test.ts @@ -0,0 +1,142 @@ +import { spawnSync } from "node:child_process"; +import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { + VISUAL_TEST_FONT_CACHE, + VISUAL_TEST_FONT_PACKAGES, + visualTestFontCacheKey, +} from "../../scripts/lib/visual-test-fonts.ts"; +import { childProcessTimeout } from "../helpers/child-process-timeout.ts"; + +/** Measured max runtime of one bash invocation of install-visual-test-fonts.sh on desktop. */ +const INSTALL_SCRIPT_MS = 60; + +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function createStubBin(options: Readonly<{ failOnApt?: boolean; aptWritesDebs?: boolean; installed?: boolean }> = {}) { + const root = await mkdtemp(path.join(tmpdir(), "visual-test-fonts-")); + roots.push(root); + const bin = path.join(root, "bin"); + const cacheDir = path.join(root, "cache dir"); + const logFile = path.join(root, "calls.log"); + await mkdir(bin, { recursive: true }); + await mkdir(cacheDir, { recursive: true }); + + const writeStub = async (name: string, body: string) => { + const file = path.join(bin, name); + await writeFile(file, `#!/usr/bin/env bash\nset -euo pipefail\n${body}\n`, "utf8"); + await chmod(file, 0o755); + }; + + // Fake sudo simply logs and executes the command directly so the test runs + // identically on hosts with or without system sudo. + await writeStub("sudo", 'exec "$@"'); + + await writeStub( + "apt-get", + options.failOnApt + ? 'echo "unexpected apt-get call: $*" >&2; exit 99' + : [ + `echo "apt-get $*" >> ${JSON.stringify(logFile)}`, + ...(options.aptWritesDebs + ? [ + 'if [[ "$1" == "install" ]]; then', + ' dir=""', + ' for arg in "$@"; do', + ' case "$arg" in Dir::Cache::archives=*) dir="${arg#Dir::Cache::archives=}" ;; esac', + " done", + ' touch "$dir/fonts-noto-core_1.deb" "$dir/fonts-noto-cjk_1.deb" "$dir/lock"', + "fi", + ] + : []), + ].join("\n"), + ); + + await writeStub("dpkg", `echo "dpkg $*" >> ${JSON.stringify(logFile)}`); + await writeStub( + "dpkg-query", + options.installed ? 'echo "install ok installed"' : 'echo "deinstall ok config-files"', + ); + + const run = (...args: string[]) => + spawnSync("bash", [VISUAL_TEST_FONT_CACHE.installScript, ...args], { + encoding: "utf8", + env: { + PATH: `${bin}:${process.env.PATH ?? ""}`, + }, + }); + + const readLog = async () => { + try { + return (await readFile(logFile, "utf8")).trim().split("\n").filter(Boolean); + } catch { + return []; + } + }; + + return { root, cacheDir, run, readLog }; +} + +describe("visualTestFontCacheKey", () => { + const digest = "baed2032d533817f3dbe6425de795788430ba345e819a1201337009ba17c9d07"; + const image = `mcr.microsoft.com/playwright:v1.62.0-noble@sha256:${digest}`; + + it("keys on the pinned image digest and package list, changing when either changes", () => { + const key = visualTestFontCacheKey(image); + expect(key).toMatch(/^fe-visual-fonts-baed2032d533-[0-9a-f]{12}$/u); + expect(visualTestFontCacheKey(image, VISUAL_TEST_FONT_PACKAGES.slice(0, -1))).not.toBe(key); + expect(visualTestFontCacheKey(`mcr.microsoft.com/playwright:v1.63.0-noble@sha256:${"f".repeat(64)}`)).not.toBe(key); + }); + + it("refuses an unpinned image without a sha256 digest", () => { + expect(() => visualTestFontCacheKey("mcr.microsoft.com/playwright:v1.62.0-noble")).toThrow(/sha256 digest/u); + }); +}); + +describe("scripts/ci/install-visual-test-fonts.sh", { timeout: childProcessTimeout(INSTALL_SCRIPT_MS) }, () => { + it("installs cached .deb files via dpkg without invoking apt-get on a cache hit", async () => { + const { cacheDir, run, readLog } = await createStubBin({ failOnApt: true }); + await writeFile(path.join(cacheDir, "fonts-noto-core_1.deb"), "deb"); + await writeFile(path.join(cacheDir, "fonts-noto-cjk_1.deb"), "deb"); + + const result = run(cacheDir, ...VISUAL_TEST_FONT_PACKAGES); + expect(result.status, result.stderr).toBe(0); + const calls = await readLog(); + expect(calls).toHaveLength(1); + expect(calls[0]).toContain("dpkg -i "); + expect(calls[0]).toContain("fonts-noto-core_1.deb"); + expect(calls[0]).toContain("fonts-noto-cjk_1.deb"); + }); + + it("downloads .deb archives, strips partial/lock metadata, and runs dpkg -i on a cache miss", async () => { + const { cacheDir, run, readLog } = await createStubBin({ aptWritesDebs: true }); + + const result = run(cacheDir, ...VISUAL_TEST_FONT_PACKAGES); + expect(result.status, result.stderr).toBe(0); + const calls = await readLog(); + expect(calls).toHaveLength(3); + expect(calls[0]).toBe("apt-get update"); + expect(calls[1]).toBe( + `apt-get install -y --download-only -o Dir::Cache::archives=${cacheDir} ${VISUAL_TEST_FONT_PACKAGES.join(" ")}`, + ); + expect(calls[2]).toContain("dpkg -i "); + await expect(stat(path.join(cacheDir, "partial"))).rejects.toThrow(); + await expect(stat(path.join(cacheDir, "lock"))).rejects.toThrow(); + }); + + it("fails closed when no package names are given or no .deb is downloaded for an uninstalled package", async () => { + const { cacheDir, run } = await createStubBin({ aptWritesDebs: false, installed: false }); + expect(run(cacheDir).status).toBe(2); + const missing = run(cacheDir, ...VISUAL_TEST_FONT_PACKAGES); + expect(missing.status).toBe(1); + expect(missing.stderr).toContain("no .deb archive downloaded"); + }); +});