// Pure pieces of the write API: request parsing, ident stamps, tree edits, the HEAD listing, the shared result. import { test } from 'node:test' import assert from 'node:assert/strict' import { execFileSync } from 'node:child_process' import { encodeTag, hashObject, ZERO_OID } from 'ply' import { unwrap } from '../src/ply-result.ts' import { MODE_BLOB } from '../src/write/constants.ts' import { type CallOpts } from '../src/write/call.ts' import { createBranch } from '../src/write/branch.ts' import { parseTime, stamp, nowSeconds } from '../src/write/identity.ts' import { createTag } from '../src/write/tag.ts' import { headFromListing } from '../src/write/head.ts' import { mapPickOutcome } from '../src/write/pick.ts' import { asBody, parseBase, parseEdit, refOrCommit } from '../src/write/request.ts' import { unifyPly, writeResult } from '../src/write/result.ts' import { emptyDir, encodeMem, fileLeaf, lookup, putAt, removeAt, renameAt, replaceOnce } from '../src/write/tree.ts' /** Null and a missing value take the fallback. An empty string and 0 stay. */ function fill(value: unknown, fallback: T): T { return value === null || value === void 0 ? fallback : value as T } /** One property. A null receiver and a missing key are holes. A stored null stays null. */ function slot(receiver: unknown, key: string): unknown { if (receiver === null || receiver === void 0) return void 0 if (typeof receiver !== 'object' && typeof receiver !== 'function') return void 0 return (receiver as Record)[key] } const EMPTY_BLOB = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391' const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904' const code = (fn: () => unknown) => { try { fn() } catch (e) { return (e as Partial<{ code: string; message: string }>) } return null } const errCode = (err: ReturnType): string => { if (err === null) return '' return typeof err.code === 'string' ? err.code : '' } const thrownCode = (err: unknown): string => { if (err === null || typeof err !== 'object' || !('code' in err)) return '' return typeof err.code === 'string' ? err.code : '' } test('parseBase rejects the zero oid and accepts a commit id or a branch', () => { const missing: Record = {} assert.deepEqual(parseBase(missing.base), { kind: 'omit' }) assert.deepEqual(parseBase(null), { kind: 'omit' }) assert.deepEqual(parseBase(''), { kind: 'omit' }) assert.equal(parseBase('main').kind, 'ref') const oid = 'a'.repeat(40) assert.deepEqual(parseBase(oid), { kind: 'oid', oid }) const zero = code(() => parseBase('0'.repeat(40))) assert.equal(slot(zero, 'code'), 'bad_request') assert.match(fill(slot(zero, 'message'), ''), /omit base to create a root commit/) assert.equal(ZERO_OID, '0'.repeat(40)) }) test('parseEdit: empty find creates, delete and rename, changes xor path', () => { const now = nowSeconds() const author = { name: 'w', email: 'w@x' } const created = parseEdit(asBody({ path: 'a.txt', content: 'hi', author, message: 'm' }), now) assert.deepEqual(created.changes, [{ kind: 'create', path: 'a.txt', content: 'hi', mode: MODE_BLOB }]) assert.equal(created.committer, null) assert.equal(created.ref, null) assert.equal(created.base.kind, 'omit') const bareEdit = parseEdit(asBody({ path: 'a.txt', find: 'hi', author, message: 'm' }), now) assert.deepEqual(bareEdit.changes, [{ kind: 'edit', path: 'a.txt', find: 'hi', replace: '' }]) const renamedFrom = parseEdit(asBody({ author, message: 'm', changes: [{ op: 'rename', from: 'a.txt', to: 'b.txt' }] }), now) assert.deepEqual(renamedFrom.changes, [{ kind: 'rename', from: 'a.txt', to: 'b.txt' }]) const renamedPath = parseEdit(asBody({ author, message: 'm', changes: [{ op: 'rename', path: 'a.txt', from: 'c.txt', to: 'b.txt' }] }), now) assert.deepEqual(renamedPath.changes, [{ kind: 'rename', from: 'a.txt', to: 'b.txt' }]) const bad = (body: Record) => errCode(code(() => parseEdit(asBody(body), now))) assert.equal(bad({ path: 'a.txt', delete: false, author, message: 'm' }), 'bad_request') assert.equal(bad({ path: 'a.txt', find: null, author, message: 'm' }), 'bad_request') assert.equal(bad({ path: 'a.txt', content: null, author, message: 'm' }), 'bad_request') assert.equal(bad({ path: 'a.txt', content: 'hi', mode: '', author, message: 'm' }), 'bad_request') assert.equal(bad({ path: 'a.txt', content: 'hi', author, committer: null, message: 'm' }), 'bad_request') assert.equal(bad({ changes: null, author, message: 'm' }), 'bad_request') assert.equal(bad({ author, message: 'm', changes: [{ op: 'rename', path: null, from: 'a.txt', to: 'b.txt' }] }), 'bad_request') const edited = parseEdit(asBody({ path: 'a.txt', find: 'hi', replace: 'yo', author, message: 'm' }), now) assert.equal(slot(edited.changes[0], 'kind'), 'edit') const deleted = parseEdit(asBody({ path: 'a.txt', delete: true, author, message: 'm' }), now) assert.deepEqual(deleted.changes, [{ kind: 'delete', path: 'a.txt' }]) const renamed = parseEdit(asBody({ path: 'a.txt', to: 'b.txt', author, message: 'm' }), now) assert.deepEqual(renamed.changes, [{ kind: 'rename', from: 'a.txt', to: 'b.txt' }]) const many = parseEdit(asBody({ author, message: 'm', changes: [{ op: 'write', path: 'a.txt', content: 'z', mode: '100755' }] }), now) assert.equal(slot(many.changes[0], 'kind'), 'write') assert.equal(slot(code(() => parseEdit(asBody({ path: 'a', changes: [{ op: 'create', path: 'b' }], author, message: 'm' }), now)), 'code'), 'bad_request') }) test('timezone offsets and unix seconds', () => { const now = nowSeconds() const india = stamp({ name: 'w', email: 'w@x', tz: '+0530', time: 1700000000 }, 'author', now) assert.equal(india.line, 'w 1700000000 +0530') const west = stamp({ name: 'w', email: 'w@x', tz: '-1200', time: 1700000000 }, 'author', now) assert.equal(west.tz, '-1200') assert.equal(slot(code(() => stamp({ name: 'w', email: 'w@x', tz: '+9999' }, 'author', now)), 'code'), 'bad_request') assert.equal(slot(code(() => stamp({ name: 'w', email: 'w@x', tz: '-1201' }, 'author', now)), 'code'), 'bad_request') assert.equal(parseTime(0, 'time'), 0) assert.equal(slot(code(() => parseTime(-1, 'time')), 'code'), 'bad_request') const utc = stamp({ name: 'w', email: 'w@x', time: 1700000000 }, 'author', now) assert.equal(utc.line, 'w 1700000000 +0000') const omitted = stamp({ name: 'w', email: 'w@x' }, 'author', now) assert.equal(omitted.time, now) assert.equal(omitted.tz, '+0000') assert.equal(errCode(code(() => stamp({ name: 'w', email: 'w@x', time: null }, 'author', now))), 'bad_request') assert.equal(errCode(code(() => stamp({ name: 'w', email: 'w@x', tz: null }, 'author', now))), 'bad_request') }) test('tree edits prune empty directories and refuse a rename into itself', () => { const leaf = fileLeaf(MODE_BLOB, EMPTY_BLOB) let mem = putAt(emptyDir(), ['a.txt'], leaf, false, 'a.txt') mem = putAt(mem, ['dir', 'b.txt'], leaf, false, 'dir/b.txt') assert.equal(slot(code(() => putAt(mem, ['a.txt'], leaf, false, 'a.txt')), 'code'), 'bad_request') mem = removeAt(mem, ['dir', 'b.txt'], 'dir/b.txt') assert.equal(lookup(mem, ['dir']), null) mem = putAt(mem, ['old.txt'], leaf, false, 'old.txt') mem = renameAt(mem, ['old.txt'], ['new.txt']) assert.equal(slot(lookup(mem, ['new.txt']), 'kind'), 'lazy') assert.equal(slot(code(() => renameAt(mem, ['new.txt'], ['new.txt', 'x'])), 'code'), 'bad_request') const built = encodeMem(emptyDir()) assert.equal(built.oid, EMPTY_TREE) assert.equal(built.trees.length, 1) }) test('replaceOnce counts every non-overlapping match and replaces exactly one', () => { const enc = (s: string) => new TextEncoder().encode(s) const many = replaceOnce(enc('ababa'), enc('a'), enc('c')) assert.deepEqual(many, { kind: 'count', matches: 3 }) const none = replaceOnce(enc('zzz'), enc('a'), enc('c')) assert.deepEqual(none, { kind: 'count', matches: 0 }) const one = replaceOnce(enc('abc'), enc('b'), enc('c')) assert.equal(one.kind, 'replaced') if (one.kind === 'replaced') assert.equal(new TextDecoder().decode(one.data), 'acc') }) test('HEAD listing: unborn, born, detached, absent', () => { const oid = 'a'.repeat(40) assert.deepEqual(headFromListing({ refs: new Map(), head: null, unborn: { target: 'refs/heads/main' } }), { kind: 'unborn', ref: 'refs/heads/main' }) const bornRefs = new Map([['HEAD', { oid }]]) assert.deepEqual(headFromListing({ refs: bornRefs, head: 'refs/heads/main', unborn: null }), { kind: 'born', ref: 'refs/heads/main', oid }) // an unborn line wins even if a HEAD ref is also listed assert.equal(headFromListing({ refs: bornRefs, head: 'refs/heads/main', unborn: { target: 'refs/heads/trunk' } }).kind, 'unborn') assert.deepEqual(headFromListing({ refs: new Map([['HEAD', { oid }]]), head: null, unborn: null }), { kind: 'detached', oid }) assert.deepEqual(headFromListing({ refs: new Map(), head: null, unborn: null }), { kind: 'absent' }) }) test('a bad branch from, tag message, or annotated flag is rejected before a transport', async () => { const opts = {} as CallOpts const remote = 'https://example.invalid/repo' const from = await createBranch(remote, 'main', 1, opts).then(() => null, (err: unknown) => err) assert.equal(thrownCode(from), 'bad_request') const zero = await createBranch(remote, 'main', '0'.repeat(40), opts).then(() => null, (err: unknown) => err) assert.equal(thrownCode(zero), 'bad_request') const tagger = { name: 'w', email: 'w@x' } const message = await createTag(remote, { name: 'v1', target: 'main', message: 1, tagger }, opts).then(() => null, (err: unknown) => err) assert.equal(thrownCode(message), 'bad_request') const flag = await createTag(remote, { name: 'v1', target: 'main', annotated: 'yes' }, opts).then(() => null, (err: unknown) => err) assert.equal(thrownCode(flag), 'bad_request') const nullMessage = await createTag(remote, { name: 'v1', target: 'main', message: null }, opts).then(() => null, (err: unknown) => err) assert.equal(thrownCode(nullMessage), 'bad_request') }) test('refOrCommit accepts a branch or a 40-hex commit and rejects zero', () => { assert.equal(refOrCommit('main', 'from'), 'refs/heads/main') const oid = 'b'.repeat(40) assert.equal(refOrCommit(oid, 'onto'), oid) assert.equal(slot(code(() => refOrCommit('0'.repeat(40), 'from')), 'code'), 'bad_request') assert.equal(slot(code(() => refOrCommit('', 'from')), 'code'), 'bad_request') }) test('cherry-pick outcomes map exhaustively: empty, ok, kept_empty, and nothing else', () => { const ref = 'refs/heads/main' const oid = 'c'.repeat(40) const onto = 'd'.repeat(40) assert.deepEqual(mapPickOutcome({ outcome: 'empty', ref, oid }, false), { kind: 'empty', ref, oid }) assert.deepEqual(mapPickOutcome({ outcome: 'ok', ref, oid, tree: 't', onto, pushBytes: 12 }, false), { kind: 'applied', name: 'cherry_pick', ref, oid, oldOid: onto, tree: 't', pushBytes: 12, }) assert.deepEqual(mapPickOutcome({ outcome: 'kept_empty', ref, oid, tree: 't', onto, pushBytes: 12 }, false), { kind: 'applied', name: 'cherry_pick', ref, oid, oldOid: onto, tree: 't', pushBytes: 12, }) const reverted = mapPickOutcome({ outcome: 'kept_empty', ref, oid, tree: 't', onto, pushBytes: 12 }, true) assert.equal(reverted.kind, 'applied') if (reverted.kind === 'applied') { assert.equal(reverted.name, 'revert') assert.equal(reverted.oldOid, onto) } assert.deepEqual(mapPickOutcome({ outcome: 'ok', ref, oid }, false), { kind: 'applied', name: 'cherry_pick', ref, oid, oldOid: null, tree: null, pushBytes: 0, }) assert.deepEqual(mapPickOutcome({ outcome: 'ok', ref, oid, onto: null, tree: null, pushBytes: 0 }, false), { kind: 'applied', name: 'cherry_pick', ref, oid, oldOid: null, tree: null, pushBytes: 0, }) assert.deepEqual(mapPickOutcome({ outcome: 'empty', ref, oid, tree: 't', onto, pushBytes: 12 }, false), { kind: 'empty', ref, oid }) // A non-null non-string is kept. writeResult is what turns a non-string onto into null. const numbered = mapPickOutcome({ outcome: 'ok', ref, oid, onto: 4, tree: 5, pushBytes: '12' }, false) assert.equal(numbered.kind, 'applied') if (numbered.kind === 'applied') { assert.equal(numbered.oldOid, 4) assert.equal(numbered.tree, 5) assert.equal(numbered.pushBytes, '12') } assert.equal(slot(code(() => mapPickOutcome({ outcome: 'applied', ref, oid }, false)), 'code'), 'internal') }) test('write results share oid aliases and empty outcomes are noops', () => { const empty = writeResult('empty', 'refs/heads/main', 'abc', 'abc') assert.equal(empty.noop, true) assert.equal(empty.newCommit, 'abc') assert.equal(empty.oldCommit, 'abc') assert.equal(empty.onto, 'abc') const created = writeResult('commit', 'refs/heads/main', 'abc', null) assert.equal(created.oldOid, null) assert.equal(created.onto, null) assert.equal(created.noop, false) const viaTheirs = writeResult('merge', 'refs/heads/main', 'abc', 'def', { onto: null, theirs: 'ghi' }) assert.equal(viaTheirs.onto, 'ghi') assert.equal(viaTheirs.theirs, 'ghi') assert.equal(writeResult('merge', 'refs/heads/main', 'abc', 'def', { onto: '' }).onto, '') assert.equal(writeResult('merge', 'refs/heads/main', 'abc', 'def', { onto: 1, theirs: 'ghi' }).onto, null) const folded = unifyPly({ newCommit: 'abc', oldCommit: 'def', tree: 'ttt', pushBytes: 4 }, 'commit', 'refs/heads/main') assert.equal(folded.oid, 'abc') assert.equal(folded.oldOid, 'def') assert.equal(folded.newCommit, 'abc') assert.equal(folded.oldCommit, 'def') assert.equal(folded.onto, 'def') assert.equal(folded.outcome, 'commit') assert.equal(folded.tree, 'ttt') assert.equal(folded.pushBytes, 4) assert.equal(folded.noop, false) const ranked = unifyPly({ oid: null, newCommit: 'abc', oldCommit: null, ours: null, oldTip: 'def', onto: null, theirs: 'ghi', tree: null, newTree: 'ttt', pushBytes: null, }, 'merge', 'refs/heads/main') assert.equal(ranked.oid, 'abc') assert.equal(ranked.oldOid, 'def') assert.equal(ranked.onto, 'ghi') assert.equal(ranked.tree, 'ttt') assert.equal(ranked.pushBytes, 0) const preferred = unifyPly({ oid: 'aaa', newCommit: 'bbb', oldCommit: 'ccc', ours: 'ddd', onto: 'eee', theirs: 'fff', pushBytes: 0 }, 'commit', 'refs/heads/main') assert.equal(preferred.oid, 'aaa') assert.equal(preferred.oldOid, 'ccc') assert.equal(preferred.onto, 'eee') assert.equal(preferred.pushBytes, 0) assert.equal(unifyPly({ oid: 'abc', oldCommit: 'def', noop: false }, 'empty', 'refs/heads/main').noop, false) assert.equal(unifyPly({ oid: 'abc', oldCommit: 'def' }, 'empty', 'refs/heads/main').noop, true) }) test('annotated tag bytes hash the way git hash-object does', () => { const object = 'a'.repeat(40) const tagger = 'w 1700000000 +0530' const data = unwrap(encodeTag({ object, type: 'commit', tag: 'v2', tagger, message: 'version two\n' })) const oid = hashObject('tag', data) as string const gitOid = execFileSync('git', ['hash-object', '-t', 'tag', '--stdin'], { input: data }).toString().trim() assert.equal(oid, gitOid) })