Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an initial commit using pygit2?

Tags:

git

python

pygit2

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.

like image 263
Connor Fuhrman Avatar asked Jun 11 '26 12:06

Connor Fuhrman


1 Answers

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", "[email protected]")
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:

  • https://gist.github.com/lig/dc1ede7e09488a62116fe90aa31617d9
  • https://gist.github.com/metatoaster/6026706
  • Create, Clone, and Push to GitHub repo using PyGitHub and PyGit2
like image 123
Connor Fuhrman Avatar answered Jun 13 '26 00:06

Connor Fuhrman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!