| 1 | import fs from 'node:fs' |
| 2 | |
| 3 | export const commitViaApi = async ({ context, github, baseBranch, branchName, filePaths, message }) => { |
| 4 | const owner = context.repo.owner |
| 5 | const repo = context.repo.repo |
| 6 | const repositoryNameWithOwner = `${owner}/${repo}` |
| 7 | |
| 8 | // The GitHub API requires POSIX paths even on Windows runners. |
| 9 | const additions = filePaths.map((rawPath) => { |
| 10 | const path = rawPath.split('\\').join('/') |
| 11 | |
| 12 | return { |
| 13 | path, |
| 14 | contents: fs.readFileSync(rawPath).toString('base64'), |
| 15 | } |
| 16 | }) |
| 17 | |
| 18 | let expectedHeadOid |
| 19 | |
| 20 | try { |
| 21 | const { data } = await github.rest.git.getRef({ |
| 22 | owner, |
| 23 | repo, |
| 24 | ref: `heads/${branchName}`, |
| 25 | }) |
| 26 | |
| 27 | expectedHeadOid = data.object.sha |
| 28 | } catch (err) { |
| 29 | if (err.status !== 404) throw err |
| 30 | |
| 31 | const { data: baseRef } = await github.rest.git.getRef({ |
| 32 | owner, |
| 33 | repo, |
| 34 | ref: `heads/${baseBranch}`, |
| 35 | }) |
| 36 | |
| 37 | expectedHeadOid = baseRef.object.sha |
| 38 | |
| 39 | await github.rest.git.createRef({ |
| 40 | owner, |
| 41 | repo, |
| 42 | ref: `refs/heads/${branchName}`, |
| 43 | sha: expectedHeadOid, |
| 44 | }) |
| 45 | } |
| 46 | |
| 47 | const mutation = ` |
| 48 | mutation ($input: CreateCommitOnBranchInput!) { |
| 49 | createCommitOnBranch(input: $input) { |
| 50 | commit { oid url } |
| 51 | } |
| 52 | }` |
| 53 | |
| 54 | const { createCommitOnBranch } = await github.graphql(mutation, { |
| 55 | input: { |
| 56 | branch: { repositoryNameWithOwner, branchName }, |
| 57 | message: { headline: message }, |
| 58 | expectedHeadOid, |
| 59 | fileChanges: { additions }, |
| 60 | }, |