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

Fix all Warnings #781

Merged
merged 17 commits into from
Apr 30, 2021
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Contributing

If you reading this - then you have decided to contribute to our project. Oh, poor you...
If you're reading this - then you have decided to contribute to our project. Oh, poor you...
Rules are very simple:
1. Fork this repository to your own account
2. Make your changes and verify that tests pass (or wait that our CI/CD will do everything for you)
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ diktat {
reporter = "custom:name:pathToJar"
}
```
Name parameter is the name of your reporter and as the last parameter you should specify path to jar, which contains your reporter.
Name parameter is the name of your reporter and as the last parameter you should specify a path to jar, which contains your reporter.
[Example of the junit custom reporter.](https://github.com/kryanod/ktlint-junit-reporter)

You can also specify an output.
Expand Down Expand Up @@ -286,7 +286,7 @@ for example, a filename of file where the code is stored;
3) We added a bunch of visitors, checkers and fixers that will extended KTlint functionaliity with code style rules;
4) We have proposed a code style for Kotlin language.

Before you make a pull request, make sure the build is clean as we have lot of tests and other prechecks:
Before you make a pull request, make sure the build is clean as we have a lot of tests and other prechecks:

```bash
$ mvn clean install
Expand Down
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 Expand Up @@ -130,11 +135,6 @@ data class CommonConfiguration(private val configuration: Map<String, String>?)
}
}

/**
* False if configuration has been read from config file, true if defaults are used
*/
val isDefault = configuration == null

companion object {
/**
* Counter that helps not to raise multiple warnings about kotlin version
Expand Down
2 changes: 1 addition & 1 deletion diktat-gradle-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Build of gradle plugin is performed by gradle, but is wrapped in maven build. The module's `pom.xml` isn't exactly accurate
and doesn't include gradle-specific dependencies, that are automatically provided by gradle when applying the plugin.

To avoid versions duplication, diktat and ktlint versions are passed to gradle via properties when running gradle task from maven.
To avoid versions duplication, diktat and ktlint versions are passed to gradle via properties when running gradle task from a maven.
kentr0w marked this conversation as resolved.
Show resolved Hide resolved
These versions are then written in a file and then included in the plugin jar to determine dependencies for JavaExec.

Gradle plugin marker pom, which is normally produced by `java-gradle-plugin` plugin during gradle build,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,21 @@ 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 @@ -25,7 +25,7 @@ import javax.inject.Inject
*
* Note: class being `open` is required for gradle to create a task.
*/
open class DiktatJavaExecTaskBase @Inject constructor(
class DiktatJavaExecTaskBase @Inject constructor(
kentr0w marked this conversation as resolved.
Show resolved Hide resolved
gradleVersionString: String,
diktatExtension: DiktatExtension,
diktatConfiguration: Configuration,
Expand Down Expand Up @@ -94,6 +94,9 @@ open class DiktatJavaExecTaskBase @Inject constructor(
logger.debug("Setting JavaExec args to $args")
}

/**
* Function to execute diKTat
*/
@TaskAction
override fun exec() {
if (shouldRun) {
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
kentr0w marked this conversation as resolved.
Show resolved Hide resolved
*/
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) }
node.kDocBasicTags().let { checkEmptyLineBeforeBasicTags(it) }
node.kDocBasicTags().let { checkEmptyLinesBetweenBasicTags(it) }
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,23 @@ 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 }
.equals(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 +324,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 +340,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
@@ -1,7 +1,6 @@
package org.cqfn.diktat.ruleset.rules.chapter3

import org.cqfn.diktat.common.config.rules.RulesConfig
import org.cqfn.diktat.ruleset.constants.EmitType
import org.cqfn.diktat.ruleset.constants.Warnings.STRING_TEMPLATE_CURLY_BRACES
import org.cqfn.diktat.ruleset.constants.Warnings.STRING_TEMPLATE_QUOTES
import org.cqfn.diktat.ruleset.rules.DiktatRule
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -489,15 +489,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 @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,13 @@ class NullChecksRule(configRules: List<RulesConfig>) : DiktatRule(
when (condition.operationToken) {
// `==` and `===` comparison can be fixed with `?:` operator
ElementType.EQEQ, ElementType.EQEQEQ ->
warnAndFixOnNullCheck(condition, true,
warnAndFixOnNullCheck(condition,
"use '.let/.also/?:/e.t.c' instead of ${condition.text}") {
fixNullInIfCondition(node, condition, true)
}
// `!==` and `!==` comparison can be fixed with `.let/also` operators
ElementType.EXCLEQ, ElementType.EXCLEQEQEQ ->
warnAndFixOnNullCheck(condition, true,
warnAndFixOnNullCheck(condition,
"use '.let/.also/?:/e.t.c' instead of ${condition.text}") {
fixNullInIfCondition(node, condition, false)
}
Expand Down Expand Up @@ -140,7 +140,6 @@ class NullChecksRule(configRules: List<RulesConfig>) : DiktatRule(
if (listOf(ElementType.EXCLEQ, ElementType.EXCLEQEQEQ).contains(condition.operationToken)) {
warnAndFixOnNullCheck(
condition,
true,
"use 'requireNotNull' instead of require(${condition.text})"
) {
val variableName = (binaryExprNode.psi as KtBinaryExpression).left!!.text
Expand Down Expand Up @@ -185,7 +184,6 @@ class NullChecksRule(configRules: List<RulesConfig>) : DiktatRule(

private fun warnAndFixOnNullCheck(
condition: KtBinaryExpression,
canBeAutoFixed: Boolean,
kentr0w marked this conversation as resolved.
Show resolved Hide resolved
freeText: String,
autofix: () -> Unit) {
AVOID_NULL_CHECKS.warnAndFix(
Expand All @@ -195,7 +193,7 @@ class NullChecksRule(configRules: List<RulesConfig>) : DiktatRule(
freeText,
condition.node.startOffset,
condition.node,
canBeAutoFixed,
true,
) {
autofix()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,6 @@ class AccurateCalculationsRule(configRules: List<RulesConfig>) : DiktatRule(

/**
* @param node
* @param autoCorrect
* @param emit
*/
override fun logic(node: ASTNode) {
when (val psi = node.psi) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ class LambdaLengthRule(configRules: List<RulesConfig>) : DiktatRule(
val copyNode = node.clone() as ASTNode
val sizeLambda = countCodeLines(copyNode)
if (sizeLambda > configuration.maxLambdaLength) {
copyNode.findAllNodesWithCondition({ it.elementType == ElementType.LAMBDA_EXPRESSION }).forEachIndexed { index, node ->
copyNode.findAllNodesWithCondition({ it.elementType == ElementType.LAMBDA_EXPRESSION }).forEachIndexed { index, astNode ->
if (index > 0) {
node.treeParent.removeChild(node)
astNode.treeParent.removeChild(astNode)
}
}
val isIt = copyNode.findAllNodesWithSpecificType(ElementType.REFERENCE_EXPRESSION).map { re -> re.text }.contains("it")
Expand Down
Loading