read

If you ever run swfitlint in a CI/CD pipeline, you might have experienced errors merely due to linting. You have to fix it, push it, then wait for another few minutes (or hours) for the CI to build..

We can do better. In this post, I will discuss 2 ways.

If you need a primer on SwiftLint, I wrote this.

Solution 1: Strict Mode

In CI, we usually lint with strict mode, which means any violation will error out.

The mode is specified in fastlane or by passing --strict.

However, the standard run script in build phase omits that. So if you want, you can edit to:

${PODS_ROOT}/SwiftLint/swiftlint" lint --strict

Or ever better, you can show the offending line as an error:

${PODS_ROOT}/SwiftLint/swiftlint" lint --strict | sed "s/warning:/error:/

However, the tradeoff is that developers can’t write messy temp codes anymore. 😭

Solution 2: Pre-commit hook

A better solution is to add a pre-commit hook that runs swiftlint, and will stop the commit if there is any violation.

I didn’t come up with the script. I forked from candostdagdeviren, be strict, fix bugs, removed autocorrection and points to swiftlint in Pods.

This is my pre-commit script.

#!/bin/bash

SWIFT_LINT=./Pods/SwiftLint/swiftlint

if [[ -e "${SWIFT_LINT}" ]]; then
    # Export files in SCRIPT_INPUT_FILE_$count to lint against later
    count=0
    while IFS= read -r file_path; do
        export SCRIPT_INPUT_FILE_$count="$file_path"
        count=$((count + 1))
    done < <(git diff --name-only --cached --diff-filter=d | grep ".swift$")
    export SCRIPT_INPUT_FILE_COUNT=$count

    if [ "$count" -eq 0 ]; then
        echo "No files to lint!"
        exit 0
    fi

    echo "Found $count lintable files! Linting now.."
    $SWIFT_LINT --use-script-input-files --strict --config .swiftlint.yml
    RESULT=$? # swiftline exit value is number of errors

    if [ $RESULT -eq 0 ]; then
        echo "🎉  Well done. No violation."
    fi
    exit $RESULT
else
    echo "⚠️  WARNING: SwiftLint not found in $SWIFT_LINT"
    echo "⚠️  You might want to edit .git/hooks/pre-commit to locate your swiftlint"
    exit 0
fi

Don’t worry, it runs very fast, because it lints only the Swift files that will be committed to git.

Add to your repo in .git/hooks/pre-commit, and you’ll never have embarassing commits again. 🎉


Image

@samwize

¯\_(ツ)_/¯

Back to Home