30 lines · 1.8 KBRaw
| 1 | import { agentsSection } from "@refs/protocol"; |
| 2 | import { commitBody, gitObject, pushRef, treeBody } from "./gitwrite.ts"; |
| 3 | |
| 4 | const encoder = new TextEncoder(); |
| 5 | |
| 6 | /** The files a new repository starts with, so agents that open it know to work over the ref protocol. */ |
| 7 | export function starterFiles(input: { readonly repo: string; readonly name: string; readonly description: string; readonly origin: string; readonly branch: string }): { readonly path: string; readonly text: string }[] { |
| 8 | const agents = `# AGENTS.md\n\n${agentsSection(input)}`; |
| 9 | return [ |
| 10 | { path: "AGENTS.md", text: agents }, |
| 11 | { path: "CLAUDE.md", text: "@AGENTS.md\n" }, |
| 12 | { path: "README.md", text: `# ${input.name}\n${input.description ? `\n${input.description}\n` : ""}` }, |
| 13 | ]; |
| 14 | } |
| 15 | |
| 16 | /** Writes `files` as the first commit of the empty branch `branch`. Fails, without changing anything, when the branch already exists. */ |
| 17 | export async function writeFirstCommit( |
| 18 | handle: ArtifactsRepo, |
| 19 | branch: string, |
| 20 | files: readonly { readonly path: string; readonly text: string }[], |
| 21 | author: { readonly name: string; readonly email: string }, |
| 22 | at: number, |
| 23 | message: string, |
| 24 | ): Promise<{ ok: true; commit: string } | { ok: false; reason: string }> { |
| 25 | const blobs = await Promise.all(files.map(async (file) => ({ path: file.path, blob: await gitObject("blob", encoder.encode(file.text)) }))); |
| 26 | const tree = await gitObject("tree", treeBody(blobs.map(({ path, blob }) => ({ mode: "100644", name: path, hash: blob.hash })))); |
| 27 | const commit = await gitObject("commit", commitBody({ tree: tree.hash, parents: [], author, at, message })); |
| 28 | const pushed = await pushRef(handle, `refs/heads/${branch}`, "0".repeat(40), commit.hash, [...blobs.map(({ blob }) => blob), tree, commit]); |
| 29 | return pushed.ok ? { ok: true, commit: commit.hash } : pushed; |
| 30 | } |