pygit2
pygit2 copied to clipboard
_pygit2.GitError: reference 'refs/heads/master' not found
import pygit2
from github import Github
github_username = "user"
github_password = "password"
github_email = "email"
# login to github and
authenticated_github_user = Github(github_username, github_password)
user = authenticated_github_user.get_user()
is_org: bool = False
# create the new repository
if is_org:
org = authenticated_github_user.get_organization('someorg')
repo = org.create_repo('projectname', description='somedescription')
else:
repo = user.create_repo('testrepo_github_api', description='this is a test')
# clone the repository
repoClone = pygit2.clone_repository(repo.git_url, '/tmp/test_clone')
#create some new files in the repo
repo.create_file("README.md", "init commit", 'readmeText')
# Commit it
repoClone.remotes.set_url("origin", repo.clone_url)
index = repoClone.index
index.add_all()
index.write()
author = pygit2.Signature("Jesus Christ", github_email)
commiter = pygit2.Signature("Jesus Christ", github_email)
tree = index.write_tree()
oid = repoClone.create_commit('refs/heads/master', author, commiter, "init commit", tree, [repoClone.head.get_object().hex])
remote = repoClone.remotes["origin"]
credentials = pygit2.UserPass(github_username, github_password)
remote.credentials = credentials
callbacks = pygit2.RemoteCallbacks(credentials=credentials)
remote.push(['refs/heads/master'], callbacks=callbacks)
This results in
oid = repoClone.create_commit('HEAD', author, commiter, "init commit", tree, [repoClone.head.get_object().hex])
_pygit2.GitError: reference 'refs/heads/master' not found
git show-ref
is empty, but this is pretty much expected, no?
This commit and push still go through, but the error is nevertheless thrown.
Am I doing something wrong?
@Zethson
Didn't look at the GitHub API but it seems like you create a repo but do not initialize it. Thus, there is no master branch yet.
What happens if you use regular git
on commandline after you created the GitHub Repo?
I was able to reproduce this error with a new repository that has zero commits as @omniproc mentioned. The offending line of code is repoClone.head.get_object()
I think what's happening is that its looking at .git/HEAD
file, which for a new repo has ref: refs/heads/master
, and its trying to read .git/refs/heads/master
file to get the commit sha1 and failing since the file does not exist. Hence, _pygit2.GitError: reference 'refs/heads/master' not found
What I don't get is how did it complete execution successfully?!
This commit and push still go through, but the error is nevertheless thrown.
It should throw an exception and stop execution!
IMHO, what you're seeing is the expected behavior and consider it a user error where the head object wasn't checked. I'd confirm that it did not create the commit in the provided example and close this issue. Which didn't happen in my test case.
Any way to validate before crashing?