Skip to content

Commit

Permalink
Removed file path from warning messages (#621)
Browse files Browse the repository at this point in the history
### What's done:
* Changed code
* Changed tests
  • Loading branch information
petertrr authored Dec 9, 2020
1 parent ac07d98 commit d2223c5
Show file tree
Hide file tree
Showing 18 changed files with 71 additions and 84 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ class AvoidUtilityClass(private val configRules: List<RulesConfig>) : Rule("avoi
emitWarn = emit
isFixMode = autoCorrect
val config by configRules.getCommonConfiguration()
val fileName = node.getRootNode().getFileName()
if (!(node.hasTestAnnotation() || isLocatedInTest(fileName.splitPathToDirs(), config.testAnchors))) {
val filePath = node.getRootNode().getFilePath()
if (!(node.hasTestAnnotation() || isLocatedInTest(filePath.splitPathToDirs(), config.testAnchors))) {
if (node.elementType == OBJECT_DECLARATION || node.elementType == CLASS) {
checkClass(node)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import org.cqfn.diktat.ruleset.constants.EmitType
import org.cqfn.diktat.ruleset.constants.Warnings.FILE_NAME_INCORRECT
import org.cqfn.diktat.ruleset.constants.Warnings.FILE_NAME_MATCH_CLASS
import org.cqfn.diktat.ruleset.utils.getAllChildrenWithType
import org.cqfn.diktat.ruleset.utils.getFileName
import org.cqfn.diktat.ruleset.utils.getFilePath
import org.cqfn.diktat.ruleset.utils.getFirstChildWithType
import org.cqfn.diktat.ruleset.utils.isPascalCase

Expand All @@ -29,7 +29,7 @@ import java.io.File
class FileNaming(private val configRules: List<RulesConfig>) : Rule("file-naming") {
private var isFixMode: Boolean = false
private lateinit var emitWarn: EmitType
private lateinit var fileName: String
private lateinit var filePath: String

override fun visit(node: ASTNode,
autoCorrect: Boolean,
Expand All @@ -38,24 +38,24 @@ class FileNaming(private val configRules: List<RulesConfig>) : Rule("file-naming
isFixMode = autoCorrect

if (node.elementType == FILE) {
fileName = node.getFileName()
filePath = node.getFilePath()
checkFileNaming(node)
checkClassNameMatchesWithFile(node)
}
}

private fun checkFileNaming(node: ASTNode) {
val (name, extension) = getFileParts(fileName)
val (name, extension) = getFileParts(filePath)
if (!name.isPascalCase() || !validExtensions.contains(extension)) {
FILE_NAME_INCORRECT.warnAndFix(configRules, emitWarn, isFixMode, "$name$extension", 0, node) {
// FixMe: we can add an autocorrect here in future, but is there any purpose to change file or class name?
}
}
}

@Suppress("UnsafeCallOnNullableType")
@Suppress("UnsafeCallOnNullableType", "ControlFlowWithEmptyBody")
private fun checkClassNameMatchesWithFile(fileLevelNode: ASTNode) {
val (fileNameWithoutSuffix, fileNameSuffix) = getFileParts(fileName)
val (fileNameWithoutSuffix, fileNameSuffix) = getFileParts(filePath)
val classes = fileLevelNode.getAllChildrenWithType(CLASS)
if (classes.size == 1) {
val className = classes[0].getFirstChildWithType(IDENTIFIER)!!.text
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import com.pinterest.ktlint.core.ast.isLeaf
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.lexer.KtTokens.PACKAGE_KEYWORD
import org.slf4j.LoggerFactory
import java.util.concurrent.atomic.AtomicInteger
Expand Down Expand Up @@ -54,13 +55,13 @@ class PackageNaming(private val configRules: List<RulesConfig>) : Rule("package-
.domainName

if (node.elementType == PACKAGE_DIRECTIVE) {
val fileName = node.getRootNode().getFileName()
val filePath = node.getRootNode().getFilePath()
// calculating package name based on the directory where the file is placed
val realPackageName = calculateRealPackageName(fileName)
val realPackageName = calculateRealPackageName(filePath)

// if node isLeaf - this means that there is no package name declared
if (node.isLeaf()) {
warnAndFixMissingPackageName(node, realPackageName, fileName)
warnAndFixMissingPackageName(node, realPackageName, filePath)
return
}

Expand All @@ -80,7 +81,8 @@ class PackageNaming(private val configRules: List<RulesConfig>) : Rule("package-
private fun warnAndFixMissingPackageName(
initialPackageDirectiveNode: ASTNode,
realPackageName: List<String>,
fileName: String) {
filePath: String) {
val fileName = filePath.substringAfterLast(File.separator)
PACKAGE_NAME_MISSING.warnAndFix(configRules, emitWarn, isFixMode, fileName,
initialPackageDirectiveNode.startOffset, initialPackageDirectiveNode) {
if (realPackageName.isNotEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ package org.cqfn.diktat.ruleset.rules.comments
import org.cqfn.diktat.common.config.rules.RuleConfiguration
import org.cqfn.diktat.common.config.rules.RulesConfig
import org.cqfn.diktat.common.config.rules.getRuleConfig
import org.cqfn.diktat.common.config.rules.isRuleEnabled
import org.cqfn.diktat.ruleset.constants.EmitType
import org.cqfn.diktat.ruleset.constants.Warnings
import org.cqfn.diktat.ruleset.constants.Warnings.HEADER_CONTAINS_DATE_OR_AUTHOR
import org.cqfn.diktat.ruleset.constants.Warnings.HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE
import org.cqfn.diktat.ruleset.constants.Warnings.HEADER_MISSING_OR_WRONG_COPYRIGHT
Expand All @@ -15,7 +13,6 @@ import org.cqfn.diktat.ruleset.constants.Warnings.WRONG_COPYRIGHT_YEAR
import org.cqfn.diktat.ruleset.utils.findChildAfter
import org.cqfn.diktat.ruleset.utils.findChildBefore
import org.cqfn.diktat.ruleset.utils.getAllChildrenWithType
import org.cqfn.diktat.ruleset.utils.getFileName
import org.cqfn.diktat.ruleset.utils.getFirstChildWithType
import org.cqfn.diktat.ruleset.utils.moveChildBefore

Expand Down Expand Up @@ -44,7 +41,6 @@ import java.time.LocalDate
@Suppress("ForbiddenComment")
class HeaderCommentRule(private val configRules: List<RulesConfig>) : Rule("header-comment") {
private val copyrightWords = setOf("copyright", "版权")
private var fileName: String = ""
private var isFixMode: Boolean = false
private lateinit var emitWarn: EmitType

Expand All @@ -55,7 +51,6 @@ class HeaderCommentRule(private val configRules: List<RulesConfig>) : Rule("head
emitWarn = emit

if (node.elementType == FILE) {
fileName = node.getFileName()
checkCopyright(node)
if (checkHeaderKdocPosition(node)) {
checkHeaderKdoc(node)
Expand Down Expand Up @@ -87,8 +82,9 @@ class HeaderCommentRule(private val configRules: List<RulesConfig>) : Rule("head
?: run {
val numDeclaredClassesAndObjects = node.getAllChildrenWithType(ElementType.CLASS).size +
node.getAllChildrenWithType(ElementType.OBJECT_DECLARATION).size
if (numDeclaredClassesAndObjects == 0 || numDeclaredClassesAndObjects > 1) {
HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE.warn(configRules, emitWarn, isFixMode, fileName, node.startOffset, node)
if (numDeclaredClassesAndObjects != 1) {
HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE.warn(configRules, emitWarn, isFixMode,
"there are $numDeclaredClassesAndObjects declared classes and/or objects", node.startOffset, node)
}
}
}
Expand All @@ -105,7 +101,7 @@ class HeaderCommentRule(private val configRules: List<RulesConfig>) : Rule("head
val firstKdoc = node.findChildAfter(IMPORT_LIST, KDOC)
// if `firstKdoc.treeParent` is File then it's a KDoc not bound to any other structures
if (node.findChildBefore(PACKAGE_DIRECTIVE, KDOC) == null && firstKdoc != null && firstKdoc.treeParent.elementType == FILE) {
HEADER_NOT_BEFORE_PACKAGE.warnAndFix(configRules, emitWarn, isFixMode, fileName, firstKdoc.startOffset, firstKdoc) {
HEADER_NOT_BEFORE_PACKAGE.warnAndFix(configRules, emitWarn, isFixMode, "header KDoc is located after package or imports", firstKdoc.startOffset, firstKdoc) {
node.moveChildBefore(firstKdoc, node.getFirstChildWithType(PACKAGE_DIRECTIVE), true)
// ensure there is no empty line between copyright and header kdoc
node.findChildBefore(PACKAGE_DIRECTIVE, BLOCK_COMMENT)?.apply {
Expand Down Expand Up @@ -144,7 +140,7 @@ class HeaderCommentRule(private val configRules: List<RulesConfig>) : Rule("head
}
}

@Suppress("TOO_LONG_FUNCTION")
@Suppress("TOO_LONG_FUNCTION", "ComplexMethod")
private fun checkCopyright(node: ASTNode) {
val configuration = CopyrightConfiguration(configRules.getRuleConfig(HEADER_MISSING_OR_WRONG_COPYRIGHT)?.configuration
?: mapOf())
Expand All @@ -162,7 +158,14 @@ class HeaderCommentRule(private val configRules: List<RulesConfig>) : Rule("head
copyrightWords.any { commentNode.text.contains(it, ignoreCase = true) }
}
if (isWrongCopyright || isMissingCopyright || isCopyrightInsideKdoc) {
HEADER_MISSING_OR_WRONG_COPYRIGHT.warnAndFix(configRules, emitWarn, isFixMode, fileName, node.startOffset, node) {
val freeText = when {
// If `isCopyrightInsideKdoc` then `isMissingCopyright` is true too, but warning text from `isCopyrightInsideKdoc` is preferable.
isCopyrightInsideKdoc -> "copyright is placed inside KDoc, but should be inside a block comment"
isWrongCopyright -> "copyright comment doesn't have correct copyright text"
isMissingCopyright -> "copyright is mandatory, but is missing"
else -> error("Should never get to this point")
}
HEADER_MISSING_OR_WRONG_COPYRIGHT.warnAndFix(configRules, emitWarn, isFixMode, freeText, node.startOffset, node) {
headerComment?.let { node.removeChild(it) }
// do not insert empty line before header kdoc
val newLines = node.findChildBefore(PACKAGE_DIRECTIVE, KDOC)?.let { "\n" } ?: "\n\n"
Expand All @@ -181,7 +184,7 @@ class HeaderCommentRule(private val configRules: List<RulesConfig>) : Rule("head
val copyrightWithCorrectYear = makeCopyrightCorrectYear(copyrightText)

if (copyrightWithCorrectYear.isNotEmpty()) {
WRONG_COPYRIGHT_YEAR.warnAndFix(configRules, emitWarn, isFixMode, fileName, node.startOffset, node) {
WRONG_COPYRIGHT_YEAR.warnAndFix(configRules, emitWarn, isFixMode, "year should be $curYear", node.startOffset, node) {
(headerComment as LeafElement).replaceWithText(headerComment.text.replace(copyrightText, copyrightWithCorrectYear))
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import org.cqfn.diktat.common.config.rules.RulesConfig
import org.cqfn.diktat.common.config.rules.getRuleConfig
import org.cqfn.diktat.ruleset.constants.EmitType
import org.cqfn.diktat.ruleset.constants.Warnings.FILE_IS_TOO_LONG
import org.cqfn.diktat.ruleset.utils.getFileName
import org.cqfn.diktat.ruleset.utils.getFilePath
import org.cqfn.diktat.ruleset.utils.splitPathToDirs

import com.pinterest.ktlint.core.Rule
Expand All @@ -18,7 +18,11 @@ import org.slf4j.LoggerFactory
*/
class FileSize(private val configRules: List<RulesConfig>) : Rule("file-size") {
private var isFixMode: Boolean = false
private var fileName: String? = null
private val configuration by lazy {
FileSizeConfiguration(
this.configRules.getRuleConfig(FILE_IS_TOO_LONG)?.configuration ?: mapOf()
)
}
private lateinit var emitWarn: EmitType

override fun visit(node: ASTNode,
Expand All @@ -27,31 +31,19 @@ class FileSize(private val configRules: List<RulesConfig>) : Rule("file-size") {
emitWarn = emit
isFixMode = autoCorrect
if (node.elementType == ElementType.FILE) {
fileName = node.getFileName()
val configuration = FileSizeConfiguration(
this.configRules.getRuleConfig(FILE_IS_TOO_LONG)?.configuration ?: mapOf()
)
val ignoreFolders = configuration.ignoreFolders

val realFilePath = calculateFilePath(fileName)

if (!realFilePath.contains(SRC_PATH)) {
val filePathParts = node.getFilePath().splitPathToDirs()
if (SRC_PATH !in filePathParts) {
log.error("$SRC_PATH directory is not found in file path")
} else {
if (ignoreFolders.none { realFilePath.containsAll(it.splitPathToDirs()) }) {
if (configuration.ignoreFolders.none {
filePathParts.containsAll(it.splitPathToDirs())
}) {
checkFileSize(node, configuration.maxSize)
}
}
return
}
}

private fun calculateFilePath(fileName: String?): List<String> = fileName?.splitPathToDirs()
?: run {
log.error("Could not find absolute path to file")
listOf()
}

private fun checkFileSize(node: ASTNode, maxSize: Long) {
val size = node
.text
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import org.cqfn.diktat.ruleset.constants.Warnings.FILE_UNORDERED_IMPORTS
import org.cqfn.diktat.ruleset.constants.Warnings.FILE_WILDCARD_IMPORTS
import org.cqfn.diktat.ruleset.rules.PackageNaming.Companion.PACKAGE_SEPARATOR
import org.cqfn.diktat.ruleset.utils.StandardPlatforms
import org.cqfn.diktat.ruleset.utils.getFileName
import org.cqfn.diktat.ruleset.utils.handleIncorrectOrder
import org.cqfn.diktat.ruleset.utils.moveChildBefore

Expand Down Expand Up @@ -50,7 +49,6 @@ import org.jetbrains.kotlin.psi.KtImportDirective
*/
class FileStructureRule(private val configRules: List<RulesConfig>) : Rule("file-structure") {
private var isFixMode: Boolean = false
private var fileName: String = ""
private val domainName by lazy {
configRules
.getCommonConfiguration()
Expand All @@ -73,7 +71,6 @@ class FileStructureRule(private val configRules: List<RulesConfig>) : Rule("file
emitWarn = emit

if (node.elementType == ElementType.FILE) {
fileName = node.getFileName()
val wildcardImportsConfig = WildCardImportsConfig(
this.configRules.getRuleConfig(FILE_WILDCARD_IMPORTS)?.configuration ?: emptyMap()
)
Expand All @@ -97,7 +94,8 @@ class FileStructureRule(private val configRules: List<RulesConfig>) : Rule("file
)
val hasCode = node.getChildren(codeTokens).isNotEmpty()
if (!hasCode) {
FILE_CONTAINS_ONLY_COMMENTS.warn(configRules, emitWarn, isFixMode, fileName, node.startOffset, node)
val freeText = if (node.text.isEmpty()) "file is empty" else "file contains no code"
FILE_CONTAINS_ONLY_COMMENTS.warn(configRules, emitWarn, isFixMode, freeText, node.startOffset, node)
}
return hasCode
}
Expand Down Expand Up @@ -183,7 +181,7 @@ class FileStructureRule(private val configRules: List<RulesConfig>) : Rule("file
.map { group -> group.sortedBy { it.text } }

if (sortedImportsGroups.flatten() != imports) {
FILE_UNORDERED_IMPORTS.warnAndFix(configRules, emitWarn, isFixMode, fileName, node.startOffset, node) {
FILE_UNORDERED_IMPORTS.warnAndFix(configRules, emitWarn, isFixMode, "${sortedImportsGroups.flatten().first().text}...", node.startOffset, node) {
rearrangeImports(node, imports, sortedImportsGroups)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import org.cqfn.diktat.common.config.rules.getRuleConfig
import org.cqfn.diktat.ruleset.constants.EmitType
import org.cqfn.diktat.ruleset.constants.Warnings.WRONG_INDENTATION
import org.cqfn.diktat.ruleset.utils.getAllLeafsWithSpecificType
import org.cqfn.diktat.ruleset.utils.getFileName
import org.cqfn.diktat.ruleset.utils.getFilePath
import org.cqfn.diktat.ruleset.utils.indentBy
import org.cqfn.diktat.ruleset.utils.indentation.ArrowInWhenChecker
import org.cqfn.diktat.ruleset.utils.indentation.AssignmentOperatorChecker
Expand Down Expand Up @@ -45,6 +45,7 @@ import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
import org.jetbrains.kotlin.com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.com.intellij.util.containers.Stack
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtLoopExpression
Expand All @@ -61,11 +62,11 @@ import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
* @see CustomIndentationChecker
*/
class IndentationRule(private val configRules: List<RulesConfig>) : Rule("indentation") {
private var fileName: String = ""
private var isFixMode: Boolean = false
private val configuration: IndentationConfig by lazy {
IndentationConfig(configRules.getRuleConfig(WRONG_INDENTATION)?.configuration ?: mapOf())
}
private lateinit var filePath: String
private lateinit var emitWarn: EmitType
private lateinit var customIndentationCheckers: List<CustomIndentationChecker>

Expand All @@ -76,7 +77,7 @@ class IndentationRule(private val configRules: List<RulesConfig>) : Rule("indent
emitWarn = emit

if (node.elementType == FILE) {
fileName = node.getFileName()
filePath = node.getFilePath()

customIndentationCheckers = listOf(
::AssignmentOperatorChecker,
Expand Down Expand Up @@ -132,6 +133,7 @@ class IndentationRule(private val configRules: List<RulesConfig>) : Rule("indent
val numBlankLinesAfter = lastChild.text.count { it == '\n' }
if (lastChild.elementType != WHITE_SPACE || numBlankLinesAfter != 1) {
val warnText = if (lastChild.elementType != WHITE_SPACE || numBlankLinesAfter == 0) "no newline" else "too many blank lines"
val fileName = filePath.substringAfterLast(File.separator)
WRONG_INDENTATION.warnAndFix(configRules, emitWarn, isFixMode, "$warnText at the end of file $fileName", node.startOffset + node.textLength, node) {
if (lastChild.elementType != WHITE_SPACE) {
node.addChild(PsiWhiteSpaceImpl("\n"), null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ class KdocComments(private val configRules: List<RulesConfig>) : Rule("kdoc-comm
isFixMode = autoCorrect

val config = configRules.getCommonConfiguration().value
val fileName = node.getRootNode().getFileName()
if (!(node.hasTestAnnotation() || isLocatedInTest(fileName.splitPathToDirs(), config.testAnchors))) {
val filePath = node.getRootNode().getFilePath()
if (!(node.hasTestAnnotation() || isLocatedInTest(filePath.splitPathToDirs(), config.testAnchors))) {
when (node.elementType) {
FILE -> checkTopLevelDoc(node)
CLASS -> checkClassElements(node)
Expand Down
Loading

0 comments on commit d2223c5

Please sign in to comment.