git-hooks/pre-commit

72 lines
2.4 KiB
Bash

#!/usr/bin/env bash
#
# https://medium.com/cognitio/verify-license-header-before-commit-2eb0c1841121
# @author : Gobinath Loganathan
missing_copyright=()
year=$(date +'%Y')
IFS=$'\n'
if git rev-parse --verify HEAD >/dev/null 2>&1; then
against=HEAD
else
# Initial Commit
against=$(git hash-object -t tree /dev/null)
fi
# Retrieve the list of newly added files.
new_files=($(git diff --cached --name-only --diff-filter=AM $against))
if [ -n "$new_files" ]; then
for new_file in "${new_files[@]}"; do
test_Copyright=$(grep -L 'SPDX-FileCopyrightText: [12][0-9][0-9][0-9]' "$new_file" 2>&1)
test_Current=$(egrep -L "SPDX-FileCopyrightText: $year|SPDX-FileCopyrightText: [12][0-9][0-9][0-9] - $year" "$new_file" 2>&1)
test_License=$(grep -L 'SPDX-License-Identifier: .' "$new_file" 2>&1)
dir_name=$(dirname "${new_file}")
file_name=$(basename "${new_file}")
if [[ "$dir_name" == "." ]]; then dir_name="HERE"; fi
if [[ "$new_file" == LICENSE* || "$new_file" == ".reuse/dep5" || -e "$new_file.license" ]]; then
test_Copyright=""
test_Current=""
test_License=""
elif grep -q "${new_file}" .reuse/dep5 2>/dev/null; then
test_Copyright=""
test_Current=""
test_License=""
elif grep -q "${dir_name}/*" .reuse/dep5 2>/dev/null; then
test_Copyright=""
test_Current=""
test_License=""
elif [[ "$new_file" == override/etc/s6-overlay/s6-rc.d* ]]; then
dir_name=$(basename "${dir_name}")
if [[ "$file_name" == "type" || "$dir_name" == "dependencies.d" || "$dir_name" == "contents.d" ]]; then
missing_copyright+=($new_file)
echo -e "\e[31mAdd DEP5 License Override:\e[0m $new_file"
test_Copyright=""
test_Current=""
test_License=""
fi
fi
if [ -n "$test_Copyright" ]; then
missing_copyright+=($test_Copyright)
echo -e "\e[31mMissing SPDX-FileCopyrightText:\e[0m $test_Copyright"
elif [ -n "$test_License" ]; then
missing_copyright+=($test_License)
echo -e "\e[31mMissing SPDX-License-Identifier:\e[0m $test_License"
elif [ -n "$test_Current" ]; then
missing_copyright+=(${test_Current})
echo -e "\e[31mSPDX-FileCopyrightText Needs $year Update:\e[0m $test_Current"
fi
done
if [ -n "$missing_copyright" ]; then
exit 1
else
echo -e "\e[32mNew files have appropriate SPDX information.\e[0m";
exit 0
fi
fi