Usage: `addFileToGit(foo.txt, "some file contents")`. Uses the "octokit" to add a single file to your gitub repo. Adapted from a Ruby guide by http://mattgreensmith.net
const Octokit = require('@octokit/rest'); // https://octokit.github.io/rest.js/ | |
// Customize this stuff: | |
const auth = 'your-key-generated-in-github-ui'; // PRIVATE! | |
const owner = 'repo-owner'; | |
const repo = 'your-repo-name'; | |
// Constants | |
const userAgent = 'git commiter v1'; | |
const ref = 'heads/master'; | |
const FILE = '100644'; // commit mode | |
const octokit = new Octokit({ auth, userAgent }); | |
// Create a single-file commit on top of head. | |
async function addFileToGit(path, content) { | |
// 1. Get the sha of the last commit | |
const { data: { object } } = await octokit.git.getRef({repo, owner, ref}); | |
const sha_latest_commit = object.sha; | |
// 2. Find and store the SHA for the tree object that the heads/master commit points to. | |
const { data: { tree }} = await octokit.git.getCommit({repo, owner, commit_sha: sha_latest_commit}) | |
const sha_base_tree = tree.sha; | |
// 3. Create some content | |
const { data: { sha: blob_sha } } = await octokit.git.createBlob({ | |
repo, | |
owner, | |
encoding: "utf-8", | |
content, | |
}); | |
// 4. Create a new tree with the content in place | |
const { data: new_tree } = await octokit.git.createTree({ | |
repo, | |
owner, | |
base_tree: sha_base_tree, // if we don't set this, all other files will show up as deleted. | |
tree: [ | |
{ | |
path, | |
mode: FILE, | |
type: 'blob', | |
sha: blob_sha, | |
} | |
], | |
}); | |
// 5. Create a new commit with this tree object | |
const { data: new_commit } = await octokit.git.createCommit({ | |
repo, | |
owner, | |
message: "addFileToGit.js scripted commit", | |
tree: new_tree.sha, | |
parents: [ | |
sha_latest_commit | |
], | |
}); | |
// 6. Move the reference to point at new commit. | |
const { data: { object: updated_ref } } = await octokit.git.updateRef({ | |
repo, | |
owner, | |
ref, | |
sha: new_commit.sha, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
This function makes it easy to write a string as a file to a git repo.