Skip to content

Commit

Permalink
Merge branch 'master' into bugfix/AddInLongLineAnalysisEQEQEQAndEXCLE…
Browse files Browse the repository at this point in the history
…QEQEQ
  • Loading branch information
Arrgentum authored Jun 22, 2022
2 parents 67b8a3d + b4fed8f commit 9562d9f
Show file tree
Hide file tree
Showing 191 changed files with 1,980 additions and 1,048 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ const val DIKTAT_COMMON = "DIKTAT_COMMON"
*/
const val DIKTAT = "diktat"

/**
* this constant will be used everywhere in the code to mark usage of Diktat ruleset
*/
const val DIKTAT_RULE_SET_ID = "diktat-ruleset"
const val DIKTAT_ANALYSIS_CONF = "diktat-analysis.yml"
const val DIKTAT_CONF_PROPERTY = "diktat.config.path"

/**
* This interface represents individual inspection in rule set.
*/
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 @@ -34,7 +34,7 @@ val jacocoVersion = project.properties.getOrDefault("jacocoVersion", "0.8.7") as
dependencies {
implementation(kotlin("gradle-plugin-api"))

implementation("org.cqfn.diktat:diktat-rules:$diktatVersion") {
implementation("org.cqfn.diktat:diktat-common:$diktatVersion") {
exclude("org.jetbrains.kotlin", "kotlin-compiler-embeddable")
exclude("org.jetbrains.kotlin", "kotlin-stdlib-jdk8")
exclude("org.jetbrains.kotlin", "kotlin-stdlib-jdk7")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package org.cqfn.diktat.plugin.gradle

import org.cqfn.diktat.common.config.rules.DIKTAT_CONF_PROPERTY
import org.cqfn.diktat.plugin.gradle.DiktatGradlePlugin.Companion.DIKTAT_CHECK_TASK
import org.cqfn.diktat.plugin.gradle.DiktatGradlePlugin.Companion.DIKTAT_FIX_TASK
import org.cqfn.diktat.plugin.gradle.DiktatGradlePlugin.Companion.MIN_JVM_REQUIRES_ADD_OPENS
import org.cqfn.diktat.ruleset.rules.DIKTAT_CONF_PROPERTY

import generated.DIKTAT_VERSION
import generated.KTLINT_VERSION
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.cqfn.diktat.plugin.gradle

import org.cqfn.diktat.ruleset.rules.DIKTAT_CONF_PROPERTY
import org.cqfn.diktat.common.config.rules.DIKTAT_CONF_PROPERTY

import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
import org.junit.jupiter.api.AfterEach
Expand Down Expand Up @@ -207,7 +208,7 @@ class DiktatJavaExecTaskTest {
}

private fun combinePathParts(vararg parts: String) = parts.joinToString(File.separator)

companion object {
private const val DIKTAT_CHECK_TASK = "diktatCheck"
}
Expand Down
5 changes: 5 additions & 0 deletions diktat-maven-plugin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@
</configuration>
</execution>
</executions>
<configuration>
<args>
<arg>-Xuse-k2</arg>
</args>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
@file:Suppress(
"Deprecation"
)

package org.cqfn.diktat.plugin.maven

import org.cqfn.diktat.ruleset.rules.DiktatRuleSetProvider
Expand All @@ -7,8 +11,8 @@ import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.core.Reporter
import com.pinterest.ktlint.core.RuleExecutionException
import com.pinterest.ktlint.core.RuleSet
import com.pinterest.ktlint.core.api.FeatureInAlphaState
import com.pinterest.ktlint.core.internal.CurrentBaseline
import com.pinterest.ktlint.core.internal.containsLintError
import com.pinterest.ktlint.core.internal.loadBaseline
import com.pinterest.ktlint.reporter.baseline.BaselineReporter
import com.pinterest.ktlint.reporter.html.HtmlReporter
Expand Down Expand Up @@ -94,7 +98,6 @@ abstract class DiktatBaseMojo : AbstractMojo() {
/**
* @param params instance of [KtLint.ExperimentalParams] used in analysis
*/
@OptIn(FeatureInAlphaState::class)
abstract fun runAction(params: KtLint.ExperimentalParams)

/**
Expand Down Expand Up @@ -210,7 +213,7 @@ abstract class DiktatBaseMojo : AbstractMojo() {
.forEach { file ->
log.debug("Checking file $file")
try {
reporterImpl.before(file.path)
reporterImpl.before(file.absolutePath)
checkFile(
file,
lintErrors,
Expand All @@ -220,15 +223,14 @@ abstract class DiktatBaseMojo : AbstractMojo() {
),
ruleSets
)
reporterImpl.after(file.path)
reporterImpl.after(file.absolutePath)
} catch (e: RuleExecutionException) {
log.error("Unhandled exception during rule execution: ", e)
throw MojoExecutionException("Unhandled exception during rule execution", e)
}
}
}

@OptIn(FeatureInAlphaState::class)
private fun checkFile(file: File,
lintErrors: MutableList<LintError>,
baselineErrors: List<LintError>,
Expand All @@ -237,18 +239,13 @@ abstract class DiktatBaseMojo : AbstractMojo() {
val text = file.readText()
val params =
KtLint.ExperimentalParams(
fileName = file.relativeTo(mavenProject.basedir).path,
fileName = file.absolutePath,
text = text,
ruleSets = ruleSets,
userData = mapOf("file_path" to file.path),
script = file.extension.equals("kts", ignoreCase = true),
cb = { lintError, isCorrected ->
if (baselineErrors.none {
// ktlint's BaselineReporter stores only these fields
it.line == lintError.line && it.col == lintError.col &&
it.ruleId == lintError.ruleId
}) {
reporterImpl.onLintError(file.path, lintError, isCorrected)
if (!baselineErrors.containsLintError(lintError)) {
reporterImpl.onLintError(file.absolutePath, lintError, isCorrected)
lintErrors.add(lintError)
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,11 @@ class DiktatFixMojo : DiktatBaseMojo() {
@OptIn(FeatureInAlphaState::class)
override fun runAction(params: KtLint.ExperimentalParams) {
val fileName = params.fileName
val filePath = params.userData["file_path"] ?: error("File path should be provided")
val fileContent = File(filePath).readText(charset("UTF-8"))
val fileContent = File(fileName).readText(charset("UTF-8"))
val formattedText = KtLint.format(params)
if (fileContent != formattedText) {
log.info("Original and formatted content differ, writing to $fileName...")
File(filePath).writeText(formattedText, charset("UTF-8"))
File(fileName).writeText(formattedText, charset("UTF-8"))
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class DiktatMavenPluginIntegrationTest {

with(SoftAssertions()) {
try {
assertThat(mavenLog).containsPattern("""Original and formatted content differ, writing to [:\w/\\]+Test\.kt\.\.\.""")
assertThat(mavenLog).containsPattern("""Original and formatted content differ, writing to [:\w/\\-]+Test\.kt\.\.\.""")
assertThat(mavenLog).containsPattern("There are \\d+ lint errors")
assertThat(mavenLog).contains("[MISSING_KDOC_TOP_LEVEL]")
} finally {
Expand Down
1 change: 1 addition & 0 deletions diktat-rules/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@
<configuration>
<args>
<arg>-Xinline-classes</arg>
<arg>-Xuse-k2</arg>
</args>
</configuration>
</plugin>
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package org.cqfn.diktat.ruleset.rules

import org.cqfn.diktat.common.config.rules.DIKTAT_ANALYSIS_CONF
import org.cqfn.diktat.common.config.rules.DIKTAT_COMMON
import org.cqfn.diktat.common.config.rules.DIKTAT_CONF_PROPERTY
import org.cqfn.diktat.common.config.rules.DIKTAT_RULE_SET_ID
import org.cqfn.diktat.common.config.rules.RulesConfig
import org.cqfn.diktat.common.config.rules.RulesConfigReader
import org.cqfn.diktat.ruleset.constants.EmitType
import org.cqfn.diktat.ruleset.constants.Warnings
import org.cqfn.diktat.ruleset.dummy.DummyWarning
import org.cqfn.diktat.ruleset.rules.OrderedRuleSet.Companion.ordered
import org.cqfn.diktat.ruleset.rules.chapter1.FileNaming
import org.cqfn.diktat.ruleset.rules.chapter1.IdentifierNaming
import org.cqfn.diktat.ruleset.rules.chapter1.PackageNaming
Expand Down Expand Up @@ -81,22 +83,13 @@ import org.cqfn.diktat.ruleset.rules.chapter6.classes.SingleConstructorRule
import org.cqfn.diktat.ruleset.rules.chapter6.classes.SingleInitRule
import org.cqfn.diktat.ruleset.rules.chapter6.classes.StatelessClassesRule

import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.RuleSet
import com.pinterest.ktlint.core.RuleSetProvider
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.org.jline.utils.Levenshtein
import org.slf4j.LoggerFactory

import java.io.File

/**
* this constant will be used everywhere in the code to mark usage of Diktat ruleset
*/
const val DIKTAT_RULE_SET_ID = "diktat-ruleset"
const val DIKTAT_ANALYSIS_CONF = "diktat-analysis.yml"
const val DIKTAT_CONF_PROPERTY = "diktat.config.path"

/**
* [RuleSetProvider] that provides diKTat ruleset.
* By default it is expected to have diktat-analysis.yml configuration in the root folder where 'ktlint' is run
Expand Down Expand Up @@ -144,9 +137,6 @@ class DiktatRuleSetProvider(private var diktatConfigFile: String = DIKTAT_ANALYS
// We don't have a way to enforce a specific order, so we should just be careful when adding new rules to this list and, when possible,
// cover new rules in smoke test as well. If a rule needs to be at a specific position in a list, please add comment explaining it (like for NewlinesRule).
val rules = listOf(
// test warning that can be used for manual testing of diktat
::DummyWarning,

// comments & documentation
::CommentsRule,
::SingleConstructorRule, // this rule can add properties to a primary constructor, so should be before KdocComments
Expand Down Expand Up @@ -231,13 +221,10 @@ class DiktatRuleSetProvider(private var diktatConfigFile: String = DIKTAT_ANALYS
.map {
it.invoke(configRules)
}
val orderedRules = rules.mapIndexed { index, rule ->
if (index != 0) OrderedRule(rule, rules[index - 1]) else rule
}
return RuleSet(
DIKTAT_RULE_SET_ID,
rules = orderedRules.toTypedArray()
)
rules = rules.toTypedArray()
).ordered()
}

private fun validate(config: RulesConfig) =
Expand Down Expand Up @@ -269,43 +256,7 @@ class DiktatRuleSetProvider(private var diktatConfigFile: String = DIKTAT_ANALYS

private fun resolveConfigFileFromSystemProperty(): String? = System.getProperty(DIKTAT_CONF_PROPERTY)

/**
* This is a wrapper around Ktlint Rule which adjusts visitorModifiers to keep order with prevRule
* Added as a workaround after introducing a new logic for sorting KtLint Rules: https://github.com/pinterest/ktlint/issues/1478
*
* @property rule KtLink Rule which this class wraps
*
* @param prevRule previous KtLink Rule, the wrapped rule is called after prevRule
*/
internal class OrderedRule(val rule: Rule, prevRule: Rule) : Rule(rule.id, adjustVisitorModifiers(rule, prevRule)) {
/**
* Delegating a call of this method
*/
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: EmitType
) {
rule.visit(node, autoCorrect, emit)
}
}

companion object {
private val log = LoggerFactory.getLogger(DiktatRuleSetProvider::class.java)

private fun adjustVisitorModifiers(rule: Rule, prevRule: Rule): Set<Rule.VisitorModifier> {
val visitorModifiers: Set<Rule.VisitorModifier> = rule.visitorModifiers
require(visitorModifiers.none { it is Rule.VisitorModifier.RunAfterRule }) {
"Rule ${rule.id} already contains VisitorModifier.RunAfterRule"
}
require(rule.id != prevRule.id) {
"PrevRule has same ID as rule: ${rule.id}"
}
return visitorModifiers + Rule.VisitorModifier.RunAfterRule(
ruleId = prevRule.id,
loadOnlyWhenOtherRuleIsLoaded = false,
runOnlyWhenOtherRuleIsEnabled = false
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package org.cqfn.diktat.ruleset.rules

import org.cqfn.diktat.ruleset.constants.EmitType
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.RuleSet
import org.jetbrains.kotlin.com.intellij.lang.ASTNode

/**
* This is a wrapper around Ktlint RuleSet which adjusts visitorModifiers for all rules to keep order with prevRule
* Added as a workaround after introducing a new logic for sorting KtLint Rules: https://github.com/pinterest/ktlint/issues/1478
*
* @param id ID of RuleSet
* @param rules rules which belongs to current RuleSet
*/
class OrderedRuleSet(id: String, vararg rules: Rule) : RuleSet(id, rules = adjustRules(id, rules = rules)) {
companion object {
private fun adjustRules(ruleSetId: String, vararg rules: Rule): Array<out Rule> {
if (rules.isEmpty()) {
return rules
}
return rules.mapIndexed { index, rule ->
if (index == 0) {
checkVisitorModifiers(rule)
rule
} else {
OrderedRule(ruleSetId, rule, rules[index - 1])
}
}.toTypedArray()
}

private fun adjustVisitorModifiers(
ruleSetId: String,
rule: Rule,
prevRule: Rule
): Set<Rule.VisitorModifier> {
val visitorModifiers: Set<Rule.VisitorModifier> = rule.visitorModifiers
checkVisitorModifiers(rule)
require(rule.id != prevRule.id) {
"PrevRule has same ID as rule: ${rule.id}"
}
return visitorModifiers + Rule.VisitorModifier.RunAfterRule(
ruleId = ruleSetId + ":" + prevRule.id,
loadOnlyWhenOtherRuleIsLoaded = false,
runOnlyWhenOtherRuleIsEnabled = false
)
}

private fun checkVisitorModifiers(rule: Rule) {
require(rule.visitorModifiers.none { it is Rule.VisitorModifier.RunAfterRule }) {
"Rule ${rule.id} contains VisitorModifier.RunAfterRule"
}
}

/**
* @return a rule to which a logic is delegated
*/
internal fun Rule.delegatee(): Rule = if (this is OrderedRule) this.rule else this

/**
* @return RuleSet with ordered rules
*/
fun RuleSet.ordered(): OrderedRuleSet = OrderedRuleSet(id = id, rules = rules)

/**
* @property rule wraps this rule to keep order
*/
private class OrderedRule(
ruleSetId: String,
val rule: Rule,
prevRule: Rule
) : Rule(rule.id, adjustVisitorModifiers(ruleSetId, rule, prevRule)) {
/**
* Delegating a call of this method
*/
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: EmitType
) {
rule.visit(node, autoCorrect, emit)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class FileNaming(configRules: List<RulesConfig>) : DiktatRule(

companion object {
// FixMe: should be moved to properties
const val NAME_ID = "aag-file-naming"
const val NAME_ID = "file-naming"
val validExtensions = listOf(".kt", ".kts")
}
}
Loading

0 comments on commit 9562d9f

Please sign in to comment.