Julian Silden Langlo
Julian Silden Langlo

Reputation: 364

Is there a flag you can set in code that will prompt git to warn you before commiting code?

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

Upvotes: 1

Views: 310

Answers (1)

Thomas
Thomas

Reputation: 182000

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.

Upvotes: 3

Related Questions