main
ply4 git calls29 ms43 KiB3 cachedprotocol v2
181 lines8.1 KiBRaw
1import { readFile, writeFile } from 'node:fs/promises'
2import { PIN, planBump, pinSpec } from './bump-plan.ts'
3import { ROOT } from './cf.ts'
4import { fetchOriginMain, originMainReason } from './preflight.ts'
5import { errorMessage, run } from './proc.ts'
6import { fail, pass, type StageResult } from './result.ts'
7import type { CdConfig } from './config.ts'
9const INSTEAD = ['ssh://git@github.com/', 'git+ssh://git@github.com/', 'git@github.com:']
10const INSTEAD_KEY = 'url.https://github.com/.insteadof'
12export type BumpValue = {
13 readonly sha: string
14 readonly from: string | null
15 readonly committed: boolean
16 readonly branch: string | null
19async function git(args: readonly string[], cwd = ROOT): Promise<{ code: number; stdout: string; stderr: string }> {
20 return run('git', args, { cwd })
23export async function readPlyPin(): Promise<string | null> {
24 try {
25 const pkg = JSON.parse(await readFile(`${ROOT}/package.json`, 'utf8')) as { dependencies?: { ply?: string } }
26 return PIN.exec(pkg.dependencies?.ply ?? '')?.[1] ?? null
27 } catch {
28 return null
29 }
32export async function resolvePlySha(sha: string | null): Promise<string> {
33 if (sha) return sha
34 const remote = await git(['ls-remote', 'https://github.com/ivarvong/ply.git', 'refs/heads/main'])
35 if (remote.code !== 0) throw new Error(`git ls-remote failed: ${remote.stderr.slice(0, 300)}`)
36 const resolved = remote.stdout.trim().split(/\s+/)[0] ?? ''
37 if (!/^[0-9a-f]{40}$/.test(resolved)) throw new Error('git ls-remote did not return a ply main sha')
38 return resolved
41async function ensureHttps(): Promise<() => Promise<void>> {
42 const current = await git(['config', '--local', '--get-all', INSTEAD_KEY])
43 const have = new Set((current.code === 0 ? current.stdout : '').split('\n').map(line => line.trim()).filter(Boolean))
44 const added: string[] = []
45 for (const value of INSTEAD) {
46 if (have.has(value)) continue
47 const set = await git(['config', '--local', '--add', INSTEAD_KEY, value])
48 if (set.code !== 0) throw new Error(`git config insteadOf failed: ${set.stderr.slice(0, 300)}`)
49 added.push(value)
50 }
51 return async () => {
52 for (const value of added) await git(['config', '--local', '--unset', INSTEAD_KEY, value])
53 }
56async function restorePinFiles(): Promise<void> {
57 await git(['checkout', '--', 'package.json', 'package-lock.json'])
60function bumpFail(reason: string) {
61 return fail('bump', reason, false, 'harness_fault')
64async function returnTo(branch: string, head: string): Promise<string | null> {
65 const target = branch || head
66 if (!target) return null
67 const back = await git(['checkout', target])
68 return back.code === 0 ? null : (back.stderr || back.stdout).trim().slice(0, 300)
71/** Commit the pin onto `branch`, whose parent is `base` (origin/main), not the checkout we started on. */
72async function commitOnMain(branch: string, base: string, sha: string, spec: string, from: string): Promise<StageResult<BumpValue>> {
73 const current = await git(['branch', '--show-current'])
74 const startedBranch = current.stdout.trim()
75 const started = await git(['rev-parse', 'HEAD'])
76 const startedHead = started.stdout.trim()
77 const onBump = startedBranch === branch
78 const name = await git(['config', 'user.name'])
79 const email = await git(['config', 'user.email'])
80 if (name.code !== 0 || !name.stdout.trim() || email.code !== 0 || !email.stdout.trim()) {
81 return bumpFail( 'git user.name and user.email must be set')
82 }
83 if (onBump) {
84 const reset = await git(['reset', '--hard', base])
85 if (reset.code !== 0) return bumpFail( `could not reset ${branch} onto origin/main: ${reset.stderr.slice(0, 300)}`)
86 } else {
87 const detached = await git(['checkout', '--detach', base])
88 if (detached.code !== 0) return bumpFail( `could not detach at origin/main: ${detached.stderr.slice(0, 300)}`)
89 }
90 let failure: string | null = null
91 let removeHttps: (() => Promise<void>) | null = null
92 try {
93 const pkgText = await readFile(`${ROOT}/package.json`, 'utf8')
94 if (!pkgText.includes(spec)) failure = 'dependencies.ply text was not found in package.json'
95 if (!failure) await writeFile(`${ROOT}/package.json`, pkgText.replace(spec, pinSpec(sha)))
96 if (!failure) removeHttps = await ensureHttps()
97 if (!failure) {
98 const installed = await run('npm', ['install'], { cwd: ROOT })
99 if (installed.code !== 0) failure = `npm install failed: ${installed.stderr.slice(0, 400)}`
100 }
101 if (!failure) {
102 const lock = JSON.parse(await readFile(`${ROOT}/package-lock.json`, 'utf8')) as {
103 packages?: { 'node_modules/ply'?: { resolved?: string } }
104 }
105 const resolved = lock.packages?.['node_modules/ply']?.resolved ?? ''
106 if (!resolved.endsWith(`#${sha}`)) failure = 'package-lock.json did not record the ply pin'
107 }
108 if (!failure) {
109 const gateEnv = {
110 ...process.env,
111 GIT_AUTHOR_NAME: process.env.GIT_AUTHOR_NAME || 'ply-web',
112 GIT_AUTHOR_EMAIL: process.env.GIT_AUTHOR_EMAIL || 'ply-web@example.com',
113 GIT_COMMITTER_NAME: process.env.GIT_COMMITTER_NAME || process.env.GIT_AUTHOR_NAME || 'ply-web',
114 GIT_COMMITTER_EMAIL: process.env.GIT_COMMITTER_EMAIL || process.env.GIT_AUTHOR_EMAIL || 'ply-web@example.com',
115 }
116 for (const [cmd, args] of [
117 ['npm', ['run', 'typecheck']],
118 ['npx', ['oxlint']],
119 ['npm', ['test']],
120 ] as const) {
121 const gate = await run(cmd, args, { cwd: ROOT, env: gateEnv })
122 if (gate.code !== 0) {
123 failure = `${cmd} ${args.join(' ')} failed: ${gate.stderr.slice(-400) || gate.stdout.slice(-400)}`
124 break
125 }
126 }
127 }
128 if (!failure) {
129 const added = await git(['add', 'package.json', 'package-lock.json'])
130 if (added.code !== 0) failure = `git add failed: ${added.stderr.slice(0, 300)}`
131 }
132 if (!failure) {
133 const committed = await git(['commit', '-m', `Pin ply to ${sha}.`])
134 if (committed.code !== 0) failure = `git commit failed: ${committed.stderr.slice(0, 300)}`
135 }
136 } catch (error) {
137 failure = errorMessage(error)
138 } finally {
139 if (removeHttps) await removeHttps()
140 }
141 if (failure) {
142 await restorePinFiles()
143 if (!onBump) {
144 const back = await returnTo(startedBranch, startedHead)
145 if (back) failure = `${failure}; also could not return to the previous checkout: ${back}`
146 }
147 return bumpFail( failure)
148 }
149 if (!onBump) {
150 const forced = await git(['branch', '-f', branch, 'HEAD'])
151 if (forced.code !== 0) {
152 const back = await returnTo(startedBranch, startedHead)
153 const reason = `could not point ${branch} at the pin commit: ${forced.stderr.slice(0, 300)}`
154 return bumpFail( back ? `${reason}; also could not return to the previous checkout: ${back}` : reason)
155 }
156 const onto = await git(['checkout', branch])
157 if (onto.code !== 0) return bumpFail( `pin is committed but checkout ${branch} failed: ${onto.stderr.slice(0, 300)}`)
158 }
159 return pass('bump', { sha, from, committed: true, branch })
162export async function stageBump(config: CdConfig, shaArg: string | null): Promise<StageResult<BumpValue>> {
163 try {
164 const sha = await resolvePlySha(shaArg ?? config.sha)
165 const dirty = await git(['status', '--porcelain', '--untracked-files=no'])
166 if (dirty.code !== 0) return bumpFail( `git status failed: ${dirty.stderr.slice(0, 300)}`)
167 if (dirty.stdout.trim()) return bumpFail( 'tracked files are modified; bump wants a clean tree')
168 const base = await fetchOriginMain(ROOT)
169 if (!base.ok) return bumpFail( originMainReason(base))
170 const shown = await git(['show', `${base.sha}:package.json`])
171 if (shown.code !== 0) return bumpFail( 'origin/main has no package.json')
172 const spec = (JSON.parse(shown.stdout) as { dependencies?: { ply?: string } }).dependencies?.ply
173 if (typeof spec !== 'string') return bumpFail( 'package.json has no dependencies.ply')
174 const plan = planBump(spec, sha)
175 if (plan.kind === 'invalid') return bumpFail( plan.reason)
176 if (plan.kind === 'unchanged') return pass('bump', { sha, from: null, committed: false, branch: null })
177 return await commitOnMain(config.bumpBranch, base.sha, sha, spec, plan.from)
178 } catch (error) {
179 return bumpFail( errorMessage(error))
180 }
Diagnostics4 git calls · 29 ms
CallStatusSizeTime029 ms
discover200152 B2 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
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 B · hit2 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
git.response.bytes=145
git.response.cache=HIT
git.response.duration_ms=2
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 · hit3 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=3
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=61
Open pack map
fetch2002.6 KiB · hit24 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=24
git.response.bytes=2681
git.response.cache=HIT
git.response.duration_ms=24
git.fetch.wants=c18c6b0af824dadc25e26c22d7a6c813485d031a
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=2681
git.pkt.payload.max=2660
git.sideband.band1.bytes=2659
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
a5e30e80c9688a31
Request
fabe04d0…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format