3

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 ?

mythicalcoder
  • 3,143
  • 1
  • 32
  • 42

2 Answers2

4

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.

0

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.

Jeehut
  • 20,202
  • 8
  • 59
  • 80
  • +1 for the link to AnyLint. I use Periphery instead SwiftLint Analyzer, I use AnyLinter instead SwiftLint CustomRegexRules. – Blazej SLEBODA Apr 15 '23 at 15:34