Skip to content

Instantly share code, notes, and snippets.

@cantidio
Last active April 13, 2018 21:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cantidio/1a1204fdf96eb3ba02ff to your computer and use it in GitHub Desktop.
Save cantidio/1a1204fdf96eb3ba02ff to your computer and use it in GitHub Desktop.
github api commit creation

HOW to CREATE a commit using github API

1. Get the Reference of the branch you want to commit to and store the SHA for the latest commit (SHA-LATEST-COMMIT)

https://developer.github.com/v3/git/refs/#get-a-reference

  const res = getReference( BRANCH );
  const baseCommitSHA = res.object.sha;
2. Get the sha of the tree

https://developer.github.com/v3/git/commits/#get-a-commit

  const res = getCommit(baseCommitSHA);
  const baseTreeSHA = res.tree.sha;
3. Create a new Tree Data:

https://developer.github.com/v3/git/trees/#create-a-tree

  //Method 1
  const dataEncoding = 'base64';
  const fileContent = new Buffer(fs.readFileSync(filePath)).toString(dataEncoding),
  const res = createBlob({
    content: fileContent,
    encoding: dataEncoding
  });
  const fileSHA = res.sha;

**At this point you should use in the treeData the field sha **

  • If you don't have larger files or binaries: Just read the file contents and encode them in utf-8.
//Method 2
const fileContent = new Buffer(fs.readFileSync(filePath)).toString('utf-8'),

**At this point you should use in the treeData the field content **

Create your tree JSON:

// Using method 1
const treeData = [
  {
    path: "file.js",
    mode: "100644",
    type: "blob",
    sha: fileSHA
  },
];
// Using method 2
const treeData = [
  {
    path: "file.js",
    mode: "100644",
    type: "blob",
    content: fileContent
  },
];

Finally create the new tree and Store it's sha

//If you want to delete a file in this commit, you should not use the base_tree, every entry not sent = deleted file.
//If you don't want to delete any file, use the tree_base = baseTreeSHA
const res = createTree({
  base_tree: baseTreeSHA,
  tree: treeData
});
const treeSHA = res.sha;
4. Create a commit with your new tree and Store it's sha

https://developer.github.com/v3/git/commits/#create-a-commit

const res = createCommit({
  message: 'my commit message',
  tree: treeSHA,
  parents: [baseCommitSHA]
});
const commitSHA = res.sha;
5. Update the reference of your branch

https://developer.github.com/v3/git/refs/

  updateReference({
    sha: commitSHA
  });
6. Celebrate!

If everything have gone right at this time you should have a another commit with your changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment