How can I use the Github API to push an empty commit

Viewed 104

I want to be able to create an initialize the main branch of a repository without it having any files in it through the Github API. Normally this would be done like so with git:

git init
git remote add origin <url>
git commit --allow-empty
git push origin main

However with the Github API I am able to easily create the repository but I am unable to commit an empty commit to it. Using the empty tree and committing that only causes the Github API to say that the repository is empty, and then do nothing. Ideally I would like to not have to create a dummy file and then delete it, but that appears to be the only way currently. Please let me know if there is any way to create an empty commit without the use of a dummy file.

tl;dr: Is there any ways to emulate git's --allow-empty commit using the Github API?

1 Answers

There is no native way to include an --allow-empty option.

As documented in "GitHub v3 API - how do I create the initial commit in a repository?", you can use the create commit endpoint to create a commit that points to the empty tree, after having created a dummy file.

The update reference endpoint can then make the branch point to the commit you just created.

curl \
  -X PATCH \
  -H "Accept: application/vnd.github+json" \ 
  -H "Authorization: token <TOKEN>" \
  https://api.github.com/repos/OWNER/REPO/git/refs/main \
  -d '{"sha":"aa218f56b14c9653891f9e74264a383fa43fefbd","force":true}'

With aa218f56b14c9653891f9e74264a383fa43fefbd the SHA of the empty commit created before.

Related