Skip to content

Instantly share code, notes, and snippets.

@qwertzguy
Last active July 6, 2023 08:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save qwertzguy/3df69c05ed9c5bfd95b373a5a61e769c to your computer and use it in GitHub Desktop.
Save qwertzguy/3df69c05ed9c5bfd95b373a5a61e769c to your computer and use it in GitHub Desktop.
Git pre-commit hook to find unused Java imports
#!/bin/bash
#
# Git pre-commit hook to find unused Java imports.
#
# Install:
# curl https://gist.githubusercontent.com/qwertzguy/3df69c05ed9c5bfd95b373a5a61e769c/raw/pre-commit > .git/hooks/pre-commit && chmod 755 .git/hooks/pre-commit
exec 1>&2
modified_files=$(git diff --cached --name-only --diff-filter=ACM -- *.java)
[ "$modified_files" == "" ] && exit 0
for file in $modified_files; do
imported=$(sed -n '/^import .*\w;$/ {s/import .*\.\(.*\);/\1/; p}' "$file")
importedRegex=$(echo "$imported" | sed '/^$/d; s/^/\(?<![a-zA-Z0-9]\)/; s/$/\(?![a-zA-Z0-9]\)/' | tr '\n' '|' | sed 's/|$//')
num_imported=$(echo "$imported" | wc -l)
used=$(grep -v -E '^import ' "$file" | grep -o -P "$importedRegex" | sort | uniq)
num_used=$(echo "$used" | wc -l)
if [ ! "$num_used" -eq "$num_imported" ]; then
echo "Unused imports found in $file:"
(echo "$imported"; echo "$used") | sort | uniq -u | xargs -L1 echo " "
exit 1
fi
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment