Renaming files using the GitHub api

Owen Bodley
2 min readNov 23, 2016

--

We support file renaming in Obehave’s online editor. The editor is backed by various storage services, one of which is GitHub. When we implemented file renaming, it wasn’t immediately obvious how to use GitHub’s (fantastic!) api to do this.

Please excuse the directness of this post, I almost didn’t write it, but I figured that it might just help some poor developer get the job done. If something isn’t clear, please comment below and I’ll do my best to help.

Renaming a file in a single commit requires a few steps. If you don’t mind making 2 commits, then it is simpler to delete the file and then create it again using a new name. If however you do just want to make a single commit, here are the steps:

1. Get the current branch

https://developer.github.com/v3/repos/branches/#get-branch

GET 
https://api.github.com/repos/:owner/:repo/branches/:branch
Headers
"Authorization" : "token <your-token>"

Note the sha from the response object for steps 2 and 4 below.

2. Get the current tree

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

GET 
https://api.github.com/repos/:owner/:repo/git/trees/:sha
Headers
"Authorization" : "token <your-token>"

Copy the response json and find the file you want to rename. Take note of the file’s path, mode, type and sha. You will need each of these in step 3 below.

3. Create a new tree

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

POST
https://api.github.com/repos/:owner/:repo/git/trees?recursive=1
Headers
"Authorization" : "token <your-token>"
"Content-type" : "application/json"
Body
{
// The sha of the tree from step 2 (above).
"base_tree":"",
// An array with a single object
// (or multiple objects if you need to rename multiple files).
"tree" : [
{
// Your new file name.
"path" : "",
// The mode from step 2 (above).
"mode" : "",
// The type from step 2 (above).
"type" : "",
// The sha from step 2 (above).
"sha" : ""
}
]
}

Retrieve the sha from the response object for step 4 below.

4. Create a commit for the new tree

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

POST
https://api.github.com/repos/:owner/:repo/git/commits
Headers
"Authorization" : "token <your-token>"
"Content-type" : "application/json"
Body
{
// A helpful commit message.
"message" : "",
// The sha from step 3 (above).
"tree" : "",
// An array with a single string; the sha from step 1 (above).
"parents" : [""]
}

Save the commit sha from the response object for step 5 (below).

5. Point your branch at the new commit

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

PATCH
https://api.github.com/repos/:owner/:repo/git/refs/heads/:branch
Headers
"Authorization" : "token <your-token>"
"Content-type" : "application/json"
Body
{
// The sha from step 4 (above).
"sha" : ""
}

--

--

Owen Bodley

Mechanical engineer turned software geek. I get a kick out of making stuff that delights & also bikes, boats, black coffee and red wine.