@leed-ai/git-gateway-testkit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +19 -2
  3. package/dist/contract-suite/ancestry-cases.d.ts +4 -0
  4. package/dist/contract-suite/ancestry-cases.js +49 -0
  5. package/dist/contract-suite/ancestry-cases.js.map +1 -0
  6. package/dist/contract-suite/backend-case.d.ts +35 -0
  7. package/dist/contract-suite/backend-case.js +17 -0
  8. package/dist/contract-suite/backend-case.js.map +1 -0
  9. package/dist/contract-suite/backend-contract-suite.d.ts +44 -0
  10. package/dist/contract-suite/backend-contract-suite.js +59 -0
  11. package/dist/contract-suite/backend-contract-suite.js.map +1 -0
  12. package/dist/contract-suite/backend-fixtures.d.ts +25 -0
  13. package/dist/contract-suite/backend-fixtures.js +79 -0
  14. package/dist/contract-suite/backend-fixtures.js.map +1 -0
  15. package/dist/contract-suite/content-cases.d.ts +4 -0
  16. package/dist/contract-suite/content-cases.js +31 -0
  17. package/dist/contract-suite/content-cases.js.map +1 -0
  18. package/dist/contract-suite/lifecycle-cases.d.ts +4 -0
  19. package/dist/contract-suite/lifecycle-cases.js +86 -0
  20. package/dist/contract-suite/lifecycle-cases.js.map +1 -0
  21. package/dist/contract-suite/push-cases.d.ts +4 -0
  22. package/dist/contract-suite/push-cases.js +92 -0
  23. package/dist/contract-suite/push-cases.js.map +1 -0
  24. package/dist/contract-suite/push-helpers.d.ts +17 -0
  25. package/dist/contract-suite/push-helpers.js +47 -0
  26. package/dist/contract-suite/push-helpers.js.map +1 -0
  27. package/dist/contract-suite/read-cases.d.ts +4 -0
  28. package/dist/contract-suite/read-cases.js +186 -0
  29. package/dist/contract-suite/read-cases.js.map +1 -0
  30. package/dist/contract-suite/transport-cases.d.ts +4 -0
  31. package/dist/contract-suite/transport-cases.js +105 -0
  32. package/dist/contract-suite/transport-cases.js.map +1 -0
  33. package/dist/git-binary.d.ts +19 -0
  34. package/dist/git-binary.js +54 -0
  35. package/dist/git-binary.js.map +1 -0
  36. package/dist/git-sandbox.d.ts +33 -0
  37. package/dist/git-sandbox.js +76 -0
  38. package/dist/git-sandbox.js.map +1 -0
  39. package/dist/memory/memory-backend.d.ts +45 -0
  40. package/dist/memory/memory-backend.js +154 -0
  41. package/dist/memory/memory-backend.js.map +1 -0
  42. package/dist/memory/memory-reads.d.ts +9 -0
  43. package/dist/memory/memory-reads.js +39 -0
  44. package/dist/memory/memory-reads.js.map +1 -0
  45. package/dist/memory/memory-repository.d.ts +38 -0
  46. package/dist/memory/memory-repository.js +97 -0
  47. package/dist/memory/memory-repository.js.map +1 -0
  48. package/dist/memory/memory-tokens.d.ts +28 -0
  49. package/dist/memory/memory-tokens.js +59 -0
  50. package/dist/memory/memory-tokens.js.map +1 -0
  51. package/dist/memory/pack-selection.d.ts +30 -0
  52. package/dist/memory/pack-selection.js +104 -0
  53. package/dist/memory/pack-selection.js.map +1 -0
  54. package/dist/memory/receive-pack-service.d.ts +15 -0
  55. package/dist/memory/receive-pack-service.js +126 -0
  56. package/dist/memory/receive-pack-service.js.map +1 -0
  57. package/dist/memory/smart-http-server.d.ts +15 -0
  58. package/dist/memory/smart-http-server.js +65 -0
  59. package/dist/memory/smart-http-server.js.map +1 -0
  60. package/dist/memory/upload-pack-service.d.ts +15 -0
  61. package/dist/memory/upload-pack-service.js +123 -0
  62. package/dist/memory/upload-pack-service.js.map +1 -0
  63. package/dist/node/serve-fetch-handler.d.ts +16 -0
  64. package/dist/node/serve-fetch-handler.js +52 -0
  65. package/dist/node/serve-fetch-handler.js.map +1 -0
  66. package/dist/node/serve-streaming.d.ts +16 -0
  67. package/dist/node/serve-streaming.js +87 -0
  68. package/dist/node/serve-streaming.js.map +1 -0
  69. package/package.json +175 -4
  70. package/src/contract-suite/ancestry-cases.ts +56 -0
  71. package/src/contract-suite/backend-case.ts +53 -0
  72. package/src/contract-suite/backend-contract-suite.ts +89 -0
  73. package/src/contract-suite/backend-fixtures.ts +89 -0
  74. package/src/contract-suite/content-cases.ts +55 -0
  75. package/src/contract-suite/lifecycle-cases.ts +121 -0
  76. package/src/contract-suite/push-cases.ts +123 -0
  77. package/src/contract-suite/push-helpers.ts +63 -0
  78. package/src/contract-suite/read-cases.ts +213 -0
  79. package/src/contract-suite/transport-cases.ts +134 -0
  80. package/src/git-binary.ts +65 -0
  81. package/src/git-sandbox.ts +87 -0
  82. package/src/memory/memory-backend.ts +188 -0
  83. package/src/memory/memory-reads.ts +52 -0
  84. package/src/memory/memory-repository.ts +115 -0
  85. package/src/memory/memory-tokens.ts +64 -0
  86. package/src/memory/pack-selection.ts +127 -0
  87. package/src/memory/receive-pack-service.ts +141 -0
  88. package/src/memory/smart-http-server.ts +78 -0
  89. package/src/memory/upload-pack-service.ts +132 -0
  90. package/src/node/serve-fetch-handler.ts +71 -0
  91. package/src/node/serve-streaming.ts +107 -0
@@ -0,0 +1,213 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { assertEqual, assertTrue, present } from '@leed-ai/git-gateway-contract/behaviour/assertions';
3
+ import { sameBytes, utf8 } from '@leed-ai/git-gateway-contract/reference/bytes';
4
+ import { ZERO_SHA } from '@leed-ai/git-gateway-contract/schemas/sha';
5
+
6
+ import { backendCase, type BackendCase, type BackendContext } from './backend-case.ts';
7
+ import { fixtureCommit, type FixtureCommit } from './backend-fixtures.ts';
8
+ import { expectAccepted, newObjects, pushRef, seedRepo } from './push-helpers.ts';
9
+
10
+ const GROUP = 'reads';
11
+ const MISSING = '0123456789abcdef0123456789abcdef01234567';
12
+
13
+ const FILES = {
14
+ 'README.md': '# Read cases\n',
15
+ 'bin/run.sh': { content: '#!/bin/sh\necho hi\n', mode: '100755' as const },
16
+ link: { content: 'README.md', mode: '120000' as const },
17
+ 'content/pages/about.md': 'About\n',
18
+ };
19
+
20
+ /** Seeds a repository with a small history: root → second (on main), plus a merge on top. */
21
+ async function seedHistory(
22
+ context: BackendContext,
23
+ ): Promise<{ root: FixtureCommit; second: FixtureCommit; side: FixtureCommit; merge: FixtureCommit }> {
24
+ const root = await seedRepo(context, FILES);
25
+ const second = await fixtureCommit(
26
+ { ...FILES, 'content/pages/about.md': 'About, revised\n' },
27
+ [root.sha],
28
+ 'Revise about\n',
29
+ );
30
+ expectAccepted(
31
+ await pushRef(context, 'refs/heads/main', root.sha, second.sha, newObjects(second, root)),
32
+ 'refs/heads/main',
33
+ );
34
+ const side = await fixtureCommit({ ...FILES, 'side.txt': 'side\n' }, [root.sha], 'Side change\n');
35
+ const merge = await fixtureCommit(
36
+ { ...FILES, 'content/pages/about.md': 'About, revised\n', 'side.txt': 'side\n' },
37
+ [second.sha, side.sha],
38
+ 'Merge side\n\nGateway-Idempotency-Key: contract:merge\n',
39
+ );
40
+ const objects = [...side.objects, ...merge.objects];
41
+ expectAccepted(
42
+ await pushRef(context, 'refs/heads/main', second.sha, merge.sha, objects),
43
+ 'refs/heads/main',
44
+ );
45
+ return { root, second, side, merge };
46
+ }
47
+
48
+ const textOf = (bytes: Uint8Array | null): string | null =>
49
+ bytes === null ? null : new TextDecoder().decode(bytes);
50
+
51
+ /** resolveRef, readCommit, readTree, readBlob, readFile and log. */
52
+ export const readCases: readonly BackendCase[] = [
53
+ backendCase(GROUP, 'readCommit returns a pushed commit exactly, trailer parsed', async (context) => {
54
+ const { root, merge } = await seedHistory(context);
55
+ assertEqual(await context.backend.readCommit(context.repo, root.sha), root.commit, 'root commit');
56
+ const read = present(await context.backend.readCommit(context.repo, merge.sha), 'merge commit');
57
+ assertEqual(read, merge.commit, 'merge commit with two parents');
58
+ assertEqual(read.idempotencyKey, 'contract:merge', 'idempotency trailer parsed');
59
+ }),
60
+ backendCase(GROUP, 'readCommit of an unknown id is null', async (context) => {
61
+ await seedRepo(context);
62
+ assertEqual(await context.backend.readCommit(context.repo, MISSING), null, 'null');
63
+ }),
64
+ backendCase(GROUP, 'reading an id as the wrong kind of object is null', async (context) => {
65
+ const root = await seedRepo(context, FILES);
66
+ const blob = present(
67
+ root.objects.find((object) => object.type === 'blob'),
68
+ 'a blob',
69
+ );
70
+ const { backend, repo } = context;
71
+ assertEqual(await backend.readCommit(repo, blob.sha), null, 'readCommit of a blob');
72
+ assertEqual(await backend.readCommit(repo, root.commit.tree), null, 'readCommit of a tree');
73
+ assertEqual(await backend.readTree(repo, blob.sha), null, 'readTree of a blob');
74
+ assertEqual(await backend.readTree(repo, root.sha), null, 'readTree of a commit');
75
+ assertEqual(await backend.readBlob(repo, root.commit.tree), null, 'readBlob of a tree');
76
+ assertEqual(await backend.readBlob(repo, root.sha), null, 'readBlob of a commit');
77
+ }),
78
+ backendCase(GROUP, 'readTree lists one level in stored order with kinds and modes', async (context) => {
79
+ const { root } = await seedHistory(context);
80
+ const entries = present(await context.backend.readTree(context.repo, root.commit.tree), 'root tree');
81
+ assertEqual(
82
+ entries.map((entry) => [entry.name, entry.type, entry.mode]),
83
+ [
84
+ ['README.md', 'blob', '100644'],
85
+ ['bin', 'tree', '040000'],
86
+ ['content', 'tree', '040000'],
87
+ ['link', 'blob', '120000'],
88
+ ],
89
+ 'root entries',
90
+ );
91
+ const bin = present(
92
+ entries.find((entry) => entry.name === 'bin'),
93
+ 'bin entry',
94
+ );
95
+ const binEntries = present(await context.backend.readTree(context.repo, bin.sha), 'bin tree');
96
+ assertEqual(
97
+ binEntries.map((entry) => [entry.name, entry.type, entry.mode]),
98
+ [['run.sh', 'blob', '100755']],
99
+ 'subtree',
100
+ );
101
+ assertTrue(
102
+ entries.every((entry) => root.objects.some((object) => object.sha === entry.sha)),
103
+ 'entry ids match',
104
+ );
105
+ }),
106
+ backendCase(GROUP, 'readTree of an unknown id is null', async (context) => {
107
+ await seedRepo(context);
108
+ assertEqual(await context.backend.readTree(context.repo, MISSING), null, 'null');
109
+ }),
110
+ backendCase(GROUP, 'readBlob returns bytes by id, null for an unknown id', async (context) => {
111
+ const root = await seedRepo(context, FILES);
112
+ const blob = present(
113
+ root.objects.find((object) => object.type === 'blob' && textOf(object.data) === 'About\n'),
114
+ 'about blob',
115
+ );
116
+ assertTrue(
117
+ sameBytes(present(await context.backend.readBlob(context.repo, blob.sha), 'blob'), blob.data),
118
+ 'bytes',
119
+ );
120
+ assertEqual(await context.backend.readBlob(context.repo, MISSING), null, 'unknown id');
121
+ }),
122
+ backendCase(GROUP, 'readFile reads by branch and by commit id, nested paths included', async (context) => {
123
+ const { root } = await seedHistory(context);
124
+ const { backend, repo } = context;
125
+ assertEqual(
126
+ textOf(await backend.readFile(repo, 'main', 'content/pages/about.md')),
127
+ 'About, revised\n',
128
+ 'at main',
129
+ );
130
+ assertEqual(
131
+ textOf(await backend.readFile(repo, root.sha, 'content/pages/about.md')),
132
+ 'About\n',
133
+ 'at the root commit',
134
+ );
135
+ assertEqual(
136
+ textOf(await backend.readFile(repo, 'main', 'bin/run.sh')),
137
+ '#!/bin/sh\necho hi\n',
138
+ 'executable file',
139
+ );
140
+ assertEqual(textOf(await backend.readFile(repo, 'main', 'link')), 'README.md', 'symlink target');
141
+ }),
142
+ backendCase(
143
+ GROUP,
144
+ 'readFile is null for a missing path, a directory, a missing branch or commit',
145
+ async (context) => {
146
+ await seedHistory(context);
147
+ const { backend, repo } = context;
148
+ assertEqual(await backend.readFile(repo, 'main', 'nope.md'), null, 'missing path');
149
+ assertEqual(await backend.readFile(repo, 'main', 'content/pages/nope.md'), null, 'missing nested path');
150
+ assertEqual(await backend.readFile(repo, 'main', 'README.md/x'), null, 'beneath a file');
151
+ assertEqual(await backend.readFile(repo, 'main', 'content'), null, 'a directory');
152
+ assertEqual(await backend.readFile(repo, 'no-such-branch', 'README.md'), null, 'missing branch');
153
+ assertEqual(await backend.readFile(repo, MISSING, 'README.md'), null, 'missing commit');
154
+ },
155
+ ),
156
+ backendCase(
157
+ GROUP,
158
+ 'log lists the first-parent chain newest first, with limit and offset',
159
+ async (context) => {
160
+ const { root, second, merge } = await seedHistory(context);
161
+ const { backend, repo } = context;
162
+ const shas = async (ref: string, limit: number, offset?: number): Promise<string[]> =>
163
+ (await backend.log(repo, ref, offset === undefined ? { limit } : { limit, offset })).map(
164
+ (commit) => commit.sha,
165
+ );
166
+ assertEqual(await shas('main', 10), [merge.sha, second.sha, root.sha], 'first parents only');
167
+ assertEqual(await shas('main', 2), [merge.sha, second.sha], 'limit');
168
+ assertEqual(await shas('main', 10, 1), [second.sha, root.sha], 'offset');
169
+ assertEqual(await shas('main', 10, 3), [], 'offset past the end');
170
+ assertEqual(await shas(second.sha, 10), [second.sha, root.sha], 'from a commit id');
171
+ assertEqual((await backend.log(repo, 'main', { limit: 1 }))[0], merge.commit, 'commits are complete');
172
+ assertEqual(await backend.log(repo, 'no-such-branch', { limit: 5 }), [], 'missing branch');
173
+ },
174
+ ),
175
+ backendCase(
176
+ GROUP,
177
+ 'resolveRef resolves short names, full refs and tags; null when missing',
178
+ async (context) => {
179
+ const seeded = await seedRepo(context);
180
+ expectAccepted(await pushRef(context, 'refs/tags/v1.0.0', ZERO_SHA, seeded.sha), 'refs/tags/v1.0.0');
181
+ const { backend, repo } = context;
182
+ assertEqual(await backend.resolveRef(repo, 'main'), seeded.sha, 'short name');
183
+ assertEqual(await backend.resolveRef(repo, 'refs/heads/main'), seeded.sha, 'full ref');
184
+ assertEqual(await backend.resolveRef(repo, 'refs/tags/v1.0.0'), seeded.sha, 'lightweight tag');
185
+ assertEqual(await backend.resolveRef(repo, 'staging'), null, 'missing branch');
186
+ assertEqual(await backend.resolveRef(repo, 'refs/tags/v9'), null, 'missing tag');
187
+ },
188
+ ),
189
+ backendCase(GROUP, 'unicode paths and every byte value round-trip', async (context) => {
190
+ const bytes = Uint8Array.from({ length: 512 }, (_, index) => index % 256);
191
+ await seedRepo(context, {
192
+ 'pages/café/naïve 日本.md': 'unicode\n',
193
+ 'data/all-bytes.bin': { content: bytes },
194
+ });
195
+ const { backend, repo } = context;
196
+ assertEqual(
197
+ textOf(await backend.readFile(repo, 'main', 'pages/café/naïve 日本.md')),
198
+ 'unicode\n',
199
+ 'unicode path',
200
+ );
201
+ assertTrue(
202
+ sameBytes(present(await backend.readFile(repo, 'main', 'data/all-bytes.bin'), 'binary'), bytes),
203
+ 'all bytes',
204
+ );
205
+ assertTrue(
206
+ sameBytes(
207
+ utf8('unicode\n'),
208
+ present(await backend.readFile(repo, 'main', 'pages/café/naïve 日本.md'), 'f'),
209
+ ),
210
+ 'bytes',
211
+ );
212
+ }),
213
+ ];
@@ -0,0 +1,134 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { assertEqual, assertTrue } from '@leed-ai/git-gateway-contract/behaviour/assertions';
3
+ import { sameBytes } from '@leed-ai/git-gateway-contract/reference/bytes';
4
+ import { ZERO_SHA } from '@leed-ai/git-gateway-contract/schemas/sha';
5
+ import { GitRemote } from '@leed-ai/git-gateway-contract/storage/git-remote';
6
+ import { isCoreError } from '@leed-ai/git-gateway-core/core-error';
7
+
8
+ import { backendCase, type BackendCase } from './backend-case.ts';
9
+ import { fixtureCommit } from './backend-fixtures.ts';
10
+ import { expectAccepted, pushNewBranch, pushRef, seedRepo } from './push-helpers.ts';
11
+
12
+ const GROUP = 'transport';
13
+
14
+ const sortedShas = (objects: readonly { sha: string }[]): string[] =>
15
+ objects.map((object) => object.sha).toSorted();
16
+
17
+ /** Empty repositories, gitRemote, push and fetch over the host's smart-HTTP remote. */
18
+ export const transportCases: readonly BackendCase[] = [
19
+ backendCase(GROUP, 'an empty repository has no refs, no history and no files', async (context) => {
20
+ const { backend, repo } = context;
21
+ await backend.createRepo(repo);
22
+ assertEqual(await backend.resolveRef(repo, 'main'), null, 'resolveRef');
23
+ assertEqual(await backend.log(repo, 'main', { limit: 10 }), [], 'log');
24
+ assertEqual(await backend.readFile(repo, 'main', 'README.md'), null, 'readFile');
25
+ const reader = await context.client('read');
26
+ assertEqual((await reader.advertisement('git-upload-pack')).refs, [], 'upload-pack advertises no refs');
27
+ const writer = await context.client('write');
28
+ assertEqual((await writer.advertisement('git-receive-pack')).refs, [], 'receive-pack advertises no refs');
29
+ }),
30
+ backendCase(GROUP, 'gitRemote mints a remote whose headers authorize it', async (context) => {
31
+ await context.backend.createRepo(context.repo);
32
+ for (const access of ['read', 'write'] as const) {
33
+ const remote = await context.backend.gitRemote(context.repo, access);
34
+ assertTrue(GitRemote.safeParse(remote).success, `${access} remote is a GitRemote`);
35
+ assertTrue(remote.url.endsWith('.git'), `${access} remote URL ends in .git`);
36
+ assertTrue(!remote.url.includes('@'), `${access} remote URL carries no credential`);
37
+ }
38
+ }),
39
+ backendCase(GROUP, 'a push to an empty repository creates the branch', async (context) => {
40
+ const seeded = await seedRepo(context);
41
+ assertEqual(
42
+ await context.backend.resolveRef(context.repo, 'main'),
43
+ seeded.sha,
44
+ 'resolveRef sees the push',
45
+ );
46
+ const advertised = (await (await context.client('read')).advertisement('git-upload-pack')).refs;
47
+ assertTrue(
48
+ advertised.some((ref) => ref.name === 'refs/heads/main' && ref.sha === seeded.sha),
49
+ 'advertised',
50
+ );
51
+ }),
52
+ backendCase(GROUP, 'a fetch returns every pushed object byte for byte', async (context) => {
53
+ const seeded = await seedRepo(context, {
54
+ 'a.txt': 'a\n',
55
+ 'dir/b.txt': 'b\n',
56
+ 'dir/sub/c.bin': { content: new Uint8Array([0, 1, 2]) },
57
+ });
58
+ const fetched = await (await context.client('read')).fetchPack({ wants: [seeded.sha] });
59
+ assertEqual(sortedShas(fetched.objects), sortedShas(seeded.objects), 'the same object ids');
60
+ for (const object of seeded.objects) {
61
+ const got = fetched.objects.find((candidate) => candidate.sha === object.sha);
62
+ assertTrue(
63
+ got?.type === object.type && sameBytes(got.data, object.data),
64
+ `object ${object.sha} round-trips`,
65
+ );
66
+ }
67
+ }),
68
+ backendCase(GROUP, 'a fetch with haves leaves out what the client has', async (context) => {
69
+ const first = await seedRepo(context);
70
+ const second = await fixtureCommit({ 'README.md': '# Seed\n', 'new.txt': 'new\n' }, [first.sha]);
71
+ expectAccepted(
72
+ await pushRef(context, 'refs/heads/main', first.sha, second.sha, second.objects),
73
+ 'refs/heads/main',
74
+ );
75
+ const fetched = await (
76
+ await context.client('read')
77
+ ).fetchPack({ wants: [second.sha], haves: [first.sha] });
78
+ const got = new Set(fetched.objects.map((object) => object.sha));
79
+ assertTrue(got.has(second.sha), 'the new commit is sent');
80
+ assertTrue(!got.has(first.sha), 'the had commit is not sent');
81
+ }),
82
+ backendCase(
83
+ GROUP,
84
+ 'a second branch can point at an existing commit with an empty pack',
85
+ async (context) => {
86
+ const seeded = await seedRepo(context);
87
+ expectAccepted(
88
+ await pushRef(context, 'refs/heads/staging', ZERO_SHA, seeded.sha),
89
+ 'refs/heads/staging',
90
+ );
91
+ assertEqual(await context.backend.resolveRef(context.repo, 'staging'), seeded.sha, 'staging');
92
+ },
93
+ ),
94
+ backendCase(GROUP, 'a read remote cannot push when the host scopes credentials', async (context) => {
95
+ const seeded = await seedRepo(context);
96
+ if (!context.behaviour.readRemoteCannotPush) return;
97
+ const next = await fixtureCommit({ 'x.txt': 'x\n' }, [seeded.sha]);
98
+ let pushed = false;
99
+ try {
100
+ const report = await (
101
+ await context.client('read')
102
+ ).push([{ oldSha: seeded.sha, newSha: next.sha, ref: 'refs/heads/main' }], next.objects);
103
+ pushed = report.refs.every((ref) => ref.status === 'ok');
104
+ } catch (error) {
105
+ assertTrue(
106
+ isCoreError(error, 'remote_error') || isCoreError(error, 'remote_http_error'),
107
+ `refused by the remote, got ${String(error)}`,
108
+ );
109
+ }
110
+ assertTrue(!pushed, 'the push did not succeed');
111
+ assertEqual(await context.backend.resolveRef(context.repo, 'main'), seeded.sha, 'main unchanged');
112
+ }),
113
+ backendCase(
114
+ GROUP,
115
+ 'pushes from new branches are visible to resolveRef and the advertisement',
116
+ async (context) => {
117
+ const seeded = await seedRepo(context);
118
+ const feature = await fixtureCommit({ 'feature.txt': 'f\n' }, [seeded.sha]);
119
+ await pushNewBranch(context, 'feature/one', feature);
120
+ assertEqual(
121
+ await context.backend.resolveRef(context.repo, 'refs/heads/feature/one'),
122
+ feature.sha,
123
+ 'full ref',
124
+ );
125
+ const refs = (await (await context.client('write')).advertisement('git-receive-pack')).refs.map(
126
+ (ref) => ref.name,
127
+ );
128
+ assertTrue(
129
+ refs.includes('refs/heads/feature/one') && refs.includes('refs/heads/main'),
130
+ 'both branches advertised',
131
+ );
132
+ },
133
+ ),
134
+ ];
@@ -0,0 +1,65 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { execFileSync } from 'node:child_process';
3
+
4
+ import { z } from 'zod';
5
+
6
+ /** The version of a git binary, parsed from `git --version`. */
7
+ export const GitVersion = z
8
+ .object({
9
+ major: z.number().int().nonnegative().describe('Major version number, e.g. 2 for git 2.43.0.'),
10
+ minor: z.number().int().nonnegative().describe('Minor version number, e.g. 43 for git 2.43.0.'),
11
+ patch: z
12
+ .number()
13
+ .int()
14
+ .nonnegative()
15
+ .describe('Patch version number, e.g. 0 for git 2.43.0; 0 when the binary reports only two parts.'),
16
+ raw: z
17
+ .string()
18
+ .min(1)
19
+ .describe(
20
+ 'The version text exactly as git printed it after "git version", e.g. "2.39.5 (Apple Git-154)".',
21
+ ),
22
+ })
23
+ .strict()
24
+ .meta({
25
+ id: 'GitVersion',
26
+ title: 'Git version',
27
+ description: 'The version of the git binary a conformance run drives, parsed from `git --version`.',
28
+ examples: [{ major: 2, minor: 43, patch: 0, raw: '2.43.0' }],
29
+ });
30
+
31
+ /** The version of a git binary, inferred from {@link GitVersion}. */
32
+ export type GitVersion = z.infer<typeof GitVersion>;
33
+
34
+ // Only the leading numbers are matched; the rest of the line is kept verbatim in `raw`. (A pattern
35
+ // that also matched the suffix, as `\S*(?:\s.*)?$`, backtracks in polynomial time.)
36
+ const VERSION_PREFIX = 'git version ';
37
+ const VERSION_NUMBERS = /^(\d+)\.(\d+)(?:\.(\d+))?(?![\d.]*\d)/;
38
+
39
+ /** Parses the output of `git --version`; throws on anything else. */
40
+ export function parseGitVersion(output: string): GitVersion {
41
+ const line = output.trim();
42
+ const raw = line.startsWith(VERSION_PREFIX) ? line.slice(VERSION_PREFIX.length) : '';
43
+ const match = line.includes('\n') ? null : VERSION_NUMBERS.exec(raw);
44
+ if (match === null) throw new Error(`not a git --version line: ${JSON.stringify(output)}`);
45
+ const [, major, minor, patch] = match;
46
+ return GitVersion.parse({ major: Number(major), minor: Number(minor), patch: Number(patch ?? 0), raw });
47
+ }
48
+
49
+ /** The git binary to drive: `GIT_BINARY` from the environment when set, otherwise `git` on the PATH. */
50
+ export function gitBinary(env: Readonly<Record<string, string | undefined>> = process.env): string {
51
+ const configured = env['GIT_BINARY']?.trim();
52
+ return configured === undefined || configured === '' ? 'git' : configured;
53
+ }
54
+
55
+ /** Runs `<binary> --version` and parses the result. */
56
+ export function readGitVersion(binary: string = gitBinary()): GitVersion {
57
+ return parseGitVersion(execFileSync(binary, ['--version'], { encoding: 'utf8' }));
58
+ }
59
+
60
+ /** True when `version` is at least `major.minor.patch`. */
61
+ export function isAtLeast(version: GitVersion, major: number, minor: number, patch = 0): boolean {
62
+ if (version.major !== major) return version.major > major;
63
+ if (version.minor !== minor) return version.minor > minor;
64
+ return version.patch >= patch;
65
+ }
@@ -0,0 +1,87 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { spawn } from 'node:child_process';
3
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+
7
+ import { gitBinary } from './git-binary.ts';
8
+
9
+ /** What a git invocation produced. */
10
+ export interface GitRun {
11
+ readonly status: number | null;
12
+ readonly stdout: string;
13
+ readonly stderr: string;
14
+ }
15
+
16
+ /**
17
+ * A scratch directory where the real git binary (`GIT_BINARY`, or `git` on the PATH) runs isolated
18
+ * from the user's and the system's configuration: the conformance harness drives git clients
19
+ * against a gateway or a backend served on loopback with it. Call {@link dispose} when done.
20
+ */
21
+ export class GitSandbox {
22
+ readonly dir = mkdtempSync(join(tmpdir(), 'git-gateway-testkit-'));
23
+
24
+ constructor() {
25
+ writeFileSync(
26
+ join(this.dir, '.gitconfig'),
27
+ '[user]\n\tname = Conformance\n\temail = conformance@example.com\n[init]\n\tdefaultBranch = main\n',
28
+ );
29
+ }
30
+
31
+ /**
32
+ * Runs git in `cwd` (default the sandbox) with extra `-c` settings. Asynchronous, so an HTTP
33
+ * server in this process keeps answering while git talks to it.
34
+ */
35
+ async run(
36
+ args: readonly string[],
37
+ options: { cwd?: string; config?: readonly string[] } = {},
38
+ ): Promise<GitRun> {
39
+ const config = (options.config ?? []).flatMap((setting) => ['-c', setting]);
40
+ const child = spawn(gitBinary(), [...config, ...args], {
41
+ cwd: options.cwd ?? this.dir,
42
+ env: {
43
+ PATH: process.env['PATH'],
44
+ HOME: this.dir,
45
+ GIT_CONFIG_NOSYSTEM: '1',
46
+ GIT_CONFIG_GLOBAL: join(this.dir, '.gitconfig'),
47
+ GIT_TERMINAL_PROMPT: '0',
48
+ LC_ALL: 'C',
49
+ },
50
+ stdio: ['ignore', 'pipe', 'pipe'],
51
+ });
52
+ let stdout = '';
53
+ let stderr = '';
54
+ child.stdout.setEncoding('utf8').on('data', (chunk: string) => {
55
+ stdout += chunk;
56
+ });
57
+ child.stderr.setEncoding('utf8').on('data', (chunk: string) => {
58
+ stderr += chunk;
59
+ });
60
+ const status = await new Promise<number | null>((resolve, reject) => {
61
+ child.on('error', reject);
62
+ child.on('close', resolve);
63
+ });
64
+ return { status, stdout, stderr };
65
+ }
66
+
67
+ /** Runs git and returns trimmed stdout, failing on a non-zero exit. */
68
+ async ok(
69
+ args: readonly string[],
70
+ options: { cwd?: string; config?: readonly string[] } = {},
71
+ ): Promise<string> {
72
+ const result = await this.run(args, options);
73
+ if (result.status !== 0)
74
+ throw new Error(`git ${args.join(' ')} failed (${result.status}): ${result.stderr}`);
75
+ return result.stdout.trim();
76
+ }
77
+
78
+ /** A path inside the sandbox. */
79
+ path(...parts: string[]): string {
80
+ return join(this.dir, ...parts);
81
+ }
82
+
83
+ /** Removes the scratch directory. */
84
+ dispose(): void {
85
+ rmSync(this.dir, { recursive: true, force: true });
86
+ }
87
+ }