Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ClassOrdering rule reports a list of errors #3142

Merged
merged 3 commits into from
Oct 15, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,22 +68,28 @@ class ClassOrdering(config: Config = Config.empty) : Rule(config) {
override fun visitClassBody(classBody: KtClassBody) {
super.visitClassBody(classBody)

comparator.findOutOfOrder(classBody.declarations)?.let {
report(CodeSmell(issue, Entity.from(classBody), generateMessage(it)))
val misorders = comparator.findOutOfOrder(classBody.declarations)
if (misorders.isNotEmpty()) {
report(
misorders.map {
CodeSmell(
issue = issue,
entity = Entity.from(it.first),
message = "${it.first.description} should not come before ${it.second.description}",
references = listOf(Entity.from(classBody))
)
schalkms marked this conversation as resolved.
Show resolved Hide resolved
}
)
}
}

private fun generateMessage(misordered: Pair<KtDeclaration, KtDeclaration>): String {
return "${misordered.first.description} should not come before ${misordered.second.description}"
}
}

private fun Comparator<KtDeclaration>.findOutOfOrder(
declarations: List<KtDeclaration>
): Pair<KtDeclaration, KtDeclaration>? {
declarations.zipWithNext { a, b -> if (compare(a, b) > 0) return Pair(a, b) }
return null
}
): List<Pair<KtDeclaration, KtDeclaration>> =
declarations
.zipWithNext { a, b -> if (compare(a, b) > 0) Pair(a, b) else null }
.filterNotNull()

private val KtDeclaration.description: String
get() = when (this) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,5 +196,30 @@ class ClassOrderingSpec : Spek({

assertThat(subject.compileAndLint(code)).hasSize(0)
}

it("does report all issues in a class with multiple misorderings") {
val code = """
class MultipleMisorders(private val x: String) {
companion object {
const val IMPORTANT_VALUE = 3
}

fun returnX() = x

constructor(z: Int): this(z.toString())

val y = x
}
""".trimIndent()

val findings = subject.compileAndLint(code)
assertThat(findings).hasSize(3)
assertThat(findings[0].message)
.isEqualTo("Companion object should not come before returnX (function)")
assertThat(findings[1].message)
.isEqualTo("returnX (function) should not come before MultipleMisorders (secondary constructor)")
assertThat(findings[2].message)
.isEqualTo("MultipleMisorders (secondary constructor) should not come before y (property)")
}
}
})