Skip to content

Instantly share code, notes, and snippets.

@AlexBaranowski
Last active November 27, 2019 20:03
Show Gist options
  • Save AlexBaranowski/80e9bb093b7c75481d051d66ba180d6c to your computer and use it in GitHub Desktop.
Save AlexBaranowski/80e9bb093b7c75481d051d66ba180d6c to your computer and use it in GitHub Desktop.
#!/bin/bash
# Author: Aleksander Baranowski
# License: MIT (https://choosealicense.com/licenses/mit/)
# This simple script looks for changed .sh file from the last git commit
# then run shellcheck on them.
# USAGE: shellcheck_ci repo_root_dir
# Exit codes:
# 98 - required command is not installed
# 1 - some file failed check
# 0 - success
# VARS
MY_REQUIRED_COMMANDS="python shellcheck git"
MY_DIR_TO_CHECK=""
MY_FILES_TO_CHECK=""
check_required_commands(){
for my_command in $MY_REQUIRED_COMMANDS; do
hash "$my_command" 2>/dev/null || {
echo "Script require $my_command command! Aborting."; exit 98;
} # Using 98 as exit code
done
}
print_help(){
echo "Usage: $0 DIRECTORY_TO_CHECK"
exit 1
}
setup_script(){
if [ $# -ne 1 ];then
print_help
fi
MY_DIR_TO_CHECK="$1"
[ -d "$MY_DIR_TO_CHECK" ] || { echo "$1 is not directory!"; exit 1; }
}
find_files_to_check(){
pushd "$MY_DIR_TO_CHECK" > /dev/null
MY_FILES_TO_CHECK=$(git show --pretty="format:" --name-only | grep ".*\.sh$")
echo "Found $( echo "$MY_FILES_TO_CHECK" | wc -w) *.sh file/s"
popd > /dev/null
}
run_shellcheck(){
if [[ -z "$MY_FILES_TO_CHECK" ]]; then
echo "No *.sh script found - skipping"
exit 0
else
# disable fail on first error; multiple scripts might not pass;
# fail_flag is now responsible for exit code
set +e
fail_flag=0
for i in $MY_FILES_TO_CHECK; do
output=$(shellcheck --format=json "${MY_DIR_TO_CHECK}/${i}")
output_status=$?
if [[ $output_status -ne 0 ]]; then
fail_flag=$((fail_flag+1))
echo "==== Script $i REPORT: ===="
echo "$output" | python -m json.tool
fi
done
fi
if [[ $fail_flag -ne 0 ]]; then
echo "$fail_flag script/s failed :(" && exit 1
else
echo "All script/s passed :)"
fi
}
check_required_commands
setup_script "$@"
find_files_to_check
run_shellcheck
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment