3

Is there a way to git push, but, if the branch doesn't exist in the remote, throw an error or exit non-zero instead of creating a new branch on the server?

The use case is the following. I am creating scripts to help automate the scm workflow in my company. If someone accidentally mistypes a branch name as input into the script, I don't want a new branch created on the remote. I already can manually check remote branch existence, but I wondered if git supports this feature.

2
  • Why don't you rename the misspelled branch and delete push again, and then delete the old one? Commented Jun 17, 2015 at 13:46
  • I don't want any decisions made by the script. I don't want the script to decide that you meant to have a different branch name or a branch deleted. If the assumptions of the script are invalid, I want it to simply abort Commented Jun 17, 2015 at 19:04

2 Answers 2

2

No, there is currently not a way to do this with a single call to git-push.


Possible workarounds:

Existence of a remote branch can be checked like this:

#!/bin/bash if ! git ls-remote --exit-code $remote /refs/heads/$branch then echo >&2 "Error: Remote branch does not exist" exit 1 fi exit 0 

Which could be included in a pre-push hook as well if desired. Something like this (place in .git/hooks/pre-push):

#!/bin/sh remote="$1" url="$2" while read local_ref local_sha remote_ref remote_sha do if ! git ls-remote --exit-code $url $remote_ref then echo >&2 "Remote branch does not exist, not pushing" exit 1 fi done exit 0 

Which will cause the desired behavior:

$ git push origin master:branch_that_does_not_exist Remote branch does not exist, not pushing error: failed to push some refs to '[email protected]:some/repository.git' 

If you have access to the server you can also create a pre-recieve hook to reject creation of new branches.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to change the settings on push.default in git config. Check out the git config documentation to configure it exactly like how you want it (defaults for branching, pushing, etc).

1 Comment

Unfortunately this doesn't work for me since I will be providing multiple branch refspecs in the same push and don't need to checkout multiple branches, one after another, to take advantage of push.default

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.