Replies: 1 comment
-
Ok this was super hard, you have to create a branch with the same name as the PR branch in the base repo, then add the same commit you want to add to the PR in this branch. You can then delete this temporary branch export async function pushToPr({
files,
branch,
auth,
owner,
repo,
}: {
auth: string
branch: string
files: { filePath: string; content: string }[]
owner: string
repo: string
}) {
const octokit = new Octokit({
auth,
})
const [currentCommit] = await Promise.all([
getCurrentCommit({ octokit: octokit.rest, owner, repo, branch }),
])
console.log(`last commit is ${currentCommit.commitSha}`)
const {
data: [pr],
} = await octokit.rest.repos.listPullRequestsAssociatedWithCommit({
commit_sha: currentCommit.commitSha,
owner,
repo,
})
let prUrl = pr?.html_url || ''
const base = pr?.base?.repo
let baseOwner = base?.owner?.login
let baseRepo = base?.name
const [withBlobs] = await Promise.all([
Promise.all(
files.map(async (x) => {
const encoding = 'utf-8'
const blobData = await octokit.rest.git.createBlob({
owner: baseOwner,
repo: baseRepo,
content: x.content,
encoding,
})
return {
...x,
blobSha: blobData.data.sha,
blob: blobData.data,
}
}),
),
])
console.log('creating new tree')
const { data: newTree } = await octokit.rest.git.createTree({
owner: baseOwner,
repo: baseRepo,
tree: withBlobs.map(({ blobSha, filePath }) => ({
path: filePath,
mode: `100644`,
type: `blob`,
sha: blobSha,
})),
base_tree: currentCommit.treeSha,
})
const commitMessage = `Update ${files
.map((x) => '`' + x.filePath + '`')
.join(', ')}`
console.log('creating commit')
const { data: newCommit } = await octokit.rest.git.createCommit({
owner: baseOwner,
repo: baseRepo,
message: commitMessage,
tree: newTree.sha,
committer: committer,
parents: [currentCommit.commitSha],
})
console.log(`updating ref`, branch)
await octokit.rest.git
.deleteRef({
owner: baseOwner,
repo: baseRepo,
ref: `heads/${branch}`,
sha: newCommit.sha,
})
.catch((e) => {
if (
e instanceof RequestError &&
e.message.toLowerCase().includes('does not exist')
) {
return {}
}
throw e
})
await octokit.rest.git.createRef({
owner: baseOwner,
repo: baseRepo,
ref: `refs/heads/${branch}`,
sha: newCommit.sha,
})
const {} = await octokit.rest.git.updateRef({
owner,
repo,
ref: `heads/${branch}`,
force: true, // or errors with Update is not a fast forward
sha: newCommit.sha,
})
octokit.rest.git
.deleteRef({
owner: baseOwner,
repo: baseRepo,
ref: `heads/${branch}`,
sha: newCommit.sha,
})
.catch((e) => null)
return { prUrl }
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am using the following code to push to a PR, but at the moment of
updateRef
i get the error422: Object does not exist
I didn't find any example showing this use case, what should i do?
Beta Was this translation helpful? Give feedback.
All reactions