mythicalcoder
mythicalcoder

Reputation: 3291

Regex for swiftlint custom rule

I am creating custom rules in swiftlint program.
This is my reference: https://github.com/realm/SwiftLint

I wanted to add a custom rule where I have to detect 2 or more spaces after ','. So I added this rule.

comma_space_rule:
  regex: ",[ ]{2,}"
  message: "Expected only one space after ',"

But this is not working. The swiftlint help doesn't help much. Also the github doesn't mention the regex rules.

So I looked into Swift regex format and this seems to be fine. Am I missing something here ?

Upvotes: 3

Views: 3982

Answers (2)

Cihat Gündüz
Cihat Gündüz

Reputation: 21468

Creating custom rules with SwiftLint is hard as there's no level of validation, like there is with tests for "normal" rules. Try out AnyLint instead which is written exactly to solve this issue. It's written in Swift, but works for any language as it's Regex-based.

Your use case would look like this in AnyLint:

// MARK: CommaSpace
try Lint.checkFileContents(
    checkInfo: "CommaSpace: Expected only one space after a comma.",
    regex: #", {2,}"#,
    matchingExamples: ["[1,  2]", "obj.foo(x,    y)"],
    nonMatchingExamples: ["[1, 2]", "obj.foo(x, y)"],
    includeFilters: [#".*\.swift"#]
)

With AnyLint, you could even provide an autocorrectReplacement for autocorrection like so:

// MARK: CommaSpace
try Lint.checkFileContents(
    checkInfo: ... // same parameters as above, plus:
    autoCorrectReplacement: ", ",
    autoCorrectExamples: [
        ["before": "[1,  2]", "after": "[1, 2]"],
        ["before": "obj.foo(x,    y)", "after": "obj.foo(x, y)"],
    ]
)

I hope this helps.

Upvotes: 0

user4481037
user4481037

Reputation:

Your custom rule works for me. These are the steps I followed:

Added a .swiftlint.yml in the same directory as my .xcodeproj file with the following contents:

custom_rules:
  comma_space_rule:
    regex: ",[ ]{2,}"
    message: "Expected only one space after ',"

Added a new "Run Script Phase" to the Xcode project:

if which swiftlint >/dev/null; then
    swiftlint
else
    echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi

Building gives me the expected warning.

Upvotes: 4

Related Questions