Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master' into bugfix/incorrect-fi…
Browse files Browse the repository at this point in the history
…x-null-safety

# Conflicts:
#	diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/rules/chapter4/NullChecksRule.kt
  • Loading branch information
kentr0w committed Apr 30, 2021
2 parents 45864c0 + 4c81b3f commit af0bf24
Show file tree
Hide file tree
Showing 47 changed files with 119 additions and 134 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ abstract class JsonResourceConfigReader<T> {
protected abstract fun parseResource(fileStream: BufferedReader): T

companion object {
/**
* A [Logger] that can be used
*/
val log: Logger = LoggerFactory.getLogger(JsonResourceConfigReader::class.java)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ import java.util.concurrent.atomic.AtomicInteger
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString

/**
* Name of common configuration
*/
const val DIKTAT_COMMON = "DIKTAT_COMMON"

/**
Expand Down Expand Up @@ -49,7 +52,6 @@ data class RulesConfig(
* @property config a map of strings with configuration options for a particular rule
*/
open class RuleConfiguration(protected val config: Map<String, String>)
object EmptyConfiguration : RuleConfiguration(emptyMap())

/**
* class returns the list of configurations that we have read from a yml: diktat-analysis.yml
Expand Down Expand Up @@ -87,6 +89,9 @@ open class RulesConfigReader(override val classLoader: ClassLoader) : JsonResour
}

companion object {
/**
* A [Logger] that can be used
*/
val log: Logger = LoggerFactory.getLogger(RulesConfigReader::class.java)
}
}
Expand Down
14 changes: 9 additions & 5 deletions diktat-gradle-plugin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform.getCurr

plugins {
`java-gradle-plugin`
kotlin("jvm") version "1.4.32"
kotlin("jvm") version "1.3.72"
jacoco
id("pl.droidsonroids.jacoco.testkit") version "1.0.7"
id("org.gradle.test-retry") version "1.2.1"
Expand All @@ -26,10 +26,13 @@ val jacocoVersion = project.properties.getOrDefault("jacocoVersion", "0.8.6") as
dependencies {
implementation(kotlin("gradle-plugin-api"))

implementation("com.pinterest.ktlint:ktlint-core:$ktlintVersion") {
exclude("com.pinterest.ktlint", "ktlint-ruleset-standard")
implementation("org.cqfn.diktat:diktat-rules:$diktatVersion") {
exclude("org.jetbrains.kotlin", "kotlin-compiler-embeddable")
exclude("org.jetbrains.kotlin", "kotlin-stdlib-jdk8")
exclude("org.jetbrains.kotlin", "kotlin-stdlib-jdk7")
exclude("org.jetbrains.kotlin", "kotlin-stdlib")
exclude("org.jetbrains.kotlin", "kotlin-stdlib-common")
}
implementation("org.cqfn.diktat:diktat-rules:$diktatVersion")

testImplementation("org.junit.jupiter:junit-jupiter-api:$junitVersion")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:$junitVersion")
Expand Down Expand Up @@ -62,7 +65,8 @@ tasks.withType<KotlinCompile> {
apiVersion = "1.3"
jvmTarget = "1.8"
useIR = true
}
allWarningsAsErrors = true
}

dependsOn.add(generateVersionsFile)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,24 @@ class DiktatGradlePlugin : Plugin<Project> {
}

companion object {
/**
* Task to check diKTat
*/
const val DIKTAT_CHECK_TASK = "diktatCheck"

/**
* DiKTat configuration
*/
const val DIKTAT_CONFIGURATION = "diktat"

/**
* DiKTat extension
*/
const val DIKTAT_EXTENSION = "diktat"

/**
* Task to run diKTat with fix
*/
const val DIKTAT_FIX_TASK = "diktatFix"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ open class DiktatJavaExecTaskBase @Inject constructor(
project.logger.debug("Setting JavaExec args to $args")
}

/**
* Function to execute diKTat
*/
@TaskAction
override fun exec() {
if (shouldRun) {
Expand Down
5 changes: 5 additions & 0 deletions diktat-rules/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@
</configuration>
</execution>
</executions>
<configuration>
<args>
<arg>-Xinline-classes</arg>
</args>
</configuration>
</plugin>

<plugin>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ typealias ListOfPairs = MutableList<Pair<ASTNode, String>>
"WRONG_NEWLINES"
)
enum class Warnings(
val canBeAutoCorrected: Boolean,
private val canBeAutoCorrected: Boolean,
val ruleId: String,
private val warn: String) : Rule {
// ======== dummy test warning ======
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class DummyWarning(configRules: List<RulesConfig>) : DiktatRule(
Warnings.FILE_NAME_MATCH_CLASS
)
) {
@Suppress("UNUSED")
private lateinit var filePath: String

@Suppress("EmptyFunctionBlock")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ private fun validateYear() {
val files = File("diktat-rules/src/test/resources/test/paragraph2/header")
files
.listFiles()
.filterNot { it.name.contains("CopyrightDifferentYearTest.kt") }
.forEach { file ->
?.filterNot { it.name.contains("CopyrightDifferentYearTest.kt") }
?.forEach { file ->
val tempFile = createTempFile().toFile()
tempFile.printWriter().use { writer ->
file.forEachLine { line ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ private typealias DiktatConfigRule = org.cqfn.diktat.common.config.rules.Rule
@Suppress("TooGenericExceptionCaught")
abstract class DiktatRule(id: String,
val configRules: List<RulesConfig>,
val inspections: List<DiktatConfigRule>) : Rule(id) {
private val inspections: List<DiktatConfigRule>) : Rule(id) {
/**
* Default value is false
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ import com.pinterest.ktlint.core.ast.ElementType.DESTRUCTURING_DECLARATION
import com.pinterest.ktlint.core.ast.ElementType.DESTRUCTURING_DECLARATION_ENTRY
import com.pinterest.ktlint.core.ast.ElementType.FILE
import com.pinterest.ktlint.core.ast.ElementType.FUNCTION_TYPE
import com.pinterest.ktlint.core.ast.ElementType.PROPERTY
import com.pinterest.ktlint.core.ast.ElementType.REFERENCE_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.TYPE_PARAMETER
import com.pinterest.ktlint.core.ast.ElementType.TYPE_REFERENCE
Expand Down Expand Up @@ -163,7 +162,7 @@ class IdentifierNaming(configRules: List<RulesConfig>) : DiktatRule(
var namesOfVariables = extractVariableIdentifiers(node)
// Only local private properties will be autofix in order not to break code if there are usages in other files.
// Destructuring declarations are only allowed for local variables/values, so we don't need to calculate `isFix` for every node in `namesOfVariables`
val isFix = isFixMode && if (node.elementType == PROPERTY) (node.psi as KtProperty).run { isLocal || isPrivate() } else true
val isFix = isFixMode && if (node.elementType == ElementType.PROPERTY) (node.psi as KtProperty).run { isLocal || isPrivate() } else true
namesOfVariables
.forEach { variableName ->
// variable should not contain only one letter in it's name. This is a bad example: b512
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ class CommentsRule(configRules: List<RulesConfig>) : DiktatRule(
private val importOrPackageRegex = """^(import|package)?\s+([a-zA-Z.])+;*$""".toRegex()
private val functionRegex = """^(public|private|protected)*\s*(override|abstract|actual|expect)*\s?fun\s+\w+(\(.*\))?(\s*:\s*\w+)?\s*[{=]${'$'}""".toRegex()
private val rightBraceRegex = """^\s*}$""".toRegex()
private val requirePartOfCode = """val |var |=|(\{((.|\n)*)\})""".toRegex()
private val requirePartOfCode = """val |var |=|(\{((.|\n)*)})""".toRegex()
private val codeFileStartCases = listOf(classRegex, importOrPackageRegex, functionRegex, rightBraceRegex)
private val eolCommentStart = """// \S""".toRegex()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,6 @@ class CommentsFormatting(configRules: List<RulesConfig>) : DiktatRule(
IF_ELSE_COMMENTS, WRONG_NEWLINES_AROUND_KDOC)) {
/**
* @param node
* @param autoCorrect
* @param emit
*/
override fun logic(node: ASTNode) {
val configuration = CommentsFormattingConfiguration(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,6 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
KDOC_NO_CONSTRUCTOR_PROPERTY_WITH_COMMENT, MISSING_KDOC_CLASS_ELEMENTS, MISSING_KDOC_TOP_LEVEL)) {
/**
* @param node
* @param autoCorrect
* @param emit
*/
override fun logic(node: ASTNode) {
val config = configRules.getCommonConfiguration()
Expand All @@ -76,13 +74,13 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
?.findChildByType(KDOC) ?: return
val propertiesInKdoc = kdocBeforeClass
.kDocTags()
?.filter { it.knownTag == KDocKnownTag.PROPERTY }
.filter { it.knownTag == KDocKnownTag.PROPERTY }
val propertyNames = (node.psi as KtParameterList)
.parameters
.mapNotNull { it.nameIdentifier?.text }
propertiesInKdoc
?.filterNot { it.getSubjectName() == null || it.getSubjectName() in propertyNames }
?.forEach { KDOC_EXTRA_PROPERTY.warn(configRules, emitWarn, isFixMode, it.text, it.node.startOffset, node) }
.filterNot { it.getSubjectName() == null || it.getSubjectName() in propertyNames }
.forEach { KDOC_EXTRA_PROPERTY.warn(configRules, emitWarn, isFixMode, it.text, it.node.startOffset, node) }
}

@Suppress("UnsafeCallOnNullableType", "ComplexMethod")
Expand Down Expand Up @@ -126,7 +124,7 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
private fun checkBasicKdocBeforeClass(node: ASTNode, kdocBeforeClass: ASTNode) {
val propertyInClassKdoc = kdocBeforeClass
.kDocTags()
?.firstOrNull { it.knownTag == KDocKnownTag.PROPERTY && it.getSubjectName() == node.findChildByType(IDENTIFIER)!!.text }
.firstOrNull { it.knownTag == KDocKnownTag.PROPERTY && it.getSubjectName() == node.findChildByType(IDENTIFIER)!!.text }
if (propertyInClassKdoc == null && node.getFirstChildWithType(MODIFIER_LIST).isAccessibleOutside()) {
KDOC_NO_CONSTRUCTOR_PROPERTY.warnAndFix(configRules, emitWarn, isFixMode,
"add <${node.findChildByType(IDENTIFIER)!!.text}> to KDoc", node.startOffset, node) {
Expand All @@ -142,12 +140,12 @@ class KdocComments(configRules: List<RulesConfig>) : DiktatRule(
prevComment: ASTNode) {
val propertyInClassKdoc = kdocBeforeClass
.kDocTags()
?.firstOrNull { it.knownTag == KDocKnownTag.PROPERTY && it.getSubjectName() == node.findChildByType(IDENTIFIER)!!.text }
.firstOrNull { it.knownTag == KDocKnownTag.PROPERTY && it.getSubjectName() == node.findChildByType(IDENTIFIER)!!.text }
?.node
val propertyInLocalKdoc = if (prevComment.elementType == KDOC) {
prevComment
.kDocTags()
?.firstOrNull { it.knownTag == KDocKnownTag.PROPERTY && it.getSubjectName() == node.findChildByType(IDENTIFIER)!!.text }
.firstOrNull { it.knownTag == KDocKnownTag.PROPERTY && it.getSubjectName() == node.findChildByType(IDENTIFIER)!!.text }
?.node
} else {
null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ class KdocFormatting(configRules: List<RulesConfig>) : DiktatRule(

/**
* @param node
* @param autoCorrect
* @param emit
*/
override fun logic(node: ASTNode) {
versionRegex ?: run {
Expand All @@ -86,8 +84,8 @@ class KdocFormatting(configRules: List<RulesConfig>) : DiktatRule(
checkNoDeprecatedTag(node)
checkEmptyTags(node.kDocTags())
checkSpaceAfterTag(node.kDocTags())
node.kDocBasicTags()?.let { checkEmptyLineBeforeBasicTags(it) }
node.kDocBasicTags()?.let { checkEmptyLinesBetweenBasicTags(it) }
checkEmptyLineBeforeBasicTags(node.kDocBasicTags())
checkEmptyLinesBetweenBasicTags(node.kDocBasicTags())
checkBasicTagsOrder(node)
checkNewLineAfterSpecialTags(node)
checkAuthorAndDate(node)
Expand All @@ -111,7 +109,7 @@ class KdocFormatting(configRules: List<RulesConfig>) : DiktatRule(
@Suppress("UnsafeCallOnNullableType")
private fun checkNoDeprecatedTag(node: ASTNode) {
val kdocTags = node.kDocTags()
kdocTags?.find { it.name == "deprecated" }
kdocTags.find { it.name == "deprecated" }
?.let { kdocTag ->
KDOC_NO_DEPRECATED_TAG.warnAndFix(configRules, emitWarn, isFixMode, kdocTag.text, kdocTag.node.startOffset, kdocTag.node) {
val kdocSection = kdocTag.node.treeParent
Expand Down Expand Up @@ -175,23 +173,22 @@ class KdocFormatting(configRules: List<RulesConfig>) : DiktatRule(
val kdocTags = node.kDocTags()
// distinct basic tags which are present in current KDoc, in proper order
val basicTagsOrdered = basicTagsList.filter { basicTag ->
kdocTags?.find { it.knownTag == basicTag } != null
kdocTags.find { it.knownTag == basicTag } != null
}
// all basic tags from current KDoc
val basicTags = kdocTags?.filter { basicTagsOrdered.contains(it.knownTag) }
val basicTags = kdocTags.filter { basicTagsOrdered.contains(it.knownTag) }
val isTagsInCorrectOrder = basicTags
?.fold(mutableListOf<KDocTag>()) { acc, kdocTag ->
.fold(mutableListOf<KDocTag>()) { acc, kdocTag ->
if (acc.size > 0 && acc.last().knownTag != kdocTag.knownTag) {
acc.add(kdocTag)
} else if (acc.size == 0) {
acc.add(kdocTag)
}
acc
}
?.map { it.knownTag }
?.equals(basicTagsOrdered)
.map { it.knownTag } == basicTagsOrdered

if (kdocTags != null && !isTagsInCorrectOrder!!) {
if (!isTagsInCorrectOrder) {
KDOC_WRONG_TAGS_ORDER.warnAndFix(configRules, emitWarn, isFixMode,
basicTags.joinToString(", ") { "@${it.name}" }, basicTags
.first()
Expand Down Expand Up @@ -326,11 +323,11 @@ class KdocFormatting(configRules: List<RulesConfig>) : DiktatRule(

private fun checkAuthorAndDate(node: ASTNode) {
node.kDocTags()
?.filter {
.filter {
it.knownTag == KDocKnownTag.AUTHOR ||
it.knownTag == KDocKnownTag.SINCE && it.hasInvalidVersion()
}
?.forEach {
.forEach {
KDOC_CONTAINS_DATE_OR_AUTHOR.warn(configRules, emitWarn, isFixMode, it.text.trim(), it.startOffset, it.node)
}
}
Expand All @@ -342,7 +339,7 @@ class KdocFormatting(configRules: List<RulesConfig>) : DiktatRule(
(treeNext == null || treeNext.elementType == WHITE_SPACE && treeNext.text.count { it == '\n' } == 1)
}

private fun ASTNode.kDocBasicTags() = kDocTags()?.filter { basicTagsList.contains(it.knownTag) }
private fun ASTNode.kDocBasicTags() = kDocTags().filter { basicTagsList.contains(it.knownTag) }

private fun ASTNode.previousAsterisk() = prevSibling { it.elementType == KDOC_LEADING_ASTERISK }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,6 @@ class KdocMethods(configRules: List<RulesConfig>) : DiktatRule(
KDOC_WITHOUT_THROWS_TAG, MISSING_KDOC_ON_FUNCTION)) {
/**
* @param node
* @param autoCorrect
* @param emit
*/
override fun logic(node: ASTNode) {
if (node.elementType == FUN && node.getFirstChildWithType(MODIFIER_LIST).isAccessibleOutside() && !node.isOverridden()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import org.cqfn.diktat.ruleset.rules.DiktatRule
import org.cqfn.diktat.ruleset.utils.*

import com.pinterest.ktlint.core.ast.ElementType.BINARY_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.CONST_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.ENUM_ENTRY
import com.pinterest.ktlint.core.ast.ElementType.FLOAT_CONSTANT
import com.pinterest.ktlint.core.ast.ElementType.FUN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import org.cqfn.diktat.ruleset.rules.DiktatRule
import org.cqfn.diktat.ruleset.utils.*

import com.pinterest.ktlint.core.ast.ElementType.BINARY_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.CALL_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.DOT_QUALIFIED_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.OPERATION_REFERENCE
import com.pinterest.ktlint.core.ast.ElementType.PLUS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,7 @@ class FileStructureRule(configRules: List<RulesConfig>) : DiktatRule(
}
private val standardImportsAsName = StandardPlatforms
.values()
.map { it to it.packages }
.toMap()
.associate { it to it.packages }
.mapValues { (_, value) ->
value.map { it.split(PACKAGE_SEPARATOR).map(Name::identifier) }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -544,15 +544,15 @@ class NewlinesRule(configRules: List<RulesConfig>) : DiktatRule(
}
val callsByNewLine: ListOfList = mutableListOf()
var callsInOneNewLine: MutableList<ASTNode> = mutableListOf()
this.forEach { node ->
if (node.treePrev.isFollowedByNewline() || node.treePrev.isWhiteSpaceWithNewline()) {
this.forEach { astNode ->
if (astNode.treePrev.isFollowedByNewline() || astNode.treePrev.isWhiteSpaceWithNewline()) {
callsByNewLine.add(callsInOneNewLine)
callsInOneNewLine = mutableListOf()
callsInOneNewLine.add(node)
callsInOneNewLine.add(astNode)
} else {
callsInOneNewLine.add(node)
callsInOneNewLine.add(astNode)
}
if (node.treePrev.elementType == POSTFIX_EXPRESSION && !node.treePrev.isFollowedByNewline() && configuration.maxCallsInOneLine == 1) {
if (astNode.treePrev.elementType == POSTFIX_EXPRESSION && !astNode.treePrev.isFollowedByNewline() && configuration.maxCallsInOneLine == 1) {
return true
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,8 @@ class WhiteSpaceRule(configRules: List<RulesConfig>) : DiktatRule(
0
} else {
// this can happen, e.g. in lambdas after an arrow, where block can be not surrounded by braces
val isBlockStartingWithComment = treeNext.elementType == BLOCK && treeNext.firstChildNode.isPartOfComment()
// treeNext may not have children ( {_, _ -> })
val isBlockStartingWithComment = treeNext.elementType == BLOCK && treeNext.firstChildNode?.isPartOfComment() == true
if (textContains('\n') || treeNext.isPartOfComment() || isBlockStartingWithComment) null else text.count { it == ' ' }
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class ImmutableValNoVarRule(configRules: List<RulesConfig>) : DiktatRule(
.findAllVariablesWithAssignments { it.name != null && it.isVar }
.filter { it.value.isEmpty() }

varNoAssignments.forEach { (property, usages) ->
varNoAssignments.forEach { (_, _) ->
// FixMe: raise another warning and fix the code (change to val) for variables without assignment
}

Expand Down
Loading

0 comments on commit af0bf24

Please sign in to comment.