Skip to content

Commit

Permalink
Enable ClassOrdering rule
Browse files Browse the repository at this point in the history
  • Loading branch information
3flex committed Sep 18, 2020
1 parent 1b70029 commit cacac1f
Show file tree
Hide file tree
Showing 25 changed files with 164 additions and 161 deletions.
2 changes: 2 additions & 0 deletions config/detekt/detekt.yml
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ potential-bugs:
active: true

style:
ClassOrdering:
active: true
CollapsibleIfStatements:
active: true
EqualsNullCall:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ class AnnotationExcluder(
private val excludes: List<String>
) {

constructor(root: KtFile, excludes: SplitPattern) : this(root, excludes.mapAll { it })

private val resolvedAnnotations = root.importList
?.imports
?.asSequence()
Expand All @@ -23,6 +21,8 @@ class AnnotationExcluder(
?.map { it.substringAfterLast('.') to it }
?.toMap() ?: emptyMap()

constructor(root: KtFile, excludes: SplitPattern) : this(root, excludes.mapAll { it })

/**
* Is true if any given annotation name is declared in the SplitPattern
* which basically describes entries to exclude.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,6 @@ interface ConfigAware : Config {
private val ruleConfig: Config
get() = ruleSetConfig.subConfig(ruleId)

/**
* If your rule supports to automatically correct the misbehaviour of underlying smell,
* specify your code inside this method call, to allow the user of your rule to trigger auto correction
* only when needed.
*/
fun withAutoCorrect(block: () -> Unit) {
if (autoCorrect) {
block()
}
}

/**
* Does this rule have auto correct specified in configuration?
* For auto correction to work the rule set itself enable it.
Expand All @@ -58,6 +47,17 @@ interface ConfigAware : Config {
*/
val active: Boolean get() = valueOrDefault("active", false)

/**
* If your rule supports to automatically correct the misbehaviour of underlying smell,
* specify your code inside this method call, to allow the user of your rule to trigger auto correction
* only when needed.
*/
fun withAutoCorrect(block: () -> Unit) {
if (autoCorrect) {
block()
}
}

override fun subConfig(key: String): Config =
ruleConfig.subConfig(key)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@ data class Debt(val days: Int = 0, val hours: Int = 0, val mins: Int = 0) {
return Debt(days, hours, minutes)
}

override fun toString(): String {
return with(StringBuilder()) {
if (days > 0) append("${days}d ")
if (hours > 0) append("${hours}h ")
if (mins > 0) append("${mins}min")
toString()
}.trimEnd()
}

companion object {
val TWENTY_MINS: Debt =
Debt(0, 0, 20)
Expand All @@ -36,13 +45,4 @@ data class Debt(val days: Int = 0, val hours: Int = 0, val mins: Int = 0) {
private const val HOURS_PER_DAY = 24
private const val MINUTES_PER_HOUR = 60
}

override fun toString(): String {
return with(StringBuilder()) {
if (days > 0) append("${days}d ")
if (hours > 0) append("${hours}h ")
if (mins > 0) append("${mins}min")
toString()
}.trimEnd()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ class PathFilters internal constructor(
private val excludes: Set<PathMatcher>?
) {

fun isIgnored(path: Path): Boolean {

fun isIncluded() = includes?.any { it.matches(path) }
fun isExcluded() = excludes?.any { it.matches(path) }

return isIncluded()?.not() ?: isExcluded() ?: true
}

companion object {
fun of(includes: List<String>, excludes: List<String>): PathFilters? {
if (includes.isEmpty() && excludes.isEmpty()) {
Expand All @@ -27,14 +35,6 @@ class PathFilters internal constructor(
.toSet()
}
}

fun isIgnored(path: Path): Boolean {

fun isIncluded() = includes?.any { it.matches(path) }
fun isExcluded() = excludes?.any { it.matches(path) }

return isIncluded()?.not() ?: isExcluded() ?: true
}
}

fun Config.createPathFilters(): PathFilters? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,6 @@ import org.jetbrains.kotlin.psi.KtStatementExpression

class ElementPrinter : DetektVisitor() {

companion object {
fun dump(file: KtFile): String = ElementPrinter().run {
sb.appendLine("0: " + file.javaClass.simpleName)
visitKtFile(file)
sb.toString()
}
}

private val sb = StringBuilder()

private val indentation
Expand Down Expand Up @@ -60,4 +52,12 @@ class ElementPrinter : DetektVisitor() {
this is KtStatementExpression ||
this is KtDeclarationContainer ||
this is KtContainerNode

companion object {
fun dump(file: KtFile): String = ElementPrinter().run {
sb.appendLine("0: " + file.javaClass.simpleName)
visitKtFile(file)
sb.toString()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ class KtTreeCompiler(
private val pathFilters: PathFilters? =
PathFilters.of(spec.includes.toList(), spec.excludes.toList())

companion object {
val KT_ENDINGS = setOf("kt", "kts")
}

fun compile(path: Path): List<KtFile> {
require(Files.exists(path)) { "Given path $path does not exist!" }
return when {
Expand Down Expand Up @@ -64,4 +60,8 @@ class KtTreeCompiler(
}
return ignored ?: false
}

companion object {
val KT_ENDINGS = setOf("kt", "kts")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import javax.xml.stream.XMLStreamWriter

internal class BaselineFormat {

private val XMLStreamException.positions
get() = location.lineNumber to location.columnNumber

class InvalidState(msg: String, error: Throwable) : IllegalStateException(msg, error)

fun read(path: Path): Baseline {
Expand Down Expand Up @@ -36,9 +39,6 @@ internal class BaselineFormat {
}
}

private val XMLStreamException.positions
get() = location.lineNumber to location.columnNumber

private fun XMLStreamWriter.save(baseline: Baseline) {
document {
tag(SMELL_BASELINE) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,6 @@ abstract class FormattingRule(config: Config) : Rule(config) {

abstract val wrapping: com.pinterest.ktlint.core.Rule

protected fun issueFor(description: String) =
Issue(javaClass.simpleName, Severity.Style, description, Debt.FIVE_MINS)

/**
* Should the android style guide be enforced?
* This property is read from the ruleSet config.
Expand All @@ -39,6 +36,9 @@ abstract class FormattingRule(config: Config) : Rule(config) {
private var positionByOffset: (offset: Int) -> Pair<Int, Int> by SingleAssign()
private var root: KtFile by SingleAssign()

protected fun issueFor(description: String) =
Issue(javaClass.simpleName, Severity.Style, description, Debt.FIVE_MINS)

override fun visit(root: KtFile) {
this.root = root
root.node.putUserData(KtLint.ANDROID_USER_DATA_KEY, isAndroid)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,6 @@ open class Detekt @Inject constructor(
@get:Classpath
val pluginClasspath: ConfigurableFileCollection = objects.fileCollection()

@InputFiles
@SkipWhenEmpty
@PathSensitive(PathSensitivity.RELATIVE)
override fun getSource(): FileTree = super.getSource()

@get:InputFile
@get:Optional
@get:PathSensitive(PathSensitivity.RELATIVE)
Expand Down Expand Up @@ -133,11 +128,6 @@ open class Detekt @Inject constructor(
@get:Internal
internal val ignoreFailuresProp: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType)

@Input
override fun getIgnoreFailures(): Boolean = ignoreFailuresProp.getOrElse(false)

override fun setIgnoreFailures(value: Boolean) = ignoreFailuresProp.set(value)

@get:Internal
internal val autoCorrectProp: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType)
var autoCorrect: Boolean
Expand All @@ -148,8 +138,6 @@ open class Detekt @Inject constructor(
@get:Internal
var reports = DetektReports()

fun reports(configure: Action<DetektReports>) = configure.execute(reports)

@get:Internal
val reportsDir: Property<File> = project.objects.property(File::class.java)

Expand Down Expand Up @@ -183,6 +171,18 @@ open class Detekt @Inject constructor(

private val invoker: DetektInvoker = DetektInvoker.create(project)

@InputFiles
@SkipWhenEmpty
@PathSensitive(PathSensitivity.RELATIVE)
override fun getSource(): FileTree = super.getSource()

@Input
override fun getIgnoreFailures(): Boolean = ignoreFailuresProp.getOrElse(false)

override fun setIgnoreFailures(value: Boolean) = ignoreFailuresProp.set(value)

fun reports(configure: Action<DetektReports>) = configure.execute(reports)

@Suppress("DEPRECATION")
@TaskAction
fun check() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ open class DetektExtension @Inject constructor(objects: ObjectFactory) : CodeQua
get() = reportsDir

val reports = DetektReports()
fun reports(configure: Action<DetektReports>) = configure.execute(reports)

var input: ConfigurableFileCollection =
objects.fileCollection().from(DEFAULT_SRC_DIR_JAVA, DEFAULT_SRC_DIR_KOTLIN)
Expand Down Expand Up @@ -59,6 +58,8 @@ open class DetektExtension @Inject constructor(objects: ObjectFactory) : CodeQua
*/
var ignoredFlavors: List<String> = emptyList()

fun reports(configure: Action<DetektReports>) = configure.execute(reports)

companion object {
const val DEFAULT_SRC_DIR_JAVA = "src/main/java"
const val DEFAULT_SRC_DIR_KOTLIN = "src/main/kotlin"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,18 @@ internal class DetektAndroid(private val project: Project) {
}
}

private val BaseExtension.variants: DomainObjectSet<out BaseVariant>?
get() = when (this) {
is AppExtension -> applicationVariants
is LibraryExtension -> libraryVariants
is TestExtension -> applicationVariants
else -> null
}

private val BaseVariant.testVariants: List<BaseVariant>
get() = if (this is TestedVariant) listOfNotNull(testVariant, unitTestVariant)
else emptyList()

fun registerDetektAndroidTasks(extension: DetektExtension) {
// There is not a single Android plugin, but each registers an extension based on BaseExtension,
// so we catch them all by looking for this one
Expand Down Expand Up @@ -91,18 +103,6 @@ internal class DetektAndroid(private val project: Project) {
ignoredBuildTypes.contains(variant.buildType.name) ||
ignoredFlavors.contains(variant.flavorName)

private val BaseExtension.variants: DomainObjectSet<out BaseVariant>?
get() = when (this) {
is AppExtension -> applicationVariants
is LibraryExtension -> libraryVariants
is TestExtension -> applicationVariants
else -> null
}

private val BaseVariant.testVariants: List<BaseVariant>
get() = if (this is TestedVariant) listOfNotNull(testVariant, unitTestVariant)
else emptyList()

private fun Project.registerAndroidDetektTask(
bootClasspath: FileCollection,
extension: DetektExtension,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ internal interface DetektInvoker {
)

companion object {
private const val DRY_RUN_PROPERTY = "detekt-dry-run"

fun create(project: Project): DetektInvoker =
if (project.isDryRunEnabled()) {
DryRunInvoker(project.logger)
Expand All @@ -28,8 +30,6 @@ internal interface DetektInvoker {
private fun Project.isDryRunEnabled(): Boolean {
return hasProperty(DRY_RUN_PROPERTY) && property(DRY_RUN_PROPERTY) == "true"
}

private const val DRY_RUN_PROPERTY = "detekt-dry-run"
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,6 @@ abstract class DslTestBuilder {
}

companion object {
fun kotlin(): DslTestBuilder = KotlinBuilder()
fun groovy(): DslTestBuilder = GroovyBuilder()

private const val GROOVY_PLUGINS_SECTION = """
|plugins {
| id 'java-library'
Expand Down Expand Up @@ -126,5 +123,8 @@ abstract class DslTestBuilder {
private const val KOTLIN_APPLY_PLUGINS = """
|plugins.apply("io.gitlab.arturbosch.detekt")
|"""

fun kotlin(): DslTestBuilder = KotlinBuilder()
fun groovy(): DslTestBuilder = GroovyBuilder()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,6 @@ private open class FixedDateFile(path: String) : File(path) {

private class DifferentDateFile(path: String) : FixedDateFile(path) {

companion object {
private val random = Random(seed = 200)
private val cache = HashSet<Long>()
}

override fun lastModified(): Long {
var nextDate = random.nextLong()
while (cache.contains(nextDate)) {
Expand All @@ -79,4 +74,9 @@ private class DifferentDateFile(path: String) : FixedDateFile(path) {
cache.add(nextDate)
return nextDate
}

companion object {
private val random = Random(seed = 200)
private val cache = HashSet<Long>()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ class CognitiveComplexity private constructor() : DetektVisitor() {

private var nesting: Int = 0

private var topMostBinExpr: KtBinaryExpression? = null

private fun addComplexity() {
complexity += 1 + nesting
}
Expand Down Expand Up @@ -142,8 +144,6 @@ class CognitiveComplexity private constructor() : DetektVisitor() {
nestAround { super.visitLambdaExpression(lambdaExpression) }
}

private var topMostBinExpr: KtBinaryExpression? = null

override fun visitBinaryExpression(expression: KtBinaryExpression) {
if (topMostBinExpr == null) {
topMostBinExpr = expression
Expand Down
Loading

0 comments on commit cacac1f

Please sign in to comment.