Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions e2e/linkRewrite.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Comment on lines +10 to +15

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low: in a detached-HEAD checkout (the default for most CI checkouts), git branch --show-current prints an empty string, so expectedBranch becomes '' and the assertion expects .../blob//analyses/.... The production path instead falls back to 'main' (lib/getBuildContext.ts:17: getCurrentBranch() || 'main'), so the build emits /blob/main/ and this test fails rather than skips. CI does not run the test suites today, so this only bites someone running npm run test:e2e from a detached HEAD locally - but since the PR body cites fork/CI portability as a goal, consider mirroring the production fallback (currentGitBranch(repoRoot) || 'main') or skipping the suite when the branch is empty.


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 (`&amp;`).
// 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 &amp; last: decoding it first would turn a literal "&lt;" (encoded
// as "&amp;lt;") into "&lt;", which the &lt; replacement below would then
// incorrectly decode a second time into "<".
return value
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&#x27;/gi, "'")
.replace(/&amp;/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 &amp; last so a literal "&lt;" sequence is not double-decoded', () => {
// A branch literally named "&lt;foo" is serialized by HTML attribute
// encoding as "&amp;lt;foo". Decoding &amp; before &lt; would turn that
// into "&lt;foo" and then incorrectly decode it again into "<foo".
assert.equal(decodeHtmlEntities('&amp;lt;foo'), '&lt;foo');
});

it('still decodes a genuine &amp; to a literal ampersand', () => {
assert.equal(decodeHtmlEntities('foo &amp; bar'), 'foo & bar');
});

it('decodes both the decimal and hexadecimal apostrophe entities', () => {
// React's server renderer uses the hexadecimal form (&#x27;); some other
// encoders use the decimal form (&#39;). A branch like "feature/o'brien"
// must round-trip through either.
assert.equal(decodeHtmlEntities('feature/o&#39;brien'), "feature/o'brien");
assert.equal(decodeHtmlEntities('feature/o&#x27;brien'), "feature/o'brien");
assert.equal(decodeHtmlEntities('feature/o&#X27;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<b'), 'feature/a%3Cb');
});

it('leaves path separators and already-safe characters untouched', () => {
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
Expand Down Expand Up @@ -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`,
),
);
Comment thread
Copilot marked this conversation as resolved.
Resolved
});
});

// `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"),
Expand Down