Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

feat(docs): publish the docs pages for site search to a branch (#2832)

jerryqu-coco0a7d91c369c7
diff --git a/.github/workflows/_docs_release.yml b/.github/workflows/_docs_release.yml
index 40897632..c323fcfa 100644
--- a/.github/workflows/_docs_release.yml
+++ b/.github/workflows/_docs_release.yml
@@ -71,3 +71,13 @@ jobs:
fi
git commit -m "deploy docs from ${GITHUB_SHA::7}"
git push origin gh-pages
+ # The same pages as Markdown, for site search. This runs after the
+ # deploy, so a failure here shows in the run and leaves the site deployed.
+ - name: Publish the search content to cocoindex-io/docs search-content
+ env:
+ GIT_AUTHOR_NAME: ${{ vars.COCOINDEX_DOCS_DEPLOY_USER_NAME }}
+ GIT_AUTHOR_EMAIL: ${{ vars.COCOINDEX_DOCS_DEPLOY_USER_EMAIL }}
+ GIT_COMMITTER_NAME: ${{ vars.COCOINDEX_DOCS_DEPLOY_USER_NAME }}
+ GIT_COMMITTER_EMAIL: ${{ vars.COCOINDEX_DOCS_DEPLOY_USER_EMAIL }}
+ TARGET_REPO: [email protected]:cocoindex-io/docs.git
+ run: node docs/scripts/publish-search-content.mjs docs/dist "$TARGET_REPO" "docs pages from ${GITHUB_SHA::7}"
diff --git a/.github/workflows/docs_test.yml b/.github/workflows/docs_test.yml
index 85ae06e9..4863fe64 100644
--- a/.github/workflows/docs_test.yml
+++ b/.github/workflows/docs_test.yml
@@ -50,8 +50,14 @@ jobs:
cache-dependency-path: docs/package-lock.json
- name: Install dependencies
run: npm --prefix docs ci
+ - name: Test the search content scripts
+ run: node --test docs/scripts/export-search-content.test.mjs docs/scripts/publish-search-content.test.mjs
- name: Build docs site
run: npm --prefix docs run build
+ # A change that breaks one of the export's rules (a new kind of .md file,
+ # a different banner) fails here, in its own pull request.
+ - name: Export the search content from the build
+ run: node docs/scripts/export-search-content.mjs docs/dist "$RUNNER_TEMP/search-content"
- name: Verify docs build output exists
run: |
if [ ! -d "docs/dist" ]; then
diff --git a/docs/scripts/export-search-content.mjs b/docs/scripts/export-search-content.mjs
new file mode 100644
index 00000000..1d5de3c6
--- /dev/null
+++ b/docs/scripts/export-search-content.mjs
@@ -0,0 +1,132 @@
+// Exports the docs pages that site search indexes: the Markdown twin of every
+// page in the published page lists (llms.txt and rust/llms.txt), with the
+// banner for coding agents removed. The same banner on every page would match
+// a query equally on all of them.
+//
+// node scripts/export-search-content.mjs <build-dir> <out-dir>
+//
+// <build-dir> is a docs build (docs/dist, or a checkout of the deployed site).
+// <out-dir> receives three folders, and nothing else in it is touched:
+//
+// python/<route>.md the Python page /docs/<route>/
+// rust/<route>.md the Rust page /docs/rust/<route>/
+// examples/<slug>.md an example page /docs/examples/<slug>/
+//
+// The three folders are replaced as a whole, so a page that left the page
+// lists also leaves the export. Every .md file in the build must be either a
+// listed page's twin or one of the files for coding agents (SKIPPED). Any
+// other .md file fails the export with its name: a new kind of file gets a
+// decision, not a silent default. A failed export changes nothing in <out-dir>.
+// The docs test workflow runs the export on every build, so a change that
+// breaks one of these rules fails its own pull request.
+import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const BASE = '/docs/';
+const PAGE_LISTS = ['llms.txt', 'rust/llms.txt'];
+const TREES = ['python', 'rust', 'examples'];
+// The .md files the build writes for coding agents. They are not pages.
+const SKIPPED = [/^skill\.md$/, /^references\/[^/]+\.md$/];
+// A Markdown link to a page: the URL ends with a slash.
+const PAGE_LINK = /\]\((https?:\/\/[^)\s]+\/)\)/g;
+// The banner is the blockquote right under the title. It always carries a
+// `Source:` line, which tells it apart from a quote the page itself opens with.
+const BANNER = /^(# [^\n]*\n)\n((?:>[^\n]*\n)+)\n?/;
+
+const walkMarkdown = (root, dir = root) =>
+ readdirSync(dir).flatMap((name) => {
+ if (name.startsWith('.')) return [];
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) return walkMarkdown(root, path);
+ return name.endsWith('.md') ? [relative(root, path).split(sep).join('/')] : [];
+ });
+
+// Where a listed page's twin is in the build, and where it goes in the export.
+function twinOf(url) {
+ const { pathname } = new URL(url);
+ if (!pathname.startsWith(BASE)) return undefined;
+ const route = pathname.slice(BASE.length).replace(/\/$/, '');
+ if (!route) return undefined;
+ const source = `${route}.md`;
+ const [tree] = route.split('/');
+ return { source, target: tree === 'rust' || tree === 'examples' ? source : `python/${source}` };
+}
+
+const inside = (parent, child) => {
+ const rel = relative(parent, child);
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
+};
+
+export function exportSearchContent(buildDir, outDir) {
+ const build = resolve(buildDir);
+ const out = resolve(outDir);
+ if (inside(build, out) || inside(out, build))
+ throw new Error(`the output folder and the build folder must not contain each other: ${out}, ${build}`);
+
+ const problems = [];
+ const twins = new Map(); // source path in the build β†’ path in the export
+ for (const list of PAGE_LISTS) {
+ const path = join(build, list);
+ if (!existsSync(path)) {
+ problems.push(`missing page list ${list}`);
+ continue;
+ }
+ for (const [, url] of readFileSync(path, 'utf8').matchAll(PAGE_LINK)) {
+ // A link that leaves the docs is not a page, so it has no twin.
+ const twin = twinOf(url);
+ if (twin) twins.set(twin.source, twin.target);
+ }
+ }
+
+ const files = new Map(); // path in the export β†’ content
+ for (const [source, target] of twins) {
+ const path = join(build, source);
+ if (!existsSync(path)) {
+ problems.push(`a listed page has no .md twin: ${source}`);
+ continue;
+ }
+ const text = readFileSync(path, 'utf8').replace(/\r\n/g, '\n');
+ const banner = BANNER.exec(text);
+ if (!banner || !/^> Source: /m.test(banner[2])) {
+ problems.push(`no banner under the title of ${source}`);
+ continue;
+ }
+ files.set(target, `${banner[1]}\n${text.slice(banner[0].length)}`);
+ }
+
+ for (const file of walkMarkdown(build)) {
+ if (!twins.has(file) && !SKIPPED.some((skip) => skip.test(file)))
+ problems.push(`no rule covers ${file}: list its page, or add it to SKIPPED`);
+ }
+
+ if (problems.length)
+ throw new Error(`${problems.length} problem(s)\n${problems.map((p) => ` - ${p}`).join('\n')}`);
+
+ for (const tree of TREES) rmSync(join(out, tree), { recursive: true, force: true });
+ for (const [target, text] of files) {
+ const path = join(out, target);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, text);
+ }
+ return Object.fromEntries(
+ TREES.map((tree) => [tree, [...files.keys()].filter((f) => f.startsWith(`${tree}/`)).length]),
+ );
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ const [buildDir, outDir] = process.argv.slice(2);
+ if (!buildDir || !outDir) {
+ console.error('usage: node scripts/export-search-content.mjs <build-dir> <out-dir>');
+ process.exit(2);
+ }
+ try {
+ const count = exportSearchContent(buildDir, outDir);
+ const total = Object.values(count).reduce((a, b) => a + b, 0);
+ const parts = Object.entries(count).map(([tree, n]) => `${tree} ${n}`).join(', ');
+ console.log(`export-search-content: ${total} files (${parts}) β†’ ${outDir}`);
+ } catch (error) {
+ console.error(`export-search-content: ${error.message}`);
+ process.exit(1);
+ }
+}
diff --git a/docs/scripts/export-search-content.test.mjs b/docs/scripts/export-search-content.test.mjs
new file mode 100644
index 00000000..513af7da
--- /dev/null
+++ b/docs/scripts/export-search-content.test.mjs
@@ -0,0 +1,151 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, relative } from 'node:path';
+import { test } from 'node:test';
+import { fileURLToPath } from 'node:url';
+import { exportSearchContent } from './export-search-content.mjs';
+
+const SCRIPT = fileURLToPath(new URL('./export-search-content.mjs', import.meta.url));
+const SITE = 'https://example.com/docs';
+const BANNER =
+ '> **A notice for coding agents.** It opens every page.\n' +
+ '>\n' +
+ `> Source: ${SITE}/page/ Β· Docs index: ${SITE}/llms.txt\n` +
+ '>\n' +
+ '> A map from the old names to the new ones.\n';
+const twin = (title, body) => `# ${title}\n\n${BANNER}\n${body}\n`;
+
+const write = (root, files) => {
+ for (const [path, text] of Object.entries(files)) {
+ mkdirSync(dirname(join(root, path)), { recursive: true });
+ writeFileSync(join(root, path), text);
+ }
+};
+const tree = (root, dir = root) =>
+ readdirSync(dir)
+ .flatMap((name) => {
+ const path = join(dir, name);
+ return statSync(path).isDirectory() ? tree(root, path) : [relative(root, path)];
+ })
+ .sort();
+const snapshot = (root) => Object.fromEntries(tree(root).map((f) => [f, readFileSync(join(root, f), 'utf8')]));
+
+// A build with pages in all three trees, and the files for coding agents.
+const build = (extra = {}) => {
+ const dir = mkdtempSync(join(tmpdir(), 'search-content-build-'));
+ write(dir, {
+ 'llms.txt':
+ `# Docs\n\n> Full text: ${SITE}/llms-full.txt.\n\n` +
+ '[The project](https://project.example.org/source/)\n\n## Guide\n' +
+ `- [Guide](${SITE}/guide/): The section overview.\n` +
+ `- [App](${SITE}/guide/app/): The App page.\n` +
+ `## Examples\n- [Sample](${SITE}/examples/sample/): An example.\n`,
+ 'rust/llms.txt': `# Rust docs\n\n- [App](${SITE}/rust/guide/app/): The App page.\n`,
+ 'guide.md': twin('Guide', 'The overview.'),
+ 'guide/app.md': twin('The App', 'An **App** is the runnable unit.\n\n> A quote of the page.'),
+ 'rust/guide/app.md': twin('The App', 'The Rust page.'),
+ 'examples/sample.md': twin('Sample', 'The walkthrough.'),
+ 'skill.md': '# Skill\n',
+ 'references/notes.md': '# Notes\n',
+ 'guide/app/index.html': '<html></html>',
+ ...extra,
+ });
+ return dir;
+};
+const outDir = () => mkdtempSync(join(tmpdir(), 'search-content-out-'));
+
+test('each listed page lands in its tree, and the agent files are not copied', () => {
+ const out = outDir();
+ assert.deepEqual(exportSearchContent(build(), out), { python: 2, rust: 1, examples: 1 });
+ assert.deepEqual(tree(out), [
+ 'examples/sample.md',
+ 'python/guide.md',
+ 'python/guide/app.md',
+ 'rust/guide/app.md',
+ ]);
+});
+
+test('the banner is removed, and the title and the text of the page stay', () => {
+ const out = outDir();
+ exportSearchContent(build(), out);
+ assert.equal(
+ readFileSync(join(out, 'python/guide/app.md'), 'utf8'),
+ '# The App\n\nAn **App** is the runnable unit.\n\n> A quote of the page.\n',
+ );
+});
+
+test('a .md file that no rule covers fails the export with its name', () => {
+ const out = outDir();
+ assert.throws(
+ () => exportSearchContent(build({ 'notes/draft.md': '# Draft\n' }), out),
+ /no rule covers notes\/draft\.md/,
+ );
+ assert.deepEqual(tree(out), []);
+});
+
+test('a listed page without a twin fails the export with its name', () => {
+ const list = `- [Gone](${SITE}/guide/gone/): A page.\n`;
+ assert.throws(
+ () => exportSearchContent(build({ 'rust/llms.txt': list }), outDir()),
+ /a listed page has no \.md twin: guide\/gone\.md/,
+ );
+});
+
+test('a twin without the banner fails the export, also when it opens with its own quote', () => {
+ for (const text of ['# Plain\n\nNo banner here.\n', '# Quote\n\n> The page opens with a quote.\n\nText.\n']) {
+ assert.throws(
+ () => exportSearchContent(build({ 'guide/app.md': text }), outDir()),
+ /no banner under the title of guide\/app\.md/,
+ );
+ }
+});
+
+test('a missing page list fails the export', () => {
+ const dir = build();
+ rmSync(join(dir, 'rust/llms.txt'));
+ assert.throws(() => exportSearchContent(dir, outDir()), /missing page list rust\/llms\.txt/);
+});
+
+test('only the three folders are replaced: a page that left the lists goes, other folders stay', () => {
+ const out = outDir();
+ write(out, { 'python/old/page.md': 'stale', 'site/blogs/post.md': 'kept', 'README.md': 'kept' });
+ exportSearchContent(build(), out);
+ assert.equal(existsSync(join(out, 'python/old/page.md')), false);
+ assert.equal(readFileSync(join(out, 'site/blogs/post.md'), 'utf8'), 'kept');
+ assert.equal(readFileSync(join(out, 'README.md'), 'utf8'), 'kept');
+});
+
+test('a failed export leaves the output folder as it was', () => {
+ const out = outDir();
+ write(out, { 'python/old/page.md': 'earlier export' });
+ assert.throws(() => exportSearchContent(build({ 'stray.md': '# Stray\n' }), out));
+ assert.deepEqual(snapshot(out), { 'python/old/page.md': 'earlier export' });
+});
+
+test('a second run on the same build writes the same files', () => {
+ const dir = build();
+ const out = outDir();
+ exportSearchContent(dir, out);
+ const first = snapshot(out);
+ exportSearchContent(dir, out);
+ assert.deepEqual(snapshot(out), first);
+});
+
+test('the output folder may not be the build folder or inside it', () => {
+ const dir = build();
+ assert.throws(() => exportSearchContent(dir, dir), /must not contain each other/);
+ assert.throws(() => exportSearchContent(dir, join(dir, 'rust')), /must not contain each other/);
+ assert.equal(existsSync(join(dir, 'rust/guide/app.md')), true);
+});
+
+test('the command prints the counts, and exits 1 naming the file on a failure', () => {
+ const ok = spawnSync('node', [SCRIPT, build(), outDir()], { encoding: 'utf8' });
+ assert.equal(ok.status, 0);
+ assert.match(ok.stdout, /4 files \(python 2, rust 1, examples 1\)/);
+ const bad = spawnSync('node', [SCRIPT, build({ 'stray.md': '# Stray\n' }), outDir()], { encoding: 'utf8' });
+ assert.equal(bad.status, 1);
+ assert.match(bad.stderr, /no rule covers stray\.md/);
+ assert.equal(spawnSync('node', [SCRIPT], { encoding: 'utf8' }).status, 2);
+});
diff --git a/docs/scripts/publish-search-content.mjs b/docs/scripts/publish-search-content.mjs
new file mode 100644
index 00000000..402e27ae
--- /dev/null
+++ b/docs/scripts/publish-search-content.mjs
@@ -0,0 +1,101 @@
+// Publishes the docs pages that site search indexes: runs the export of
+// export-search-content.mjs on a docs build and pushes its three folders
+// (python/, rust/, examples/) to the branch `search-content` of a repository.
+//
+// node scripts/publish-search-content.mjs <build-dir> <repo-url> [<commit-message>]
+//
+// The branch is shared: the website publishes its own pages to another folder
+// of it. So a publish starts from the branch's tip, replaces only the export's
+// three folders, and adds one commit on top. Nothing is ever force-pushed.
+//
+// - A branch that doesn't exist yet is created with the three folders.
+// - An export that changes nothing makes no commit.
+// - When someone else pushed between the fetch and the push, the publish
+// starts again from the new tip. The export replaces its folders as a
+// whole, so it needs no merge.
+// - Any other failure is an error: a failed export pushes nothing, and a push
+// that fails while the branch stands still is not tried again.
+//
+// The commit takes its author from git's own settings (GIT_AUTHOR_NAME and the
+// like, or the git config).
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { exportSearchContent } from './export-search-content.mjs';
+
+const BRANCH = 'search-content';
+const REF = `refs/heads/${BRANCH}`;
+const ATTEMPTS = 5;
+
+const git = (cwd, ...args) =>
+ execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+
+// The commit the branch points at in the repository, or null when it has no such branch.
+const remoteTip = (cwd) => git(cwd, 'ls-remote', 'origin', REF).split(/\s/)[0] || null;
+
+// One try, in a checkout of its own: export onto the branch's tip, commit, push.
+// Returns { moved: true } when the branch moved before the push.
+function attempt(build, repo, message, beforePush) {
+ const work = mkdtempSync(join(tmpdir(), 'search-content-'));
+ try {
+ git(work, 'init', '--quiet', `--initial-branch=${BRANCH}`);
+ git(work, 'remote', 'add', 'origin', repo);
+ let tip = null;
+ if (remoteTip(work)) {
+ git(work, 'fetch', '--quiet', '--depth', '1', 'origin', REF);
+ git(work, 'reset', '--quiet', '--hard', 'FETCH_HEAD');
+ tip = git(work, 'rev-parse', 'HEAD');
+ }
+
+ const count = exportSearchContent(build, work);
+ // The checkout is the branch's tip plus the export, so every change is in
+ // the export's folders.
+ git(work, 'add', '--all');
+ if (!git(work, 'status', '--porcelain')) return { count, commit: null };
+ git(work, 'commit', '--quiet', '-m', message);
+ const commit = git(work, 'rev-parse', 'HEAD');
+
+ beforePush?.();
+ try {
+ git(work, 'push', '--quiet', 'origin', `HEAD:${REF}`);
+ } catch (error) {
+ if (remoteTip(work) === tip) throw error;
+ return { moved: true };
+ }
+ return { count, commit };
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ }
+}
+
+// Returns the export's counts and the pushed commit (null when nothing changed).
+// `beforePush` runs between the commit and the push; the tests use it to push
+// from elsewhere at that moment.
+export function publishSearchContent(buildDir, repo, { message = 'update the docs pages', beforePush } = {}) {
+ const build = resolve(buildDir);
+ for (let n = 1; n <= ATTEMPTS; n++) {
+ const result = attempt(build, repo, message, beforePush);
+ if (!result.moved) return result;
+ }
+ throw new Error(`${BRANCH} moved before each of ${ATTEMPTS} pushes`);
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ const [buildDir, repo, message] = process.argv.slice(2);
+ if (!buildDir || !repo) {
+ console.error('usage: node scripts/publish-search-content.mjs <build-dir> <repo-url> [<commit-message>]');
+ process.exit(2);
+ }
+ try {
+ const { count, commit } = publishSearchContent(buildDir, repo, { message });
+ const total = Object.values(count).reduce((a, b) => a + b, 0);
+ const parts = Object.entries(count).map(([tree, n]) => `${tree} ${n}`).join(', ');
+ const outcome = commit ? `pushed ${commit.slice(0, 7)} to ${BRANCH}` : `${BRANCH} is up to date, nothing pushed`;
+ console.log(`publish-search-content: ${total} files (${parts}); ${outcome}`);
+ } catch (error) {
+ console.error(`publish-search-content: ${error.message}`);
+ process.exit(1);
+ }
+}
diff --git a/docs/scripts/publish-search-content.test.mjs b/docs/scripts/publish-search-content.test.mjs
new file mode 100644
index 00000000..467a5bc4
--- /dev/null
+++ b/docs/scripts/publish-search-content.test.mjs
@@ -0,0 +1,180 @@
+import assert from 'node:assert/strict';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { test } from 'node:test';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { publishSearchContent } from './publish-search-content.mjs';
+
+// Every repository here is a folder in the temp directory. Git reads no
+// settings of the machine, and the commits get a fixed author.
+Object.assign(process.env, {
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Test',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Test',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+});
+
+const SCRIPT = fileURLToPath(new URL('./publish-search-content.mjs', import.meta.url));
+const SITE = 'https://example.com/docs';
+const REF = 'refs/heads/search-content';
+const twin = (title, body) => `# ${title}\n\n> Source: ${SITE}/page/\n\n${body}\n`;
+
+const temp = (name) => mkdtempSync(join(tmpdir(), `publish-search-content-${name}-`));
+const git = (cwd, ...args) => execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
+const write = (root, files) => {
+ for (const [path, text] of Object.entries(files)) {
+ mkdirSync(dirname(join(root, path)), { recursive: true });
+ writeFileSync(join(root, path), text);
+ }
+};
+
+// A build with one page in each tree.
+const build = (extra = {}) => {
+ const dir = temp('build');
+ write(dir, {
+ 'llms.txt': `- [Guide](${SITE}/guide/): A page.\n- [PDF](${SITE}/examples/pdf/): An example.\n`,
+ 'rust/llms.txt': `- [Guide](${SITE}/rust/guide/): A page.\n`,
+ 'guide.md': twin('Guide', 'The Python page.'),
+ 'rust/guide.md': twin('Guide', 'The Rust page.'),
+ 'examples/pdf.md': twin('PDF', 'The walkthrough.'),
+ ...extra,
+ });
+ return dir;
+};
+const EXPORTED = ['examples/pdf.md', 'python/guide.md', 'rust/guide.md'];
+
+// The repository the publish pushes to: its folder, and the URL to reach it.
+const remote = () => {
+ const dir = temp('remote');
+ git(dir, 'init', '--quiet', '--bare', '--initial-branch=main');
+ return { dir, url: pathToFileURL(dir).href };
+};
+// What the website's step does: one commit with `files` on the branch's tip.
+const pushFromElsewhere = ({ url }, files, message) => {
+ const work = temp('elsewhere');
+ git(work, 'init', '--quiet', '--initial-branch=search-content');
+ if (git(work, 'ls-remote', url, REF)) {
+ git(work, 'fetch', '--quiet', url, REF);
+ git(work, 'reset', '--quiet', '--hard', 'FETCH_HEAD');
+ }
+ write(work, files);
+ git(work, 'add', '--all');
+ git(work, 'commit', '--quiet', '-m', message);
+ git(work, 'push', '--quiet', url, `HEAD:${REF}`);
+};
+// The branch's commit, or '' when the repository has no such branch.
+const tip = ({ dir }) => git(dir, 'for-each-ref', '--format=%(objectname)', REF);
+const subjects = ({ dir }) => git(dir, 'log', '--format=%s', REF).split('\n');
+const files = ({ dir }) => git(dir, 'ls-tree', '-r', '--name-only', REF).split('\n').sort();
+const show = ({ dir }, path) => git(dir, 'show', `${REF}:${path}`);
+
+test('a branch that does not exist is created with only the three folders', () => {
+ const repo = remote();
+ const { count, commit } = publishSearchContent(build(), repo.url, { message: 'docs pages from abc1234' });
+ assert.deepEqual(count, { python: 1, rust: 1, examples: 1 });
+ assert.equal(commit, tip(repo));
+ assert.deepEqual(files(repo), EXPORTED);
+ assert.deepEqual(subjects(repo), ['docs pages from abc1234']);
+ assert.equal(show(repo, 'python/guide.md'), '# Guide\n\nThe Python page.');
+ assert.equal(git(repo.dir, 'for-each-ref', '--format=%(refname)'), REF);
+});
+
+test('the folders of the website stay as they are, and a page that left the build goes', () => {
+ const repo = remote();
+ pushFromElsewhere(repo, { 'site/blogs/post.md': 'a post', 'python/old.md': 'stale' }, 'the website');
+ const before = tip(repo);
+ const { commit } = publishSearchContent(build(), repo.url);
+ assert.deepEqual(files(repo), [...EXPORTED, 'site/blogs/post.md']);
+ assert.equal(show(repo, 'site/blogs/post.md'), 'a post');
+ assert.equal(git(repo.dir, 'rev-parse', `${commit}^`), before);
+});
+
+test('when the branch moves between the fetch and the push, the publish starts again from the new tip', () => {
+ const repo = remote();
+ pushFromElsewhere(repo, { 'site/blogs/post.md': 'a post' }, 'the website');
+ let pushes = 0;
+ const beforePush = () => {
+ if (pushes++ === 0) pushFromElsewhere(repo, { 'site/answers/a.md': 'an answer' }, 'the website again');
+ };
+ const { commit } = publishSearchContent(build(), repo.url, { message: 'the docs', beforePush });
+ assert.equal(pushes, 2);
+ assert.equal(commit, tip(repo));
+ assert.deepEqual(files(repo), [...EXPORTED, 'site/answers/a.md', 'site/blogs/post.md']);
+ assert.deepEqual(subjects(repo), ['the docs', 'the website again', 'the website']);
+});
+
+test('when someone else creates the branch before the first push, the publish starts again on it', () => {
+ const repo = remote();
+ let pushes = 0;
+ const beforePush = () => {
+ if (pushes++ === 0) pushFromElsewhere(repo, { 'site/blogs/post.md': 'a post' }, 'the website');
+ };
+ publishSearchContent(build(), repo.url, { message: 'the docs', beforePush });
+ assert.deepEqual(files(repo), [...EXPORTED, 'site/blogs/post.md']);
+ assert.deepEqual(subjects(repo), ['the docs', 'the website']);
+});
+
+test('a second publish of the same build makes no commit', () => {
+ const repo = remote();
+ const dir = build();
+ const first = publishSearchContent(dir, repo.url);
+ const second = publishSearchContent(dir, repo.url);
+ assert.equal(second.commit, null);
+ assert.deepEqual(second.count, first.count);
+ assert.equal(tip(repo), first.commit);
+});
+
+test('a failed export pushes nothing', () => {
+ const repo = remote();
+ pushFromElsewhere(repo, { 'python/old.md': 'earlier export' }, 'earlier');
+ const before = tip(repo);
+ assert.throws(() => publishSearchContent(build({ 'stray.md': '# Stray\n' }), repo.url), /no rule covers stray\.md/);
+ assert.equal(tip(repo), before);
+});
+
+test('a push that fails while the branch stands still is an error, and is not tried again', () => {
+ const repo = remote();
+ writeFileSync(join(repo.dir, 'hooks/pre-receive'), '#!/bin/sh\necho "pushes are closed" >&2\nexit 1\n', {
+ mode: 0o755,
+ });
+ let pushes = 0;
+ assert.throws(
+ () => publishSearchContent(build(), repo.url, { beforePush: () => pushes++ }),
+ /pushes are closed/,
+ );
+ assert.equal(pushes, 1);
+ assert.equal(tip(repo), '');
+});
+
+test('a branch that moves before every push ends the publish with an error', () => {
+ const repo = remote();
+ let pushes = 0;
+ const beforePush = () => pushFromElsewhere(repo, { [`site/${pushes++}.md`]: 'a page' }, 'the website');
+ assert.throws(() => publishSearchContent(build(), repo.url, { beforePush }), /search-content moved before each of 5 pushes/);
+ assert.equal(pushes, 5);
+ assert.deepEqual(files(repo), ['site/0.md', 'site/1.md', 'site/2.md', 'site/3.md', 'site/4.md']);
+});
+
+test('the command prints the counts and the commit, and exits 1 on a failure', () => {
+ const repo = remote();
+ const dir = build();
+ const run = (...args) => spawnSync('node', [SCRIPT, ...args], { encoding: 'utf8' });
+
+ const first = run(dir, repo.url, 'docs pages from abc1234');
+ assert.equal(first.status, 0, first.stderr);
+ assert.match(first.stdout, new RegExp(`3 files \\(python 1, rust 1, examples 1\\); pushed ${tip(repo).slice(0, 7)} to search-content`));
+ assert.deepEqual(subjects(repo), ['docs pages from abc1234']);
+
+ const again = run(dir, repo.url);
+ assert.equal(again.status, 0, again.stderr);
+ assert.match(again.stdout, /search-content is up to date, nothing pushed/);
+
+ const bad = run(build({ 'stray.md': '# Stray\n' }), repo.url);
+ assert.equal(bad.status, 1);
+ assert.match(bad.stderr, /no rule covers stray\.md/);
+ assert.equal(run(dir).status, 2);
+});