Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
petertrr authored Dec 2, 2020
2 parents 8d9e32a + 078b6d7 commit bc2e712
Show file tree
Hide file tree
Showing 48 changed files with 1,130 additions and 703 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/metrics_for_master.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ jobs:
restore-keys: |
${{ runner.os }}-maven-build-
- name: Run tests
run: mvn -B test -DskipPluginMarker
# we need to run `install` goal here so that gradle will be able to resolve dependencies and run tests on diktat-gradle-plugin
run: mvn -B install -DskipPluginMarker
- name: Generate code coverage report
uses: codecov/codecov-action@v1
with:
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ Add this plugin to your pom.xml:
<input>${project.basedir}/src/test/kotlin</input>
</inputs>
<diktatConfigFile>diktat-analysis.yml</diktatConfigFile>
<excludes>
<exclude>${project.basedir}/src/test/kotlin/excluded</exclude>
</excludes>
</configuration>
</execution>
</executions>
Expand Down Expand Up @@ -130,6 +133,7 @@ You can then configure diktat using `diktat` extension:
diktat {
inputs = files("src/**/*.kt") // file collection that will be checked by diktat
debug = true // turn on debug logging
excludes = files("src/test/kotlin/excluded") // these files will not be checked by diktat
}
```

Expand Down
2 changes: 1 addition & 1 deletion detekt-config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ complexity:
NestedBlockDepth:
excludes: ['**/resources/**']
active: true
threshold: 4
threshold: 5
StringLiteralDuplication:
active: false
excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**']
Expand Down
1 change: 1 addition & 0 deletions diktat-gradle-plugin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ repositories {
jcenter()
}

// default value is needed for correct gradle loading in IDEA; actual value from maven is used during build
val ktlintVersion = project.properties.getOrDefault("ktlintVersion", "0.39.0") as String
val diktatVersion = project.version.takeIf { it.toString() != Project.DEFAULT_VERSION } ?: "0.1.5"
val junitVersion = project.properties.getOrDefault("junitVersion", "5.7.0") as String
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,9 @@ 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
Expand Up @@ -20,6 +20,7 @@ class DiktatGradlePlugin : Plugin<Project> {
diktatExtension.inputs = project.fileTree("src").apply {
include("**/*.kt")
}
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ 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

/**
* A base diktat task for gradle <6.8, which wraps [JavaExec]
Expand Down Expand Up @@ -45,8 +46,16 @@ open class DiktatJavaExecTaskBase @Inject constructor(
if (diktatExtension.debug) {
add("--debug")
}
add(diktatExtension.inputs.files.joinToString { it.path })
diktatExtension.inputs.files.forEach {
val pattern = project.trimRootDir(it.path)
add("\"$pattern\"")
}
diktatExtension.excludes?.files?.forEach {
val pattern = project.trimRootDir(it.path)
add("\"!$pattern\"")
}
}
logger.debug("Setting JavaExec args to $args")
}

/**
Expand Down Expand Up @@ -88,3 +97,10 @@ fun Project.registerDiktatFixTask(diktatExtension: DiktatExtension, diktatConfig
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
}
.trim(File.separatorChar)
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class DiktatJavaExecTaskTest {
fun `check command line for various inputs`() {
val pwd = project.file(".")
assertCommandLineEquals(
listOf(null, "$pwd" + listOf("src", "**", "*.kt").joinToString(File.separator, prefix = File.separator)),
listOf(null, "\"${listOf("src", "**", "*.kt").joinToString(File.separator)}\""),
DiktatExtension().apply {
inputs = project.files("src/**/*.kt")
}
Expand All @@ -31,14 +31,28 @@ class DiktatJavaExecTaskTest {
fun `check command line in debug mode`() {
val pwd = project.file(".")
assertCommandLineEquals(
listOf(null, "--debug", "$pwd${listOf("src", "**", "*.kt").joinToString(File.separator, prefix = File.separator)}"),
listOf(null, "--debug", "\"${listOf("src", "**", "*.kt").joinToString(File.separator)}\""),
DiktatExtension().apply {
inputs = project.files("src/**/*.kt")
debug = true
}
)
}

@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)}\""
),
DiktatExtension().apply {
inputs = project.files("src/**/*.kt")
excludes = project.files("src/main/kotlin/generated")
}
)
}

private fun registerDiktatTask(extension: DiktatExtension) = project.tasks.register(
"test", DiktatJavaExecTaskBase::class.java,
"6.7", extension, project.configurations.create("diktat")
Expand Down
23 changes: 23 additions & 0 deletions diktat-maven-plugin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,25 @@
<artifactId>ktlint-reporter-plain</artifactId>
<version>${ktlint.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-testing</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
<version>3.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<!-- to use org.apache.maven.repository.RepositorySystem in newer maven versions and maybe other classes -->
<groupId>org.apache.maven</groupId>
<artifactId>maven-compat</artifactId>
<version>${maven.api.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down Expand Up @@ -77,6 +96,10 @@
</configuration>
</execution>
</executions>
<configuration>
<apiVersion>1.4</apiVersion>
<languageVersion>1.4</languageVersion>
</configuration>
</plugin>
</plugins>
</build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,14 @@ abstract class DiktatBaseMojo : AbstractMojo() {
/**
* Paths that will be scanned for .kt(s) files
*/
@Parameter(property = "diktat.inputs")
var inputs = listOf("\${project.basedir}/src")
@Parameter(property = "diktat.inputs", defaultValue = "\${project.basedir}/src")
lateinit var inputs: List<String>

/**
* Paths that will be excluded if encountered during diktat run
*/
@Parameter(property = "diktat.excludes", defaultValue = "")
lateinit var excludes: List<String>

/**
* Flag that indicates whether to turn debug logging on
Expand All @@ -45,7 +51,7 @@ abstract class DiktatBaseMojo : AbstractMojo() {
* Property that can be used to access various maven settings
*/
@Parameter(defaultValue = "\${project}", readonly = true)
lateinit var mavenProject: MavenProject
private lateinit var mavenProject: MavenProject

/**
* @param params instance of [KtLint.Params] used in analysis
Expand All @@ -63,7 +69,9 @@ abstract class DiktatBaseMojo : AbstractMojo() {
if (!File(configFile).exists()) {
throw MojoExecutionException("Configuration file $configFile doesn't exist")
}
log.info("Running diKTat plugin with configuration file $configFile and inputs $inputs")
log.info("Running diKTat plugin with configuration file $configFile and inputs $inputs" +
if (excludes.isNotEmpty()) " and excluding $excludes" else ""
)

val ruleSets by lazy {
listOf(DiktatRuleSetProvider(configFile).get())
Expand Down Expand Up @@ -97,12 +105,14 @@ abstract class DiktatBaseMojo : AbstractMojo() {
* @throws MojoExecutionException if [RuleExecutionException] has been thrown by ktlint
*/
private fun checkDirectory(directory: File, lintErrors: MutableList<LintError>, ruleSets: Iterable<RuleSet>) {
val (excludedDirs, excludedFiles) = excludes.map(::File).partition { it.isDirectory }
directory
.walk()
.filter { file ->
file.isDirectory || file.extension.let { it == "kt" || it == "kts" }
}
.filter { it.isFile }
.filterNot { file -> file in excludedFiles || excludedDirs.any { file.startsWith(it) } }
.forEach { file ->
log.debug("Checking file $file")
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package org.cqfn.diktat.plugin.maven

import org.apache.maven.plugin.testing.MojoRule
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.createTempFile
import kotlin.io.path.writeText

/**
* Tests for mojo configuration
*
* FixMe: `@Parameter` properties are not initialized with default values
*/
@OptIn(ExperimentalPathApi::class)
class DiktatBaseMojoTest {
@get:Rule
val mojoRule = MojoRule()

@Test
fun `test plugin configuration`() {
val pom = createTempFile()
pom.writeText(
"""
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.cqfn.diktat</groupId>
<artifactId>diktat-test</artifactId>
<version>0.1.6-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.cqfn.diktat</groupId>
<artifactId>diktat-maven-plugin</artifactId>
<configuration>
<diktatConfigFile>diktat-analysis.yml</diktatConfigFile>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
""".trimIndent()
)
val diktatCheckMojo = mojoRule.lookupMojo("check", pom.toFile()) as DiktatCheckMojo
Assert.assertEquals(false, diktatCheckMojo.debug)
Assert.assertEquals("diktat-analysis.yml", diktatCheckMojo.diktatConfigFile)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ enum class Warnings(val canBeAutoCorrected: Boolean, val ruleId: String, private
GENERIC_VARIABLE_WRONG_DECLARATION(true, "4.3.2", "variable should have explicit type declaration"),
// FixMe: change float literal to BigDecimal? Or kotlin equivalent?
FLOAT_IN_ACCURATE_CALCULATIONS(false, "4.1.1", "floating-point values shouldn't be used in accurate calculations"),
AVOID_NULL_CHECKS(false, "4.3.3", "Try to avoid explicit null-checks. Use '.let/.also/?:/e.t.c' instead of"),
AVOID_NULL_CHECKS(false, "4.3.3", "Try to avoid explicit null-checks"),

// ======== chapter 5 ========
TOO_LONG_FUNCTION(false, "5.1.1", "function is too long: split it or make more primitive"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import org.jetbrains.kotlin.psi.KtTryExpression
* - braces around `else`/`catch`/`finally`/`while` (in `do-while` loop)
*/
class BlockStructureBraces(private val configRules: List<RulesConfig>) : Rule("block-structure") {

private var isFixMode: Boolean = false
private lateinit var emitWarn: ((offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit)

Expand Down Expand Up @@ -178,6 +179,15 @@ class BlockStructureBraces(private val configRules: List<RulesConfig>) : Rule("b
if (braceSpace == null || braceSpace.elementType != WHITE_SPACE) {
node.addChild(PsiWhiteSpaceImpl(" "), nodeBefore)
} else {
if (braceSpace.treePrev.elementType in COMMENT_TYPE) {
val commentBefore = braceSpace.treePrev
if (commentBefore.treePrev.elementType == WHITE_SPACE) {
commentBefore.treeParent.removeChild(commentBefore.treePrev)
}
commentBefore.treeParent.removeChild(commentBefore)
node.treeParent.addChild(commentBefore.clone() as ASTNode, node)
node.treeParent.addChild(PsiWhiteSpaceImpl("\n"), node)
}
braceSpace.treeParent.replaceWhiteSpaceText(braceSpace, " ")
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@ import com.pinterest.ktlint.core.ast.ElementType.WHILE
import com.pinterest.ktlint.core.ast.ElementType.WHILE_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.WHITE_SPACE
import com.pinterest.ktlint.core.ast.nextSibling
import com.pinterest.ktlint.core.ast.isPartOfComment
import com.pinterest.ktlint.core.ast.prevSibling
import org.cqfn.diktat.ruleset.utils.findChildrenMatching
import org.cqfn.diktat.common.config.rules.RulesConfig
import org.cqfn.diktat.ruleset.constants.Warnings.NO_BRACES_IN_CONDITIONALS_AND_LOOPS
import org.cqfn.diktat.ruleset.utils.isSingleLineIfElse
import org.cqfn.diktat.ruleset.utils.prettyPrint
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.CompositeElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
Expand Down Expand Up @@ -130,7 +133,10 @@ class BracesInConditionalsAndLoopsRule(private val configRules: List<RulesConfig
.asSequence()
.filter { it.expression != null && it.expression!!.node.elementType == BLOCK }
.map { it.expression as KtBlockExpression }
.filter { it.statements.size == 1 }
.filter { block ->
block.statements.size == 1 &&
block.findChildrenMatching { it.isPartOfComment() }.isEmpty()
}
.forEach {
NO_BRACES_IN_CONDITIONALS_AND_LOOPS.warnAndFix(configRules, emitWarn, isFixMode, "WHEN", it.node.startOffset, it.node) {
it.astReplace(it.firstStatement!!.node.psi)
Expand Down
Loading

0 comments on commit bc2e712

Please sign in to comment.