0

A lot of times I write quick scaffolding code with hardcoded strings and other bad behaviour. But I don't want to commit these into git. So I'm wondering whether there are any flags I can set in the code that will let git stop me? Something like <git-warn>, <git-don't-commit-this>.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • You can write a pre-commit hook which can run a script and check for certain "things" in code and reject the commit based on that. – Croolman Mar 02 '20 at 09:38
  • 1
    See https://stackoverflow.com/a/14282199/6330106 and https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks. Both methods could work. – ElpieKay Mar 02 '20 at 09:39

1 Answers1

2

You can use a git pre-commit hook for this. Here is an example that uses the text NOCOMMIT or DO NOT COMMIT (with or without spaces) to block commits:

#!/usr/bin/env bash

# Configure your list of trigger words here, as a Perl-compatible regular expression.
FORBIDDEN_WORDS_REGEX='NOCOMMIT|DO *NOT *COMMIT'

# Abort on unexpected errors.
set -e

# Redirect all output to stderr.
exec 1>&2

# Use color only if stderr is connected to a terminal.
if [[ -t 2 ]]; then
  color=always
  red="\e[31;1m"
  normal="\e[0;0m"
else
  color=never
fi

# Loop over all files in the cache.
for changed_file in "$(git diff --cached --name-only)"; do
  # Dump the file from the index and search inside it for forbidden words. Each
  # matching line is printed, prefixed with the file name and line number.
  if git show ":$changed_file" | \
     grep --binary-files=without-match \
          --with-filename \
          --line-number \
          --label="$changed_file" \
          --color=$color \
          --perl-regexp \
          "$FORBIDDEN_WORDS_REGEX"
  then
    echo -e "${red}Forbidden words found matching regexp \"$FORBIDDEN_WORDS_REGEX\". Aborting commit.${normal}"
    exit 1
  fi
done

Note that pre-commit hooks must be installed in every working copy separately.

Thomas
  • 174,939
  • 50
  • 355
  • 478