Skip to content

Instantly share code, notes, and snippets.

@jboehler
Last active July 3, 2020 17:30
Show Gist options
  • Save jboehler/cad65c244df78deed0da6be80505c461 to your computer and use it in GitHub Desktop.
Save jboehler/cad65c244df78deed0da6be80505c461 to your computer and use it in GitHub Desktop.
Xcode Behavior Script: Run SwiftLint & SwiftFormat only on modified files (using git to find modified files)

Xcode Behavior Script: Run SwiftLint & SwiftFormat

In Xcode settings you can define your own Behavior Scripts. This script will apply swiftlint and swiftformat to all modified files. The modified files are detected with the help of git.

Xcode Behavoior Script can be assigned with a shortcut so this script can be used to format swift code in xcode with a shortcut. 😎

Dependence:

  • git
  • swiftlint
  • swiftformat
#!/bin/sh
# Xcode Behavior Script: Run SwiftLint & SwiftFormat only on modified files (using git to find modified files)
# add swiftlint swiftformat to PATH
export PATH=/usr/local/bin:$PATH
osascript -e "display notification \"Run SwiftFormat & SwiftLint\""
pwd=$(pwd)
staged=$(git diff --name-only --diff-filter=d --staged) # staged (ignore deleted)
unstaged=$(git diff --name-only --diff-filter=d) # unstaged (ignore deleted)
untracked=$(git ls-files --others --exclude-standard) # untracked
files=$(echo -e "$staged\n$unstaged\n$untracked" | grep ".*\.swift$" | sort | uniq)
# swiftformat
# https://github.com/nicklockwood/SwiftFormat/issues/328
swiftformatconfigpath=$(pwd)/".swiftformat"
# swiftformat
if which swiftformat >/dev/null; then
for file in $files
do
path="$pwd/$PROJECT_DIR/${file}"
swiftformat --config "$swiftformatconfigpath" "$path"
osascript -e "display notification \"$swiftformatconfigpath\""
done
else
osascript -e "display notification \"SwiftFormat not installed\""
echo "warning: SwiftFormat not installed, download from https://github.com/nicklockwood/SwiftFormat"
fi
# swiftlint
if which swiftlint >/dev/null; then
for file in $files
do
path="$pwd/$PROJECT_DIR/${file}"
swiftlint autocorrect "$path"
#swiftlint lint --path "$path"
done
else
osascript -e "display notification \"SwiftLint not installed\""
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment