Gitpython git push does not raise exception when failing to push

Viewed 685

This seems to be a known issue, however I'm looking for a workaround. Anyone know of a good workaround?

https://github.com/gitpython-developers/GitPython/issues/621

(Pdb) test = self.repo.remotes.origin.push(refspec=self.base_branch, progress=None, force=False)
2020-07-18 12:06:55,744|WARNING|guest|Error lines received while fetching: error: failed to push some refs to 'git@github.com:test/test.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
(Pdb)```
2 Answers

Since GitPython v3.1.25 you can call raise_if_error() on the object returned by push() to raise an exception if the push fails. In your example this would be:

self.repo.remotes.origin.push(refspec=self.base_branch, progress=None, force=False).raise_if_error()

If your push has succeeded, your local reference to origin/branch should be on the same commit as branch.

You can use that as a workaround.


The only case where this wouldn't work is : if you triggered git push while your local branch was at the same point as your local reference to origin/branch, while branch was updated on the actual remote.

That is : if you push without having committed anything new on the branch.
To be 100% sure : you can check before the push if branch is at origin/branch, and act accordingly (do not push ?).

Related