aboutsummaryrefslogtreecommitdiff
path: root/detekt/src/main/kotlin/formatting/CustomCommentSpacing.kt
blob: aaf7896cfd17ce2c9b6c58c62782d6adec29c58c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package at.hannibal2.skyhanni.detektrules.formatting

import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import org.jetbrains.kotlin.com.intellij.psi.PsiComment

class CustomCommentSpacing(config: Config) : Rule(config) {
    override val issue = Issue(
        "CustomCommentSpacing",
        Severity.Style,
        "Enforces custom spacing rules for comments.",
        Debt.FIVE_MINS
    )

    private val allowedPatterns = listOf(
        "#if",
        "#else",
        "#elseif",
        "#endif",
        "$$"
    )

    override fun visitComment(comment: PsiComment) {
        if (allowedPatterns.any { comment.text.contains(it) }) {
            return
        }

        /**
         * REGEX-TEST: // Test comment
         * REGEX-TEST: /* Test comment */
         */
        val commentRegex = Regex("""^(?:\/{2}|\/\*)(?:\s.*|$)""", RegexOption.DOT_MATCHES_ALL)
        if (!commentRegex.matches(comment.text)) {
            report(
                CodeSmell(
                    issue,
                    Entity.from(comment),
                    "Expected space after opening comment."
                )
            )
        }

        // Fallback to super (ostensibly a no-check)
        super.visitComment(comment)
    }
}