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

Support migration to ktlint v1 #1736

Merged
merged 3 commits into from
Sep 20, 2023
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -13,7 +13,7 @@ import com.saveourtool.diktat.ktlint.DiktatReporterFactoryImpl
import com.saveourtool.diktat.ruleset.rules.DiktatRuleConfigReaderImpl
import com.saveourtool.diktat.ruleset.rules.DiktatRuleSetFactoryImpl

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging

import java.nio.file.Path
import java.nio.file.Paths
Expand Down
1 change: 1 addition & 0 deletions diktat-common/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ dependencies {
implementation(projects.diktatApi)
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj.core)
testImplementation(libs.slf4j.api)
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.diktat.common.config.reader

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging
import java.io.IOException
import java.io.InputStream
import kotlin.jvm.Throws
Expand All @@ -22,7 +22,9 @@ abstract class AbstractConfigReader<T : Any> {
fun read(inputStream: InputStream): T? = try {
parse(inputStream)
} catch (e: IOException) {
log.error("Cannot read config from input stream due to: ", e)
log.error(e) {
"Cannot read config from input stream due to: "
}
null
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.diktat.common.config.reader

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging

import java.io.IOException
import java.util.Properties
Expand Down Expand Up @@ -30,7 +30,9 @@ open class ApplicationProperties(propertiesFileName: String) {
}

private fun errorReadingConfig(propertiesFileName: String) {
log.error("Cannot read file $propertiesFileName with configuration properties")
log.error {
"Cannot read file $propertiesFileName with configuration properties"
}
exitProcess(EXIT_STATUS_MISSING_PROPERTIES)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import com.saveourtool.diktat.common.config.rules.RulesConfigReader.Companion.lo
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.YamlConfiguration
import com.charleskorn.kaml.decodeFromStream
import mu.KLogger
import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KLogger
import io.github.oshai.kotlinlogging.KotlinLogging

import java.io.InputStream
import java.util.Locale
Expand Down Expand Up @@ -85,7 +85,7 @@ data class CommonConfiguration(private val configuration: Map<String, String>?)
val testAnchors: List<String> by lazy {
val testDirs = (configuration ?: emptyMap()).getOrDefault("testDirs", "test").split(',').map { it.trim() }
if (testDirs.any { !it.lowercase(Locale.getDefault()).endsWith("test") }) {
log.error("test directory names should end with `test`")
log.error { "test directory names should end with `test`" }
}
testDirs
}
Expand All @@ -110,7 +110,7 @@ data class CommonConfiguration(private val configuration: Map<String, String>?)
val kotlinVersion: KotlinVersion by lazy {
configuration?.get("kotlinVersion")?.kotlinVersion() ?: run {
if (visitorCounter.incrementAndGet() == 1) {
log.error("Kotlin version not specified in the configuration file. Will be using ${KotlinVersion.CURRENT} version")
log.error { "Kotlin version not specified in the configuration file. Will be using ${KotlinVersion.CURRENT} version" }
}
KotlinVersion.CURRENT
}
Expand Down
2 changes: 1 addition & 1 deletion diktat-gradle-plugin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ dependencies {
implementation(libs.kotlinx.serialization.json)
testImplementation(libs.junit.jupiter.api)
testRuntimeOnly(libs.junit.jupiter.engine)
testImplementation(libs.ktlint.cli.reporter)
testImplementation(libs.ktlint.cli.reporter.core)
testImplementation(libs.ktlint.cli.reporter.json)
testImplementation(libs.ktlint.cli.reporter.plain)
testImplementation(libs.ktlint.cli.reporter.sarif)
Expand Down
4 changes: 2 additions & 2 deletions diktat-ktlint-engine/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ project.description = "This module builds diktat-api implementation using ktlint
dependencies {
api(projects.diktatApi)
implementation(projects.diktatCommon)
implementation(libs.ktlint.core)
implementation(libs.ktlint.cli.reporter)
implementation(libs.ktlint.cli.reporter.core)
implementation(libs.ktlint.rule.engine)
implementation(libs.ktlint.rule.engine.core)
implementation(libs.ktlint.cli.reporter.baseline)
implementation(libs.ktlint.cli.reporter.checkstyle)
implementation(libs.ktlint.cli.reporter.html)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import com.saveourtool.diktat.common.config.rules.RulesConfig
import com.saveourtool.diktat.common.config.rules.isRuleEnabled
import com.saveourtool.diktat.ruleset.utils.getFilePathSafely

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging
import org.jetbrains.kotlin.com.intellij.lang.ASTNode

private typealias DiktatConfigRule = com.saveourtool.diktat.common.config.rules.Rule
Expand Down Expand Up @@ -66,11 +66,13 @@ abstract class DiktatRule(
logic(node)
} catch (internalError: Throwable) {
log.error(
"""Internal error has occurred in rule [$id]. Please make an issue on this bug at https://github.com/saveourtool/diKTat/.
As a workaround you can disable these inspections in yml config: <$inspections>.
Root cause of the problem is in [${node.getFilePathSafely()}] file.
""".trimIndent(), internalError
)
internalError
) {
"""Internal error has occurred in rule [$id]. Please make an issue on this bug at https://github.com/saveourtool/diKTat/.
As a workaround you can disable these inspections in yml config: <$inspections>.
Root cause of the problem is in [${node.getFilePathSafely()}] file.
""".trimIndent()
}
// we are very sorry for throwing common Error here, but unfortunately we are not able to throw
// any existing Exception, as they will be caught in ktlint framework and the logging will be confusing:
// in this case it will incorrectly ask you to report issues in diktat to ktlint repository
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import com.saveourtool.diktat.ruleset.rules.DiktatRule
import com.saveourtool.diktat.ruleset.utils.*
import com.saveourtool.diktat.util.isKotlinScript

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging
import org.jetbrains.kotlin.KtNodeTypes.DOT_QUALIFIED_EXPRESSION
import org.jetbrains.kotlin.KtNodeTypes.FILE_ANNOTATION_LIST
import org.jetbrains.kotlin.KtNodeTypes.PACKAGE_DIRECTIVE
Expand Down Expand Up @@ -79,8 +79,10 @@ class PackageNaming(configRules: List<RulesConfig>) : DiktatRule(
checkFilePathMatchesWithPackageName(wordsInPackageName, realPackageName, node)
}
} ?: if (visitorCounter.incrementAndGet() == 1) {
log.error("Not able to find an external configuration for domain" +
" name in the common configuration (is it missing in yml config?)")
log.error {
"Not able to find an external configuration for domain" +
" name in the common configuration (is it missing in yml config?)"
}
} else {
@Suppress("RedundantUnitExpression")
Unit
Expand Down Expand Up @@ -124,8 +126,10 @@ class PackageNaming(configRules: List<RulesConfig>) : DiktatRule(
.flatMap { it.split(".") }

return if (!filePathParts.contains(PACKAGE_PATH_ANCHOR)) {
log.error("Not able to determine a path to a scanned file or \"$PACKAGE_PATH_ANCHOR\" directory cannot be found in it's path." +
" Will not be able to determine correct package name. It can happen due to missing <$PACKAGE_PATH_ANCHOR> directory in the path")
log.error {
"Not able to determine a path to a scanned file or \"$PACKAGE_PATH_ANCHOR\" directory cannot be found in it's path." +
" Will not be able to determine correct package name. It can happen due to missing <$PACKAGE_PATH_ANCHOR> directory in the path"
}
emptyList()
} else {
// creating a real package name:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import com.saveourtool.diktat.ruleset.utils.findAllDescendantsWithSpecificType
import com.saveourtool.diktat.ruleset.utils.getFilePath
import com.saveourtool.diktat.ruleset.utils.prevSibling

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.TokenType
import org.jetbrains.kotlin.lexer.KtTokens
Expand Down Expand Up @@ -97,8 +97,10 @@ class CommentsRule(configRules: List<RulesConfig>) : DiktatRule(
parsedNode.text.contains(it.second.trim(), false)
}?.first
if (invalidNode == null) {
logger.warn("Text [${parsedNode.text}] is a piece of code, created from comment; " +
"but no matching text in comments has been found in the file ${node.getFilePath()}")
logger.warn {
"Text [${parsedNode.text}] is a piece of code, created from comment; " +
"but no matching text in comments has been found in the file ${node.getFilePath()}"
}
} else {
COMMENTED_OUT_CODE.warn(
configRules,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import com.saveourtool.diktat.ruleset.utils.isGradleScript
import com.saveourtool.diktat.ruleset.utils.isWhiteSpace
import com.saveourtool.diktat.ruleset.utils.moveChildBefore

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.KtNodeTypes.IMPORT_LIST
import org.jetbrains.kotlin.KtNodeTypes.PACKAGE_DIRECTIVE
Expand Down Expand Up @@ -142,7 +142,7 @@ class HeaderCommentRule(configRules: List<RulesConfig>) : DiktatRule(
val copyrightWithCorrectYear = makeCopyrightCorrectYear(copyrightText)

if (copyrightWithCorrectYear.isNotEmpty()) {
log.warn("Copyright year in your configuration file is not up to date.")
log.warn { "Copyright year in your configuration file is not up to date." }
}

val headerComment = node.findChildBefore(PACKAGE_DIRECTIVE, BLOCK_COMMENT)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,10 +136,9 @@ class CommentsFormatting(configRules: List<RulesConfig>) : DiktatRule(
elseKeyWord.prevNodeUntilNode(THEN, KDOC) != null -> elseKeyWord.prevNodeUntilNode(THEN, KDOC)
else -> null
}
val copyComment = comment?.copyElement()
comment?.let {
IF_ELSE_COMMENTS.warnAndFix(configRules, emitWarn, isFixMode, it.text, node.startOffset, node) {
moveCommentToElse(node, elseBlock, elseKeyWord, it, copyComment)
moveCommentToElse(node, elseBlock, elseKeyWord, it)
}
}
}
Expand All @@ -150,17 +149,16 @@ class CommentsFormatting(configRules: List<RulesConfig>) : DiktatRule(
elseBlock: ASTNode,
elseKeyWord: ASTNode,
comment: ASTNode,
copyComment: ASTNode?
) {
if (elseBlock.hasChildOfType(BLOCK)) {
val elseCodeBlock = elseBlock.getFirstChildWithType(BLOCK)!!
elseCodeBlock.addChild(copyComment!!,
elseCodeBlock.addChild(comment,
elseCodeBlock.firstChildNode.treeNext)
elseCodeBlock.addChild(PsiWhiteSpaceImpl("\n"),
elseCodeBlock.firstChildNode.treeNext)
node.removeChild(comment)
} else {
elseKeyWord.treeParent.addChild(copyComment!!, elseKeyWord.treeNext)
elseKeyWord.treeParent.addChild(comment, elseKeyWord.treeNext)
elseKeyWord.treeParent.addChild(PsiWhiteSpaceImpl("\n"), elseKeyWord.treeNext)
node.removeChild(comment)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import com.saveourtool.diktat.ruleset.rules.DiktatRule
import com.saveourtool.diktat.ruleset.utils.isPartOfComment
import com.saveourtool.diktat.ruleset.utils.isWhiteSpaceWithNewline

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging
import org.jetbrains.kotlin.KtNodeTypes.COLLECTION_LITERAL_EXPRESSION
import org.jetbrains.kotlin.KtNodeTypes.DESTRUCTURING_DECLARATION
import org.jetbrains.kotlin.KtNodeTypes.DESTRUCTURING_DECLARATION_ENTRY
Expand Down Expand Up @@ -61,8 +61,10 @@ class TrailingCommaRule(configRules: List<RulesConfig>) : DiktatRule(
private val trailingConfig = this.configRules.getRuleConfig(TRAILING_COMMA)?.configuration ?: emptyMap()
private val configuration by lazy {
if (trailingConfig.isEmpty()) {
log.warn("You have enabled TRAILING_COMMA, but rule will remain inactive until you explicitly set" +
" configuration options. See [available-rules.md] for possible configuration options.")
log.warn {
"You have enabled TRAILING_COMMA, but rule will remain inactive until you explicitly set" +
" configuration options. See [available-rules.md] for possible configuration options."
}
}
TrailingCommaConfiguration(trailingConfig)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ import org.jetbrains.kotlin.KtNodeTypes.VALUE_ARGUMENT_LIST
import org.jetbrains.kotlin.KtNodeTypes.VALUE_PARAMETER_LIST
import org.jetbrains.kotlin.lexer.KtTokens.WHITE_SPACE
import com.saveourtool.diktat.ruleset.utils.isWhiteSpaceWithNewline
import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
Expand Down Expand Up @@ -125,7 +125,7 @@ class IndentationRule(configRules: List<RulesConfig>) : DiktatRule(
if (checkIsIndentedWithSpaces(node)) {
checkIndentation(node)
} else {
log.warn("Not going to check indentation because there are tabs")
log.warn { "Not going to check indentation because there are tabs" }
}
checkNewlineAtEnd(node)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import com.saveourtool.diktat.ruleset.utils.nextCodeSibling
import com.saveourtool.diktat.ruleset.utils.parent
import com.saveourtool.diktat.ruleset.utils.prevCodeSibling

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging
import org.jetbrains.kotlin.KtNodeTypes.BINARY_EXPRESSION
import org.jetbrains.kotlin.KtNodeTypes.BLOCK
import org.jetbrains.kotlin.KtNodeTypes.CALLABLE_REFERENCE_EXPRESSION
Expand Down Expand Up @@ -464,7 +464,7 @@ class NewlinesRule(configRules: List<RulesConfig>) : DiktatRule(
SUPER_TYPE_LIST -> (node.psi as KtSuperTypeList).entries.size to "supertype list entries"
VALUE_ARGUMENT_LIST -> (node.psi as KtValueArgumentList).arguments.size to "value arguments"
else -> {
log.warn("Unexpected node element type ${node.elementType}")
log.warn { "Unexpected node element type ${node.elementType}" }
return
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import com.saveourtool.diktat.ruleset.utils.nextCodeLeaf
import com.saveourtool.diktat.ruleset.utils.parent
import com.saveourtool.diktat.ruleset.utils.prevSibling

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging
import org.jetbrains.kotlin.KtNodeTypes.ANNOTATION_ENTRY
import org.jetbrains.kotlin.KtNodeTypes.BINARY_EXPRESSION
import org.jetbrains.kotlin.KtNodeTypes.BLOCK
Expand Down Expand Up @@ -269,7 +269,7 @@ class WhiteSpaceRule(configRules: List<RulesConfig>) : DiktatRule(
VALUE_PARAMETER, PROPERTY, FUN -> handleToken(node, 0, 1)
ANNOTATION_ENTRY -> handleToken(node, 0, 0) // e.g. @param:JsonProperty
// fixme: find examples or delete this line
else -> log.warn("Colon with treeParent.elementType=${node.treeParent.elementType}, not handled by WhiteSpaceRule")
else -> log.warn { "Colon with treeParent.elementType=${node.treeParent.elementType}, not handled by WhiteSpaceRule" }
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import com.saveourtool.diktat.ruleset.utils.findLeafWithSpecificType
import com.saveourtool.diktat.ruleset.utils.getFunctionName
import com.saveourtool.diktat.ruleset.utils.isPartOfComment

import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging
import org.jetbrains.kotlin.KtNodeTypes.CALL_EXPRESSION
import org.jetbrains.kotlin.KtNodeTypes.OPERATION_REFERENCE
import org.jetbrains.kotlin.KtNodeTypes.REFERENCE_EXPRESSION
Expand Down Expand Up @@ -205,7 +205,7 @@ class CompactInitialization(configRules: List<RulesConfig>) : DiktatRule(
}
?: run {
// valid code should always have apply with either lambdaArguments or valueArguments
log.warn("apply with unexpected parameters: ${applyExpression.text}")
log.warn { "apply with unexpected parameters: ${applyExpression.text}" }
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
package com.saveourtool.diktat.ruleset.utils

import com.google.common.base.CaseFormat
import mu.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLogging

import java.util.Locale

Expand Down Expand Up @@ -77,7 +77,7 @@ fun String.toUpperSnakeCase(): String {
return this[idx].uppercaseChar().toString() + convertUnknownCaseToUpperSnake(this.substring(idx + 1))
}

log.error("Not able to fix case format for: $this")
log.error { "Not able to fix case format for: $this" }
return this
}

Expand Down Expand Up @@ -114,7 +114,7 @@ fun String.toLowerCamelCase(): String {
return this[idx].lowercaseChar().toString() + convertUnknownCaseToCamel(this.substring(idx + 1), this[idx].isUpperCase())
}

log.error("Not able to fix case format for: $this")
log.error { "Not able to fix case format for: $this" }
return this
}

Expand Down Expand Up @@ -150,7 +150,7 @@ fun String.toPascalCase(): String = when {
// FixMe: there is some discussion on how PascalN_Case should be resolved: to PascalNcase or to PascalnCase or PascalNCase (current version)
this[idx].uppercaseChar().toString() + convertUnknownCaseToCamel(substring(idx + 1), true)
} else {
log.error("Not able to fix case format for: $this")
log.error { "Not able to fix case format for: $this" }
this
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.saveourtool.diktat.ruleset.rules.chapter1.IdentifierNaming
import com.saveourtool.diktat.util.FixTestBase

import generated.WarningNames
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test

Expand All @@ -22,12 +23,14 @@ class IdentifierNamingFixTest : FixTestBase(
fixAndCompare("identifiers/IdentifierNameRegressionExpected.kt", "identifiers/IdentifierNameRegressionTest.kt")
}

@Disabled("https://github.com/saveourtool/diktat/issues/1737")
@Test
@Tag(WarningNames.CLASS_NAME_INCORRECT)
fun `incorrect class name fix`() {
fixAndCompare("class_/IncorrectClassNameExpected.kt", "class_/IncorrectClassNameTest.kt")
}

@Disabled("https://github.com/saveourtool/diktat/issues/1737")
@Test
@Tag(WarningNames.OBJECT_NAME_INCORRECT)
fun `incorrect object name fix`() {
Expand All @@ -46,6 +49,7 @@ class IdentifierNamingFixTest : FixTestBase(
fixAndCompare("identifiers/ConstantValNameExpected.kt", "identifiers/ConstantValNameTest.kt")
}

@Disabled("https://github.com/saveourtool/diktat/issues/1737")
@Test
@Tag(WarningNames.VARIABLE_NAME_INCORRECT_FORMAT)
fun `incorrect variable name case fix`() {
Expand Down
Loading
Loading