user14406060
user14406060

Reputation:

Force git to reject commits with specific content

Is it possible to add a comment to my code so GIT refuses to commit it?

The reason is that sometimes I'm working on two different strategies for fixing a problem, e.g. two different classes. Then it would be nice if could add a comment somewhere in the class like // DONT COMMIT so that I don't accidentally commit two parallel classes.

Upvotes: 4

Views: 1224

Answers (2)

axiac
axiac

Reputation: 72226

A simple pre-commit hook that does the job:

#!/usr/bin/env bash


# The text that refuses the commit
# Change it to match your needs; keep it enclosed in single quotes
MARKER='// DONT COMMIT'


# Verify the staged files for the presence of the marker text
if git diff --cached --name-only | xargs grep -q "$MARKER"; then
  echo 'Cannot commit because the "no-commit" marker has been found in one of the staged files.' 1>&2
  # Refuse to commit
  exit 1
fi

Put it into the file .git/hooks/pre-commit in your project and make the file executable (chmod +x .git/hooks/pre-commit).

It is just a stub and probably does not work as expected in all situations. Expand it to match your needs.

You can tell Git to skip the hooks by passing the option -n (or --no-verify) in the git commit command line.

Upvotes: 6

jabberwocky
jabberwocky

Reputation: 1055

I don't know how you could do that.... But I think you could get similar functionality other ways.

  1. Add a separate version of your .py file that you add to your .gitignore (git ignores every file listed here.) When testing things out you can import this trial class from the new .py
  2. Use git for this. If your trialling a new feature why not make a new branch for what you are testing: git checkout -b trying_new_class_definition

This let's you swap your two definitions by just swapping branch.

If you make updates to the main codebase you may need to rebase these onto your trial branch: git checkout trying_new_class_definition

git rebase master

Upvotes: 1

Related Questions