Commiting a new file to git, through the github api
Recently I have been working on an application that basically has a github bot (aka user) fork a repo, commit some files, and submit a PR against someone’s repo. When it came down to actually making a new git commit through the github API, I had quite a hard time. I figured it out with some help from a ruby tutorial, and now I’m going to show you how to do it.
Before we start, we need 2 things.
- Install the Octokit nuget package.
- Get a credential token
- You can get a token for a logged in user via oauth for .net
- Or you can get a token for yourself (personal access token) by going to settings=>personal access tokens at github
Ok so I’m going to walk you through the code…don’t want to wait? scroll to the bottom (or click here).
The first thing we need our user to do is create our github client object.
Then we should fork our target repo
Afterwards we need to get the last commit for the default branch. You can replace fork.DefaultBranch with an actual branch name if you wish.
Now we need to make the data, and the commit.
This line creates the content of the file you wish to add (note the Content property)
…and this line puts it into OurNewFile.md in a new tree (which I honestly don’t know much about)
Then we actually make the commit
Now we have to update our fork with our new commit
Then submit the PR!!!!