We are using a post-receive hook in Git to deploy a PHP "app". The script (Bash) checks the branch name and do a rsync on the correct server based on a prefix in the branch name.
This work pretty well, except for one thing: it tries to do a deployment when we delete a branch.
I checked at many places, and I didn't find a way to find out from the script if the operation is a delete.
Is there a way to achieve this. The script is on a bare repository (managed by Gitolite), it is not on the developers workstation.
What Happens If I Delete a Git Branch? When you delete a branch in Git, you don't delete the commits themselves. That's right: The commits are still there, and you might be able to recover them.
To delete a branch locally and push that change to the CodeCommit repository, use Git from a local repo connected to the CodeCommit repository. Deleting a branch does not delete any commits, but it does delete all references to the commits in that branch.
To fix this error, you can: Mark the master branch as unprotected (in settings > protected branches). Give yourself the permission to push (if you are not the administrator of the git repository, you will need to ask an administrator to permit you to push to the main branch).
The post-receive hook is a shell script that is executed when the push from the local machine has been received. We will write this script so that it deploys the files into required deployment directory ( ~/deploy-dir in this example). The post-receive file is located at this path: ~/bare-project.
When git receives a push, the post-receive
hook is invoked and passed data on stdin about each ref that was delivered, in rows of <old-sha> <new-sha> <ref-name>
, like so:
e1f5c274e296f1c5148161f9d4e5eb43a6743e54 1eea3f51cf926c3710f8fa4a06f503041c4597f0 refs/heads/master
When a branch is deleted, the <new-sha>
entry is all zeros, like so:
6b239c481453c7fc2513b02e8aa0cd9c1ffa25cb 0000000000000000000000000000000000000000 refs/heads/foo
So, you can adjust your post-receive
hook to detect this (and prevent this branch from triggering a deployment) using logic like:
#!/bin/sh -
while read OLDSHA NEWSHA REF ; do
if [ "$NEWSHA" = "0000000000000000000000000000000000000000" ]; then
# This ref has been deleted! Respond appropriately.
fi
done
Remember that a single push can contain update multiple branches, too! You'll probably want to accumulate a set of branches that should be deployed, that begin with the appropriate prefix and have a nonzero NEWSHA
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With