2

Using the pygit2 package how do you create an initial commit on a new repository?

I keep getting an error message that "refs/heads/master" isn't found.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Connor Fuhrman
  • 781
  • 6
  • 15
  • Why would this be different from creating any other commit? – mkrieger1 Jan 25 '22 at 02:09
  • @mkrieger1 Don't know. Just posting in case it helps someone else in the future. I've never used `pygit2` only done, e.g., `git init && git add . && git commit -am "Initial commit"`. I kept getting an error message that "refs/heads/master" wasn't found and this was my solution – Connor Fuhrman Jan 25 '22 at 02:12

1 Answers1

1

For some context I'm working on a Python module created from the current spaghetti code I use to manage a GitLab instance to post and grade assignments for a university course. Work can be found here. My application requires that I download a repository as a "template" assignment to post for all students so I need to use the same file tree with a new git repository for all students in my course (hence the need to create initial commits over and over again).

The trick here, which I could not find documented anywhere (pygit2's documentation seems to be lacking as of this posting), is to set the first argument to create_commit to "HEAD" rather than, e.g., "refs/heads/master" as in the example. Perhaps this is obvious to the git wizards out there but it took me a second to realize.

import pygit2 as git

template_proj_location = "/file/path/to/the/template"
# 'proj' is a python-gitlab object for the GitLab project this repo needs to get pushed to

repo = git.init_repository(template_proj_location, initial_head='master', origin = proj.ssh_url_to_repo)
(index := repo.index).add_all()
index.write()
tree = index.write_tree()
me = git.Signature("My Name", "myemail@email.domain.edu")
repo.create_commit("HEAD", me, me, "commit msg", tree, [])

# Now to push the repo to the new location
_, ref = repo.resolve_refish(refish=repo.head.name)
remote = repo.remotes["origin"]
remote.push([ref.name], callbacks = my_func_to_get_RemoteCallbacks_obj_for_ssh_auth)

I used the following as references:

Connor Fuhrman
  • 781
  • 6
  • 15
  • If this is sub-optimal please chime in. I have approx. 3 hours experience with `pygit2` and am just posting here since I could not find mention of `"HEAD"` as above anywhere else. – Connor Fuhrman Jan 25 '22 at 02:14
  • @mkrieger1 Remote repo shows `master` branch as expected. I don't think it's in the detached HEAD state but [I don't know enough to dispute](https://imgur.com/YQi3ZFz). It got the job done for me – Connor Fuhrman Jan 25 '22 at 02:15