sourcegraph/dev/forbidcommit.sh
Jean-Hadrien Chabran ded610d887
chore(local): add FORBIDCOMMIT pragma to prevent accidental commits (#63581)
@chrsmith suggested this idea, which I like very much as well. 

Pretty straightforward: 

- if you're adding something you really don't want to commit and suspect
your future self to forget about it, you can add `FORBIDCOMMIT` anywhere
in your changes, and precommit will prevent you from accidentally
committing it.
  - check is case insensitive.

I went for this instead of `NOCOMMIT` because it could be legitimately
be used for a var with the number of commits for example. And that's not
really something we want to add a pragma to disable the string itself
for either.


## Test plan

![CleanShot 2024-07-01 at 19 44
31@2x](https://github.com/sourcegraph/sourcegraph/assets/10151/3ff3420e-4012-4018-a1e3-42ae2fb53cb4)
2024-07-01 18:27:26 +00:00

33 lines
999 B
Bash
Executable File

#!/usr/bin/env bash
set -eu
# Select the files to inspect. We don't want to list files which are deleted, as it makes no sense
# to look for a token being committed in those.
#
# We use --diff-filter, that tells git to only include in the diff files that were:
# - "A" added
# - "C" copied
# - "M" modified
# - "R" renamed
files=$(git diff --name-only --staged --diff-filter ACMR)
function check() {
local file="$1"
if [[ "$file" == "dev/forbidcommit.sh" || "$file" == ".pre-commit-config.yaml" ]]; then
exit 0
fi
# -i means case-insensitive
# -F means searsch for a fixed string, i.e. no pattern matching.
if grep -iF 'FORBIDCOMMIT' "$file"; then
echo "🔴 Found a FORBIDCOMMIT string in git staged file: $file."
echo "You most likely added this yourself to prevent yourself from accidentally committing that file."
echo "Please look at your changes carefully before removing the FORBIDCOMMIT pragma."
exit 1
fi
}
export -f check
parallel check ::: "$files"