13

How to prevent git from pushing commits that contain given string in commit massage, e.g. "DO NOT PUSH" ?

Context/usecase:

My typical workflow is: I hack hack, splitting work into micro commits, once things work I rewrite history, changing order of commit to group them reasonably and later squashing into bigger meaningful pieces. Once work is ready, things are ready to push!

Now I would like git to prevent me from accidentally pushing into repository commits that are still in progress. I considered keeping "DO NOT PUSH" as part of commit message. How to make git automatically prevent me from pushing when it reaches such commit after git push?

(On for pre-receive hook solutions: let's consider github as example service, which AFAIK does not allow pre-recevie hooks, except in its "Enterprise" edition)

5
  • Wouldn't git stash do the job for you? Commented Feb 5, 2017 at 8:22
  • Is there anything missing from the answer? Commented Feb 5, 2017 at 9:29
  • * I have multiple branches of multiple draft micro commits and I work on them : test them, compare them etc. * git rebase -i is thing that turns out to work best for me. Once I reach desired shape, I edit and squash commits. Commented Feb 5, 2017 at 9:30
  • And why a pre-push is not appropriate? Commented Feb 5, 2017 at 10:07
  • Just needed time to take closer look again :) Thanks! Commented Feb 6, 2017 at 0:13

1 Answer 1

10

You can use a pre-push hook, but that remains a local hook which can be bypassed.
See this pre-push example which does look at each commit message

# Check for foo commit
        commit=`git rev-list -n 1 --grep '^foo' "$range"`
        if [ -n "$commit" ]
        then
echo "ERROR: git pre-push hook found commit message starting with 'foo' in $local_ref"

But the best way remains a pre-receive hook on the server side though. That way, the policy is enforced for all contributors. This is not always possible (when you don't have direct access to the remote server like GitHub, BitBucket or GitLab.com)

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

2 Comments

@Leon Sure, added.
As mentioned above, this is the correct answer but the validation must be on the server side as well. Any developer can disable the local hooks so you must verify it on the server. The only thing that you need to verify is that the answer use -n 1 which will only check the last commit so you need to do it on all of your commits since user may push several commits at once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.