Skip to content

Instantly share code, notes, and snippets.

@george-lim
Created January 20, 2020 00:58
Show Gist options
  • Save george-lim/f1166bc75d9047495934a6eb974bb127 to your computer and use it in GitHub Desktop.
Save george-lim/f1166bc75d9047495934a6eb974bb127 to your computer and use it in GitHub Desktop.
A handy Xcode run script that applies SwiftLint only to new Swift codebase changes
#!/bin/bash
# Parameters
source="$(pwd)/$1" # Track folder source where diffs are checked
index=$2 # Track diff remote
project_root=${0%/*} # Track project root folder
swiftlint_path='Pods/SwiftLint/swiftlint' # Track SwiftLint path
# Parameter check
if [[ $# < 1 ]]; then
echo $(pwd)
echo "usage: $0 SOURCE INDEX"
echo 'SOURCE -> Project source code folder'
echo 'INDEX -> git diff comparison index. Defaults to "origin/master"'
exit 1
elif [[ $# == 1 ]]; then
index=origin/master
fi
cd $project_root
# Iterate through each modified file
while read file; do
hunkCount=0 # Track number of hunks
hunkLines=() # Track each hunk range [start, end] = [hunkLines[i*2], hunkLines[i*2+1]]
# Iterate through each git diff hunk
while read hunk; do
hunkCount=$((hunkCount+1))
hunkLines+=(${hunk%%+*}) # Add hunk start line
hunkLines+=($(echo $hunk | bc)) # Add hunk end line
done< <(git diff -U0 $file | egrep '@@' | cut -d ' ' -f 3 | sed -e 's|+||' -e 's|,|+|')
# Iterate through each violation from SwiftLint
while read violation; do
line=$(echo $violation | cut -d : -f 2) # Track violation line number
# Iterate through each hunk range to see if violation applies
for i in $(seq 0 $((hunkCount-1))); do
# Check if violation is in range of hunk
if [ "$line" -ge "${hunkLines[i*2]}" ] && [ "$line" -le "${hunkLines[i*2+1]}" ]; then
# Violation output format is automatically recognized by Xcode
echo $violation
# Check if the violation contains an error, and exit immediately
if [[ $violation == *" error: "* ]]; then exit 1; fi
break
fi
done
done< <($swiftlint_path lint --path $file)
done< <(git diff --name-only --diff-filter=d $index | egrep "${source#$(pwd)/}" | egrep '.swift$')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment