(repo: string, localPath: string, mediaPath: string)
| 288 | |
| 289 | /** Commit a file to the media branch via the git database API; returns its raw URL. */ |
| 290 | const upload = (repo: string, localPath: string, mediaPath: string): string => { |
| 291 | const bytes = readFileSync(localPath); |
| 292 | const request = join(tmpdir(), `pr-media-blob-${process.pid}.json`); |
| 293 | writeFileSync(request, JSON.stringify({ content: bytes.toString("base64"), encoding: "base64" })); |
| 294 | const blob = ghJson([`repos/${repo}/git/blobs`, "--method", "POST", "--input", request]) as { |
| 295 | sha: string; |
| 296 | }; |
| 297 | |
| 298 | // Tip of the media branch, if it exists — the branch is orphan on first use. |
| 299 | let parent: { commit: string; tree: string } | undefined; |
| 300 | try { |
| 301 | const ref = ghJson([`repos/${repo}/git/ref/heads/${MEDIA_BRANCH}`]) as { |
| 302 | object: { sha: string }; |
| 303 | }; |
| 304 | const commit = ghJson([`repos/${repo}/git/commits/${ref.object.sha}`]) as { |
| 305 | tree: { sha: string }; |
| 306 | }; |
| 307 | parent = { commit: ref.object.sha, tree: commit.tree.sha }; |
| 308 | } catch { |
| 309 | parent = undefined; |
| 310 | } |
| 311 | |
| 312 | writeFileSync( |
| 313 | request, |
| 314 | JSON.stringify({ |
| 315 | ...(parent ? { base_tree: parent.tree } : {}), |
| 316 | tree: [{ path: mediaPath, mode: "100644", type: "blob", sha: blob.sha }], |
| 317 | }), |
| 318 | ); |
| 319 | const tree = ghJson([`repos/${repo}/git/trees`, "--method", "POST", "--input", request]) as { |
| 320 | sha: string; |
| 321 | }; |
| 322 | writeFileSync( |
| 323 | request, |
| 324 | JSON.stringify({ |
| 325 | message: `Add ${mediaPath}`, |
| 326 | tree: tree.sha, |
| 327 | parents: parent ? [parent.commit] : [], |
| 328 | }), |
| 329 | ); |
| 330 | const commit = ghJson([`repos/${repo}/git/commits`, "--method", "POST", "--input", request]) as { |
| 331 | sha: string; |
| 332 | }; |
| 333 | writeFileSync( |
| 334 | request, |
| 335 | parent |
| 336 | ? JSON.stringify({ sha: commit.sha }) |
| 337 | : JSON.stringify({ ref: `refs/heads/${MEDIA_BRANCH}`, sha: commit.sha }), |
| 338 | ); |
| 339 | ghJson( |
| 340 | parent |
| 341 | ? [`repos/${repo}/git/refs/heads/${MEDIA_BRANCH}`, "--method", "PATCH", "--input", request] |
| 342 | : [`repos/${repo}/git/refs`, "--method", "POST", "--input", request], |
| 343 | ); |
| 344 | return `https://raw.githubusercontent.com/${repo}/${MEDIA_BRANCH}/${mediaPath}`; |
| 345 | }; |
| 346 | |
| 347 | const inputs = process.argv.slice(2); |
no test coverage detected