Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GitHub v3 API - how do I create the initial commit in a repository?

I'm using the v3 API and managed to list repos/trees/branches, access file contents, and create blobs/trees/commits. I'm now trying to create a new repo, and managed to do it with "POST user/repos"

But when I try to create blobs/trees/commits/references in this new repo I get the same error message. (409) "Git Repository is empty.". Obviously I can go and init the repository myself through the git command line, but would rather like if my application did it for me.

Is there a way to do that? What's the first thing I need to do through the API after I create an empty repository?

Thanks

like image 313
Rui Viana Avatar asked May 28 '12 20:05

Rui Viana


1 Answers

If you want to create an empty initial commit (i.e. one without any file) you can do the following:

  1. Create the repository using the auto_init option as in Jai Pandya's answer; or, if the repository already exists, use the create file endpoint to create a dummy file - this will create the branch:
PUT https://api.github.com/repos/USER/REPO/contents/dummy

{
  "branch": "master",
  "message": "Create a dummy file for the sake of creating a branch",
  "content": "ZHVtbXk="
}

This will give you a bunch of data including a commit SHA, but you can discard all of it since we are about to obliterate that commit.

  1. Use the create commit endpoint to create a commit that points to the empty tree:
POST https://api.github.com/repos/USER/REPO/git/commits

{
  "message": "Initial commit",
  "tree": "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
}

This time you need to take note of the returned commit SHA.

  1. Use the update reference endpoint to make the branch point to the commit you just created (notice the Use Of The ForceTM):
PATCH https://api.github.com/repos/USER/REPO/git/refs/heads/master

{
    "sha": "<the SHA of the commit>",
    "force": true
}
  1. Done! Your repository has now one branch, one commit and zero files.
like image 133
Konamiman Avatar answered Oct 13 '22 15:10

Konamiman