Skip to content

Instantly share code, notes, and snippets.

@mflknr
Created February 27, 2024 12:43
Show Gist options
  • Save mflknr/5c86338c20986e410704a654179aea90 to your computer and use it in GitHub Desktop.
Save mflknr/5c86338c20986e410704a654179aea90 to your computer and use it in GitHub Desktop.
pre-commit hook for running SwiftLint and SwiftFormat on changed files
#!/bin/bash
SWIFT_LINT=/opt/homebrew/bin/swiftlint
SWIFT_LINT_CONFIG=.swiftlint.yml
SWIFT_FORMAT=/opt/homebrew/bin/swiftformat
CHANGED_FILES="$(git --no-pager diff --name-status --no-color --cached | awk '$1 != "D" && $NF ~ /\.swift?$/ { print $NF }')"
if [[ -e "${SWIFT_LINT}" || -e "${SWIFT_FORMAT}" ]]; then
count=0
if [ -z "$CHANGED_FILES" ]; then
echo "No Swift staged files."
exit 0
fi
for file_path in $CHANGED_FILES; do
export SCRIPT_INPUT_FILE_$count=$file_path
count=$((count + 1))
done
export SCRIPT_INPUT_FILE_COUNT=$count
echo "Running SwiftLint over these files:"
echo "$CHANGED_FILES"
diff=.git/unstaged-swiftlint-git-hook.diff
git diff --color=never > $diff
if [ -s $diff ]; then
git apply -R $diff
fi
$SWIFT_FORMAT $CHANGED_FILES
format_command_exit_code=$?
echo "Completed SwiftFormat run."
$SWIFT_LINT lint --use-script-input-files --quiet --fix --config $SWIFT_LINT_CONFIG
lint_command_exit_code=$?
echo "Completed SwiftLint run."
echo "$CHANGED_FILES" | while read -r file; do
if [ -f $file ]; then
git add $file
fi
done
if [ -s $diff ]; then
git apply --ignore-whitespace $diff
fi
rm $diff
unset diff
combined_exit_code=$(($format_command_exit_code + $lint_command_exit_code))
echo "Completed hook."
exit $combined_exit_code
else
echo "ERROR: SwiftLint or SwiftFormat not found."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment