Skip to content

Instantly share code, notes, and snippets.

@JamesMGreene
Last active December 16, 2019 20:35
Show Gist options
  • Save JamesMGreene/b59d80350aebbc48820a7a18a997ddc0 to your computer and use it in GitHub Desktop.
Save JamesMGreene/b59d80350aebbc48820a7a18a997ddc0 to your computer and use it in GitHub Desktop.
Pseudo-JS code for creating a commit via the GitHub API from a Probot app
// Getting tree
const { data: baseTree } = await client.gitdata.getTree({
owner: login,
repo: repo,
tree_sha: sha,
recursive: 1
})
const baseSha = baseTree.sha
const baseEntriesByPath = baseTree.tree.reduce((entriesByPath, entry) => {
entriesByPath[entry.path] = entry
return entriesByPath
}, {})
// For each file you want to update, create Blobs
const updatedFilePath = 'README.md'
const updatedFileContent = 'foobar'
const { data: blobData } = await client.gitdata.createBlob({
owner: login,
repo: repo,
content: Buffer.from(updatedFileContent).toString('base64'),
encoding: 'base64'
})
// etc. etc.
// Creating tree changeset
const treeChangeset = []
const fileMode = baseEntriesByPath[updateFilePath] ? baseEntriesByPath[updateFilePath].mode : '100644'
treeChangeset.push({ path: updateFilePath, sha: blobData.sha, mode: fileMode })
// Creating tree
const { data: newTreeData } = await client.gitdata.createTree({
owner: login,
repo: repo,
tree: treeChangeset,
base_tree: baseSha
})
// Turn that tree into a commit
// Ensure you use the user's client to make them the author here, if desired
// But definitely make the bot the committer
const userClient = getUserClientMagically()
const { data: commitData } = await userClient.gitdata.createCommit({
owner: login,
repo: repo,
message: 'Automatic commit from MyAmazingProbotApp',
parents: [baseSha],
tree: newTreeData.sha || baseSha,
committer: {
name: 'MyAmazingProbotApp[bot]',
email: 'MyAmazingProbotApp[bot]@users.noreply.github.com'
}
})
// We've committed, update the HEAD
// Updating HEAD for the commit
await client.gitdata.updateRef({
owner: login,
repo: repo,
ref: `heads/myPrBranchName`,
sha: commitData.sha
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment