// Upload pull-request screenshots and demo videos to Cap-go/pr-screenshots. // // bun scripts/upload-pr-screenshots.ts [file...] // // All files land in one commit under `capgo.app//`, so the // folder name is always the pull request that shows them. The script prints // URLs pinned to that commit SHA, ready to paste in the PR description. // It needs the GitHub CLI (`gh`) logged in with write access to the repo. import { spawnSync } from 'node:child_process' import { readFileSync, statSync } from 'node:fs' import { basename, extname } from 'node:path' import { argv, exit } from 'node:process' export const SCREENSHOT_REPO = 'Cap-go/pr-screenshots' export const SCREENSHOT_FOLDER = 'capgo.app' const BRANCH = 'main' const MAX_FILE_BYTES = 50 * 1024 * 1024 const UPDATE_ATTEMPTS = 3 const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg']) const OTHER_EXTENSIONS = new Set(['.mp4', '.mov', '.webm', '.pdf', '.html', '.md']) export interface UploadArgs { pr: number files: string[] } export function parseUploadArgs(args: string[]): UploadArgs { const [prArg, ...files] = args if (!prArg || !/^[1-9]\d*$/.test(prArg)) throw new Error('Usage: bun scripts/upload-pr-screenshots.ts [file...]') if (files.length === 0) throw new Error('Pass at least one file to upload.') const names = new Set() for (const file of files) { const extension = extname(file).toLowerCase() if (!IMAGE_EXTENSIONS.has(extension) && !OTHER_EXTENSIONS.has(extension)) throw new Error(`Unsupported file type: ${file}`) const name = basename(file) if (names.has(name)) throw new Error(`Two files are named ${name}. Rename one before uploading.`) names.add(name) } return { pr: Number(prArg), files } } export function screenshotPath(pr: number, file: string): string { return `${SCREENSHOT_FOLDER}/${pr}/${basename(file)}` } export function screenshotUrl(commitSha: string, path: string): string { // Encode each segment so names with spaces, `#` or `?` still resolve. const encodedPath = path.split('/').map(segment => encodeURIComponent(segment)).join('/') return `https://raw.githubusercontent.com/${SCREENSHOT_REPO}/${commitSha}/${encodedPath}` } export function embedMarkdown(file: string, url: string): string { const name = basename(file) return IMAGE_EXTENSIONS.has(extname(file).toLowerCase()) ? `![${name}](${url})` : `[${name}](${url})` } function gh(method: string, endpoint: string, body?: unknown): T { const result = spawnSync('gh', ['api', '-X', method, `repos/${SCREENSHOT_REPO}/${endpoint}`, ...(body ? ['--input', '-'] : [])], { encoding: 'utf8', input: body ? JSON.stringify(body) : undefined, maxBuffer: 256 * 1024 * 1024, }) if (result.status !== 0) throw new Error(`gh api ${method} ${endpoint} failed: ${result.stderr || result.stdout}`) return JSON.parse(result.stdout) as T } export function findExistingUploads(existingNames: string[], files: string[]): string[] { const existing = new Set(existingNames) return files.map(file => basename(file)).filter(name => existing.has(name)) } // Names already stored in capgo.app// at `ref`; an empty list when the folder does not exist yet. function existingNames(pr: number, ref: string): string[] { const result = spawnSync('gh', ['api', `repos/${SCREENSHOT_REPO}/contents/${SCREENSHOT_FOLDER}/${pr}?ref=${ref}`], { encoding: 'utf8' }) if (result.status !== 0) { if (/HTTP 404|Not Found/.test(`${result.stderr}${result.stdout}`)) return [] throw new Error(`Could not list ${SCREENSHOT_FOLDER}/${pr}: ${result.stderr || result.stdout}`) } return (JSON.parse(result.stdout) as Array<{ name: string }>).map(entry => entry.name) } function assertNoOverwrite(pr: number, ref: string, files: string[]) { const conflicts = findExistingUploads(existingNames(pr, ref), files) if (conflicts.length > 0) throw new Error(`${conflicts.join(', ')} already exist in ${SCREENSHOT_FOLDER}/${pr}/. Pull requests may embed them, so upload the new version under a new file name.`) } function upload({ pr, files }: UploadArgs): string { assertNoOverwrite(pr, BRANCH, files) const tree = files.map((file) => { const size = statSync(file).size if (size > MAX_FILE_BYTES) throw new Error(`${file} is larger than 50 MB. Compress it first.`) const blob = gh<{ sha: string }>('POST', 'git/blobs', { content: readFileSync(file, 'base64'), encoding: 'base64' }) return { path: screenshotPath(pr, file), mode: '100644', type: 'blob', sha: blob.sha } }) for (let attempt = 1; ; attempt++) { const head = gh<{ object: { sha: string } }>('GET', `git/ref/heads/${BRANCH}`).object.sha assertNoOverwrite(pr, head, files) const baseTree = gh<{ tree: { sha: string } }>('GET', `git/commits/${head}`).tree.sha const newTree = gh<{ sha: string }>('POST', 'git/trees', { base_tree: baseTree, tree }) const commit = gh<{ sha: string }>('POST', 'git/commits', { message: `capgo.app#${pr}: add ${files.map(file => basename(file)).join(', ')}`, tree: newTree.sha, parents: [head], }) try { gh('PATCH', `git/refs/heads/${BRANCH}`, { sha: commit.sha, force: false }) return commit.sha } catch (error) { // Another upload moved main between our read and write; rebuild on the new head. if (attempt >= UPDATE_ATTEMPTS) throw error } } } if (import.meta.main) { try { const args = parseUploadArgs(argv.slice(2)) const commitSha = upload(args) console.log(`Uploaded to https://github.com/${SCREENSHOT_REPO}/tree/${commitSha}/${SCREENSHOT_FOLDER}/${args.pr}\n`) for (const file of args.files) console.log(embedMarkdown(file, screenshotUrl(commitSha, screenshotPath(args.pr, file)))) } catch (error) { console.error(error instanceof Error ? error.message : error) exit(1) } }