main
1// Pure pieces of the write API: request parsing, ident stamps, tree edits, the HEAD listing, the shared result.
2import { test } from 'node:test'
3import assert from 'node:assert/strict'
4import { execFileSync } from 'node:child_process'
5import { encodeTag, hashObject, ZERO_OID } from 'ply'
6import { unwrap } from '../src/ply-result.ts'
7import { MODE_BLOB } from '../src/write/constants.ts'
8import { type CallOpts } from '../src/write/call.ts'
9import { createBranch } from '../src/write/branch.ts'
10import { parseTime, stamp, nowSeconds } from '../src/write/identity.ts'
11import { createTag } from '../src/write/tag.ts'
12import { headFromListing } from '../src/write/head.ts'
13import { mapPickOutcome } from '../src/write/pick.ts'
14import { asBody, parseBase, parseEdit, refOrCommit } from '../src/write/request.ts'
15import { unifyPly, writeResult } from '../src/write/result.ts'
16import { emptyDir, encodeMem, fileLeaf, lookup, putAt, removeAt, renameAt, replaceOnce } from '../src/write/tree.ts'
18/** Null and a missing value take the fallback. An empty string and 0 stay. */
19function fill<T>(value: unknown, fallback: T): T {
20 return value === null || value === void 0 ? fallback : value as T
21}
23/** One property. A null receiver and a missing key are holes. A stored null stays null. */
24function slot(receiver: unknown, key: string): unknown {
25 if (receiver === null || receiver === void 0) return void 0
26 if (typeof receiver !== 'object' && typeof receiver !== 'function') return void 0
27 return (receiver as Record<string, unknown>)[key]
28}
31const EMPTY_BLOB = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391'
32const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
33const code = (fn: () => unknown) => {
34 try { fn() } catch (e) { return (e as Partial<{ code: string; message: string }>) }
35 return null
36}
37const errCode = (err: ReturnType<typeof code>): string => {
38 if (err === null) return ''
39 return typeof err.code === 'string' ? err.code : ''
40}
41const thrownCode = (err: unknown): string => {
42 if (err === null || typeof err !== 'object' || !('code' in err)) return ''
43 return typeof err.code === 'string' ? err.code : ''
44}
46test('parseBase rejects the zero oid and accepts a commit id or a branch', () => {
47 const missing: Record<string, unknown> = {}
48 assert.deepEqual(parseBase(missing.base), { kind: 'omit' })
49 assert.deepEqual(parseBase(null), { kind: 'omit' })
50 assert.deepEqual(parseBase(''), { kind: 'omit' })
51 assert.equal(parseBase('main').kind, 'ref')
52 const oid = 'a'.repeat(40)
53 assert.deepEqual(parseBase(oid), { kind: 'oid', oid })
54 const zero = code(() => parseBase('0'.repeat(40)))
55 assert.equal(slot(zero, 'code'), 'bad_request')
56 assert.match(fill(slot(zero, 'message'), ''), /omit base to create a root commit/)
57 assert.equal(ZERO_OID, '0'.repeat(40))
58})
60test('parseEdit: empty find creates, delete and rename, changes xor path', () => {
61 const now = nowSeconds()
62 const author = { name: 'w', email: 'w@x' }
63 const created = parseEdit(asBody({ path: 'a.txt', content: 'hi', author, message: 'm' }), now)
64 assert.deepEqual(created.changes, [{ kind: 'create', path: 'a.txt', content: 'hi', mode: MODE_BLOB }])
65 assert.equal(created.committer, null)
66 assert.equal(created.ref, null)
67 assert.equal(created.base.kind, 'omit')
68 const bareEdit = parseEdit(asBody({ path: 'a.txt', find: 'hi', author, message: 'm' }), now)
69 assert.deepEqual(bareEdit.changes, [{ kind: 'edit', path: 'a.txt', find: 'hi', replace: '' }])
70 const renamedFrom = parseEdit(asBody({ author, message: 'm', changes: [{ op: 'rename', from: 'a.txt', to: 'b.txt' }] }), now)
71 assert.deepEqual(renamedFrom.changes, [{ kind: 'rename', from: 'a.txt', to: 'b.txt' }])
72 const renamedPath = parseEdit(asBody({ author, message: 'm', changes: [{ op: 'rename', path: 'a.txt', from: 'c.txt', to: 'b.txt' }] }), now)
73 assert.deepEqual(renamedPath.changes, [{ kind: 'rename', from: 'a.txt', to: 'b.txt' }])
74 const bad = (body: Record<string, unknown>) => errCode(code(() => parseEdit(asBody(body), now)))
75 assert.equal(bad({ path: 'a.txt', delete: false, author, message: 'm' }), 'bad_request')
76 assert.equal(bad({ path: 'a.txt', find: null, author, message: 'm' }), 'bad_request')
77 assert.equal(bad({ path: 'a.txt', content: null, author, message: 'm' }), 'bad_request')
78 assert.equal(bad({ path: 'a.txt', content: 'hi', mode: '', author, message: 'm' }), 'bad_request')
79 assert.equal(bad({ path: 'a.txt', content: 'hi', author, committer: null, message: 'm' }), 'bad_request')
80 assert.equal(bad({ changes: null, author, message: 'm' }), 'bad_request')
81 assert.equal(bad({ author, message: 'm', changes: [{ op: 'rename', path: null, from: 'a.txt', to: 'b.txt' }] }), 'bad_request')
82 const edited = parseEdit(asBody({ path: 'a.txt', find: 'hi', replace: 'yo', author, message: 'm' }), now)
83 assert.equal(slot(edited.changes[0], 'kind'), 'edit')
84 const deleted = parseEdit(asBody({ path: 'a.txt', delete: true, author, message: 'm' }), now)
85 assert.deepEqual(deleted.changes, [{ kind: 'delete', path: 'a.txt' }])
86 const renamed = parseEdit(asBody({ path: 'a.txt', to: 'b.txt', author, message: 'm' }), now)
87 assert.deepEqual(renamed.changes, [{ kind: 'rename', from: 'a.txt', to: 'b.txt' }])
88 const many = parseEdit(asBody({ author, message: 'm', changes: [{ op: 'write', path: 'a.txt', content: 'z', mode: '100755' }] }), now)
89 assert.equal(slot(many.changes[0], 'kind'), 'write')
90 assert.equal(slot(code(() => parseEdit(asBody({ path: 'a', changes: [{ op: 'create', path: 'b' }], author, message: 'm' }), now)), 'code'), 'bad_request')
91})
93test('timezone offsets and unix seconds', () => {
94 const now = nowSeconds()
95 const india = stamp({ name: 'w', email: 'w@x', tz: '+0530', time: 1700000000 }, 'author', now)
96 assert.equal(india.line, 'w <w@x> 1700000000 +0530')
97 const west = stamp({ name: 'w', email: 'w@x', tz: '-1200', time: 1700000000 }, 'author', now)
98 assert.equal(west.tz, '-1200')
99 assert.equal(slot(code(() => stamp({ name: 'w', email: 'w@x', tz: '+9999' }, 'author', now)), 'code'), 'bad_request')
100 assert.equal(slot(code(() => stamp({ name: 'w', email: 'w@x', tz: '-1201' }, 'author', now)), 'code'), 'bad_request')
101 assert.equal(parseTime(0, 'time'), 0)
102 assert.equal(slot(code(() => parseTime(-1, 'time')), 'code'), 'bad_request')
103 const utc = stamp({ name: 'w', email: 'w@x', time: 1700000000 }, 'author', now)
104 assert.equal(utc.line, 'w <w@x> 1700000000 +0000')
105 const omitted = stamp({ name: 'w', email: 'w@x' }, 'author', now)
106 assert.equal(omitted.time, now)
107 assert.equal(omitted.tz, '+0000')
108 assert.equal(errCode(code(() => stamp({ name: 'w', email: 'w@x', time: null }, 'author', now))), 'bad_request')
109 assert.equal(errCode(code(() => stamp({ name: 'w', email: 'w@x', tz: null }, 'author', now))), 'bad_request')
110})
112test('tree edits prune empty directories and refuse a rename into itself', () => {
113 const leaf = fileLeaf(MODE_BLOB, EMPTY_BLOB)
114 let mem = putAt(emptyDir(), ['a.txt'], leaf, false, 'a.txt')
115 mem = putAt(mem, ['dir', 'b.txt'], leaf, false, 'dir/b.txt')
116 assert.equal(slot(code(() => putAt(mem, ['a.txt'], leaf, false, 'a.txt')), 'code'), 'bad_request')
117 mem = removeAt(mem, ['dir', 'b.txt'], 'dir/b.txt')
118 assert.equal(lookup(mem, ['dir']), null)
119 mem = putAt(mem, ['old.txt'], leaf, false, 'old.txt')
120 mem = renameAt(mem, ['old.txt'], ['new.txt'])
121 assert.equal(slot(lookup(mem, ['new.txt']), 'kind'), 'lazy')
122 assert.equal(slot(code(() => renameAt(mem, ['new.txt'], ['new.txt', 'x'])), 'code'), 'bad_request')
123 const built = encodeMem(emptyDir())
124 assert.equal(built.oid, EMPTY_TREE)
125 assert.equal(built.trees.length, 1)
126})
128test('replaceOnce counts every non-overlapping match and replaces exactly one', () => {
129 const enc = (s: string) => new TextEncoder().encode(s)
130 const many = replaceOnce(enc('ababa'), enc('a'), enc('c'))
131 assert.deepEqual(many, { kind: 'count', matches: 3 })
132 const none = replaceOnce(enc('zzz'), enc('a'), enc('c'))
133 assert.deepEqual(none, { kind: 'count', matches: 0 })
134 const one = replaceOnce(enc('abc'), enc('b'), enc('c'))
135 assert.equal(one.kind, 'replaced')
136 if (one.kind === 'replaced') assert.equal(new TextDecoder().decode(one.data), 'acc')
137})
139test('HEAD listing: unborn, born, detached, absent', () => {
140 const oid = 'a'.repeat(40)
141 assert.deepEqual(headFromListing({ refs: new Map(), head: null, unborn: { target: 'refs/heads/main' } }), { kind: 'unborn', ref: 'refs/heads/main' })
142 const bornRefs = new Map([['HEAD', { oid }]])
143 assert.deepEqual(headFromListing({ refs: bornRefs, head: 'refs/heads/main', unborn: null }), { kind: 'born', ref: 'refs/heads/main', oid })
144 // an unborn line wins even if a HEAD ref is also listed
145 assert.equal(headFromListing({ refs: bornRefs, head: 'refs/heads/main', unborn: { target: 'refs/heads/trunk' } }).kind, 'unborn')
146 assert.deepEqual(headFromListing({ refs: new Map([['HEAD', { oid }]]), head: null, unborn: null }), { kind: 'detached', oid })
147 assert.deepEqual(headFromListing({ refs: new Map(), head: null, unborn: null }), { kind: 'absent' })
148})
150test('a bad branch from, tag message, or annotated flag is rejected before a transport', async () => {
151 const opts = {} as CallOpts
152 const remote = 'https://example.invalid/repo'
153 const from = await createBranch(remote, 'main', 1, opts).then(() => null, (err: unknown) => err)
154 assert.equal(thrownCode(from), 'bad_request')
155 const zero = await createBranch(remote, 'main', '0'.repeat(40), opts).then(() => null, (err: unknown) => err)
156 assert.equal(thrownCode(zero), 'bad_request')
157 const tagger = { name: 'w', email: 'w@x' }
158 const message = await createTag(remote, { name: 'v1', target: 'main', message: 1, tagger }, opts).then(() => null, (err: unknown) => err)
159 assert.equal(thrownCode(message), 'bad_request')
160 const flag = await createTag(remote, { name: 'v1', target: 'main', annotated: 'yes' }, opts).then(() => null, (err: unknown) => err)
161 assert.equal(thrownCode(flag), 'bad_request')
162 const nullMessage = await createTag(remote, { name: 'v1', target: 'main', message: null }, opts).then(() => null, (err: unknown) => err)
163 assert.equal(thrownCode(nullMessage), 'bad_request')
164})
166test('refOrCommit accepts a branch or a 40-hex commit and rejects zero', () => {
167 assert.equal(refOrCommit('main', 'from'), 'refs/heads/main')
168 const oid = 'b'.repeat(40)
169 assert.equal(refOrCommit(oid, 'onto'), oid)
170 assert.equal(slot(code(() => refOrCommit('0'.repeat(40), 'from')), 'code'), 'bad_request')
171 assert.equal(slot(code(() => refOrCommit('', 'from')), 'code'), 'bad_request')
172})
174test('cherry-pick outcomes map exhaustively: empty, ok, kept_empty, and nothing else', () => {
175 const ref = 'refs/heads/main'
176 const oid = 'c'.repeat(40)
177 const onto = 'd'.repeat(40)
178 assert.deepEqual(mapPickOutcome({ outcome: 'empty', ref, oid }, false), { kind: 'empty', ref, oid })
179 assert.deepEqual(mapPickOutcome({ outcome: 'ok', ref, oid, tree: 't', onto, pushBytes: 12 }, false), {
180 kind: 'applied', name: 'cherry_pick', ref, oid, oldOid: onto, tree: 't', pushBytes: 12,
181 })
182 assert.deepEqual(mapPickOutcome({ outcome: 'kept_empty', ref, oid, tree: 't', onto, pushBytes: 12 }, false), {
183 kind: 'applied', name: 'cherry_pick', ref, oid, oldOid: onto, tree: 't', pushBytes: 12,
184 })
185 const reverted = mapPickOutcome({ outcome: 'kept_empty', ref, oid, tree: 't', onto, pushBytes: 12 }, true)
186 assert.equal(reverted.kind, 'applied')
187 if (reverted.kind === 'applied') {
188 assert.equal(reverted.name, 'revert')
189 assert.equal(reverted.oldOid, onto)
190 }
191 assert.deepEqual(mapPickOutcome({ outcome: 'ok', ref, oid }, false), {
192 kind: 'applied', name: 'cherry_pick', ref, oid, oldOid: null, tree: null, pushBytes: 0,
193 })
194 assert.deepEqual(mapPickOutcome({ outcome: 'ok', ref, oid, onto: null, tree: null, pushBytes: 0 }, false), {
195 kind: 'applied', name: 'cherry_pick', ref, oid, oldOid: null, tree: null, pushBytes: 0,
196 })
197 assert.deepEqual(mapPickOutcome({ outcome: 'empty', ref, oid, tree: 't', onto, pushBytes: 12 }, false), { kind: 'empty', ref, oid })
198 // A non-null non-string is kept. writeResult is what turns a non-string onto into null.
199 const numbered = mapPickOutcome({ outcome: 'ok', ref, oid, onto: 4, tree: 5, pushBytes: '12' }, false)
200 assert.equal(numbered.kind, 'applied')
201 if (numbered.kind === 'applied') {
202 assert.equal(numbered.oldOid, 4)
203 assert.equal(numbered.tree, 5)
204 assert.equal(numbered.pushBytes, '12')
205 }
206 assert.equal(slot(code(() => mapPickOutcome({ outcome: 'applied', ref, oid }, false)), 'code'), 'internal')
207})
209test('write results share oid aliases and empty outcomes are noops', () => {
210 const empty = writeResult('empty', 'refs/heads/main', 'abc', 'abc')
211 assert.equal(empty.noop, true)
212 assert.equal(empty.newCommit, 'abc')
213 assert.equal(empty.oldCommit, 'abc')
214 assert.equal(empty.onto, 'abc')
215 const created = writeResult('commit', 'refs/heads/main', 'abc', null)
216 assert.equal(created.oldOid, null)
217 assert.equal(created.onto, null)
218 assert.equal(created.noop, false)
219 const viaTheirs = writeResult('merge', 'refs/heads/main', 'abc', 'def', { onto: null, theirs: 'ghi' })
220 assert.equal(viaTheirs.onto, 'ghi')
221 assert.equal(viaTheirs.theirs, 'ghi')
222 assert.equal(writeResult('merge', 'refs/heads/main', 'abc', 'def', { onto: '' }).onto, '')
223 assert.equal(writeResult('merge', 'refs/heads/main', 'abc', 'def', { onto: 1, theirs: 'ghi' }).onto, null)
224 const folded = unifyPly({ newCommit: 'abc', oldCommit: 'def', tree: 'ttt', pushBytes: 4 }, 'commit', 'refs/heads/main')
225 assert.equal(folded.oid, 'abc')
226 assert.equal(folded.oldOid, 'def')
227 assert.equal(folded.newCommit, 'abc')
228 assert.equal(folded.oldCommit, 'def')
229 assert.equal(folded.onto, 'def')
230 assert.equal(folded.outcome, 'commit')
231 assert.equal(folded.tree, 'ttt')
232 assert.equal(folded.pushBytes, 4)
233 assert.equal(folded.noop, false)
234 const ranked = unifyPly({
235 oid: null, newCommit: 'abc',
236 oldCommit: null, ours: null, oldTip: 'def',
237 onto: null, theirs: 'ghi',
238 tree: null, newTree: 'ttt',
239 pushBytes: null,
240 }, 'merge', 'refs/heads/main')
241 assert.equal(ranked.oid, 'abc')
242 assert.equal(ranked.oldOid, 'def')
243 assert.equal(ranked.onto, 'ghi')
244 assert.equal(ranked.tree, 'ttt')
245 assert.equal(ranked.pushBytes, 0)
246 const preferred = unifyPly({ oid: 'aaa', newCommit: 'bbb', oldCommit: 'ccc', ours: 'ddd', onto: 'eee', theirs: 'fff', pushBytes: 0 }, 'commit', 'refs/heads/main')
247 assert.equal(preferred.oid, 'aaa')
248 assert.equal(preferred.oldOid, 'ccc')
249 assert.equal(preferred.onto, 'eee')
250 assert.equal(preferred.pushBytes, 0)
251 assert.equal(unifyPly({ oid: 'abc', oldCommit: 'def', noop: false }, 'empty', 'refs/heads/main').noop, false)
252 assert.equal(unifyPly({ oid: 'abc', oldCommit: 'def' }, 'empty', 'refs/heads/main').noop, true)
253})
255test('annotated tag bytes hash the way git hash-object does', () => {
256 const object = 'a'.repeat(40)
257 const tagger = 'w <w@x> 1700000000 +0530'
258 const data = unwrap(encodeTag({ object, type: 'commit', tag: 'v2', tagger, message: 'version two\n' }))
259 const oid = hashObject('tag', data) as string
260 const gitOid = execFileSync('git', ['hash-object', '-t', 'tag', '--stdin'], { input: data }).toString().trim()
261 assert.equal(oid, gitOid)
262})
Diagnostics4 git calls · 164 ms
CallStatusSizeTime0164 ms
discover200152 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200145 B133 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=133 git.response.bytes=145 git.response.cache=EXPIRED git.response.duration_ms=133 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=145 git.pkt.payload.max=76 git.ls_refs.count=2 git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020040 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=41349 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=526b305930b8ef382f2d7a1f9c0238730a585921 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=6 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=41349 git.pkt.payload.max=41254 git.sideband.band1.bytes=41253 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=61 git.pack.bytes=41253 git.pack.ofs_delta=0 git.pack.ref_delta=0 git.pack.chain.max=0 git.pack.trailer=ab60efef4b7243678c75de64a4386986ee885c1c git.pack.full=61Open pack map
fetch2003.7 KiB · hit27 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=27 git.response.bytes=3757 git.response.cache=HIT git.response.duration_ms=27 git.fetch.wants=f1624c8eb8715505d2c27437319d3caef48685e5 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=3757 git.pkt.payload.max=3736 git.sideband.band1.bytes=3735 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply-web.git
- Ref
- refs/heads/main
- Commit
- 526b305930b8ef382f2d7a1f9c0238730a585921
- cf-ray
- a5e275dbbcaad806
- Request
- 491d9100…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format