Search code examples
pythongitpython

Gitpython to initialize and push a new repo


So I'm trying to use gitpython (https://gitpython.readthedocs.io/en/stable/intro.html) to do something relatively simple but having trouble.

So I've got a blank brand new repo on my bitbucket server, then I'm using gitpython to initialize a local repo, add a file, and commit successfully.

However, where I'm having trouble is pushing these changes to the brand new blank remote bitbucket repo I have. I've tried several things but I always get git push --set-upstream origin master as the error returned. But when I navigate to the the repo directory, I can see it's on the master branch, and I can see the remote repo URL when I run git status and git remote -v.

def commit_files(url):
    repo_dir = os.path.join(os.getcwd(), 'tmp')
    file_name = os.path.join(repo_dir, 'Jenkinsfile')

    repo = git.Repo.init(repo_dir)
    open(file_name, "wb").close()
    repo.index.add([file_name])
    repo.index.commit("initial commit")
    repo.create_remote("origin", url=url)
    repo.remote("origin").push()

All of the documentation and SO posts I've found only seem to go over pushing to an already existing repo after cloning it.


Solution

  • This one gave me a hard time too, since I tried the same as you, apparently:

    1. Create a new remote Git repository.

    2. Create a new local Git repository (not cloning the remote one).

    3. Add some changes to my local repository.

    4. Tried to push my changes to the remote repository.

    I finally found the reason in this to fail in the missing refspec between the local and remote repository:

    In the default case that is automatically written by a git remote add origin command, Git fetches all the references under refs/heads/ on the server and writes them to refs/remotes/origin/ locally.

    It can be solved by adding a refspec to the .push() method like this:

    repo.remote("origin").push('+refs/heads/*:refs/remotes/origin/*')
    

    This should be able to be avoided, but I could not figure out how; the author seems to prefer for people to apply a workaround than to answer the question on how to do this at Github Issue #549