git push to remote, but don't create new branch

485 views Asked by At

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

There are 2 answers

0
onionjake On BEST ANSWER

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.

1
adao7000 On

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).