Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

test(scripts): a fixture repository costs two git launches, not one per step (#9881)

Christopher Chedeau89824ae1ac28
diff --git a/scripts/check-knowledge.test.mjs b/scripts/check-knowledge.test.mjs
index f513122ee5..ba88ec91cd 100644
--- a/scripts/check-knowledge.test.mjs
+++ b/scripts/check-knowledge.test.mjs
@@ -6,6 +6,11 @@ import path from 'node:path';
import {execFileSync} from 'node:child_process';
import {createRequire} from 'node:module';
import {afterEach, describe, expect, it} from 'vitest';
+import {
+ createRepository,
+ importCommits,
+ workingTreeFiles,
+} from './lib/git-fixture.mjs';
import {
composeKnowledgeSchemas,
collectConcernMatches,
@@ -371,18 +376,21 @@ function withSystemClaims(record) {
);
}
-function commitFixture(root, message) {
- execFileSync('git', ['init', '-q'], {cwd: root});
- execFileSync('git', ['config', 'user.name', 'Fixture'], {cwd: root});
- execFileSync('git', ['config', 'user.email', '[email protected]'], {
- cwd: root,
- });
- execFileSync('git', ['add', '.'], {cwd: root});
- execFileSync('git', ['commit', '-q', '-m', message], {cwd: root});
- return execFileSync('git', ['rev-parse', 'HEAD'], {
- cwd: root,
- encoding: 'utf8',
- }).trim();
+/**
+ * Commits the fixture's working tree as it stands on `main`, after the
+ * commit there, or as the first commit of a new repository.
+ */
+function commitFixture(root, message, {create = false} = {}) {
+ const commit = {
+ ref: 'refs/heads/main',
+ name: 'commit',
+ message,
+ snapshot: true,
+ files: workingTreeFiles(root),
+ };
+ return create
+ ? createRepository(root, [commit]).commit
+ : importCommits(root, [{...commit, parent: 'refs/heads/main'}]).commit;
}
afterEach(() => {
@@ -692,6 +700,7 @@ describe('global review applicability', () => {
const baseWithoutRouting = commitFixture(
root,
'base without global routing',
+ {create: true},
);
execFileSync(
'git',
@@ -703,14 +712,7 @@ describe('global review applicability', () => {
path.join(root, 'docs/specs/AST-900/spec.md'),
withReviewApplicability(currentRecord, {'public-api': ['FR1']}),
);
- execFileSync('git', ['add', '.'], {cwd: root});
- execFileSync('git', ['commit', '-q', '-m', 'head adds global routing'], {
- cwd: root,
- });
- const proposedHead = execFileSync('git', ['rev-parse', 'HEAD'], {
- cwd: root,
- encoding: 'utf8',
- }).trim();
+ const proposedHead = commitFixture(root, 'head adds global routing');
expect(
routeGlobalReviewBaselinesAtRevision(
@@ -740,14 +742,7 @@ describe('global review applicability', () => {
).toThrow(/review head must differ/);
fs.writeFileSync(path.join(root, 'README.md'), '# Reviewed change\n');
- execFileSync('git', ['add', '.'], {cwd: root});
- execFileSync('git', ['commit', '-q', '-m', 'later review head'], {
- cwd: root,
- });
- const laterHead = execFileSync('git', ['rev-parse', 'HEAD'], {
- cwd: root,
- encoding: 'utf8',
- }).trim();
+ const laterHead = commitFixture(root, 'later review head');
expect(
routeGlobalReviewBaselinesAtRevision(root, proposedHead, laterHead, [
'public-api',
diff --git a/scripts/lib/git-fixture.mjs b/scripts/lib/git-fixture.mjs
new file mode 100644
index 0000000000..279cbb9a5e
--- /dev/null
+++ b/scripts/lib/git-fixture.mjs
@@ -0,0 +1,157 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Fixture git repositories for the scripts' tests, written by one
+ * `git fast-import` however many commits, branches and refs they hold.
+ * @input A repository path, the commits (ref, parent, message, files) and
+ * more refs to point at them.
+ * @output Each named commit's hash.
+ * @position Test support. Each git command is a process launch, and a loaded
+ * box makes every launch slow. So a fixture costs two launches: `git init`
+ * and the import.
+ */
+import {execFileSync} from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+
+const SIGNATURE = 'Fixture <[email protected]>';
+
+/**
+ * @typedef {object} FixtureCommit
+ * @property {string} ref The ref the commit moves, such as `refs/heads/main`.
+ * @property {string} [name] A name for a later commit's `parent` and for the
+ * returned hashes.
+ * @property {string} [parent] A named commit of this fixture, or any
+ * commit-ish the repository held before this import. Without it, the commit
+ * follows the last one on its ref in this import, or starts a new history.
+ * @property {string} [message]
+ * @property {Record<string, string | null>} [files] Content by path; `null`
+ * deletes the path.
+ * @property {boolean} [snapshot] The tree holds exactly `files`, with nothing
+ * kept from the parent.
+ */
+
+/**
+ * Writes `commits` into the repository at `root` with one `git fast-import`.
+ * It leaves the index and the working tree as they are.
+ * @param {string} root
+ * @param {FixtureCommit[]} commits
+ * @param {Record<string, string>} [refs] More refs, each set to a named commit.
+ * @returns {Record<string, string>} Each named commit's hash.
+ */
+export function importCommits(root, commits, refs = {}) {
+ const time = `${Math.floor(Date.now() / 1000)} +0000`;
+ /** @type {Map<string, number>} */
+ const marks = new Map();
+ /** @type {string[]} */
+ const stream = [];
+ commits.forEach((commit, index) => {
+ const mark = index + 1;
+ stream.push(
+ `commit ${commit.ref}`,
+ `mark :${mark}`,
+ `author ${SIGNATURE} ${time}`,
+ `committer ${SIGNATURE} ${time}`,
+ data(commit.message ?? 'fixture'),
+ );
+ if (commit.parent !== undefined) {
+ const parent = marks.get(commit.parent);
+ // `^0` names the commit: fast-import refuses a branch that starts
+ // from its own name.
+ stream.push(
+ `from ${parent === undefined ? `${commit.parent}^0` : `:${parent}`}`,
+ );
+ }
+ if (commit.snapshot) stream.push('deleteall');
+ for (const [file, content] of Object.entries(commit.files ?? {})) {
+ if (content === null) {
+ stream.push(`D ${quoted(file)}`);
+ } else {
+ stream.push(`M 100644 inline ${quoted(file)}`, data(content));
+ }
+ }
+ stream.push('');
+ if (commit.name !== undefined) marks.set(commit.name, mark);
+ });
+ for (const [ref, name] of Object.entries(refs)) {
+ stream.push(`reset ${ref}`, `from :${markOf(marks, name)}`, '');
+ }
+ const names = [...marks.keys()];
+ for (const name of names) stream.push(`get-mark :${marks.get(name)}`);
+ const hashes = execFileSync('git', ['-C', root, 'fast-import', '--quiet'], {
+ input: `${stream.join('\n')}\n`,
+ encoding: 'utf8',
+ })
+ .trim()
+ .split('\n');
+ return Object.fromEntries(names.map((name, i) => [name, hashes[i]]));
+}
+
+/**
+ * Creates a repository at `root` and writes `commits` into it: two process
+ * launches in all.
+ * @param {string} root
+ * @param {FixtureCommit[]} commits
+ * @param {{bare?: boolean, branch?: string, refs?: Record<string, string>}} [options]
+ * `branch` names the branch HEAD points at; it defaults to `main`.
+ * @returns {Record<string, string>} Each named commit's hash.
+ */
+export function createRepository(
+ root,
+ commits,
+ {bare = false, branch = 'main', refs = {}} = {},
+) {
+ execFileSync('git', [
+ 'init',
+ '-q',
+ ...(bare ? ['--bare'] : []),
+ `--initial-branch=${branch}`,
+ root,
+ ]);
+ return importCommits(root, commits, refs);
+}
+
+/**
+ * Every file under `root` but `.git`, by path relative to `root`, for a
+ * commit that records a working tree a test wrote.
+ * @param {string} root
+ * @returns {Record<string, string>}
+ */
+export function workingTreeFiles(root) {
+ /** @type {Record<string, string>} */
+ const files = {};
+ const pending = [''];
+ while (pending.length > 0) {
+ const relative = /** @type {string} */ (pending.pop());
+ for (const entry of fs.readdirSync(path.join(root, relative), {
+ withFileTypes: true,
+ })) {
+ const child = relative === '' ? entry.name : `${relative}/${entry.name}`;
+ if (entry.isDirectory()) {
+ if (child !== '.git') pending.push(child);
+ } else if (entry.isFile()) {
+ files[child] = fs.readFileSync(path.join(root, child), 'utf8');
+ }
+ }
+ }
+ return files;
+}
+
+/** @param {Map<string, number>} marks @param {string} name */
+function markOf(marks, name) {
+ const mark = marks.get(name);
+ if (mark === undefined) throw new Error(`no fixture commit named ${name}`);
+ return mark;
+}
+
+/** @param {string} text */
+function data(text) {
+ return `data ${Buffer.byteLength(text)}\n${text}`;
+}
+
+// fast-import needs C-style quotes for a path that starts with a quote or
+// holds a line feed, and accepts them for any path.
+/** @param {string} file */
+function quoted(file) {
+ return /[\s"\\]/.test(file) ? JSON.stringify(file) : file;
+}
diff --git a/scripts/lib/git-fixture.test.mjs b/scripts/lib/git-fixture.test.mjs
new file mode 100644
index 0000000000..a81ed63260
--- /dev/null
+++ b/scripts/lib/git-fixture.test.mjs
@@ -0,0 +1,118 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {execFileSync} from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import {afterEach, describe, expect, it} from 'vitest';
+import {
+ createRepository,
+ importCommits,
+ workingTreeFiles,
+} from './git-fixture.mjs';
+
+/** @type {string[]} */
+const roots = [];
+afterEach(() => {
+ for (const root of roots.splice(0))
+ fs.rmSync(root, {recursive: true, force: true});
+});
+
+function tempDir() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'git-fixture-'));
+ roots.push(root);
+ return root;
+}
+
+/** @param {string} root @param {string[]} args */
+const git = (root, ...args) =>
+ execFileSync('git', ['-C', root, ...args], {encoding: 'utf8'}).trim();
+
+describe('fixture repositories', () => {
+ it('writes branches, parents, files and refs, and returns each named hash', () => {
+ const root = path.join(tempDir(), 'repo');
+ const hashes = createRepository(
+ root,
+ [
+ {
+ ref: 'refs/heads/main',
+ name: 'base',
+ message: 'base',
+ files: {'a.txt': 'one\n', 'my dir/b.txt': 'two\n'},
+ },
+ {
+ ref: 'refs/heads/topic',
+ name: 'topic',
+ parent: 'base',
+ files: {'a.txt': 'topic\n'},
+ },
+ {
+ ref: 'refs/heads/main',
+ name: 'main',
+ files: {'my dir/b.txt': null, 'c.txt': 'three\n'},
+ },
+ ],
+ {refs: {'refs/remotes/origin/main': 'base'}},
+ );
+
+ expect(git(root, 'symbolic-ref', 'HEAD')).toBe('refs/heads/main');
+ expect(git(root, 'rev-parse', 'main', 'topic', 'origin/main')).toBe(
+ [hashes.main, hashes.topic, hashes.base].join('\n'),
+ );
+ expect(git(root, 'rev-parse', 'main^', 'topic^')).toBe(
+ [hashes.base, hashes.base].join('\n'),
+ );
+ expect(git(root, 'ls-tree', '-r', '--name-only', 'main')).toBe(
+ 'a.txt\nc.txt',
+ );
+ expect(git(root, 'show', 'topic:a.txt')).toBe('topic');
+ expect(git(root, 'show', `${hashes.base}:my dir/b.txt`)).toBe('two');
+ expect(git(root, 'log', '-1', '--format=%s', hashes.base)).toBe('base');
+ });
+
+ it('records a working tree exactly as a snapshot, and continues from a ref', () => {
+ const root = tempDir();
+ fs.mkdirSync(path.join(root, 'docs'));
+ fs.writeFileSync(path.join(root, 'docs/x.md'), 'x\n');
+ const {first} = createRepository(root, [
+ {
+ ref: 'refs/heads/main',
+ name: 'first',
+ snapshot: true,
+ files: workingTreeFiles(root),
+ },
+ ]);
+ fs.rmSync(path.join(root, 'docs/x.md'));
+ fs.writeFileSync(path.join(root, 'y.md'), 'y\n');
+ const {second} = importCommits(root, [
+ {
+ ref: 'refs/heads/main',
+ name: 'second',
+ parent: 'refs/heads/main',
+ snapshot: true,
+ files: workingTreeFiles(root),
+ },
+ ]);
+
+ expect(git(root, 'rev-parse', `${second}^`)).toBe(first);
+ expect(git(root, 'ls-tree', '-r', '--name-only', second)).toBe('y.md');
+ });
+
+ it('creates a bare repository on another branch', () => {
+ const root = path.join(tempDir(), 'wiki.git');
+ const {seed} = createRepository(
+ root,
+ [
+ {
+ ref: 'refs/heads/master',
+ name: 'seed',
+ files: {'ledger.json': '{}\n'},
+ },
+ ],
+ {bare: true, branch: 'master'},
+ );
+
+ expect(git(root, 'rev-parse', '--is-bare-repository')).toBe('true');
+ expect(git(root, 'rev-parse', 'HEAD')).toBe(seed);
+ });
+});
diff --git a/scripts/lib/review-diff.test.mjs b/scripts/lib/review-diff.test.mjs
index aeac7c4c92..df1af7e88d 100644
--- a/scripts/lib/review-diff.test.mjs
+++ b/scripts/lib/review-diff.test.mjs
@@ -5,6 +5,7 @@ import os from 'node:os';
import path from 'node:path';
import {execFileSync} from 'node:child_process';
import {afterEach, describe, expect, it} from 'vitest';
+import {createRepository} from './git-fixture.mjs';
import {readDiff} from './review-diff.mjs';
import {collectConcernMatches} from '../check-knowledge.mjs';
import {loadKnowledgeIndex} from '../specs-for-file.mjs';
@@ -260,46 +261,58 @@ describe('review-global-baselines.mjs', () => {
function repository(source) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'review-baselines-'));
roots.push(root);
- git(root, 'init', '-q', '-b', 'main');
- write(
+ const record = [
+ '---',
+ 'authority: current',
+ 'kind: architecture',
+ 'id: architecture:react-component-runtime',
+ '---',
+ '',
+ '# React component runtime',
+ '',
+ '<!-- review-applicability:v1 -->',
+ '',
+ '```json',
+ JSON.stringify({
+ scope: 'global',
+ triggers: {styling: ['INV2']},
+ concerns: {
+ effects: {patterns: ['\\buseEffect\\b'], claims: ['INV1']},
+ },
+ }),
+ '```',
+ '',
+ '## Requirements',
+ '',
+ '- **INV1 — Effects clean up.** Detail.',
+ '- **INV2 — Styles stay static.** Detail.',
+ '',
+ ].join('\n');
+ const before = 'export function A() {}\n';
+ write(root, 'docs/architecture/react-component-runtime.md', record);
+ write(root, 'packages/core/src/A/A.tsx', source);
+ const {base, head} = createRepository(
root,
- 'docs/architecture/react-component-runtime.md',
[
- '---',
- 'authority: current',
- 'kind: architecture',
- 'id: architecture:react-component-runtime',
- '---',
- '',
- '# React component runtime',
- '',
- '<!-- review-applicability:v1 -->',
- '',
- '```json',
- JSON.stringify({
- scope: 'global',
- triggers: {styling: ['INV2']},
- concerns: {
- effects: {patterns: ['\\buseEffect\\b'], claims: ['INV1']},
+ {
+ ref: 'refs/heads/main',
+ name: 'base',
+ message: 'base',
+ files: {
+ 'docs/architecture/react-component-runtime.md': record,
+ 'packages/core/src/A/A.tsx': before,
},
- }),
- '```',
- '',
- '## Requirements',
- '',
- '- **INV1 — Effects clean up.** Detail.',
- '- **INV2 — Styles stay static.** Detail.',
- '',
- ].join('\n'),
+ },
+ {
+ ref: 'refs/heads/main',
+ name: 'head',
+ message: 'head',
+ files: {'packages/core/src/A/A.tsx': source},
+ },
+ ],
+ {refs: {'refs/remotes/origin/main': 'base'}},
);
- write(root, 'packages/core/src/A/A.tsx', 'export function A() {}\n');
- git(root, 'add', '-A');
- git(root, 'commit', '-q', '-m', 'base');
- const base = git(root, 'rev-parse', 'HEAD');
- git(root, 'update-ref', 'refs/remotes/origin/main', base);
- write(root, 'packages/core/src/A/A.tsx', source);
- git(root, 'commit', '-q', '-am', 'head');
- return {root, base, head: git(root, 'rev-parse', 'HEAD')};
+ return {root, base, head};
}
function route({root, base, head}) {
diff --git a/scripts/pre-review.test.mjs b/scripts/pre-review.test.mjs
index bd697de77b..5e3e1c1e36 100644
--- a/scripts/pre-review.test.mjs
+++ b/scripts/pre-review.test.mjs
@@ -5,6 +5,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {describe, expect, it} from 'vitest';
+import {createRepository} from './lib/git-fixture.mjs';
import {
CHECKS,
applicableChecks,
@@ -225,19 +226,11 @@ describe('mergeConflicts', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'review-pre-test-'));
const git = (...args) =>
execFileSync('git', ['-C', root, ...args], {encoding: 'utf8'});
- git('init', '-q', '-b', 'main');
- git('config', 'user.email', '[email protected]');
- git('config', 'user.name', 'Test');
- fs.writeFileSync(path.join(root, 'a.txt'), 'one\n');
- git('add', '.');
- git('commit', '-qm', 'base');
- git('checkout', '-qb', 'topic');
- fs.writeFileSync(path.join(root, 'a.txt'), 'topic\n');
- git('commit', '-qam', 'topic');
- git('checkout', '-q', 'main');
- fs.writeFileSync(path.join(root, theirs.file), theirs.text);
- git('add', '.');
- git('commit', '-qm', 'main');
+ createRepository(root, [
+ {ref: 'refs/heads/main', name: 'base', files: {'a.txt': 'one\n'}},
+ {ref: 'refs/heads/topic', parent: 'base', files: {'a.txt': 'topic\n'}},
+ {ref: 'refs/heads/main', files: {[theirs.file]: theirs.text}},
+ ]);
return {root, git};
}
diff --git a/scripts/prune-branches.test.mjs b/scripts/prune-branches.test.mjs
index d621e20a95..289c828f69 100644
--- a/scripts/prune-branches.test.mjs
+++ b/scripts/prune-branches.test.mjs
@@ -14,6 +14,7 @@ import os from 'node:os';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {afterEach, describe, expect, it} from 'vitest';
+import {createRepository} from './lib/git-fixture.mjs';
const SCRIPT = path.join(
path.dirname(fileURLToPath(import.meta.url)),
@@ -28,22 +29,29 @@ afterEach(() => {
function setup(prStates) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'prune-'));
roots.push(root);
- const git = (cwd, ...args) =>
- execFileSync('git', args, {cwd, encoding: 'utf8'});
const origin = path.join(root, 'origin.git');
const work = path.join(root, 'work');
- git(root, 'init', '-q', '--bare', origin);
- git(root, 'init', '-q', '-b', 'main', work);
- git(work, 'config', 'user.email', '[email protected]');
- git(work, 'config', 'user.name', 'Test');
- git(work, 'commit', '-q', '--allow-empty', '-m', 'base');
- git(work, 'remote', 'add', 'origin', origin);
- // assets/pr-3 is pushed by hand: no marker.
- git(work, 'push', '-q', 'origin', 'main', 'main:assets/pr-3');
- fs.writeFileSync(path.join(work, '.pr-report-frames'), 'marker\n');
- git(work, 'add', '.pr-report-frames');
- git(work, 'commit', '-q', '-m', 'frames');
- git(work, 'push', '-q', 'origin', 'HEAD:assets/pr-1', 'HEAD:assets/pr-2');
+ createRepository(
+ origin,
+ [
+ {ref: 'refs/heads/main', name: 'base'},
+ {
+ ref: 'refs/heads/assets/pr-1',
+ name: 'frames',
+ parent: 'base',
+ files: {'.pr-report-frames': 'marker\n'},
+ },
+ ],
+ {
+ bare: true,
+ // assets/pr-3 is pushed by hand: no marker.
+ refs: {
+ 'refs/heads/assets/pr-2': 'frames',
+ 'refs/heads/assets/pr-3': 'base',
+ },
+ },
+ );
+ execFileSync('git', ['clone', '-q', origin, work]);
// A stand-in for gh: `pr view <n>` answers from prStates; `pr list` finds no PR.
const bin = path.join(root, 'bin');
fs.mkdirSync(bin);
diff --git a/scripts/release/active-release.test.mjs b/scripts/release/active-release.test.mjs
index 9c819224ea..cbd5325319 100644
--- a/scripts/release/active-release.test.mjs
+++ b/scripts/release/active-release.test.mjs
@@ -13,6 +13,11 @@ import os from 'node:os';
import path from 'node:path';
import {execFileSync} from 'node:child_process';
import {afterEach, describe, expect, it} from 'vitest';
+import {
+ createRepository,
+ importCommits,
+ workingTreeFiles,
+} from '../lib/git-fixture.mjs';
import {
buildMarker,
buildPlan,
@@ -85,12 +90,16 @@ function cutFixture(version = '0.6.5') {
path.join(root, '.changeset/in-cut.md'),
"---\n'@astryxdesign/core': patch\n---\n\n[fix] Included\n@person\n",
);
- git(root, 'init', '-q');
- git(root, 'config', 'user.name', 'Release Test');
- git(root, 'config', 'user.email', '[email protected]');
- git(root, 'add', '.');
- git(root, 'commit', '-qm', 'cut');
- return {...state, cutSha: git(root, 'rev-parse', 'HEAD')};
+ const {cut} = createRepository(root, [
+ {
+ ref: 'refs/heads/main',
+ name: 'cut',
+ message: 'cut',
+ snapshot: true,
+ files: workingTreeFiles(root),
+ },
+ ]);
+ return {...state, cutSha: cut};
}
function validate(state, overrides = {}) {
@@ -198,13 +207,16 @@ describe('one branch per release lifecycle', () => {
).toThrow(
/main declares 0\.6\.5 at the cut|release refresh cannot change version/,
);
- git(root, 'commit', '-qm', 'later', '--allow-empty');
+ const {later} = importCommits(root, [
+ {
+ ref: 'refs/heads/main',
+ name: 'later',
+ parent: 'refs/heads/main',
+ message: 'later',
+ },
+ ]);
expect(() =>
- writeAuthority(
- root,
- {...values, 'cut-sha': git(root, 'rev-parse', 'HEAD')},
- true,
- ),
+ writeAuthority(root, {...values, 'cut-sha': later}, true),
).toThrow('release refresh cannot change cutSha');
});
diff --git a/scripts/score-ledger.test.mjs b/scripts/score-ledger.test.mjs
index 5021af534a..c6365bebef 100644
--- a/scripts/score-ledger.test.mjs
+++ b/scripts/score-ledger.test.mjs
@@ -20,6 +20,7 @@ import {execFileSync} from 'node:child_process';
import http from 'node:http';
import {afterAll, beforeAll, describe, it, expect} from 'vitest';
+import {createRepository} from './lib/git-fixture.mjs';
import {
AUDIT_PROMPT,
@@ -952,30 +953,17 @@ const scorecard = (over = {}) => ({
function makeWiki(seedLedger) {
const root = fs.mkdtempSync(path.join(TEMP_ROOT, 'score-ledger-wiki-'));
const bare = path.join(root, 'wiki.git');
- const seed = path.join(root, 'seed');
const clone = path.join(root, 'clone');
- git(root, 'init', '--bare', '--initial-branch=master', bare);
- git(root, 'clone', bare, seed);
- identify(seed);
- fs.writeFileSync(
- path.join(seed, 'component-scores.json'),
- `${JSON.stringify(seedLedger, null, 2)}\n`,
- );
- git(seed, 'add', '-A');
- git(seed, 'commit', '-m', 'seed');
- git(seed, 'push', 'origin', 'master');
-
- git(root, 'clone', '--depth', '1', `file://${bare}`, clone);
- identify(clone);
+ const ledger = `${JSON.stringify(seedLedger, null, 2)}\n`;
+ const seed = {ref: 'refs/heads/master', message: 'seed', files: {'component-scores.json': ledger}};
+ createRepository(bare, [seed], {bare: true, branch: 'master'});
+ // The clone's own config names who commits there.
+ const identity = ['-c', 'user.name=Ledger Test', '-c', '[email protected]'];
+ git(root, 'clone', ...identity, '--depth', '1', `file://${bare}`, clone);
return {root, bare, clone, ledger: path.join(clone, 'component-scores.json')};
}
-function identify(dir) {
- git(dir, 'config', 'user.name', 'Ledger Test');
- git(dir, 'config', 'user.email', '[email protected]');
-}
-
const readLedger = file => JSON.parse(fs.readFileSync(file, 'utf8'));
/** What the remote actually holds, which is the only thing that counts. */
diff --git a/scripts/template-score-ledger.test.mjs b/scripts/template-score-ledger.test.mjs
index 023b720a6e..0dc578b44e 100644
--- a/scripts/template-score-ledger.test.mjs
+++ b/scripts/template-score-ledger.test.mjs
@@ -15,6 +15,7 @@ import os from 'node:os';
import path from 'node:path';
import {afterAll, beforeAll, describe, expect, it} from 'vitest';
+import {createRepository} from './lib/git-fixture.mjs';
import {TEMPLATE_RUBRIC} from '../packages/cli/assets/docs/tree/template-grading-rubric.doc.mjs';
import {
@@ -464,30 +465,37 @@ function cli(argv, {cwd = REPO_ROOT, input, env} = {}) {
}
}
-function identify(directory) {
- git(directory, 'config', 'user.name', 'Template Ledger Test');
- git(directory, 'config', 'user.email', '[email protected]');
-}
-
function makeWiki(seedLedger) {
const root = fs.mkdtempSync(path.join(TEMP_ROOT, 'template-ledger-wiki-'));
const bare = path.join(root, 'wiki.git');
- const seed = path.join(root, 'seed');
const clone = path.join(root, 'clone');
- git(root, 'init', '--bare', '--initial-branch=master', bare);
- git(root, 'clone', bare, seed);
- identify(seed);
- fs.writeFileSync(
- path.join(seed, TEMPLATE_LEDGER_FILENAME),
- `${JSON.stringify(seedLedger, null, 2)}\n`,
+ createRepository(
+ bare,
+ [
+ {
+ ref: `refs/heads/${WIKI_BRANCH}`,
+ message: 'seed',
+ files: {
+ [TEMPLATE_LEDGER_FILENAME]: `${JSON.stringify(seedLedger, null, 2)}\n`,
+ },
+ },
+ ],
+ {bare: true, branch: WIKI_BRANCH},
+ );
+ // The clone's own config names who commits there.
+ git(
+ root,
+ 'clone',
+ '-c',
+ 'user.name=Template Ledger Test',
+ '-c',
+ '--depth',
+ '1',
+ `file://${bare}`,
+ clone,
);
- git(seed, 'add', '-A');
- git(seed, 'commit', '-m', 'seed');
- git(seed, 'push', 'origin', WIKI_BRANCH);
-
- git(root, 'clone', '--depth', '1', `file://${bare}`, clone);
- identify(clone);
return {
root,
bare,