diff --git a/e2e/linkRewrite.test.mjs b/e2e/linkRewrite.test.mjs index 69c52a9c..262f3f3f 100644 --- a/e2e/linkRewrite.test.mjs +++ b/e2e/linkRewrite.test.mjs @@ -7,9 +7,104 @@ import { tmpdir } from 'node:os'; import path from 'node:path'; import url from 'node:url'; +function currentGitBranch(cwd) { + return execFileSync('git', ['branch', '--show-current'], { + cwd, + encoding: 'utf8', + }).trim(); +} + +function escapeRegExp(value) { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +// The Markdown-to-HTML pipeline percent-encodes characters that are unsafe +// in a URI (e.g. `<` becomes `%3C`), the same normalization `encodeURI` +// applies, while leaving `/` and already-escaped `%XX` sequences alone. A +// branch name containing such a character would otherwise produce an +// expected regex that never matches the real rendered href. +function encodeHrefSegment(value) { + return encodeURI(value); +} + +// Docusaurus serializes href attributes as HTML, so characters valid in a +// branch name (e.g. `&`) are entity-encoded in the rendered output (`&`). +// Decode the handful of entities HTML attribute serialization can produce +// before comparing against the raw branch name, otherwise a correct build +// fails the assertion for any branch containing one of these characters. +function decodeHtmlEntities(value) { + // Decode & last: decoding it first would turn a literal "<" (encoded + // as "&lt;") into "<", which the < replacement below would then + // incorrectly decode a second time into "<". + return value + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/'/gi, "'") + .replace(/&/g, '&'); +} + +function currentGitHubRemote(cwd) { + let remoteUrl; + try { + remoteUrl = execFileSync('git', ['remote', 'get-url', 'origin'], { + cwd, + encoding: 'utf8', + }).trim(); + } catch { + // No `origin` remote (e.g. a shallow clone without one configured): + // mirror getBuildContext.ts's `getGitHubRepoUrl() || repo` fallback + // instead of failing the suite outright. + return null; + } + const ssh = remoteUrl.match(/^git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/); + if (ssh) return `https://github.com/${ssh[1]}`; + const https = remoteUrl.match( + /^https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/, + ); + if (https) return `https://github.com/${https[1]}`; + // Origin exists but isn't a recognized github.com URL: same fallback. + return null; +} + const __dirname = path.dirname(url.fileURLToPath(import.meta.url)); const repoRoot = path.join(__dirname, '..'); +describe('decodeHtmlEntities', () => { + it('decodes & last so a literal "<" sequence is not double-decoded', () => { + // A branch literally named "<foo" is serialized by HTML attribute + // encoding as "&lt;foo". Decoding & before < would turn that + // into "<foo" and then incorrectly decode it again into " { + assert.equal(decodeHtmlEntities('foo & bar'), 'foo & bar'); + }); + + it('decodes both the decimal and hexadecimal apostrophe entities', () => { + // React's server renderer uses the hexadecimal form ('); some other + // encoders use the decimal form ('). A branch like "feature/o'brien" + // must round-trip through either. + assert.equal(decodeHtmlEntities('feature/o'brien'), "feature/o'brien"); + assert.equal(decodeHtmlEntities('feature/o'brien'), "feature/o'brien"); + assert.equal(decodeHtmlEntities('feature/o'brien'), "feature/o'brien"); + }); +}); + +describe('encodeHrefSegment', () => { + it('percent-encodes characters the Markdown-to-HTML pipeline treats as unsafe in a URI', () => { + // `<` is not in encodeURI's unescaped set, matching the percent-encoding + // micromark's URI normalization applies to link destinations. + assert.equal(encodeHrefSegment('feature/a { + assert.equal(encodeHrefSegment('feature/foo-bar_1'), 'feature/foo-bar_1'); + }); +}); + // Unit tests (lib/docusaurusConfigPreprocessor.test.mts, // lib/remarkRewriteLinks/index.test.mts) cover the pure rewrite functions in // isolation. Neither one proves the rewrites actually survive being wired @@ -312,6 +407,76 @@ describe('deploy-preview build falls back to repo/main when branch and remote de }); }); +// The suite above forces both getCurrentBranch() and getGitHubRepoUrl() to +// fail (via a broken GIT_DIR/GIT_WORK_TREE), so it only exercises +// getBuildContext.ts's hard-coded `repo`/`main` fallback branch. Neither that +// suite nor the deploy-preview suite further up (which always pins +// GITHUB_REF_NAME/REPOSITORY_URL) ever lets the two helpers' own +// `execSync('git ...')` fallbacks succeed and get wired into a rendered page: +// that success path is 100% unit-covered in isolation +// (lib/getCurrentBranch.test.mts, lib/getGitHubRepoUrl.test.mts) but +// untouched by any build here. This suite clears every env var the two +// helpers check while leaving this checkout's real `.git` working, so +// `execSync('git ...')` succeeds and the rewritten .csv link must reflect +// this checkout's actual branch and remote - a regression confined to the +// git-fallback *success* path fails here even when the env-var unit tests +// still pass in isolation. +describe('deploy-preview build falls back to real git branch/remote detection when no env vars are set', () => { + let outDir; + let expectedBranch; + let expectedRepo; + + before(async () => { + // getBuildContext.ts falls back to 'main' when getCurrentBranch() + // returns undefined, which is what happens on a detached-HEAD checkout + // (git branch --show-current prints ''). Mirror that fallback here so + // this test also passes on detached-HEAD CI checkouts. + expectedBranch = currentGitBranch(repoRoot) || 'main'; + // getBuildContext.ts falls back to the `repo` constant when + // getGitHubRepoUrl() returns undefined (no origin, or origin isn't a + // github.com URL). Mirror that fallback here too. + expectedRepo = + currentGitHubRemote(repoRoot) || 'https://github.com/cncf/techdocs'; + outDir = await mkdtemp(path.join(tmpdir(), 'techdocs-e2e-git-fallback-')); + execFileSync('npx', ['docusaurus', 'build', '--out-dir', outDir], { + cwd: repoRoot, + env: { + ...process.env, + BUILD_ENV: 'deploy-preview', + DEPLOY_PRIME_URL: 'https://deploy-preview-1--cncf-techdocs.netlify.app', + // Clear every env var getCurrentBranch()/getGitHubRepoUrl() check so + // both fall through to their `execSync('git ...')` branches instead + // of an env-provided value. + HEAD: '', + BRANCH: '', + GITHUB_HEAD_REF: '', + GITHUB_REF_NAME: '', + REPOSITORY_URL: '', + }, + stdio: 'inherit', + }); + }); + + after(async () => { + if (outDir) await rm(outDir, { recursive: true, force: true }); + }); + + it("rewrites the .csv asset link to this checkout's real git branch and remote", async () => { + const html = decodeHtmlEntities( + await readFile( + path.join(outDir, 'analyses/2023/backstage/index.html'), + 'utf-8', + ), + ); + assert.match( + html, + new RegExp( + `${escapeRegExp(expectedRepo)}/blob/${escapeRegExp(encodeHrefSegment(expectedBranch))}/analyses/2023/backstage/backstage-doc-survey\\.csv`, + ), + ); + }); +}); + // `lib/remarkRewriteLinks/index.test.mts` unit-tests the `.mdx`-specific // stripping branches in isolation ("maps (../)+docs/.../foo.mdx to // /docs/.../foo/" and "strips .mdx from site-absolute /docs/.../foo.mdx"),