Skip to content

Commit

Permalink
Making diktat consistent with own code style (#556)
Browse files Browse the repository at this point in the history
### What's done:
* Code style
* Fixing code style in tests
* Update diktat-analysis.yml
* Suppressed some warnings
  • Loading branch information
petertrr authored Dec 3, 2020
1 parent dc1ba8d commit 67ffa9c
Show file tree
Hide file tree
Showing 207 changed files with 5,696 additions and 4,629 deletions.
12 changes: 6 additions & 6 deletions diktat-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@
- name: FILE_WILDCARD_IMPORTS
enabled: true
configuration:
allowedWildcards: "kotlinx.serialization.*"
allowedWildcards: "kotlinx.serialization.*,org.cqfn.diktat.ruleset.utils.*"
- name: NO_BRACES_IN_CONDITIONALS_AND_LOOPS
enabled: true
- name: WRONG_ORDER_IN_CLASS_LIKE_STRUCTURES
Expand All @@ -125,10 +125,10 @@
enabled: true
configuration:
newlineAtEnd: true
extendedIndentOfParameters: true
extendedIndentOfParameters: false
alignedParameters: true
extendedIndentAfterOperators: true
extendedIndentBeforeDot: true
extendedIndentBeforeDot: false
indentationSize: 4
- name: EMPTY_BLOCK_STRUCTURE_ERROR
enabled: true
Expand Down Expand Up @@ -230,8 +230,8 @@
- name: TOO_LONG_FUNCTION
enabled: true
configuration:
maxFunctionLength: '30' # max length of function
isIncludeHeader: 'false' # count function's header
maxFunctionLength: 35 # max length of function
isIncludeHeader: false # count function's header
# Warns if there are nested functions
- name: AVOID_NESTED_FUNCTIONS
enabled: true
Expand Down Expand Up @@ -282,14 +282,14 @@
# Use extra functions for it instead.
- name: CUSTOM_GETTERS_SETTERS
enabled: true
# Checks if class instantiation can be wrapped in `apply` for better readability
# Checks if null-check was used explicitly (for example: if (a == null))
# Try to avoid explicit null checks (explicit comparison with `null`)
# Kotlin is declared as [Null-safe](https://kotlinlang.org/docs/reference/null-safety.html) language.
# But Kotlin architects wanted Kotlin to be fully compatible with Java, that's why `null` keyword was also introduced in Kotlin.
# There are several code-structures that can be used in Kotlin to avoid null-checks. For example: `?:`, `.let {}`, `.also {}`, e.t.c
- name: AVOID_NULL_CHECKS
enabled: true
# Checks if class instantiation can be wrapped in `apply` for better readability
- name: COMPACT_OBJECT_INITIALIZATION
enabled: true
# Checks explicit supertype qualification
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,17 @@ import kotlinx.serialization.Serializable
*/
@Serializable
data class CliArgument(
private val shortName: String,
private val helpDescr: String,
private val longName: String,
private val hasArgs: Boolean,
private val isRequired: Boolean) {
private val shortName: String,
private val helpDescr: String,
private val longName: String,
private val hasArgs: Boolean,
private val isRequired: Boolean) {
/**
* Converts parameters received from json to [Option]
*
* @return an [Option]
*/
fun convertToOption(): Option {
val resOption = Option(shortName, longName, hasArgs, helpDescr)
resOption.isRequired = isRequired
return resOption
fun convertToOption() = Option(shortName, longName, hasArgs, helpDescr).apply {
isRequired = this@CliArgument.isRequired
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,14 @@ open class ApplicationProperties(propertiesFileName: String) {

init {
val propStream = javaClass.classLoader.getResourceAsStream(propertiesFileName)
if (propStream != null) {
propStream?.let {
try {
properties.load(propStream)
properties.load(it)
} catch (e: IOException) {
errorReadingConfig(propertiesFileName)
}
} else {
errorReadingConfig(propertiesFileName)
}
?: errorReadingConfig(propertiesFileName)
}

private fun errorReadingConfig(propertiesFileName: String) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,14 @@ abstract class JsonResourceConfigReader<T> {
*/
fun readResource(resourceFileName: String): T? {
val resourceStream = getConfigFile(resourceFileName)
if (resourceStream == null) {
log.error("Not able to open file $resourceFileName from the resources")
} else {
resourceStream?.let {
try {
return parseResource(resourceStream)
return parseResource(it)
} catch (e: IOException) {
log.error("Cannot read config file $resourceFileName due to: ", e)
}
}
?: log.error("Not able to open file $resourceFileName from the resources")
return null
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ interface Rule {
*/
@Serializable
data class RulesConfig(
val name: String,
val enabled: Boolean = true,
val configuration: Map<String, String> = emptyMap()
val name: String,
val enabled: Boolean = true,
val configuration: Map<String, String> = emptyMap()
)

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ class ConfigReaderTest {
@Test
fun `testing json reading`() {
val rulesConfigList: List<RulesConfig>? = RulesConfigReader(javaClass.classLoader)
.readResource("src/test/resources/test-rules-config.yml")
require(rulesConfigList != null)
.readResource("src/test/resources/test-rules-config.yml")
requireNotNull(rulesConfigList)
assert(rulesConfigList.any { it.name == "CLASS_NAME_INCORRECT" && it.enabled })
assert(rulesConfigList.find { it.name == "CLASS_NAME_INCORRECT" }?.configuration == mapOf<String, String>())
assert(rulesConfigList.find { it.name == "DIKTAT_COMMON" }
?.configuration == mapOf("domainName" to "org.cqfn.diktat"))
?.configuration == mapOf("domainName" to "org.cqfn.diktat"))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ open class DiktatExtension {
*/
internal var diktatConfigFile: String = "diktat-analysis.yml"

/**
* Paths that will be excluded from diktat run
*/
var excludes: FileCollection? = null

/**
* Ktlint's [Reporter] which will be used during run.
* Private until I find a way to configure it.
Expand All @@ -28,9 +33,4 @@ open class DiktatExtension {
* Paths that will be scanned for .kt(s) files
*/
lateinit var inputs: FileCollection

/**
* Paths that will be excluded from diktat run
*/
var excludes: FileCollection? = null
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package org.cqfn.diktat.plugin.gradle

import generated.KTLINT_VERSION
import generated.DIKTAT_VERSION
import com.pinterest.ktlint.reporter.plain.PlainReporter
import generated.DIKTAT_VERSION
import generated.KTLINT_VERSION
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.ExternalModuleDependency
Expand All @@ -16,12 +16,14 @@ class DiktatGradlePlugin : Plugin<Project> {
* @param project a gradle [Project] that the plugin is applied to
*/
override fun apply(project: Project) {
val diktatExtension = project.extensions.create(DIKTAT_EXTENSION, DiktatExtension::class.java)
diktatExtension.inputs = project.fileTree("src").apply {
include("**/*.kt")
val diktatExtension = project.extensions.create(DIKTAT_EXTENSION, DiktatExtension::class.java).apply {
inputs = project.fileTree("src").apply {
include("**/*.kt")
}
reporter = PlainReporter(System.out)
excludes = project.files()
reporter = PlainReporter(System.out)
}
diktatExtension.excludes = project.files()
diktatExtension.reporter = PlainReporter(System.out)

// only gradle 7+ (or maybe 6.8) will embed kotlin 1.4+, kx.serialization is incompatible with kotlin 1.3, so until then we have to use JavaExec wrapper
// FixMe: when gradle with kotlin 1.4 is out, proper configurable tasks should be added
Expand All @@ -31,8 +33,8 @@ class DiktatGradlePlugin : Plugin<Project> {
configuration.dependencies.add(project.dependencies.create("com.pinterest:ktlint:$KTLINT_VERSION", closureOf<ExternalModuleDependency> {
exclude(
mutableMapOf(
"group" to "com.pinterest.ktlint",
"module" to "ktlint-ruleset-standard"
"group" to "com.pinterest.ktlint",
"module" to "ktlint-ruleset-standard"
)
)
}))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
package org.cqfn.diktat.plugin.gradle

import generated.KTLINT_VERSION
import generated.DIKTAT_VERSION
import org.cqfn.diktat.plugin.gradle.DiktatGradlePlugin.Companion.DIKTAT_CHECK_TASK
import org.cqfn.diktat.plugin.gradle.DiktatGradlePlugin.Companion.DIKTAT_FIX_TASK

import generated.DIKTAT_VERSION
import generated.KTLINT_VERSION
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.JavaExec
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.VerificationTask
import javax.inject.Inject

import java.io.File
import javax.inject.Inject

/**
* A base diktat task for gradle <6.8, which wraps [JavaExec]
*/
open class DiktatJavaExecTaskBase @Inject constructor(
gradleVersionString: String,
diktatExtension: DiktatExtension,
diktatConfiguration: Configuration,
additionalFlags: Iterable<String> = emptyList()
gradleVersionString: String,
diktatExtension: DiktatExtension,
diktatConfiguration: Configuration,
additionalFlags: Iterable<String> = emptyList()
) : JavaExec(), VerificationTask {
/**
* A backing [Property] for [getIgnoreFailures] and [setIgnoreFailures]
Expand Down Expand Up @@ -83,8 +85,8 @@ open class DiktatJavaExecTaskBase @Inject constructor(
*/
fun Project.registerDiktatCheckTask(diktatExtension: DiktatExtension, diktatConfiguration: Configuration): TaskProvider<DiktatJavaExecTaskBase> =
tasks.register(
DIKTAT_CHECK_TASK, DiktatJavaExecTaskBase::class.java, gradle.gradleVersion,
diktatExtension, diktatConfiguration
DIKTAT_CHECK_TASK, DiktatJavaExecTaskBase::class.java, gradle.gradleVersion,
diktatExtension, diktatConfiguration
)

/**
Expand All @@ -94,13 +96,13 @@ fun Project.registerDiktatCheckTask(diktatExtension: DiktatExtension, diktatConf
*/
fun Project.registerDiktatFixTask(diktatExtension: DiktatExtension, diktatConfiguration: Configuration): TaskProvider<DiktatJavaExecTaskBase> =
tasks.register(
DIKTAT_FIX_TASK, DiktatJavaExecTaskBase::class.java, gradle.gradleVersion,
diktatExtension, diktatConfiguration, listOf("-F ")
DIKTAT_FIX_TASK, DiktatJavaExecTaskBase::class.java, gradle.gradleVersion,
diktatExtension, diktatConfiguration, listOf("-F ")
)

private fun Project.trimRootDir(path: String) = if (path.startsWith(rootDir.absolutePath)) {
path.drop(rootDir.absolutePath.length)
} else {
path
}
path.drop(rootDir.absolutePath.length)
} else {
path
}
.trim(File.separatorChar)
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ import groovy.lang.Closure
* @property suffix version suffix
*/
internal data class GradleVersion(
val major: Int,
val minor: Int,
val patch: Int,
val suffix: String?) {
val major: Int,
val minor: Int,
val patch: Int,
val suffix: String?) {
companion object {
/**
* @param version string representation of version, e.g. from [org.gradle.api.invocation.Gradle.getGradleVersion]
Expand All @@ -41,13 +41,12 @@ internal data class GradleVersion(
fun <T> Any.closureOf(action: T.() -> Unit): Closure<Any?> =
KotlinClosure1(action, this, this)

// GENERIC_NAME is suppressed until https://github.com/cqfn/diKTat/issues/493
@Suppress("MISSING_KDOC_TOP_LEVEL", "MISSING_KDOC_CLASS_ELEMENTS", "GENERIC_NAME", "KDOC_NO_CONSTRUCTOR_PROPERTY",
"MISSING_KDOC_ON_FUNCTION", "KDOC_WITHOUT_PARAM_TAG", "KDOC_WITHOUT_RETURN_TAG")
@Suppress("MISSING_KDOC_TOP_LEVEL", "MISSING_KDOC_CLASS_ELEMENTS", "KDOC_NO_CONSTRUCTOR_PROPERTY",
"MISSING_KDOC_ON_FUNCTION", "KDOC_WITHOUT_PARAM_TAG", "KDOC_WITHOUT_RETURN_TAG")
class KotlinClosure1<in T : Any?, V : Any>(
val function: T.() -> V?,
owner: Any? = null,
thisObject: Any? = null
val function: T.() -> V?,
owner: Any? = null,
thisObject: Any? = null
) : Closure<V?>(owner, thisObject) {
@Suppress("unused") // to be called dynamically by Groovy
fun doCall(it: T): V? = it.function()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ class DiktatJavaExecTaskTest {

@Test
fun `check command line for various inputs`() {
val pwd = project.file(".")
assertCommandLineEquals(
listOf(null, "\"${listOf("src", "**", "*.kt").joinToString(File.separator)}\""),
DiktatExtension().apply {
Expand All @@ -29,7 +28,6 @@ class DiktatJavaExecTaskTest {

@Test
fun `check command line in debug mode`() {
val pwd = project.file(".")
assertCommandLineEquals(
listOf(null, "--debug", "\"${listOf("src", "**", "*.kt").joinToString(File.separator)}\""),
DiktatExtension().apply {
Expand All @@ -41,7 +39,6 @@ class DiktatJavaExecTaskTest {

@Test
fun `check command line with excludes`() {
val pwd = project.file(".")
assertCommandLineEquals(
listOf(null, "\"${listOf("src", "**", "*.kt").joinToString(File.separator)}\"",
"\"!${listOf("src", "main", "kotlin", "generated").joinToString(File.separator)}\""
Expand Down
Loading

0 comments on commit 67ffa9c

Please sign in to comment.