Add naming rules (#1697)
* Add naming rules for packages, classes, objects, functions and properties
Closes #44
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d76d74..eb4aa0c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,9 +30,9 @@
### Added
* Wrap blocks in case the max line length is exceeded or in case the block contains a new line `wrapping` ([#1643](https://github.com/pinterest/ktlint/issue/1643))
-
* patterns can be read in from `stdin` with the `--patterns-from-stdin` command line options/flags ([#1606](https://github.com/pinterest/ktlint/pull/1606))
* Add basic formatting for context receiver in `indent` rule and new experimental rule `context-receiver-wrapping` ([#1672](https://github.com/pinterest/ktlint/issue/1672))
+* Add naming rules for packages (`package-naming`), classes (`class-naming`), objects (`object-naming`), functions (`function-naming`) and properties (`property-naming`) ([#44](https://github.com/pinterest/ktlint/issue/44))
### Fixed
diff --git a/docs/rules/experimental.md b/docs/rules/experimental.md
index 2aa8180..ee6c8ad 100644
--- a/docs/rules/experimental.md
+++ b/docs/rules/experimental.md
@@ -37,6 +37,38 @@
Rule id: `function-signature`
+## Naming
+
+### Class naming
+
+Enforce naming of class.
+
+Rule id: `experimental:class-naming`
+
+### Function naming
+
+Enforce naming of function.
+
+Rule id: `experimental:function-naming`
+
+### Object naming
+
+Enforce naming of object.
+
+Rule id: `experimental:object-naming`
+
+### Package naming
+
+Enforce naming of package.
+
+Rule id: `experimental:package-naming`
+
+### Property naming
+
+Enforce naming of property.
+
+Rule id: `experimental:property-naming`
+
## Spacing
### Fun keyword spacing
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/KtLint.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/KtLint.kt
index 0f56f42..93fb770 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/KtLint.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/KtLint.kt
@@ -1,11 +1,11 @@
package com.pinterest.ktlint.core
import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.codeStyleSetProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.CODE_STYLE_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigDefaults
-import com.pinterest.ktlint.core.api.EditorConfigDefaults.Companion.emptyEditorConfigDefaults
+import com.pinterest.ktlint.core.api.EditorConfigDefaults.Companion.EMPTY_EDITOR_CONFIG_DEFAULTS
import com.pinterest.ktlint.core.api.EditorConfigOverride
-import com.pinterest.ktlint.core.api.EditorConfigOverride.Companion.emptyEditorConfigOverride
+import com.pinterest.ktlint.core.api.EditorConfigOverride.Companion.EMPTY_EDITOR_CONFIG_OVERRIDE
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.internal.EditorConfigFinder
@@ -13,7 +13,7 @@
import com.pinterest.ktlint.core.internal.EditorConfigLoader
import com.pinterest.ktlint.core.internal.RuleExecutionContext
import com.pinterest.ktlint.core.internal.SuppressHandler
-import com.pinterest.ktlint.core.internal.ThreadSafeEditorConfigCache.Companion.threadSafeEditorConfigCache
+import com.pinterest.ktlint.core.internal.ThreadSafeEditorConfigCache.Companion.THREAD_SAFER_EDITOR_CONFIG_CACHE
import com.pinterest.ktlint.core.internal.VisitorProvider
import com.pinterest.ktlint.core.internal.createRuleExecutionContext
import com.pinterest.ktlint.core.internal.toQualifiedRuleId
@@ -47,7 +47,7 @@
internal const val UTF8_BOM = "\uFEFF"
public const val STDIN_FILE: String = "<stdin>"
- internal val editorConfigLoader = EditorConfigLoader(FileSystems.getDefault())
+ internal val EDITOR_CONFIG_LOADER = EditorConfigLoader(FileSystems.getDefault())
/**
* Parameters to invoke [KtLint.lint] and [KtLint.format] API's.
@@ -94,8 +94,8 @@
@Deprecated("Marked for removal in KtLint 0.48. Use 'editorConfigDefaults' to specify default property values")
val editorConfigPath: String? = null,
val debug: Boolean = false,
- val editorConfigDefaults: EditorConfigDefaults = emptyEditorConfigDefaults,
- val editorConfigOverride: EditorConfigOverride = emptyEditorConfigOverride,
+ val editorConfigDefaults: EditorConfigDefaults = EMPTY_EDITOR_CONFIG_DEFAULTS,
+ val editorConfigOverride: EditorConfigOverride = EMPTY_EDITOR_CONFIG_OVERRIDE,
val isInvokedFromCli: Boolean = false,
) {
internal val ruleRunners: Set<RuleRunner> =
@@ -337,7 +337,7 @@
* Reduce memory usage by cleaning internal caches.
*/
public fun trimMemory() {
- threadSafeEditorConfigCache.clear()
+ THREAD_SAFER_EDITOR_CONFIG_CACHE.clear()
}
/**
@@ -357,7 +357,7 @@
* '.editorconfig' files which need to be observed.
*/
public fun reloadEditorConfigFile(path: Path) {
- threadSafeEditorConfigCache.reloadIfExists(
+ THREAD_SAFER_EDITOR_CONFIG_CACHE.reloadIfExists(
Resource.Resources.ofPath(path, StandardCharsets.UTF_8),
)
}
@@ -387,11 +387,11 @@
val codeStyle =
params
.editorConfigOverride
- .properties[codeStyleSetProperty]
+ .properties[CODE_STYLE_PROPERTY]
?.parsed
?.safeAs<DefaultEditorConfigProperties.CodeStyleValue>()
- ?: codeStyleSetProperty.defaultValue
- return EditorConfigGenerator(editorConfigLoader).generateEditorconfig(
+ ?: CODE_STYLE_PROPERTY.defaultValue
+ return EditorConfigGenerator(EDITOR_CONFIG_LOADER).generateEditorconfig(
filePath,
params.getRules(),
params.debug,
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/Baseline.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/Baseline.kt
index 07918cc..f396189 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/Baseline.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/Baseline.kt
@@ -15,7 +15,7 @@
import org.w3c.dom.Element
import org.xml.sax.SAXException
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* Baseline of lint errors to be ignored in subsequent calls to ktlint.
@@ -64,18 +64,18 @@
status = VALID,
)
} catch (e: IOException) {
- logger.error { "Unable to parse baseline file: $path" }
+ LOGGER.error { "Unable to parse baseline file: $path" }
} catch (e: ParserConfigurationException) {
- logger.error { "Unable to parse baseline file: $path" }
+ LOGGER.error { "Unable to parse baseline file: $path" }
} catch (e: SAXException) {
- logger.error { "Unable to parse baseline file: $path" }
+ LOGGER.error { "Unable to parse baseline file: $path" }
}
// Baseline can not be parsed.
try {
baselineFile.delete()
} catch (e: IOException) {
- logger.error { "Unable to delete baseline file: $path" }
+ LOGGER.error { "Unable to delete baseline file: $path" }
}
return Baseline(status = INVALID)
}
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/EditorConfigDefaults.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/EditorConfigDefaults.kt
index bf79ceb..7284f2f 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/EditorConfigDefaults.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/EditorConfigDefaults.kt
@@ -9,28 +9,35 @@
*/
public data class EditorConfigDefaults(public val value: EditorConfig) {
public companion object {
- private val editorConfigDefaultsLoader = EditorConfigDefaultsLoader()
+ private val EDITOR_CONFIG_DEFAULTS_LOADER = EditorConfigDefaultsLoader()
/**
* Loads properties from [path]. [path] may either locate a file (also allows specifying a file with a name other
* than ".editorconfig") or a directory in which a file with name ".editorconfig" is expected to exist. Properties
* from all globs are returned.
*
- * If [path] is not valid then the [emptyEditorConfigDefaults] is returned.
+ * If [path] is not valid then the [EMPTY_EDITOR_CONFIG_DEFAULTS] is returned.
*
* The property "root" which denotes whether the parent directory is to be checked for the existence of a fallback
* ".editorconfig" is ignored entirely.
*/
public fun load(path: Path?): EditorConfigDefaults =
if (path == null) {
- emptyEditorConfigDefaults
+ EMPTY_EDITOR_CONFIG_DEFAULTS
} else {
- editorConfigDefaultsLoader.load(path)
+ EDITOR_CONFIG_DEFAULTS_LOADER.load(path)
}
/**
* Empty representation of [EditorConfigDefaults].
*/
- public val emptyEditorConfigDefaults: EditorConfigDefaults = EditorConfigDefaults(EditorConfig.builder().build())
+ public val EMPTY_EDITOR_CONFIG_DEFAULTS: EditorConfigDefaults = EditorConfigDefaults(EditorConfig.builder().build())
+
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("EMPTY_EDITOR_CONFIG_DEFAULTS"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val emptyEditorConfigDefaults: EditorConfigDefaults = EMPTY_EDITOR_CONFIG_DEFAULTS
}
}
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/EditorConfigOverride.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/EditorConfigOverride.kt
index 8d9c28c..9b24353 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/EditorConfigOverride.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/EditorConfigOverride.kt
@@ -69,6 +69,13 @@
* Get the empty [EditorConfigOverride]. As it does not contain any properties, all properties fall back on
* their respective default values.
*/
- public val emptyEditorConfigOverride: EditorConfigOverride = EditorConfigOverride()
+ public val EMPTY_EDITOR_CONFIG_OVERRIDE: EditorConfigOverride = EditorConfigOverride()
+
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("EMPTY_EDITOR_CONFIG_OVERRIDE"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val emptyEditorConfigOverride: EditorConfigOverride = EMPTY_EDITOR_CONFIG_OVERRIDE
}
}
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/UsesEditorConfigProperties.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/UsesEditorConfigProperties.kt
index 5482aa0..a7a6fb8 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/UsesEditorConfigProperties.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/UsesEditorConfigProperties.kt
@@ -2,10 +2,10 @@
import com.pinterest.ktlint.core.IndentConfig
import com.pinterest.ktlint.core.KtLint
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.CODE_STYLE_PROPERTY
import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.CodeStyleValue
import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.CodeStyleValue.android
import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.CodeStyleValue.official
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.codeStyleSetProperty
import com.pinterest.ktlint.core.initKtLintKLogger
import mu.KotlinLogging
import org.ec4j.core.model.Property
@@ -13,7 +13,7 @@
import org.ec4j.core.model.PropertyType.PropertyValueParser.EnumValueParser
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* Indicates [com.pinterest.ktlint.core.Rule] uses properties loaded from `.editorconfig` file.
@@ -58,10 +58,10 @@
* be parsed explicitly to prevent class cast exceptions.
*/
private fun EditorConfigProperties.getEditorConfigCodeStyle() =
- codeStyleSetProperty
+ CODE_STYLE_PROPERTY
.type
.parse(
- get(codeStyleSetProperty.type.name)?.sourceValue,
+ get(CODE_STYLE_PROPERTY.type.name)?.sourceValue,
).parsed
?: official
@@ -86,7 +86,7 @@
codeStyleValue: CodeStyleValue,
): T {
if (editorConfigProperty.deprecationWarning != null) {
- logger.warn { "Property '${editorConfigProperty.type.name}' is deprecated: ${editorConfigProperty.deprecationWarning}" }
+ LOGGER.warn { "Property '${editorConfigProperty.type.name}' is deprecated: ${editorConfigProperty.deprecationWarning}" }
}
val property = get(editorConfigProperty.type.name)
@@ -99,7 +99,7 @@
// If the property value is remapped to a non-null value then return it immediately.
val originalValue = property.sourceValue
if (newValue.toString() != originalValue) {
- logger.trace {
+ LOGGER.trace {
"Value of '.editorconfig' property '${editorConfigProperty.type.name}' is remapped " +
"from '$originalValue' to '$newValue'"
}
@@ -130,7 +130,7 @@
?: editorConfigProperty
.getDefaultValue(codeStyleValue)
.also {
- logger.trace {
+ LOGGER.trace {
"No value of '.editorconfig' property '${editorConfigProperty.type.name}' was found. Value " +
"has been defaulted to '$it'. Setting the value explicitly in '.editorconfig' " +
"removes this message from the log."
@@ -218,7 +218,7 @@
official,
}
- public val codeStyleSetProperty: UsesEditorConfigProperties.EditorConfigProperty<CodeStyleValue> =
+ public val CODE_STYLE_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<CodeStyleValue> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
"ktlint_code_style",
@@ -231,10 +231,18 @@
)
@Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("CODE_STYLE_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val codeStyleSetProperty: UsesEditorConfigProperties.EditorConfigProperty<CodeStyleValue> =
+ CODE_STYLE_PROPERTY
+
+ @Deprecated(
message = "Marked for removal in KtLint 0.48",
replaceWith = ReplaceWith("ktlintDisabledRulesProperty"),
)
- public val disabledRulesProperty: UsesEditorConfigProperties.EditorConfigProperty<String> =
+ public val DISABLED_RULES_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<String> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
"disabled_rules",
@@ -258,7 +266,7 @@
deprecationWarning = "Rename property 'disabled_rules' to 'ktlint_disabled_rules' in all '.editorconfig' files.",
)
- public val ktlintDisabledRulesProperty: UsesEditorConfigProperties.EditorConfigProperty<String> =
+ public val KTLINT_DISABLED_RULES_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<String> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
"ktlint_disabled_rules",
@@ -281,13 +289,29 @@
},
)
- public val indentStyleProperty: UsesEditorConfigProperties.EditorConfigProperty<PropertyType.IndentStyleValue> =
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("KTLINT_DISABLED_RULES_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val ktlintDisabledRulesProperty: UsesEditorConfigProperties.EditorConfigProperty<String> =
+ KTLINT_DISABLED_RULES_PROPERTY
+
+ public val INDENT_STYLE_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<PropertyType.IndentStyleValue> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.indent_style,
defaultValue = PropertyType.IndentStyleValue.space,
)
- public val indentSizeProperty: UsesEditorConfigProperties.EditorConfigProperty<Int> =
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("INDENT_STYLE_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val indentStyleProperty: UsesEditorConfigProperties.EditorConfigProperty<PropertyType.IndentStyleValue> =
+ INDENT_STYLE_PROPERTY
+
+ public val INDENT_SIZE_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<Int> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.indent_size,
defaultValue = IndentConfig.DEFAULT_INDENT_CONFIG.tabWidth,
@@ -301,13 +325,29 @@
},
)
- public val insertNewLineProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("INDENT_SIZE_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val indentSizeProperty: UsesEditorConfigProperties.EditorConfigProperty<Int> =
+ INDENT_SIZE_PROPERTY
+
+ public val INSERT_FINAL_NEWLINE_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.insert_final_newline,
defaultValue = true,
)
- public val maxLineLengthProperty: UsesEditorConfigProperties.EditorConfigProperty<Int> =
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("INSERT_FINAL_NEWLINE_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val insertNewLineProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
+ INSERT_FINAL_NEWLINE_PROPERTY
+
+ public val MAX_LINE_LENGTH_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<Int> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.max_line_length,
defaultValue = -1,
@@ -328,14 +368,22 @@
},
)
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("MAX_LINE_LENGTH_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val maxLineLengthProperty: UsesEditorConfigProperties.EditorConfigProperty<Int> =
+ MAX_LINE_LENGTH_PROPERTY
+
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> = listOf(
- codeStyleSetProperty,
- disabledRulesProperty,
- ktlintDisabledRulesProperty,
- indentStyleProperty,
- indentSizeProperty,
- insertNewLineProperty,
- maxLineLengthProperty,
+ CODE_STYLE_PROPERTY,
+ DISABLED_RULES_PROPERTY,
+ KTLINT_DISABLED_RULES_PROPERTY,
+ INDENT_STYLE_PROPERTY,
+ INDENT_SIZE_PROPERTY,
+ INSERT_FINAL_NEWLINE_PROPERTY,
+ MAX_LINE_LENGTH_PROPERTY,
)
}
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigDefaultsLoader.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigDefaultsLoader.kt
index 457c323..154a0ba 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigDefaultsLoader.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigDefaultsLoader.kt
@@ -1,9 +1,9 @@
package com.pinterest.ktlint.core.internal
import com.pinterest.ktlint.core.api.EditorConfigDefaults
-import com.pinterest.ktlint.core.api.EditorConfigDefaults.Companion.emptyEditorConfigDefaults
+import com.pinterest.ktlint.core.api.EditorConfigDefaults.Companion.EMPTY_EDITOR_CONFIG_DEFAULTS
import com.pinterest.ktlint.core.initKtLintKLogger
-import com.pinterest.ktlint.core.internal.ThreadSafeEditorConfigCache.Companion.threadSafeEditorConfigCache
+import com.pinterest.ktlint.core.internal.ThreadSafeEditorConfigCache.Companion.THREAD_SAFER_EDITOR_CONFIG_CACHE
import java.nio.charset.StandardCharsets
import java.nio.file.Path
import kotlin.io.path.isDirectory
@@ -14,7 +14,7 @@
import org.ec4j.core.Resource
import org.ec4j.core.model.Version
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* Load all properties from an ".editorconfig" file without filtering on a glob.
@@ -27,26 +27,26 @@
* than ".editorconfig") or a directory in which a file with name ".editorconfig" is expected to exist. Properties
* from all globs are returned.
*
- * If [path] is not valid then the [emptyEditorConfigDefaults] is returned.
+ * If [path] is not valid then the [EMPTY_EDITOR_CONFIG_DEFAULTS] is returned.
*
* The property "root" which denotes whether the parent directory is to be checked for the existence of a fallback
* ".editorconfig" is ignored entirely.
*/
fun load(path: Path?): EditorConfigDefaults {
if (path == null || path.pathString.isBlank()) {
- return emptyEditorConfigDefaults
+ return EMPTY_EDITOR_CONFIG_DEFAULTS
}
val editorConfigFilePath = path.editorConfigFilePath()
if (editorConfigFilePath.notExists()) {
- logger.warn { "File or directory '$path' is not found. Can not load '.editorconfig' properties" }
- return emptyEditorConfigDefaults
+ LOGGER.warn { "File or directory '$path' is not found. Can not load '.editorconfig' properties" }
+ return EMPTY_EDITOR_CONFIG_DEFAULTS
}
- return threadSafeEditorConfigCache
+ return THREAD_SAFER_EDITOR_CONFIG_CACHE
.get(editorConfigFilePath.resource(), editorConfigLoader)
.also {
- logger.trace {
+ LOGGER.trace {
it
.toString()
.split("\n")
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigFinder.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigFinder.kt
index 0d22eae..3176252 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigFinder.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigFinder.kt
@@ -18,23 +18,23 @@
import org.ec4j.core.model.Version
import org.jetbrains.kotlin.konan.file.File
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
internal class EditorConfigFinder {
/**
* Finds all relevant ".editorconfig" files for the given path.
*/
fun findEditorConfigs(path: Path): List<Path> {
- readWriteLock.read {
- val cacheValue = inMemoryMap[path]
+ READ_WRITE_LOCK.read {
+ val cacheValue = IN_MEMORY_CACHE[path]
?.also {
- logger.info { "Retrieving EditorConfig cache entry for path $path" }
+ LOGGER.info { "Retrieving EditorConfig cache entry for path $path" }
}
return cacheValue
- ?: readWriteLock.write {
+ ?: READ_WRITE_LOCK.write {
cacheEditorConfigs(path)
.also { cacheValue ->
- logger.info { "Creating cache entry for path $path with value $cacheValue" }
+ LOGGER.info { "Creating cache entry for path $path with value $cacheValue" }
}
}
}
@@ -54,7 +54,7 @@
// Resolve against original path as the drive letter seems to get lost on WindowsOs
path.resolve(it)
}.toList()
- inMemoryMap[path] = editorConfigPaths
+ IN_MEMORY_CACHE[path] = editorConfigPaths
return editorConfigPaths
}
@@ -72,7 +72,7 @@
fileAttrs: BasicFileAttributes,
): FileVisitResult {
if (filePath.File().name == ".editorconfig") {
- logger.trace { "- File: $filePath: add to list of accessed files" }
+ LOGGER.trace { "- File: $filePath: add to list of accessed files" }
result.add(filePath)
}
return FileVisitResult.CONTINUE
@@ -84,10 +84,10 @@
): FileVisitResult {
visitedDirectoryCount++
return if (Files.isHidden(dirPath)) {
- logger.trace { "- Dir: $dirPath: Ignore" }
+ LOGGER.trace { "- Dir: $dirPath: Ignore" }
FileVisitResult.SKIP_SUBTREE
} else {
- logger.trace { "- Dir: $dirPath: Traverse" }
+ LOGGER.trace { "- Dir: $dirPath: Traverse" }
FileVisitResult.CONTINUE
}
}
@@ -95,7 +95,7 @@
)
}.also { duration ->
// TODO: Remove (or reduce loglevel to debug/trace) before release 0.48
- logger.info {
+ LOGGER.info {
"Scanning file system to find all '.editorconfig' files in directory '$path' scanned $visitedDirectoryCount directories in $duration ms"
}
}
@@ -108,7 +108,7 @@
// cache provided by KtLint. As of this the list of parental ".editorconfig" files can be extracted from the
// cache.
createLoaderService().queryProperties(path.resource())
- return editorConfigCache.getPaths()
+ return EDITOR_CONFIG_CACHE.getPaths()
}
private fun Path?.resource() =
@@ -116,16 +116,16 @@
private fun createLoaderService() =
ResourcePropertiesService.builder()
- .cache(editorConfigCache)
+ .cache(EDITOR_CONFIG_CACHE)
.loader(org.ec4j.core.EditorConfigLoader.of(Version.CURRENT))
.build()
private companion object {
// Do not reuse the generic threadSafeEditorConfigCache to prevent that results are incorrect due to other
// calls to KtLint that result in changing the cache
- val editorConfigCache = ThreadSafeEditorConfigCache()
+ val EDITOR_CONFIG_CACHE = ThreadSafeEditorConfigCache()
- private val readWriteLock = ReentrantReadWriteLock()
- private val inMemoryMap = HashMap<Path, List<Path>>()
+ private val READ_WRITE_LOCK = ReentrantReadWriteLock()
+ private val IN_MEMORY_CACHE = HashMap<Path, List<Path>>()
}
}
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigGenerator.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigGenerator.kt
index 89f4705..ef53d8f 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigGenerator.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigGenerator.kt
@@ -8,7 +8,7 @@
import mu.KotlinLogging
import org.ec4j.core.model.Property
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* Generates Kotlin section content for `.editorconfig` file.
@@ -69,7 +69,7 @@
codeStyle,
)
}
- logger.debug {
+ LOGGER.debug {
"Rule '${rule.id}' uses property '${property.type.name}' with default value '$value'"
}
ConfigurationSetting(
@@ -95,7 +95,7 @@
codeStyle,
)
}
- logger.debug {
+ LOGGER.debug {
"Class '${DefaultEditorConfigProperties::class.simpleName}' uses property '${editorConfigProperty.type.name}' with default value '$value'"
}
ConfigurationSetting(
@@ -109,7 +109,7 @@
groupBy { it.key }
.filter { (_, configurationSettingsGroup) -> configurationSettingsGroup.countDistinctValues() > 1 }
.forEach {
- logger.error {
+ LOGGER.error {
val usages = it.value.joinToString { it.usage }.toList().sorted()
"Property '${it.key}' has multiple usages ($usages) which defines different default values for the property. Check the resulting '.editorcconfig' file carefully."
}
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigLoader.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigLoader.kt
index ea2f675..57ab77d 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigLoader.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/EditorConfigLoader.kt
@@ -2,13 +2,13 @@
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.api.EditorConfigDefaults
-import com.pinterest.ktlint.core.api.EditorConfigDefaults.Companion.emptyEditorConfigDefaults
+import com.pinterest.ktlint.core.api.EditorConfigDefaults.Companion.EMPTY_EDITOR_CONFIG_DEFAULTS
import com.pinterest.ktlint.core.api.EditorConfigOverride
-import com.pinterest.ktlint.core.api.EditorConfigOverride.Companion.emptyEditorConfigOverride
+import com.pinterest.ktlint.core.api.EditorConfigOverride.Companion.EMPTY_EDITOR_CONFIG_OVERRIDE
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.initKtLintKLogger
-import com.pinterest.ktlint.core.internal.ThreadSafeEditorConfigCache.Companion.threadSafeEditorConfigCache
+import com.pinterest.ktlint.core.internal.ThreadSafeEditorConfigCache.Companion.THREAD_SAFER_EDITOR_CONFIG_CACHE
import java.nio.charset.StandardCharsets
import java.nio.file.FileSystem
import java.nio.file.FileSystems
@@ -23,7 +23,7 @@
import org.ec4j.core.model.Version
import org.jetbrains.kotlin.utils.addToStdlib.applyIf
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* Loader for `.editorconfig` properties for files on [fileSystem].
@@ -62,7 +62,7 @@
isStdIn: Boolean = false,
alternativeEditorConfig: Path? = null,
rules: Set<Rule>,
- editorConfigOverride: EditorConfigOverride = emptyEditorConfigOverride,
+ editorConfigOverride: EditorConfigOverride = EMPTY_EDITOR_CONFIG_OVERRIDE,
debug: Boolean = false,
): EditorConfigProperties {
if (!isStdIn && filePath.isNullOrNotSupported()) {
@@ -89,7 +89,7 @@
else -> filePath
}
- return createLoaderService(rules, emptyEditorConfigDefaults)
+ return createLoaderService(rules, EMPTY_EDITOR_CONFIG_DEFAULTS)
.queryProperties(normalizedFilePath.resource())
.properties
.also { loaded ->
@@ -99,7 +99,7 @@
loaded[it.key.type.name] = property(it.key, it.value)
}
}.also { editorConfigProperties ->
- logger.trace { editorConfigProperties.prettyPrint(normalizedFilePath) }
+ LOGGER.trace { editorConfigProperties.prettyPrint(normalizedFilePath) }
}
}
@@ -125,8 +125,8 @@
public fun load(
filePath: Path?,
rules: Set<Rule> = emptySet(),
- editorConfigDefaults: EditorConfigDefaults = emptyEditorConfigDefaults,
- editorConfigOverride: EditorConfigOverride = emptyEditorConfigOverride,
+ editorConfigDefaults: EditorConfigDefaults = EMPTY_EDITOR_CONFIG_DEFAULTS,
+ editorConfigOverride: EditorConfigOverride = EMPTY_EDITOR_CONFIG_OVERRIDE,
): EditorConfigProperties {
// TODO: Move to class init once method load PropertiesForFiles has been removed.
require(rules.isNotEmpty()) {
@@ -145,7 +145,7 @@
loaded[it.key.type.name] = property(it.key, it.value)
}
}.also { editorConfigProperties ->
- logger.trace { editorConfigProperties.prettyPrint(normalizedFilePath) }
+ LOGGER.trace { editorConfigProperties.prettyPrint(normalizedFilePath) }
}
}
@@ -199,9 +199,9 @@
) =
ResourcePropertiesService.builder()
.keepUnset(true)
- .cache(threadSafeEditorConfigCache)
+ .cache(THREAD_SAFER_EDITOR_CONFIG_CACHE)
.loader(editorConfigLoader)
- .applyIf(editorConfigDefaults != emptyEditorConfigDefaults) {
+ .applyIf(editorConfigDefaults != EMPTY_EDITOR_CONFIG_DEFAULTS) {
defaultEditorConfigs(editorConfigDefaults.value)
}.build()
@@ -230,7 +230,7 @@
replaceWith = ReplaceWith("KtLint.trimMemory()"),
)
public fun trimMemory() {
- threadSafeEditorConfigCache.clear()
+ THREAD_SAFER_EDITOR_CONFIG_CACHE.clear()
}
public companion object {
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/IdNamingPolicy.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/IdNamingPolicy.kt
index 5fd72ce..e86b006 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/IdNamingPolicy.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/IdNamingPolicy.kt
@@ -5,8 +5,8 @@
*/
internal object IdNamingPolicy {
private const val SIMPLE_ID_REGEX = "[a-z]+(-[a-z]+)*"
- private val ruleIdRegex = "($SIMPLE_ID_REGEX:)?($SIMPLE_ID_REGEX)".toRegex()
- private val ruleSetIdRegex = "($SIMPLE_ID_REGEX)".toRegex()
+ private val RULE_ID_REGEX = "($SIMPLE_ID_REGEX:)?($SIMPLE_ID_REGEX)".toRegex()
+ private val RULE_SET_ID_REGEX = "($SIMPLE_ID_REGEX)".toRegex()
/**
* Checks provided [ruleId] is valid.
@@ -14,7 +14,7 @@
* Will throw [IllegalArgumentException] on invalid [ruleId] name.
*/
internal fun enforceRuleIdNaming(ruleId: String) =
- require(ruleId.matches(ruleIdRegex)) { "Rule id '$ruleId' must match '${ruleIdRegex.pattern}'" }
+ require(ruleId.matches(RULE_ID_REGEX)) { "Rule id '$ruleId' must match '${RULE_ID_REGEX.pattern}'" }
/**
* Checks provided [ruleSetId] is valid.
@@ -22,5 +22,5 @@
* Will throw [IllegalArgumentException] on invalid [ruleSetId] name.
*/
internal fun enforceRuleSetIdNaming(ruleSetId: String) =
- require(ruleSetId.matches(ruleSetIdRegex)) { "RuleSet id '$ruleSetId' must match '${ruleSetIdRegex.pattern}'" }
+ require(ruleSetId.matches(RULE_SET_ID_REGEX)) { "RuleSet id '$ruleSetId' must match '${RULE_SET_ID_REGEX.pattern}'" }
}
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/RuleExecutionContext.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/RuleExecutionContext.kt
index c2dcea9..c1c1de6 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/RuleExecutionContext.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/RuleExecutionContext.kt
@@ -9,7 +9,7 @@
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.KtFile
-private val kotlinPsiFileFactoryProvider = KotlinPsiFileFactoryProvider()
+private val KOTLIN_PSI_FILE_FACTORY_PROVIDER = KotlinPsiFileFactoryProvider()
internal class RuleExecutionContext(
val rootNode: FileASTNode,
@@ -29,7 +29,7 @@
}
internal fun createRuleExecutionContext(params: KtLint.ExperimentalParams): RuleExecutionContext {
- val psiFileFactory = kotlinPsiFileFactoryProvider.getKotlinPsiFileFactory(params.isInvokedFromCli)
+ val psiFileFactory = KOTLIN_PSI_FILE_FACTORY_PROVIDER.getKotlinPsiFileFactory(params.isInvokedFromCli)
val normalizedText = normalizeText(params.text)
val positionInTextLocator = buildPositionInTextLocator(normalizedText)
@@ -52,7 +52,7 @@
val rootNode = psiFile.node
- val editorConfigProperties = KtLint.editorConfigLoader.load(
+ val editorConfigProperties = KtLint.EDITOR_CONFIG_LOADER.load(
filePath = params.normalizedFilePath,
rules = params.getRules(),
editorConfigDefaults = params.editorConfigDefaults,
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/RuleRunnerSorter.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/RuleRunnerSorter.kt
index 992e041..bf6cafb 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/RuleRunnerSorter.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/RuleRunnerSorter.kt
@@ -5,7 +5,7 @@
import com.pinterest.ktlint.core.initKtLintKLogger
import mu.KotlinLogging
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* Sorts the [RuleRunner]s based on [Rule.VisitorModifier]s.
@@ -37,7 +37,7 @@
.joinToString(prefix = "Rules will be executed in order below (unless disabled):") {
"\n - $it"
}
- .let { logger.debug(it) }
+ .let { LOGGER.debug(it) }
}
}
}
@@ -96,14 +96,14 @@
if (this.none { it.runsAfter(currentRuleRunner) }) {
// The RunAfterRule refers to a rule which is not loaded at all.
if (runAfterRule.loadOnlyWhenOtherRuleIsLoaded) {
- logger.warn {
+ LOGGER.warn {
"Skipping rule with id '${currentRuleRunner.qualifiedRuleId}' as it requires " +
"that the rule with id '${runAfterRule.ruleId}' is loaded. However, " +
"no rule with this id is loaded."
}
continue
} else {
- logger.debug {
+ LOGGER.debug {
"Rule with id '${currentRuleRunner.qualifiedRuleId}' should run after the " +
"rule with id '${runAfterRule.ruleId}'. However, the latter " +
"rule is not loaded and is allowed to be ignored. For best results, it is " +
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/SuppressHandler.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/SuppressHandler.kt
index 883b01c..fa2496b 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/SuppressHandler.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/SuppressHandler.kt
@@ -20,7 +20,7 @@
)
val autoCorrect = this.autoCorrect && !suppress
val emit = if (suppress) {
- suppressEmit
+ SUPPRESS_EMIT
} else {
this.emit
}
@@ -29,6 +29,6 @@
private companion object {
// Swallow violation so that it is not emitted
- val suppressEmit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit = { _, _, _ -> }
+ val SUPPRESS_EMIT: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit = { _, _, _ -> }
}
}
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/SuppressionLocatorBuilder.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/SuppressionLocatorBuilder.kt
index ec42f38..d500e22 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/SuppressionLocatorBuilder.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/SuppressionLocatorBuilder.kt
@@ -19,15 +19,15 @@
/**
* No suppression is detected. Always returns `false`.
*/
- val noSuppression: SuppressionLocator = { _, _, _ -> false }
+ val NO_SUPPRESSION: SuppressionLocator = { _, _, _ -> false }
- private val suppressAnnotationRuleMap = mapOf(
+ private val SUPPRESS_ANNOTATION_RULE_MAP = mapOf(
"RemoveCurlyBracesFromTemplate" to "string-template",
)
- private val suppressAnnotations = setOf("Suppress", "SuppressWarnings")
- private const val suppressAllKtlintRules = "ktlint-all"
+ private val SUPPRESS_ANNOTATIONS = setOf("Suppress", "SuppressWarnings")
+ private const val SUPPRESS_ALL_KTLINT_RULES = "ktlint-all"
- private val commentRegex = Regex("\\s")
+ private val COMMENT_REGEX = Regex("\\s")
/**
* Builds [SuppressionLocator] for given [rootNode] of AST tree.
@@ -37,7 +37,7 @@
): SuppressionLocator {
val hintsList = collect(rootNode)
return if (hintsList.isEmpty()) {
- noSuppression
+ NO_SUPPRESSION
} else {
toSuppressedRegionsLocator(hintsList)
}
@@ -99,7 +99,7 @@
// Extract all Suppress annotations and create SuppressionHints
val psi = node.psi
if (psi is KtAnnotated) {
- createSuppressionHintFromAnnotations(psi, suppressAnnotations, suppressAnnotationRuleMap)
+ createSuppressionHintFromAnnotations(psi, SUPPRESS_ANNOTATIONS, SUPPRESS_ANNOTATION_RULE_MAP)
?.let {
result.add(it)
}
@@ -137,7 +137,7 @@
private fun splitCommentBySpace(
comment: String,
) = comment
- .replace(commentRegex, " ")
+ .replace(COMMENT_REGEX, " ")
.replace(" {2,}", " ")
.split(" ")
@@ -164,7 +164,7 @@
.let { suppressedRules ->
when {
suppressedRules.isEmpty() -> null
- suppressedRules.contains(suppressAllKtlintRules) ->
+ suppressedRules.contains(SUPPRESS_ALL_KTLINT_RULES) ->
SuppressionHint(
IntRange(psi.startOffset, psi.endOffset),
emptySet(),
@@ -185,7 +185,7 @@
when {
it == "ktlint" -> {
// Disable all rules
- suppressAllKtlintRules
+ SUPPRESS_ALL_KTLINT_RULES
}
it.startsWith("ktlint:") -> {
// Disable specific rule
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/ThreadSafeEditorConfigCache.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/ThreadSafeEditorConfigCache.kt
index 67ca346..63a1afd 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/ThreadSafeEditorConfigCache.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/ThreadSafeEditorConfigCache.kt
@@ -11,7 +11,7 @@
import org.ec4j.core.Resource
import org.ec4j.core.model.EditorConfig
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* In-memory [Cache] implementation that could be safely accessed from any [Thread].
@@ -31,14 +31,14 @@
readWriteLock.read {
val cachedEditConfig = inMemoryMap[resource]
?.also {
- logger.trace { "Retrieving EditorConfig cache entry for path ${resource.path}" }
+ LOGGER.trace { "Retrieving EditorConfig cache entry for path ${resource.path}" }
}?.editConfig
return cachedEditConfig
?: readWriteLock.write {
CacheValue(resource, editorConfigLoader)
.also { cacheValue ->
inMemoryMap[resource] = cacheValue
- logger.trace { "Creating new EditorConfig cache entry for path ${resource.path}" }
+ LOGGER.trace { "Creating new EditorConfig cache entry for path ${resource.path}" }
}.editConfig
}
}
@@ -56,7 +56,7 @@
.copy(editConfig = cacheValue.editorConfigLoader.load(resource))
.let { cacheValue -> inMemoryMap[resource] = cacheValue }
.also {
- logger.trace { "Reload EditorConfig cache entry for path ${resource.path}" }
+ LOGGER.trace { "Reload EditorConfig cache entry for path ${resource.path}" }
}
}
}
@@ -69,7 +69,7 @@
fun clear() = readWriteLock.write {
inMemoryMap
.also {
- logger.trace { "Removing ${it.size} entries from the EditorConfig cache" }
+ LOGGER.trace { "Removing ${it.size} entries from the EditorConfig cache" }
}.clear()
}
@@ -95,6 +95,6 @@
}
internal companion object {
- val threadSafeEditorConfigCache = ThreadSafeEditorConfigCache()
+ val THREAD_SAFER_EDITOR_CONFIG_CACHE = ThreadSafeEditorConfigCache()
}
}
diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/VisitorProvider.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/VisitorProvider.kt
index 3c20127..9920b9c 100644
--- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/VisitorProvider.kt
+++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/VisitorProvider.kt
@@ -3,22 +3,22 @@
import com.pinterest.ktlint.core.KtLint
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.RuleRunner
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.disabledRulesProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.ktlintDisabledRulesProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.DISABLED_RULES_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.KTLINT_DISABLED_RULES_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties.EditorConfigProperty
import com.pinterest.ktlint.core.initKtLintKLogger
import mu.KotlinLogging
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* The VisitorProvider is created for each file being scanned. As the [RuleRunnerSorter] logs the order in which the
* rules are executed, a singleton instance of the class is used to prevent that the logs are flooded with duplicate
* log lines.
*/
-private val ruleRunnerSorter = RuleRunnerSorter()
+private val RULE_RUNNER_SORTER = RuleRunnerSorter()
internal class VisitorProvider(
private val params: KtLint.ExperimentalParams,
@@ -28,8 +28,8 @@
recreateRuleSorter: Boolean = false,
) : UsesEditorConfigProperties {
override val editorConfigProperties: List<EditorConfigProperty<*>> = listOf(
- ktlintDisabledRulesProperty,
- disabledRulesProperty,
+ KTLINT_DISABLED_RULES_PROPERTY,
+ DISABLED_RULES_PROPERTY,
)
/**
@@ -39,7 +39,7 @@
if (recreateRuleSorter) {
RuleRunnerSorter()
} else {
- ruleRunnerSorter
+ RULE_RUNNER_SORTER
}.getSortedRuleRunners(params.ruleRunners, params.debug)
internal fun visitor(editorConfigProperties: EditorConfigProperties): ((rule: Rule, fqRuleId: String) -> Unit) -> Unit {
@@ -47,7 +47,7 @@
ruleRunners
.filter { ruleRunner -> isNotDisabled(editorConfigProperties, ruleRunner.qualifiedRuleId) }
if (enabledRuleRunners.isEmpty()) {
- logger.debug { "Skipping file as no enabled rules are found to be executed" }
+ LOGGER.debug { "Skipping file as no enabled rules are found to be executed" }
return { _ -> }
}
val ruleRunnersToBeSkipped =
@@ -59,7 +59,7 @@
enabledRuleRunners.none { it.qualifiedRuleId == runAfterRule.ruleId.toQualifiedRuleId() }
}
if (ruleRunnersToBeSkipped.isNotEmpty()) {
- logger.debug {
+ LOGGER.debug {
ruleRunnersToBeSkipped
.forEach {
println(
@@ -72,7 +72,7 @@
}
val ruleRunnersToExecute = enabledRuleRunners - ruleRunnersToBeSkipped.toSet()
if (ruleRunnersToExecute.isEmpty()) {
- logger.debug { "Skipping file as no enabled rules are found to be executed" }
+ LOGGER.debug { "Skipping file as no enabled rules are found to be executed" }
return { _ -> }
}
return { visit ->
@@ -84,13 +84,13 @@
private fun isNotDisabled(editorConfigProperties: EditorConfigProperties, qualifiedRuleId: String): Boolean {
val ktlintDisabledRulesProperty =
- if (editorConfigProperties.containsKey(ktlintDisabledRulesProperty.type.name) ||
- !editorConfigProperties.containsKey(disabledRulesProperty.type.name)
+ if (editorConfigProperties.containsKey(KTLINT_DISABLED_RULES_PROPERTY.type.name) ||
+ !editorConfigProperties.containsKey(DISABLED_RULES_PROPERTY.type.name)
) {
// New property takes precedence when defined, or, when both old and new property are not defined.
- editorConfigProperties.getEditorConfigValue(ktlintDisabledRulesProperty)
+ editorConfigProperties.getEditorConfigValue(KTLINT_DISABLED_RULES_PROPERTY)
} else {
- editorConfigProperties.getEditorConfigValue(disabledRulesProperty)
+ editorConfigProperties.getEditorConfigValue(DISABLED_RULES_PROPERTY)
}
return ktlintDisabledRulesProperty
.split(",")
diff --git a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/DisabledRulesTest.kt b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/DisabledRulesTest.kt
index 3383f71..1664b43 100644
--- a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/DisabledRulesTest.kt
+++ b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/DisabledRulesTest.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.core
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.disabledRulesProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.ktlintDisabledRulesProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.DISABLED_RULES_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.KTLINT_DISABLED_RULES_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigOverride
import com.pinterest.ktlint.core.ast.ElementType
import org.assertj.core.api.Assertions.assertThat
@@ -60,7 +60,7 @@
RuleProvider { NoVarRule(ruleId) },
),
cb = { e, _ -> add(e) },
- editorConfigOverride = EditorConfigOverride.from(disabledRulesProperty to disabledRuleId),
+ editorConfigOverride = EditorConfigOverride.from(DISABLED_RULES_PROPERTY to disabledRuleId),
),
)
},
@@ -78,7 +78,7 @@
RuleProvider { NoVarRule("no-var") },
),
cb = { e, _ -> add(e) },
- editorConfigOverride = EditorConfigOverride.from(disabledRulesProperty to "no-var"),
+ editorConfigOverride = EditorConfigOverride.from(DISABLED_RULES_PROPERTY to "no-var"),
),
)
},
@@ -96,7 +96,7 @@
RuleProvider { NoVarRule("experimental:no-var") },
),
cb = { e, _ -> add(e) },
- editorConfigOverride = EditorConfigOverride.from(disabledRulesProperty to "experimental:no-var"),
+ editorConfigOverride = EditorConfigOverride.from(DISABLED_RULES_PROPERTY to "experimental:no-var"),
),
)
},
@@ -130,7 +130,7 @@
RuleProvider { NoVarRule(ruleId) },
),
cb = { e, _ -> add(e) },
- editorConfigOverride = EditorConfigOverride.from(ktlintDisabledRulesProperty to disabledRuleId),
+ editorConfigOverride = EditorConfigOverride.from(KTLINT_DISABLED_RULES_PROPERTY to disabledRuleId),
),
)
},
@@ -148,7 +148,7 @@
RuleProvider { NoVarRule("no-var") },
),
cb = { e, _ -> add(e) },
- editorConfigOverride = EditorConfigOverride.from(ktlintDisabledRulesProperty to "no-var"),
+ editorConfigOverride = EditorConfigOverride.from(KTLINT_DISABLED_RULES_PROPERTY to "no-var"),
),
)
},
@@ -166,7 +166,7 @@
RuleProvider { NoVarRule("experimental:no-var") },
),
cb = { e, _ -> add(e) },
- editorConfigOverride = EditorConfigOverride.from(ktlintDisabledRulesProperty to "experimental:no-var"),
+ editorConfigOverride = EditorConfigOverride.from(KTLINT_DISABLED_RULES_PROPERTY to "experimental:no-var"),
),
)
},
diff --git a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/KtLintTest.kt b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/KtLintTest.kt
index 5ae1798..bcc9abd 100644
--- a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/KtLintTest.kt
+++ b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/KtLintTest.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.core
import com.pinterest.ktlint.core.AutoCorrectErrorRule.Companion.STRING_VALUE_AFTER_AUTOCORRECT
-import com.pinterest.ktlint.core.DummyRuleWithCustomEditorConfigProperty.Companion.SOME_CUSTOM_RULE_PROPERTY
+import com.pinterest.ktlint.core.DummyRuleWithCustomEditorConfigProperty.Companion.SOME_CUSTOM_RULE_PROPERTY_NAME
import com.pinterest.ktlint.core.Rule.VisitorModifier.RunAsLateAsPossible
import com.pinterest.ktlint.core.Rule.VisitorModifier.RunOnRootNodeOnly
import com.pinterest.ktlint.core.RuleExecutionCall.RuleMethod.AFTER_CHILDREN
@@ -179,7 +179,7 @@
ruleSets = listOf(
RuleSet("standard", DummyRuleWithCustomEditorConfigProperty()),
),
- userData = mapOf(SOME_CUSTOM_RULE_PROPERTY to "false"),
+ userData = mapOf(SOME_CUSTOM_RULE_PROPERTY_NAME to "false"),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
@@ -188,7 +188,7 @@
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage(
- "UserData should not contain '.editorconfig' properties [$SOME_CUSTOM_RULE_PROPERTY]. Such" +
+ "UserData should not contain '.editorconfig' properties [$SOME_CUSTOM_RULE_PROPERTY_NAME]. Such" +
" properties should be passed via the 'ExperimentalParams.editorConfigOverride' field. " +
"Note that this is only required for properties that (potentially) contain a value that " +
"differs from the actual value in the '.editorconfig' file.",
@@ -342,7 +342,7 @@
ruleProviders = setOf(
RuleProvider { DummyRuleWithCustomEditorConfigProperty() },
),
- userData = mapOf(SOME_CUSTOM_RULE_PROPERTY to "false"),
+ userData = mapOf(SOME_CUSTOM_RULE_PROPERTY_NAME to "false"),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
@@ -351,7 +351,7 @@
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage(
- "UserData should not contain '.editorconfig' properties [$SOME_CUSTOM_RULE_PROPERTY]. Such" +
+ "UserData should not contain '.editorconfig' properties [$SOME_CUSTOM_RULE_PROPERTY_NAME]. Such" +
" properties should be passed via the 'ExperimentalParams.editorConfigOverride' field. " +
"Note that this is only required for properties that (potentially) contain a value that " +
"differs from the actual value in the '.editorconfig' file.",
@@ -606,7 +606,7 @@
ruleSets = listOf(
RuleSet("standard", DummyRuleWithCustomEditorConfigProperty()),
),
- userData = mapOf(SOME_CUSTOM_RULE_PROPERTY to "false"),
+ userData = mapOf(SOME_CUSTOM_RULE_PROPERTY_NAME to "false"),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
@@ -615,7 +615,7 @@
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage(
- "UserData should not contain '.editorconfig' properties [$SOME_CUSTOM_RULE_PROPERTY]. Such" +
+ "UserData should not contain '.editorconfig' properties [$SOME_CUSTOM_RULE_PROPERTY_NAME]. Such" +
" properties should be passed via the 'ExperimentalParams.editorConfigOverride' field. " +
"Note that this is only required for properties that (potentially) contain a value that " +
"differs from the actual value in the '.editorconfig' file.",
@@ -835,7 +835,7 @@
ruleProviders = setOf(
RuleProvider { DummyRuleWithCustomEditorConfigProperty() },
),
- userData = mapOf(SOME_CUSTOM_RULE_PROPERTY to "false"),
+ userData = mapOf(SOME_CUSTOM_RULE_PROPERTY_NAME to "false"),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
@@ -844,7 +844,7 @@
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage(
- "UserData should not contain '.editorconfig' properties [$SOME_CUSTOM_RULE_PROPERTY]. Such" +
+ "UserData should not contain '.editorconfig' properties [$SOME_CUSTOM_RULE_PROPERTY_NAME]. Such" +
" properties should be passed via the 'ExperimentalParams.editorConfigOverride' field. " +
"Note that this is only required for properties that (potentially) contain a value that " +
"differs from the actual value in the '.editorconfig' file.",
@@ -1467,15 +1467,15 @@
Rule("dummy-rule-with-custom-editor-config-property"),
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
- listOf(someCustomRuleProperty)
+ listOf(SOME_CUSTOM_RULE_PROPERTY)
companion object {
- const val SOME_CUSTOM_RULE_PROPERTY = "some-custom-rule-property"
+ const val SOME_CUSTOM_RULE_PROPERTY_NAME = "some-custom-rule-property"
- val someCustomRuleProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
+ val SOME_CUSTOM_RULE_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
- SOME_CUSTOM_RULE_PROPERTY,
+ SOME_CUSTOM_RULE_PROPERTY_NAME,
"some-custom-rule-property-description",
PropertyType.PropertyValueParser.BOOLEAN_VALUE_PARSER,
setOf(true.toString(), false.toString()),
diff --git a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/UsesEditorConfigPropertiesTest.kt b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/UsesEditorConfigPropertiesTest.kt
index a895d15..0af039e 100644
--- a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/UsesEditorConfigPropertiesTest.kt
+++ b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/UsesEditorConfigPropertiesTest.kt
@@ -1,10 +1,10 @@
package com.pinterest.ktlint.core
import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.disabledRulesProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentSizeProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.ktlintDisabledRulesProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.DISABLED_RULES_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.KTLINT_DISABLED_RULES_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import org.assertj.core.api.Assertions.assertThat
import org.ec4j.core.model.Property
@@ -17,12 +17,12 @@
@Test
fun `Given that editor config property indent_size is set to an integer value then return that integer value via the getEditorConfigValue of the node`() {
val editorConfigProperties = createEditorConfigPropertiesFrom(
- indentSizeProperty,
+ INDENT_SIZE_PROPERTY,
SOME_INTEGER_VALUE.toString(),
)
- val actual = with(EditorConfigPropertiesTester(indentSizeProperty)) {
- editorConfigProperties.getEditorConfigValue(indentSizeProperty)
+ val actual = with(EditorConfigPropertiesTester(INDENT_SIZE_PROPERTY)) {
+ editorConfigProperties.getEditorConfigValue(INDENT_SIZE_PROPERTY)
}
assertThat(actual).isEqualTo(SOME_INTEGER_VALUE)
@@ -31,12 +31,12 @@
@Test
fun `Given that editor config property indent_size is set to value 'unset' then return -1 as value via the getEditorConfigValue of the node`() {
val editorConfigProperties = createEditorConfigPropertiesFrom(
- indentSizeProperty,
+ INDENT_SIZE_PROPERTY,
"unset",
)
- val actual = with(EditorConfigPropertiesTester(indentSizeProperty)) {
- editorConfigProperties.getEditorConfigValue(indentSizeProperty)
+ val actual = with(EditorConfigPropertiesTester(INDENT_SIZE_PROPERTY)) {
+ editorConfigProperties.getEditorConfigValue(INDENT_SIZE_PROPERTY)
}
assertThat(actual).isEqualTo(-1)
@@ -45,12 +45,12 @@
@Test
fun `Issue 1485 - Given that editor config property indent_size is set to value 'tab' then return tabWidth as value via the getEditorConfigValue of the node`() {
val editorConfigProperties = createEditorConfigPropertiesFrom(
- indentSizeProperty,
+ INDENT_SIZE_PROPERTY,
"tab",
)
- val actual = with(EditorConfigPropertiesTester(indentSizeProperty)) {
- editorConfigProperties.getEditorConfigValue(indentSizeProperty)
+ val actual = with(EditorConfigPropertiesTester(INDENT_SIZE_PROPERTY)) {
+ editorConfigProperties.getEditorConfigValue(INDENT_SIZE_PROPERTY)
}
assertThat(actual).isEqualTo(IndentConfig.DEFAULT_INDENT_CONFIG.tabWidth)
@@ -58,8 +58,8 @@
@Test
fun `Given that editor config property indent_size is not set then return the default tabWidth as value via the getEditorConfigValue of the node`() {
- val actual = with(EditorConfigPropertiesTester(indentSizeProperty)) {
- emptyMap<String, Property>().getEditorConfigValue(indentSizeProperty)
+ val actual = with(EditorConfigPropertiesTester(INDENT_SIZE_PROPERTY)) {
+ emptyMap<String, Property>().getEditorConfigValue(INDENT_SIZE_PROPERTY)
}
assertThat(actual).isEqualTo(IndentConfig.DEFAULT_INDENT_CONFIG.tabWidth)
@@ -73,12 +73,12 @@
@Test
fun `Given that editor config property max_line_length is set to an integer value then return that integer value via the getEditorConfigValue of the node`() {
val editorConfigProperties = createEditorConfigPropertiesFrom(
- maxLineLengthProperty,
+ MAX_LINE_LENGTH_PROPERTY,
SOME_INTEGER_VALUE.toString(),
)
- val actual = with(EditorConfigPropertiesTester(maxLineLengthProperty)) {
- editorConfigProperties.getEditorConfigValue(maxLineLengthProperty)
+ val actual = with(EditorConfigPropertiesTester(MAX_LINE_LENGTH_PROPERTY)) {
+ editorConfigProperties.getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
}
assertThat(actual).isEqualTo(SOME_INTEGER_VALUE)
@@ -87,12 +87,12 @@
@Test
fun `Given that editor config property max_line_length is set to value 'off' then return -1 via the getEditorConfigValue of the node`() {
val editorConfigProperties = createEditorConfigPropertiesFrom(
- maxLineLengthProperty,
+ MAX_LINE_LENGTH_PROPERTY,
"off",
)
- val actual = with(EditorConfigPropertiesTester(maxLineLengthProperty)) {
- editorConfigProperties.getEditorConfigValue(maxLineLengthProperty)
+ val actual = with(EditorConfigPropertiesTester(MAX_LINE_LENGTH_PROPERTY)) {
+ editorConfigProperties.getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
}
assertThat(actual).isEqualTo(-1)
@@ -101,12 +101,12 @@
@Test
fun `Given that editor config property max_line_length is set to value 'unset' for android then return 100 via the getEditorConfigValue of the node`() {
val editorConfigProperties = createEditorConfigPropertiesFrom(
- maxLineLengthProperty,
+ MAX_LINE_LENGTH_PROPERTY,
"unset",
).plus(ANDROID_CODE_STYLE)
- val actual = with(EditorConfigPropertiesTester(maxLineLengthProperty)) {
- editorConfigProperties.getEditorConfigValue(maxLineLengthProperty)
+ val actual = with(EditorConfigPropertiesTester(MAX_LINE_LENGTH_PROPERTY)) {
+ editorConfigProperties.getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
}
assertThat(actual).isEqualTo(100)
@@ -115,12 +115,12 @@
@Test
fun `Given that editor config property max_line_length is set to value 'unset' for non-android then return -1 via the getEditorConfigValue of the node`() {
val editorConfigProperties = createEditorConfigPropertiesFrom(
- maxLineLengthProperty,
+ MAX_LINE_LENGTH_PROPERTY,
"unset",
).plus(OFFICIAL_CODE_STYLE)
- val actual = with(EditorConfigPropertiesTester(maxLineLengthProperty)) {
- editorConfigProperties.getEditorConfigValue(maxLineLengthProperty)
+ val actual = with(EditorConfigPropertiesTester(MAX_LINE_LENGTH_PROPERTY)) {
+ editorConfigProperties.getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
}
assertThat(actual).isEqualTo(-1)
@@ -128,8 +128,8 @@
@Test
fun `Given that editor config property max_line_length is not set for android then return 100 via the getEditorConfigValue of the node`() {
- val actual = with(EditorConfigPropertiesTester(maxLineLengthProperty)) {
- ANDROID_CODE_STYLE.getEditorConfigValue(maxLineLengthProperty)
+ val actual = with(EditorConfigPropertiesTester(MAX_LINE_LENGTH_PROPERTY)) {
+ ANDROID_CODE_STYLE.getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
}
assertThat(actual).isEqualTo(100)
@@ -137,8 +137,8 @@
@Test
fun `Given that editor config property max_line_length is not set for non-android then return -1 via the getEditorConfigValue of the node`() {
- val actual = with(EditorConfigPropertiesTester(maxLineLengthProperty)) {
- OFFICIAL_CODE_STYLE.getEditorConfigValue(maxLineLengthProperty)
+ val actual = with(EditorConfigPropertiesTester(MAX_LINE_LENGTH_PROPERTY)) {
+ OFFICIAL_CODE_STYLE.getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
}
assertThat(actual).isEqualTo(-1)
@@ -149,12 +149,12 @@
@Test
fun `Given that editor config property disabled_rules is set and has spacing around the comma, then retrieve the list without those spaces'`() {
val editorConfigProperties = createEditorConfigPropertiesFrom(
- disabledRulesProperty,
+ DISABLED_RULES_PROPERTY,
"$RULE_A, $RULE_B,$RULE_C , $RULE_D",
)
- val actual = with(EditorConfigPropertiesTester(disabledRulesProperty)) {
- editorConfigProperties.getEditorConfigValue(disabledRulesProperty)
+ val actual = with(EditorConfigPropertiesTester(DISABLED_RULES_PROPERTY)) {
+ editorConfigProperties.getEditorConfigValue(DISABLED_RULES_PROPERTY)
}
assertThat(actual).isEqualTo("$RULE_A,$RULE_B,$RULE_C,$RULE_D")
@@ -163,12 +163,12 @@
@Test
fun `Given that editor config property ktlint_disabled_rules is set and has spacing around the comma, then retrieve the list without those spaces'`() {
val editorConfigProperties = createEditorConfigPropertiesFrom(
- ktlintDisabledRulesProperty,
+ KTLINT_DISABLED_RULES_PROPERTY,
"$RULE_A, $RULE_B,$RULE_C , $RULE_D",
)
- val actual = with(EditorConfigPropertiesTester(ktlintDisabledRulesProperty)) {
- editorConfigProperties.getEditorConfigValue(ktlintDisabledRulesProperty)
+ val actual = with(EditorConfigPropertiesTester(KTLINT_DISABLED_RULES_PROPERTY)) {
+ editorConfigProperties.getEditorConfigValue(KTLINT_DISABLED_RULES_PROPERTY)
}
assertThat(actual).isEqualTo("$RULE_A,$RULE_B,$RULE_C,$RULE_D")
@@ -187,11 +187,11 @@
const val RULE_D = "rule-d"
const val SOME_INTEGER_VALUE = 123
val ANDROID_CODE_STYLE = createEditorConfigPropertiesFrom(
- DefaultEditorConfigProperties.codeStyleSetProperty,
+ DefaultEditorConfigProperties.CODE_STYLE_PROPERTY,
DefaultEditorConfigProperties.CodeStyleValue.android.name.lowercase(),
)
val OFFICIAL_CODE_STYLE = createEditorConfigPropertiesFrom(
- DefaultEditorConfigProperties.codeStyleSetProperty,
+ DefaultEditorConfigProperties.CODE_STYLE_PROPERTY,
DefaultEditorConfigProperties.CodeStyleValue.official.name.lowercase(),
)
diff --git a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/VisitorProviderTest.kt b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/VisitorProviderTest.kt
index 981a3d2..be5b913 100644
--- a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/VisitorProviderTest.kt
+++ b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/VisitorProviderTest.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.core
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.disabledRulesProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.ktlintDisabledRulesProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.DISABLED_RULES_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.KTLINT_DISABLED_RULES_PROPERTY
import com.pinterest.ktlint.core.internal.VisitorProvider
import org.assertj.core.api.Assertions.assertThat
import org.ec4j.core.model.Property
@@ -132,7 +132,7 @@
}
private fun disabledRulesEditorConfigProperties(vararg ruleIds: String) =
- with(disabledRulesProperty) {
+ with(DISABLED_RULES_PROPERTY) {
mapOf(
type.name to
Property.builder()
@@ -262,7 +262,7 @@
}
private fun ktlintDisabledRulesEditorConfigProperties(vararg ruleIds: String) =
- with(ktlintDisabledRulesProperty) {
+ with(KTLINT_DISABLED_RULES_PROPERTY) {
mapOf(
type.name to
Property.builder()
diff --git a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigDefaultsLoaderTest.kt b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigDefaultsLoaderTest.kt
index 9af533e..9d1257f 100644
--- a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigDefaultsLoaderTest.kt
+++ b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigDefaultsLoaderTest.kt
@@ -3,7 +3,7 @@
import com.google.common.jimfs.Configuration
import com.google.common.jimfs.Jimfs
import com.pinterest.ktlint.core.api.EditorConfigDefaults
-import com.pinterest.ktlint.core.api.EditorConfigDefaults.Companion.emptyEditorConfigDefaults
+import com.pinterest.ktlint.core.api.EditorConfigDefaults.Companion.EMPTY_EDITOR_CONFIG_DEFAULTS
import java.nio.file.FileSystem
import java.nio.file.Files
import java.nio.file.Path
@@ -33,7 +33,7 @@
fun `Given a null path then return empty editor config default`() {
val actual = editorConfigDefaultsLoader.load(null)
- assertThat(actual).isEqualTo(emptyEditorConfigDefaults)
+ assertThat(actual).isEqualTo(EMPTY_EDITOR_CONFIG_DEFAULTS)
}
@Test
@@ -42,7 +42,7 @@
fileSystemMock.normalizedPath(""),
)
- assertThat(actual).isEqualTo(emptyEditorConfigDefaults)
+ assertThat(actual).isEqualTo(EMPTY_EDITOR_CONFIG_DEFAULTS)
}
@Test
@@ -52,7 +52,7 @@
fileSystemMock.normalizedPath(" "),
)
- assertThat(actual).isEqualTo(emptyEditorConfigDefaults)
+ assertThat(actual).isEqualTo(EMPTY_EDITOR_CONFIG_DEFAULTS)
}
@Test
@@ -61,7 +61,7 @@
fileSystemMock.normalizedPath("/path/to/non/existing/file.kt"),
)
- assertThat(actual).isEqualTo(emptyEditorConfigDefaults)
+ assertThat(actual).isEqualTo(EMPTY_EDITOR_CONFIG_DEFAULTS)
}
@ParameterizedTest(name = "Filename: {0}")
diff --git a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigLoaderTest.kt b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigLoaderTest.kt
index c07af8c..64a603f 100644
--- a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigLoaderTest.kt
+++ b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigLoaderTest.kt
@@ -3,7 +3,7 @@
import com.google.common.jimfs.Configuration
import com.google.common.jimfs.Jimfs
import com.pinterest.ktlint.core.Rule
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.insertNewLineProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INSERT_FINAL_NEWLINE_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigOverride
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.internal.EditorConfigLoader.Companion.convertToRawValues
@@ -233,7 +233,7 @@
val parsedEditorConfig = editorConfigLoader.load(
filePath = null,
rules = rules,
- editorConfigOverride = EditorConfigOverride.from(insertNewLineProperty to "true"),
+ editorConfigOverride = EditorConfigOverride.from(INSERT_FINAL_NEWLINE_PROPERTY to "true"),
)
assertThat(parsedEditorConfig.convertToRawValues()).containsExactly(
@@ -246,7 +246,7 @@
val parsedEditorConfig = editorConfigLoader.load(
filePath = null,
rules = rules,
- editorConfigOverride = EditorConfigOverride.from(insertNewLineProperty to "true"),
+ editorConfigOverride = EditorConfigOverride.from(INSERT_FINAL_NEWLINE_PROPERTY to "true"),
)
assertThat(parsedEditorConfig.convertToRawValues()).containsExactly(
@@ -428,7 +428,7 @@
val editorConfigProperties = editorConfigLoader.load(
lintFile,
rules = rules.plus(FinalNewlineRule()),
- editorConfigOverride = EditorConfigOverride.from(insertNewLineProperty to "true"),
+ editorConfigOverride = EditorConfigOverride.from(INSERT_FINAL_NEWLINE_PROPERTY to "true"),
)
val parsedEditorConfig = editorConfigProperties.convertToRawValues()
@@ -458,7 +458,7 @@
val editorConfigProperties = editorConfigLoader.load(
lintFile,
rules = rules.plus(FinalNewlineRule()),
- editorConfigOverride = EditorConfigOverride.from(insertNewLineProperty to "false"),
+ editorConfigOverride = EditorConfigOverride.from(INSERT_FINAL_NEWLINE_PROPERTY to "false"),
)
val parsedEditorConfig = editorConfigProperties.convertToRawValues()
@@ -677,7 +677,7 @@
val parsedEditorConfig = editorConfigLoader.loadPropertiesForFile(
filePath = null,
rules = rules,
- editorConfigOverride = EditorConfigOverride.from(insertNewLineProperty to "true"),
+ editorConfigOverride = EditorConfigOverride.from(INSERT_FINAL_NEWLINE_PROPERTY to "true"),
)
assertThat(parsedEditorConfig.convertToRawValues()).containsExactly(
@@ -690,7 +690,7 @@
val parsedEditorConfig = editorConfigLoader.loadPropertiesForFile(
filePath = null,
rules = rules,
- editorConfigOverride = EditorConfigOverride.from(insertNewLineProperty to "true"),
+ editorConfigOverride = EditorConfigOverride.from(INSERT_FINAL_NEWLINE_PROPERTY to "true"),
)
assertThat(parsedEditorConfig.convertToRawValues()).containsExactly(
@@ -872,7 +872,7 @@
val editorConfigProperties = editorConfigLoader.loadPropertiesForFile(
lintFile,
rules = rules.plus(FinalNewlineRule()),
- editorConfigOverride = EditorConfigOverride.from(insertNewLineProperty to "true"),
+ editorConfigOverride = EditorConfigOverride.from(INSERT_FINAL_NEWLINE_PROPERTY to "true"),
)
val parsedEditorConfig = editorConfigProperties.convertToRawValues()
@@ -902,7 +902,7 @@
val editorConfigProperties = editorConfigLoader.loadPropertiesForFile(
lintFile,
rules = rules.plus(FinalNewlineRule()),
- editorConfigOverride = EditorConfigOverride.from(insertNewLineProperty to "false"),
+ editorConfigOverride = EditorConfigOverride.from(INSERT_FINAL_NEWLINE_PROPERTY to "false"),
)
val parsedEditorConfig = editorConfigProperties.convertToRawValues()
diff --git a/ktlint-reporter-html/src/test/kotlin/com/pinterest/ktlint/reporter/html/HtmlReporterTest.kt b/ktlint-reporter-html/src/test/kotlin/com/pinterest/ktlint/reporter/html/HtmlReporterTest.kt
index 2286c94..c4603eb 100644
--- a/ktlint-reporter-html/src/test/kotlin/com/pinterest/ktlint/reporter/html/HtmlReporterTest.kt
+++ b/ktlint-reporter-html/src/test/kotlin/com/pinterest/ktlint/reporter/html/HtmlReporterTest.kt
@@ -32,7 +32,7 @@
class HtmlReporterTest {
@Test
- fun shouldRenderEmptyReportWhen_NoIssuesFound() {
+ fun `Should render empty report when no issues found`() {
val out = ByteArrayOutputStream()
val reporter = HtmlReporter(PrintStream(out, true))
reporter.afterAll()
@@ -62,7 +62,7 @@
}
@Test
- fun shouldRenderIssuesWhen_LintProblemsFound() {
+ fun `Should render issues when lint problems found`() {
val out = ByteArrayOutputStream()
val reporter = HtmlReporter(PrintStream(out, true))
@@ -105,7 +105,7 @@
}
@Test
- fun shouldNotRenderCorrectedIssuesWhen_LintOneIsFound() {
+ fun `Should not render corrected issues when lint one is found`() {
val out = ByteArrayOutputStream()
val reporter = HtmlReporter(PrintStream(out, true))
@@ -154,7 +154,7 @@
}
@Test
- fun shouldRenderIssuesAndEscapeSpecialHtmlSymbolsWhen_LintProblemsFound() {
+ fun `Should render issues and escape special HTML symbols when lint problems found`() {
val out = ByteArrayOutputStream()
val reporter = HtmlReporter(PrintStream(out, true))
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/BlockCommentInitialStarAlignmentRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/BlockCommentInitialStarAlignmentRule.kt
index dec78d3..b8aae0d 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/BlockCommentInitialStarAlignmentRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/BlockCommentInitialStarAlignmentRule.kt
@@ -11,7 +11,7 @@
*/
public class BlockCommentInitialStarAlignmentRule :
Rule(
- "$experimentalRulesetId:block-comment-initial-star-alignment",
+ "$EXPERIMENTAL_RULE_SET_ID:block-comment-initial-star-alignment",
visitorModifiers = setOf(
// The block comment is a node which can contain multiple lines. The indent of the second and later line
// should be determined based on the indent of the block comment node. This indent is determined by the
@@ -31,7 +31,7 @@
val modifiedLines = mutableListOf<String>()
lines.forEach { line ->
val modifiedLine =
- continuationCommentRegex
+ CONTINUATION_COMMENT_REGEX
.find(line)
?.let { matchResult ->
val (prefix, content) = matchResult.destructured
@@ -56,6 +56,6 @@
}
private companion object {
- val continuationCommentRegex = Regex("^([\t ]+\\*)(.*)$")
+ val CONTINUATION_COMMENT_REGEX = Regex("^([\t ]+\\*)(.*)$")
}
}
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRule.kt
new file mode 100644
index 0000000..6129d8f
--- /dev/null
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRule.kt
@@ -0,0 +1,29 @@
+package com.pinterest.ktlint.ruleset.experimental
+
+import com.pinterest.ktlint.core.Rule
+import com.pinterest.ktlint.core.ast.ElementType.CLASS
+import com.pinterest.ktlint.core.ast.ElementType.IDENTIFIER
+import org.jetbrains.kotlin.com.intellij.lang.ASTNode
+
+/**
+ * https://kotlinlang.org/docs/coding-conventions.html#naming-rules
+ */
+public class ClassNamingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:class-naming") {
+ override fun beforeVisitChildNodes(
+ node: ASTNode,
+ autoCorrect: Boolean,
+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
+ ) {
+ node
+ .takeIf { node.elementType == CLASS }
+ ?.findChildByType(IDENTIFIER)
+ ?.takeUnless { it.text.matches(VALID_CLASS_NAME_REGEXP) }
+ ?.let {
+ emit(it.startOffset, "Class name should start with an uppercase letter and use camel case", false)
+ }
+ }
+
+ private companion object {
+ val VALID_CLASS_NAME_REGEXP = Regex("[A-Z][a-zA-Z0-9]*")
+ }
+}
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/CommentWrappingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/CommentWrappingRule.kt
index 8c87247..1b7b770 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/CommentWrappingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/CommentWrappingRule.kt
@@ -20,12 +20,12 @@
* another element on the same line is replaced with an EOL comment, if possible.
*/
public class CommentWrappingRule :
- Rule("$experimentalRulesetId:comment-wrapping"),
+ Rule("$EXPERIMENTAL_RULE_SET_ID:comment-wrapping"),
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(
- DefaultEditorConfigProperties.indentSizeProperty,
- DefaultEditorConfigProperties.indentStyleProperty,
+ DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY,
+ DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY,
)
override fun beforeVisitChildNodes(
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ContextReceiverWrappingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ContextReceiverWrappingRule.kt
index f931fae..830915f 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ContextReceiverWrappingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ContextReceiverWrappingRule.kt
@@ -30,13 +30,13 @@
* whenever the max line length is exceeded.
*/
public class ContextReceiverWrappingRule :
- Rule("$experimentalRulesetId:context-receiver-wrapping"),
+ Rule("$EXPERIMENTAL_RULE_SET_ID:context-receiver-wrapping"),
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(
- DefaultEditorConfigProperties.indentSizeProperty,
- DefaultEditorConfigProperties.indentStyleProperty,
- DefaultEditorConfigProperties.maxLineLengthProperty,
+ DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY,
+ DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY,
+ DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY,
)
private lateinit var indent: String
@@ -45,11 +45,11 @@
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
with(editorConfigProperties) {
val indentConfig = IndentConfig(
- indentStyle = getEditorConfigValue(DefaultEditorConfigProperties.indentStyleProperty),
- tabWidth = getEditorConfigValue(DefaultEditorConfigProperties.indentSizeProperty),
+ indentStyle = getEditorConfigValue(DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY),
+ tabWidth = getEditorConfigValue(DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY),
)
indent = indentConfig.indent
- maxLineLength = getEditorConfigValue(DefaultEditorConfigProperties.maxLineLengthProperty)
+ maxLineLength = getEditorConfigValue(DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY)
}
}
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/DiscouragedCommentLocationRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/DiscouragedCommentLocationRule.kt
index 146276a..3e68c54 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/DiscouragedCommentLocationRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/DiscouragedCommentLocationRule.kt
@@ -27,7 +27,7 @@
* foo(t: T) = "some-result"
* ```
*/
-public class DiscouragedCommentLocationRule : Rule("$experimentalRulesetId:discouraged-comment-location") {
+public class DiscouragedCommentLocationRule : Rule("$EXPERIMENTAL_RULE_SET_ID:discouraged-comment-location") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ExperimentalRuleSetProvider.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ExperimentalRuleSetProvider.kt
index 370a65c..a44991e 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ExperimentalRuleSetProvider.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ExperimentalRuleSetProvider.kt
@@ -5,11 +5,11 @@
import com.pinterest.ktlint.core.RuleSetProvider
import com.pinterest.ktlint.core.RuleSetProviderV2
-public const val experimentalRulesetId: String = "experimental"
+public const val EXPERIMENTAL_RULE_SET_ID: String = "experimental"
public class ExperimentalRuleSetProvider :
RuleSetProviderV2(
- id = experimentalRulesetId,
+ id = EXPERIMENTAL_RULE_SET_ID,
about = About(
maintainer = "KtLint",
description = "Experimental rules based on the Kotlin coding conventions (https://kotlinlang.org/docs/coding-conventions.html) and Android Kotlin styleguide (https://developer.android.com/kotlin/style-guide). Rules are intended to be promoted to the standard ruleset once they are stable",
@@ -24,7 +24,7 @@
replaceWith = ReplaceWith("getRuleProviders()"),
)
override fun get(): RuleSet = RuleSet(
- experimentalRulesetId,
+ EXPERIMENTAL_RULE_SET_ID,
UnnecessaryParenthesesBeforeTrailingLambdaRule(),
TypeParameterListSpacingRule(),
TypeArgumentListSpacingRule(),
@@ -42,6 +42,11 @@
NullableTypeSpacingRule(),
FunctionSignatureRule(),
ContextReceiverWrappingRule(),
+ ClassNamingRule(),
+ FunctionNamingRule(),
+ ObjectNamingRule(),
+ PackageNamingRule(),
+ PropertyNamingRule(),
)
override fun getRuleProviders(): Set<RuleProvider> =
@@ -63,5 +68,10 @@
RuleProvider { NullableTypeSpacingRule() },
RuleProvider { FunctionSignatureRule() },
RuleProvider { ContextReceiverWrappingRule() },
+ RuleProvider { ClassNamingRule() },
+ RuleProvider { FunctionNamingRule() },
+ RuleProvider { ObjectNamingRule() },
+ RuleProvider { PackageNamingRule() },
+ RuleProvider { PropertyNamingRule() },
)
}
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunKeywordSpacingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunKeywordSpacingRule.kt
index 685de41..ac0a3eb 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunKeywordSpacingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunKeywordSpacingRule.kt
@@ -10,7 +10,7 @@
/**
* Lints and formats the spacing after the fun keyword
*/
-public class FunKeywordSpacingRule : Rule("$experimentalRulesetId:fun-keyword-spacing") {
+public class FunKeywordSpacingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:fun-keyword-spacing") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRule.kt
new file mode 100644
index 0000000..eb12ecd
--- /dev/null
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRule.kt
@@ -0,0 +1,73 @@
+package com.pinterest.ktlint.ruleset.experimental
+
+import com.pinterest.ktlint.core.Rule
+import com.pinterest.ktlint.core.ast.ElementType.ANNOTATION_ENTRY
+import com.pinterest.ktlint.core.ast.ElementType.FUN
+import com.pinterest.ktlint.core.ast.ElementType.IDENTIFIER
+import com.pinterest.ktlint.core.ast.ElementType.MODIFIER_LIST
+import com.pinterest.ktlint.core.ast.ElementType.TYPE_REFERENCE
+import com.pinterest.ktlint.core.ast.children
+import com.pinterest.ktlint.core.ast.nextLeaf
+import org.jetbrains.kotlin.com.intellij.lang.ASTNode
+
+/**
+ * https://kotlinlang.org/docs/coding-conventions.html#function-names
+ */
+public class FunctionNamingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:function-naming") {
+ override fun beforeVisitChildNodes(
+ node: ASTNode,
+ autoCorrect: Boolean,
+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
+ ) {
+ node
+ .takeIf { node.elementType == FUN }
+ ?.takeUnless {
+ node.isFactoryMethod() ||
+ node.isTestMethod() ||
+ node.hasValidFunctionName()
+ }?.let {
+ val identifierOffset =
+ node
+ .findChildByType(IDENTIFIER)
+ ?.startOffset
+ ?: 1
+ emit(identifierOffset, "Function name should start with a lowercase letter (except factory methods) and use camel case", false)
+ }
+ }
+
+ private fun ASTNode.isFactoryMethod() =
+ findChildByType(TYPE_REFERENCE)?.text == findChildByType(IDENTIFIER)?.text
+
+ private fun ASTNode.isTestMethod() =
+ hasBackTickedIdentifier() && hasTestAnnotation()
+
+ private fun ASTNode.hasBackTickedIdentifier() =
+ findChildByType(IDENTIFIER)
+ ?.text
+ .orEmpty()
+ .matches(BACK_TICKED_FUNCTION_NAME_REGEXP)
+
+ private fun ASTNode.hasTestAnnotation() =
+ findChildByType(MODIFIER_LIST)
+ ?.children()
+ .orEmpty()
+ .any { it.hasAnnotationWithIdentifierEndingWithTest() }
+
+ private fun ASTNode.hasAnnotationWithIdentifierEndingWithTest() =
+ elementType == ANNOTATION_ENTRY &&
+ nextLeaf { it.elementType == IDENTIFIER }
+ ?.text
+ .orEmpty()
+ .endsWith("Test")
+
+ private fun ASTNode.hasValidFunctionName() =
+ findChildByType(IDENTIFIER)
+ ?.text
+ .orEmpty()
+ .matches(VALID_FUNCTION_NAME_REGEXP)
+
+ private companion object {
+ val VALID_FUNCTION_NAME_REGEXP = Regex("[a-z][a-zA-Z0-9]*")
+ val BACK_TICKED_FUNCTION_NAME_REGEXP = Regex("`.*`")
+ }
+}
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionReturnTypeSpacingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionReturnTypeSpacingRule.kt
index bb0e085..2f32413 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionReturnTypeSpacingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionReturnTypeSpacingRule.kt
@@ -9,7 +9,7 @@
import com.pinterest.ktlint.core.ast.upsertWhitespaceAfterMe
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
-public class FunctionReturnTypeSpacingRule : Rule("$experimentalRulesetId:function-return-type-spacing") {
+public class FunctionReturnTypeSpacingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:function-return-type-spacing") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionSignatureRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionSignatureRule.kt
index 0333154..a83776a 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionSignatureRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionSignatureRule.kt
@@ -2,9 +2,9 @@
import com.pinterest.ktlint.core.IndentConfig
import com.pinterest.ktlint.core.Rule
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentSizeProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentStyleProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.ast.ElementType.ANNOTATION
@@ -46,7 +46,7 @@
public class FunctionSignatureRule :
Rule(
- id = "$experimentalRulesetId:function-signature",
+ id = "$EXPERIMENTAL_RULE_SET_ID:function-signature",
visitorModifiers = setOf(
// Run after wrapping and spacing rules
VisitorModifier.RunAsLateAsPossible,
@@ -55,11 +55,11 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(
- indentSizeProperty,
- indentStyleProperty,
- maxLineLengthProperty,
- forceMultilineWhenParameterCountGreaterOrEqualThanProperty,
- functionBodyExpressionWrappingProperty,
+ INDENT_SIZE_PROPERTY,
+ INDENT_STYLE_PROPERTY,
+ MAX_LINE_LENGTH_PROPERTY,
+ FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY,
+ FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY,
)
private var indent: String? = null
@@ -69,14 +69,14 @@
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
with(editorConfigProperties) {
- functionSignatureWrappingMinimumParameters = getEditorConfigValue(forceMultilineWhenParameterCountGreaterOrEqualThanProperty)
- functionBodyExpressionWrapping = getEditorConfigValue(functionBodyExpressionWrappingProperty)
+ functionSignatureWrappingMinimumParameters = getEditorConfigValue(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY)
+ functionBodyExpressionWrapping = getEditorConfigValue(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY)
val indentConfig = IndentConfig(
- indentStyle = getEditorConfigValue(indentStyleProperty),
- tabWidth = getEditorConfigValue(indentSizeProperty),
+ indentStyle = getEditorConfigValue(INDENT_STYLE_PROPERTY),
+ tabWidth = getEditorConfigValue(INDENT_SIZE_PROPERTY),
)
indent = indentConfig.indent
- maxLineLength = getEditorConfigValue(maxLineLengthProperty)
+ maxLineLength = getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
}
}
@@ -687,7 +687,7 @@
?.prevCodeLeaf()
public companion object {
- public val forceMultilineWhenParameterCountGreaterOrEqualThanProperty: UsesEditorConfigProperties.EditorConfigProperty<Int> =
+ public val FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<Int> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
"ktlint_function_signature_rule_force_multiline_when_parameter_count_greater_or_equal_than",
@@ -700,7 +700,15 @@
defaultValue = -1,
)
- public val functionBodyExpressionWrappingProperty: UsesEditorConfigProperties.EditorConfigProperty<FunctionBodyExpressionWrapping> =
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val forceMultilineWhenParameterCountGreaterOrEqualThanProperty: UsesEditorConfigProperties.EditorConfigProperty<Int> =
+ FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY
+
+ public val FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<FunctionBodyExpressionWrapping> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
"ktlint_function_signature_body_expression_wrapping",
@@ -714,6 +722,14 @@
defaultValue = default,
)
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val functionBodyExpressionWrappingProperty: UsesEditorConfigProperties.EditorConfigProperty<FunctionBodyExpressionWrapping> =
+ FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY
+
private val INDENT_WITH_CLOSING_PARENTHESIS = Regex("\\s*\\) =")
}
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionStartOfBodySpacingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionStartOfBodySpacingRule.kt
index f35403c..96789bf 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionStartOfBodySpacingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionStartOfBodySpacingRule.kt
@@ -12,7 +12,7 @@
/**
* Lints and formats the spacing after the fun keyword
*/
-public class FunctionStartOfBodySpacingRule : Rule("$experimentalRulesetId:function-start-of-body-spacing") {
+public class FunctionStartOfBodySpacingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:function-start-of-body-spacing") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionTypeReferenceSpacingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionTypeReferenceSpacingRule.kt
index bf14e64..d6cd6b7 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionTypeReferenceSpacingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionTypeReferenceSpacingRule.kt
@@ -9,7 +9,7 @@
import com.pinterest.ktlint.core.ast.nextSibling
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
-public class FunctionTypeReferenceSpacingRule : Rule("$experimentalRulesetId:function-type-reference-spacing") {
+public class FunctionTypeReferenceSpacingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:function-type-reference-spacing") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/KdocWrappingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/KdocWrappingRule.kt
index d28cdac..7e2454d 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/KdocWrappingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/KdocWrappingRule.kt
@@ -18,12 +18,12 @@
* Checks external wrapping of KDoc comment. Wrapping inside the KDoc comment is not altered.
*/
public class KdocWrappingRule :
- Rule("$experimentalRulesetId:kdoc-wrapping"),
+ Rule("$EXPERIMENTAL_RULE_SET_ID:kdoc-wrapping"),
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(
- DefaultEditorConfigProperties.indentSizeProperty,
- DefaultEditorConfigProperties.indentStyleProperty,
+ DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY,
+ DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY,
)
override fun beforeVisitChildNodes(
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ModifierListSpacingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ModifierListSpacingRule.kt
index a94ea36..85ffb6c 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ModifierListSpacingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ModifierListSpacingRule.kt
@@ -17,7 +17,7 @@
/**
* Lint and format the spacing between the modifiers in and after the last modifier in a modifier list.
*/
-public class ModifierListSpacingRule : Rule("$experimentalRulesetId:modifier-list-spacing") {
+public class ModifierListSpacingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:modifier-list-spacing") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/NullableTypeSpacingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/NullableTypeSpacingRule.kt
index ae2a6e9..104d9df 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/NullableTypeSpacingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/NullableTypeSpacingRule.kt
@@ -7,7 +7,7 @@
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
-public class NullableTypeSpacingRule : Rule("$experimentalRulesetId:nullable-type-spacing") {
+public class NullableTypeSpacingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:nullable-type-spacing") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ObjectNamingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ObjectNamingRule.kt
new file mode 100644
index 0000000..1ce7a16
--- /dev/null
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ObjectNamingRule.kt
@@ -0,0 +1,29 @@
+package com.pinterest.ktlint.ruleset.experimental
+
+import com.pinterest.ktlint.core.Rule
+import com.pinterest.ktlint.core.ast.ElementType.IDENTIFIER
+import com.pinterest.ktlint.core.ast.ElementType.OBJECT_DECLARATION
+import org.jetbrains.kotlin.com.intellij.lang.ASTNode
+
+/**
+ * https://kotlinlang.org/docs/coding-conventions.html#naming-rules
+ */
+public class ObjectNamingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:object-naming") {
+ override fun beforeVisitChildNodes(
+ node: ASTNode,
+ autoCorrect: Boolean,
+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
+ ) {
+ node
+ .takeIf { node.elementType == OBJECT_DECLARATION }
+ ?.findChildByType(IDENTIFIER)
+ ?.takeUnless { it.text.matches(VALID_OBJECT_NAME_REGEXP) }
+ ?.let {
+ emit(it.startOffset, "Object name should start with an uppercase letter and use camel case", false)
+ }
+ }
+
+ private companion object {
+ val VALID_OBJECT_NAME_REGEXP = Regex("[A-Z][a-zA-Z]*")
+ }
+}
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/PackageNamingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/PackageNamingRule.kt
new file mode 100644
index 0000000..206fc52
--- /dev/null
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/PackageNamingRule.kt
@@ -0,0 +1,33 @@
+package com.pinterest.ktlint.ruleset.experimental
+
+import com.pinterest.ktlint.core.Rule
+import com.pinterest.ktlint.core.ast.ElementType.DOT_QUALIFIED_EXPRESSION
+import com.pinterest.ktlint.core.ast.ElementType.PACKAGE_DIRECTIVE
+import com.pinterest.ktlint.core.ast.ElementType.REFERENCE_EXPRESSION
+import com.pinterest.ktlint.core.ast.nextCodeSibling
+import org.jetbrains.kotlin.com.intellij.lang.ASTNode
+
+/**
+ * https://kotlinlang.org/docs/coding-conventions.html#naming-rules
+ */
+public class PackageNamingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:package-naming") {
+ override fun beforeVisitChildNodes(
+ node: ASTNode,
+ autoCorrect: Boolean,
+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
+ ) {
+ node
+ .takeIf { node.elementType == PACKAGE_DIRECTIVE }
+ ?.firstChildNode
+ ?.nextCodeSibling()
+ ?.takeIf { it.elementType == DOT_QUALIFIED_EXPRESSION || it.elementType == REFERENCE_EXPRESSION }
+ ?.takeUnless { it.text.matches(VALID_PACKAGE_NAME_REGEXP) }
+ ?.let {
+ emit(it.startOffset, "Package name should contain lowercase characters only", false)
+ }
+ }
+
+ private companion object {
+ val VALID_PACKAGE_NAME_REGEXP = Regex("[a-z]+(\\.[a-z]+)*")
+ }
+}
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ParameterListSpacingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ParameterListSpacingRule.kt
index 9dcee1b..e7b1375 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ParameterListSpacingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ParameterListSpacingRule.kt
@@ -25,7 +25,7 @@
* comma's and colons. However, it does have a more complete view on the higher concept of the parameter-list without
* interfering of the parameter-list-wrapping rule.
*/
-public class ParameterListSpacingRule : Rule("$experimentalRulesetId:parameter-list-spacing") {
+public class ParameterListSpacingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:parameter-list-spacing") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRule.kt
new file mode 100644
index 0000000..4b434e2
--- /dev/null
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRule.kt
@@ -0,0 +1,143 @@
+package com.pinterest.ktlint.ruleset.experimental
+
+import com.pinterest.ktlint.core.Rule
+import com.pinterest.ktlint.core.ast.ElementType.CLASS_BODY
+import com.pinterest.ktlint.core.ast.ElementType.CONST_KEYWORD
+import com.pinterest.ktlint.core.ast.ElementType.FILE
+import com.pinterest.ktlint.core.ast.ElementType.IDENTIFIER
+import com.pinterest.ktlint.core.ast.ElementType.MODIFIER_LIST
+import com.pinterest.ktlint.core.ast.ElementType.OBJECT_DECLARATION
+import com.pinterest.ktlint.core.ast.ElementType.OVERRIDE_KEYWORD
+import com.pinterest.ktlint.core.ast.ElementType.PRIVATE_KEYWORD
+import com.pinterest.ktlint.core.ast.ElementType.PROPERTY
+import com.pinterest.ktlint.core.ast.ElementType.PROPERTY_ACCESSOR
+import com.pinterest.ktlint.core.ast.ElementType.VAL_KEYWORD
+import com.pinterest.ktlint.core.ast.children
+import org.jetbrains.kotlin.com.intellij.lang.ASTNode
+import org.jetbrains.kotlin.com.intellij.psi.tree.IElementType
+
+/**
+ * https://kotlinlang.org/docs/coding-conventions.html#function-names
+ * https://kotlinlang.org/docs/coding-conventions.html#property-names
+ */
+public class PropertyNamingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:property-naming") {
+ override fun beforeVisitChildNodes(
+ node: ASTNode,
+ autoCorrect: Boolean,
+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
+ ) {
+ node
+ .takeIf { node.elementType == PROPERTY }
+ ?.let { property -> visitProperty(property, emit) }
+ }
+
+ private fun visitProperty(
+ property: ASTNode,
+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
+ ) {
+ property
+ .findChildByType(IDENTIFIER)
+ ?.let { identifier ->
+ when {
+ property.hasCustomGetter() -> {
+ // Can not reliably determine whether the value is immutable or not
+ }
+ property.isBackingProperty() -> {
+ visitBackingProperty(identifier, emit)
+ }
+ property.hasConstModifier() ||
+ property.isTopLevelValue() ||
+ property.isObjectValue() -> {
+ visitConstProperty(identifier, emit)
+ }
+ else -> {
+ visitNonConstProperty(identifier, emit)
+ }
+ }
+ }
+ }
+
+ private fun visitBackingProperty(
+ identifier: ASTNode,
+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
+ ) {
+ identifier
+ .text
+ .takeUnless { it.matches(BACKING_PROPERTY_LOWER_CAMEL_CASE_REGEXP) }
+ ?.let {
+ emit(identifier.startOffset, "Backing property name should start with underscore followed by lower camel case", false)
+ }
+ }
+
+ private fun visitConstProperty(
+ identifier: ASTNode,
+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
+ ) {
+ identifier
+ .text
+ .takeUnless { it.matches(SCREAMING_SNAKE_CASE_REGEXP) }
+ ?.let {
+ emit(identifier.startOffset, "Property name should use the screaming snake case notation when the value can not be changed", false)
+ }
+ }
+
+ private fun visitNonConstProperty(
+ identifier: ASTNode,
+ emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
+ ) {
+ identifier
+ .text
+ .takeUnless { it.matches(LOWER_CAMEL_CASE_REGEXP) }
+ ?.let {
+ emit(identifier.startOffset, "Property name should start with a lowercase letter and use camel case", false)
+ }
+ }
+
+ private fun ASTNode.hasCustomGetter() =
+ findChildByType(PROPERTY_ACCESSOR)
+ ?.firstChildNode
+ ?.text == "get"
+
+ private fun ASTNode.hasConstModifier() =
+ hasModifier(CONST_KEYWORD)
+
+ private fun ASTNode.hasModifier(iElementType: IElementType) =
+ findChildByType(MODIFIER_LIST)
+ ?.children()
+ .orEmpty()
+ .any { it.elementType == iElementType }
+
+ private fun ASTNode.isTopLevelValue() =
+ treeParent.elementType == FILE && containsValKeyword()
+
+ private fun ASTNode.containsValKeyword() =
+ children().any { it.elementType == VAL_KEYWORD }
+
+ private fun ASTNode.isObjectValue() =
+ treeParent.elementType == CLASS_BODY &&
+ treeParent?.treeParent?.elementType == OBJECT_DECLARATION &&
+ containsValKeyword() &&
+ !hasModifier(OVERRIDE_KEYWORD)
+
+ private fun ASTNode.isBackingProperty() =
+ takeIf { hasModifier(PRIVATE_KEYWORD) }
+ ?.findChildByType(IDENTIFIER)
+ ?.takeIf { it.text.startsWith("_") }
+ ?.let { identifier ->
+ this.hasPublicProperty(identifier.text.removePrefix("_"))
+ }
+ ?: false
+
+ private fun ASTNode.hasPublicProperty(identifier: String) =
+ treeParent
+ .children()
+ .filter { it.elementType == PROPERTY }
+ .mapNotNull { it.findChildByType(IDENTIFIER) }
+ .any { it.text == identifier }
+
+ private companion object {
+ val LOWER_CAMEL_CASE_REGEXP = Regex("[a-z][a-zA-Z0-9]*")
+ val SCREAMING_SNAKE_CASE_REGEXP = Regex("[A-Z][_A-Z0-9]*")
+ val BACKING_PROPERTY_LOWER_CAMEL_CASE_REGEXP = Regex("_[a-z][a-zA-Z0-9]*")
+ }
+}
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/SpacingBetweenFunctionNameAndOpeningParenthesisRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/SpacingBetweenFunctionNameAndOpeningParenthesisRule.kt
index fed365b..cb14a09 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/SpacingBetweenFunctionNameAndOpeningParenthesisRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/SpacingBetweenFunctionNameAndOpeningParenthesisRule.kt
@@ -6,7 +6,7 @@
import com.pinterest.ktlint.core.ast.nextSibling
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
-public class SpacingBetweenFunctionNameAndOpeningParenthesisRule : Rule("$experimentalRulesetId:spacing-between-function-name-and-opening-parenthesis") {
+public class SpacingBetweenFunctionNameAndOpeningParenthesisRule : Rule("$EXPERIMENTAL_RULE_SET_ID:spacing-between-function-name-and-opening-parenthesis") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/TypeArgumentListSpacingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/TypeArgumentListSpacingRule.kt
index a33d7f5..02ea65b 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/TypeArgumentListSpacingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/TypeArgumentListSpacingRule.kt
@@ -22,7 +22,7 @@
/**
* Lints and formats the spacing before and after the angle brackets of a type argument list.
*/
-public class TypeArgumentListSpacingRule : Rule("$experimentalRulesetId:type-argument-list-spacing") {
+public class TypeArgumentListSpacingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:type-argument-list-spacing") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/TypeParameterListSpacingRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/TypeParameterListSpacingRule.kt
index 2d49c60..d6a3960 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/TypeParameterListSpacingRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/TypeParameterListSpacingRule.kt
@@ -24,7 +24,7 @@
/**
* Lints and formats the spacing before and after the angle brackets of a type parameter list.
*/
-public class TypeParameterListSpacingRule : Rule("$experimentalRulesetId:type-parameter-list-spacing") {
+public class TypeParameterListSpacingRule : Rule("$EXPERIMENTAL_RULE_SET_ID:type-parameter-list-spacing") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/UnnecessaryParenthesesBeforeTrailingLambdaRule.kt b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/UnnecessaryParenthesesBeforeTrailingLambdaRule.kt
index 1c5781d..47ff539 100644
--- a/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/UnnecessaryParenthesesBeforeTrailingLambdaRule.kt
+++ b/ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/UnnecessaryParenthesesBeforeTrailingLambdaRule.kt
@@ -14,7 +14,7 @@
/**
* Ensures there are no unnecessary parentheses before a trailing lambda.
*/
-public class UnnecessaryParenthesesBeforeTrailingLambdaRule : Rule("$experimentalRulesetId:unnecessary-parentheses-before-trailing-lambda") {
+public class UnnecessaryParenthesesBeforeTrailingLambdaRule : Rule("$EXPERIMENTAL_RULE_SET_ID:unnecessary-parentheses-before-trailing-lambda") {
override fun beforeVisitChildNodes(
node: ASTNode,
autoCorrect: Boolean,
diff --git a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRuleTest.kt b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRuleTest.kt
new file mode 100644
index 0000000..9c5542d
--- /dev/null
+++ b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/ClassNamingRuleTest.kt
@@ -0,0 +1,36 @@
+package com.pinterest.ktlint.ruleset.experimental
+
+import com.pinterest.ktlint.test.KtLintAssertThat
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.params.ParameterizedTest
+import org.junit.jupiter.params.provider.ValueSource
+
+class ClassNamingRuleTest {
+ private val classNamingRuleAssertThat =
+ KtLintAssertThat.assertThatRule { ClassNamingRule() }
+
+ @Test
+ fun `Given a valid class name then do not emit`() {
+ val code =
+ """
+ class Foo1
+ """.trimIndent()
+ classNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @ParameterizedTest(name = ": {0}")
+ @ValueSource(
+ strings = [
+ "foo",
+ "Foo_Bar",
+ ],
+ )
+ fun `Given an invalid class name then do emit`(className: String) {
+ val code =
+ """
+ class $className
+ """.trimIndent()
+ classNamingRuleAssertThat(code)
+ .hasLintViolationWithoutAutoCorrect(1, 7, "Class name should start with an uppercase letter and use camel case")
+ }
+}
diff --git a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRuleTest.kt b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRuleTest.kt
new file mode 100644
index 0000000..1407faf
--- /dev/null
+++ b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionNamingRuleTest.kt
@@ -0,0 +1,73 @@
+package com.pinterest.ktlint.ruleset.experimental
+
+import com.pinterest.ktlint.test.KtLintAssertThat
+import org.junit.jupiter.api.DisplayName
+import org.junit.jupiter.api.Nested
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.params.ParameterizedTest
+import org.junit.jupiter.params.provider.ValueSource
+
+class FunctionNamingRuleTest {
+ private val functionNamingRuleAssertThat =
+ KtLintAssertThat.assertThatRule { FunctionNamingRule() }
+
+ @Test
+ fun `Given a valid function name then do not emit`() {
+ val code =
+ """
+ fun foo1() = "foo"
+ """.trimIndent()
+ functionNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @Test
+ fun `Given a factory method then do not emit`() {
+ val code =
+ """
+ interface Foo
+ class FooImpl : Foo
+ fun Foo(): Foo = FooImpl()
+ """.trimIndent()
+ functionNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @DisplayName("Given a method with name between backticks")
+ @Nested
+ inner class BackTickedFunction {
+ @Test
+ fun `Given a function not annotated with a Test annotation then do emit`() {
+ val code =
+ """
+ fun `Some name`() {}
+ """.trimIndent()
+ functionNamingRuleAssertThat(code)
+ .hasLintViolationWithoutAutoCorrect(1, 5, "Function name should start with a lowercase letter (except factory methods) and use camel case")
+ }
+
+ @Test
+ fun `Given a function annotated with a Test annotation then do not emit`() {
+ val code =
+ """
+ @Test
+ fun `Some descriptive test name`() {}
+ """.trimIndent()
+ functionNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+ }
+
+ @ParameterizedTest(name = ": {0}")
+ @ValueSource(
+ strings = [
+ "Foo",
+ "Foo_Bar",
+ ],
+ )
+ fun `Given an invalid function name then do emit`(functionName: String) {
+ val code =
+ """
+ fun $functionName() = "foo"
+ """.trimIndent()
+ functionNamingRuleAssertThat(code)
+ .hasLintViolationWithoutAutoCorrect(1, 5, "Function name should start with a lowercase letter (except factory methods) and use camel case")
+ }
+}
diff --git a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionSignatureRuleTest.kt b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionSignatureRuleTest.kt
index 9806e4d..ec0978b 100644
--- a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionSignatureRuleTest.kt
+++ b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/FunctionSignatureRuleTest.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.ruleset.experimental
-import com.pinterest.ktlint.ruleset.experimental.FunctionSignatureRule.Companion.forceMultilineWhenParameterCountGreaterOrEqualThanProperty
-import com.pinterest.ktlint.ruleset.experimental.FunctionSignatureRule.Companion.functionBodyExpressionWrappingProperty
+import com.pinterest.ktlint.ruleset.experimental.FunctionSignatureRule.Companion.FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY
+import com.pinterest.ktlint.ruleset.experimental.FunctionSignatureRule.Companion.FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY
import com.pinterest.ktlint.ruleset.standard.IndentationRule
import com.pinterest.ktlint.ruleset.standard.NoMultipleSpacesRule
import com.pinterest.ktlint.ruleset.standard.SpacingAroundAngleBracketsRule
@@ -443,7 +443,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(forceMultilineWhenParameterCountGreaterOrEqualThanProperty to 2)
+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to 2)
.hasLintViolations(
LintViolation(2, 7, "Newline expected after opening parenthesis"),
LintViolation(2, 15, "Parameter should start on a newline"),
@@ -471,7 +471,7 @@
}
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
- .withEditorConfigOverride(forceMultilineWhenParameterCountGreaterOrEqualThanProperty to 2)
+ .withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to 2)
.hasLintViolations(
LintViolation(1, 7, "Newline expected after opening parenthesis"),
LintViolation(1, 15, "Parameter should start on a newline"),
@@ -689,7 +689,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(functionBodyExpressionWrappingProperty to bodyExpressionWrapping)
+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)
.hasNoLintViolations()
}
@@ -714,7 +714,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(functionBodyExpressionWrappingProperty to bodyExpressionWrapping)
+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolation(2, 33, "Newline expected before expression body")
.isFormattedAs(formattedCode)
@@ -743,7 +743,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(functionBodyExpressionWrappingProperty to bodyExpressionWrapping)
+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolation(2, 33, "Newline expected before expression body")
.isFormattedAs(formattedCode)
@@ -777,7 +777,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(functionBodyExpressionWrappingProperty to bodyExpressionWrapping)
+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolations(
LintViolation(3, 5, "No whitespace expected between opening parenthesis and first parameter name"),
@@ -811,7 +811,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(functionBodyExpressionWrappingProperty to bodyExpressionWrapping)
+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolations(
LintViolation(3, 5, "No whitespace expected between opening parenthesis and first parameter name"),
@@ -848,7 +848,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(functionBodyExpressionWrappingProperty to bodyExpressionWrapping)
+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolations(
LintViolation(3, 5, "No whitespace expected between opening parenthesis and first parameter name"),
@@ -883,7 +883,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(functionBodyExpressionWrappingProperty to bodyExpressionWrapping)
+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolations(
LintViolation(3, 5, "No whitespace expected between opening parenthesis and first parameter name"),
@@ -920,7 +920,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(functionBodyExpressionWrappingProperty to bodyExpressionWrapping)
+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolations(
LintViolation(3, 5, "No whitespace expected between opening parenthesis and first parameter name"),
@@ -958,7 +958,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(functionBodyExpressionWrappingProperty to bodyExpressionWrapping)
+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolation(5, 4, "First line of body expression fits on same line as function signature")
.isFormattedAs(formattedCode)
@@ -982,7 +982,7 @@
""".trimIndent()
functionSignatureWrappingRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(functionBodyExpressionWrappingProperty to bodyExpressionWrapping)
+ .withEditorConfigOverride(FUNCTION_BODY_EXPRESSION_WRAPPING_PROPERTY to bodyExpressionWrapping)
.addAdditionalRuleProvider { IndentationRule() }
.hasNoLintViolations()
}
diff --git a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/ObjectNamingRuleTest.kt b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/ObjectNamingRuleTest.kt
new file mode 100644
index 0000000..8837f9f
--- /dev/null
+++ b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/ObjectNamingRuleTest.kt
@@ -0,0 +1,37 @@
+package com.pinterest.ktlint.ruleset.experimental
+
+import com.pinterest.ktlint.test.KtLintAssertThat
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.params.ParameterizedTest
+import org.junit.jupiter.params.provider.ValueSource
+
+class ObjectNamingRuleTest {
+ private val objectNamingRuleAssertThat =
+ KtLintAssertThat.assertThatRule { ObjectNamingRule() }
+
+ @Test
+ fun `Given a valid class name then do not emit`() {
+ val code =
+ """
+ object Foo
+ """.trimIndent()
+ objectNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @ParameterizedTest(name = ": {0}")
+ @ValueSource(
+ strings = [
+ "foo",
+ "Foo1",
+ "Foo_Bar",
+ ],
+ )
+ fun `Given an invalid object name then do emit`(className: String) {
+ val code =
+ """
+ object $className
+ """.trimIndent()
+ objectNamingRuleAssertThat(code)
+ .hasLintViolationWithoutAutoCorrect(1, 8, "Object name should start with an uppercase letter and use camel case")
+ }
+}
diff --git a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/PackageNamingRuleTest.kt b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/PackageNamingRuleTest.kt
new file mode 100644
index 0000000..2b7bed6
--- /dev/null
+++ b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/PackageNamingRuleTest.kt
@@ -0,0 +1,68 @@
+package com.pinterest.ktlint.ruleset.experimental
+
+import com.pinterest.ktlint.test.KtLintAssertThat
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.params.ParameterizedTest
+import org.junit.jupiter.params.provider.ValueSource
+
+class PackageNamingRuleTest {
+ private val packageNamingRuleAssertThat =
+ KtLintAssertThat.assertThatRule { PackageNamingRule() }
+
+ @Test
+ fun `Given a valid single level package name then do not emit`() {
+ val code =
+ """
+ package foo
+ """.trimIndent()
+ packageNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @Test
+ fun `Given a valid multi level package name then do not emit`() {
+ val code =
+ """
+ package foo.foo
+ """.trimIndent()
+ packageNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @ParameterizedTest(name = ": {0}")
+ @ValueSource(
+ strings = [
+ "Foo",
+ "foo.Foo",
+ "foo_bar",
+ "foo.foo_bar",
+ "foo1",
+ "foo.foo1",
+ ],
+ )
+ fun `Given a package name containing a non-lowercase characters then do emit`(packageName: String) {
+ val code =
+ """
+ package $packageName
+ """.trimIndent()
+ packageNamingRuleAssertThat(code)
+ .hasLintViolationWithoutAutoCorrect(1, 9, "Package name should contain lowercase characters only")
+ }
+
+ @Test
+ fun `Given a package name with containing a non-lowercase characters which is suppressed then do not emit`() {
+ val code =
+ """
+ @file:Suppress("ktlint:experimental:package-naming")
+ package foo.fooBar
+ """.trimIndent()
+ packageNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @Test
+ fun `Given a package name with containing a non-lowercase characters which is suppressed via ktlint directive in comment then do not emit`() {
+ val code =
+ """
+ package foo.fooBar // ktlint-disable experimental:package-naming
+ """.trimIndent()
+ packageNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+}
diff --git a/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRuleTest.kt b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRuleTest.kt
new file mode 100644
index 0000000..f1d7538
--- /dev/null
+++ b/ktlint-ruleset-experimental/src/test/kotlin/com/pinterest/ktlint/ruleset/experimental/PropertyNamingRuleTest.kt
@@ -0,0 +1,128 @@
+package com.pinterest.ktlint.ruleset.experimental
+
+import com.pinterest.ktlint.test.KtLintAssertThat
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.params.ParameterizedTest
+import org.junit.jupiter.params.provider.ValueSource
+
+class PropertyNamingRuleTest {
+ private val propertyNamingRuleAssertThat =
+ KtLintAssertThat.assertThatRule { PropertyNamingRule() }
+
+ @Test
+ fun `Given a valid property name then do not emit`() {
+ val code =
+ """
+ var foo = "foo"
+ """.trimIndent()
+ propertyNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @ParameterizedTest(name = ": {0}")
+ @ValueSource(
+ strings = [
+ "Foo",
+ "Foo1",
+ "Foo_Bar",
+ ],
+ )
+ fun `Given an invalid property name then do emit`(propertyName: String) {
+ val code =
+ """
+ var $propertyName = "foo"
+ """.trimIndent()
+ propertyNamingRuleAssertThat(code)
+ .hasLintViolationWithoutAutoCorrect(1, 5, "Property name should start with a lowercase letter and use camel case")
+ }
+
+ @Test
+ fun `Given a const property name not in screaming case notation then do emit`() {
+ val code =
+ """
+ const val foo = "foo"
+ const val FOO_BAR_2 = "foo-bar-2"
+ """.trimIndent()
+ propertyNamingRuleAssertThat(code)
+ .hasLintViolationWithoutAutoCorrect(1, 11, "Property name should use the screaming snake case notation when the value can not be changed")
+ }
+
+ @Test
+ fun `Given a top level val property name not in screaming case notation then do emit`() {
+ val code =
+ """
+ val foo = Foo()
+ val FOO_BAR = FooBar()
+ """.trimIndent()
+ propertyNamingRuleAssertThat(code)
+ .hasLintViolationWithoutAutoCorrect(1, 5, "Property name should use the screaming snake case notation when the value can not be changed")
+ }
+
+ @Test
+ fun `Given an object val property name not having a custom get function and not in screaming case notation then do emit`() {
+ val code =
+ """
+ class Foo {
+ companion object {
+ val foo = Foo()
+ val FOO_BAR = FooBar()
+ }
+ }
+ """.trimIndent()
+ propertyNamingRuleAssertThat(code)
+ .hasLintViolationWithoutAutoCorrect(3, 13, "Property name should use the screaming snake case notation when the value can not be changed")
+ }
+
+ @Test
+ fun `Given an object override val property name not having a custom get function and not in screaming case notation then do not emit`() {
+ val code =
+ """
+ open class Foo {
+ open val foo = "foo"
+ }
+
+ val BAR = object : Foo() {
+ override val foo = "bar"
+ }
+ """.trimIndent()
+ propertyNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @Test
+ fun `Given an object val property name having a custom get function and not in screaming case notation then do not emit`() {
+ val code =
+ """
+ class Foo {
+ companion object {
+ val foo
+ get() = foobar() // Lint can not check whether data is immutable
+ }
+ }
+ """.trimIndent()
+ propertyNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @Test
+ fun `Given a backing val property name having a custom get function and not in screaming case notation then do not emit`() {
+ val code =
+ """
+ class Foo {
+ private val _element2List = mutableListOf<Element>()
+
+ val element2List: List<Element>
+ get() = _elementList
+ }
+ """.trimIndent()
+ propertyNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+
+ @Test
+ fun `Given a local variable then do not emit`() {
+ val code =
+ """
+ fun foo() {
+ val bar2 = "bar"
+ }
+ """.trimIndent()
+ propertyNamingRuleAssertThat(code).hasNoLintViolations()
+ }
+}
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ArgumentListWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ArgumentListWrappingRule.kt
index f2bfb91..85cf1e6 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ArgumentListWrappingRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ArgumentListWrappingRule.kt
@@ -2,9 +2,9 @@
import com.pinterest.ktlint.core.IndentConfig
import com.pinterest.ktlint.core.Rule
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentSizeProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentStyleProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.ast.ElementType
@@ -52,9 +52,9 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(
- indentSizeProperty,
- indentStyleProperty,
- maxLineLengthProperty,
+ INDENT_SIZE_PROPERTY,
+ INDENT_STYLE_PROPERTY,
+ MAX_LINE_LENGTH_PROPERTY,
)
private var editorConfigIndent = IndentConfig.DEFAULT_INDENT_CONFIG
@@ -63,10 +63,10 @@
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
editorConfigIndent = IndentConfig(
- indentStyle = editorConfigProperties.getEditorConfigValue(indentStyleProperty),
- tabWidth = editorConfigProperties.getEditorConfigValue(indentSizeProperty),
+ indentStyle = editorConfigProperties.getEditorConfigValue(INDENT_STYLE_PROPERTY),
+ tabWidth = editorConfigProperties.getEditorConfigValue(INDENT_SIZE_PROPERTY),
)
- maxLineLength = editorConfigProperties.getEditorConfigValue(maxLineLengthProperty)
+ maxLineLength = editorConfigProperties.getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
}
override fun beforeVisitChildNodes(
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ChainWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ChainWrappingRule.kt
index e2e4461..e8a9477 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ChainWrappingRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ChainWrappingRule.kt
@@ -44,8 +44,8 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(
- DefaultEditorConfigProperties.indentSizeProperty,
- DefaultEditorConfigProperties.indentStyleProperty,
+ DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY,
+ DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY,
)
private var indent: String? = null
@@ -57,8 +57,8 @@
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
with(editorConfigProperties) {
val indentConfig = IndentConfig(
- indentStyle = getEditorConfigValue(com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentStyleProperty),
- tabWidth = getEditorConfigValue(com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentSizeProperty),
+ indentStyle = getEditorConfigValue(com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY),
+ tabWidth = getEditorConfigValue(com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY),
)
indent = indentConfig.indent
}
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/EnumEntryNameCaseRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/EnumEntryNameCaseRule.kt
index 6fe1795..4ad2f3f 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/EnumEntryNameCaseRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/EnumEntryNameCaseRule.kt
@@ -11,7 +11,7 @@
*/
public class EnumEntryNameCaseRule : Rule("enum-entry-name-case") {
internal companion object {
- val regex = "[A-Z]([A-Za-z\\d]*|[A-Z_\\d]*)".regExIgnoringDiacriticsAndStrokesOnLetters()
+ val ENUM_ENTRY_IDENTIFIER_REGEX = "[A-Z]([A-Za-z\\d]*|[A-Z_\\d]*)".regExIgnoringDiacriticsAndStrokesOnLetters()
}
override fun beforeVisitChildNodes(
@@ -25,7 +25,7 @@
val enumEntry = node.psi as? KtEnumEntry ?: return
val name = enumEntry.name ?: return
- if (!name.matches(regex)) {
+ if (!name.matches(ENUM_ENTRY_IDENTIFIER_REGEX)) {
emit(
node.startOffset,
"Enum entry name should be uppercase underscore-separated names like \"ENUM_ENTRY\" or upper camel-case like \"EnumEntry\"",
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/FilenameRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/FilenameRule.kt
index 9cab0a2..47ddec8 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/FilenameRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/FilenameRule.kt
@@ -155,7 +155,7 @@
private fun String.shouldMatchPascalCase(
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
) {
- if (!this.matches(pascalCaseRegEx)) {
+ if (!this.matches(PASCAL_CASE_REGEX)) {
emit(0, "File name '$this.kt' should conform PascalCase", false)
}
}
@@ -172,7 +172,7 @@
?.let { TopLevelDeclaration(elementType, it) }
private companion object {
- val pascalCaseRegEx = "^[A-Z][A-Za-z\\d]*$".regExIgnoringDiacriticsAndStrokesOnLetters()
+ val PASCAL_CASE_REGEX = "^[A-Z][A-Za-z\\d]*$".regExIgnoringDiacriticsAndStrokesOnLetters()
val NON_CLASS_RELATED_TOP_LEVEL_DECLARATION_TYPES = listOf(OBJECT_DECLARATION, TYPEALIAS, PROPERTY)
}
}
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/FinalNewlineRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/FinalNewlineRule.kt
index 4ae1eca..d488146 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/FinalNewlineRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/FinalNewlineRule.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.Rule
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.insertNewLineProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INSERT_FINAL_NEWLINE_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.ast.isRoot
@@ -15,13 +15,13 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> = listOf(
- insertNewLineProperty,
+ INSERT_FINAL_NEWLINE_PROPERTY,
)
private var insertFinalNewline by Delegates.notNull<Boolean>()
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
- insertFinalNewline = editorConfigProperties.getEditorConfigValue(insertNewLineProperty)
+ insertFinalNewline = editorConfigProperties.getEditorConfigValue(INSERT_FINAL_NEWLINE_PROPERTY)
}
override fun beforeVisitChildNodes(
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ImportOrderingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ImportOrderingRule.kt
index 2338d1d..45fbae3 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ImportOrderingRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ImportOrderingRule.kt
@@ -17,7 +17,7 @@
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
import org.jetbrains.kotlin.psi.KtImportDirective
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* Import ordering is configured via EditorConfig's property `ij_kotlin_imports_layout`, so the Kotlin IDE plugin also recongizes it. Supported values:
@@ -41,14 +41,14 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> = listOf(
- ideaImportsLayoutProperty,
+ IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY,
)
private lateinit var importsLayout: List<PatternEntry>
private lateinit var importSorter: ImportSorter
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
- importsLayout = editorConfigProperties.getEditorConfigValue(ideaImportsLayoutProperty)
+ importsLayout = editorConfigProperties.getEditorConfigValue(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY)
importSorter = ImportSorter(importsLayout)
}
@@ -97,7 +97,7 @@
if (hasComments) {
emit(
node.startOffset,
- errorMessages.getOrDefault(importsLayout, CUSTOM_ERROR_MESSAGE) +
+ ERROR_MESSAGES.getOrDefault(importsLayout, CUSTOM_ERROR_MESSAGE) +
" -- no autocorrection due to comments in the import list",
false,
)
@@ -107,7 +107,7 @@
if (autoCorrectSortOrder || autoCorrectWhitespace) {
emit(
node.startOffset,
- errorMessages.getOrDefault(importsLayout, CUSTOM_ERROR_MESSAGE),
+ ERROR_MESSAGES.getOrDefault(importsLayout, CUSTOM_ERROR_MESSAGE),
true,
)
}
@@ -176,9 +176,6 @@
}
public companion object {
- internal const val IDEA_IMPORTS_LAYOUT_PROPERTY_NAME = "ij_kotlin_imports_layout"
- private const val PROPERTY_DESCRIPTION = "Defines imports order layout for Kotlin files"
-
/**
* Alphabetical with capital letters before lower case letters (e.g. Z before a).
* No blank lines between major groups (android, com, junit, net, org, java, javax).
@@ -203,12 +200,12 @@
private const val ASCII_ERROR_MESSAGE = "Imports must be ordered in lexicographic order without any empty lines in-between"
private const val CUSTOM_ERROR_MESSAGE = "Imports must be ordered according to the pattern specified in .editorconfig"
- private val errorMessages = mapOf(
+ private val ERROR_MESSAGES = mapOf(
IDEA_PATTERN to IDEA_ERROR_MESSAGE,
ASCII_PATTERN to ASCII_ERROR_MESSAGE,
)
- private val editorConfigPropertyParser: (String, String?) -> PropertyType.PropertyValue<List<PatternEntry>> =
+ private val EDITOR_CONFIG_PROPERTY_PARSER: (String, String?) -> PropertyType.PropertyValue<List<PatternEntry>> =
{ _, value ->
when {
value.isNullOrBlank() -> PropertyType.PropertyValue.invalid(
@@ -216,14 +213,14 @@
"Import layout must contain at least one entry of a wildcard symbol (*)",
)
value == "idea" -> {
- logger.warn { "`idea` is deprecated! Please use `*,java.**,javax.**,kotlin.**,^` instead to ensure that the Kotlin IDE plugin recognizes the value" }
+ LOGGER.warn { "`idea` is deprecated! Please use `*,java.**,javax.**,kotlin.**,^` instead to ensure that the Kotlin IDE plugin recognizes the value" }
PropertyType.PropertyValue.valid(
value,
IDEA_PATTERN,
)
}
value == "ascii" -> {
- logger.warn { "`ascii` is deprecated! Please use `*` instead to ensure that the Kotlin IDE plugin recognizes the value" }
+ LOGGER.warn { "`ascii` is deprecated! Please use `*` instead to ensure that the Kotlin IDE plugin recognizes the value" }
PropertyType.PropertyValue.valid(
value,
ASCII_PATTERN,
@@ -243,16 +240,24 @@
}
}
- public val ideaImportsLayoutProperty: UsesEditorConfigProperties.EditorConfigProperty<List<PatternEntry>> =
+ public val IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<List<PatternEntry>> =
UsesEditorConfigProperties.EditorConfigProperty<List<PatternEntry>>(
type = PropertyType(
- IDEA_IMPORTS_LAYOUT_PROPERTY_NAME,
- PROPERTY_DESCRIPTION,
- editorConfigPropertyParser,
+ "ij_kotlin_imports_layout",
+ "Defines imports order layout for Kotlin files",
+ EDITOR_CONFIG_PROPERTY_PARSER,
),
defaultValue = IDEA_PATTERN,
defaultAndroidValue = ASCII_PATTERN,
propertyWriter = { it.joinToString(separator = ",") },
)
+
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val ideaImportsLayoutProperty: UsesEditorConfigProperties.EditorConfigProperty<List<PatternEntry>> =
+ IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY
}
}
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/IndentationRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/IndentationRule.kt
index f6e26ac..eab2f00 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/IndentationRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/IndentationRule.kt
@@ -4,8 +4,8 @@
import com.pinterest.ktlint.core.IndentConfig.IndentStyle.SPACE
import com.pinterest.ktlint.core.IndentConfig.IndentStyle.TAB
import com.pinterest.ktlint.core.Rule
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentSizeProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentStyleProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.ast.ElementType.ANNOTATED_EXPRESSION
@@ -106,7 +106,7 @@
import org.jetbrains.kotlin.psi.psiUtil.leaves
import org.jetbrains.kotlin.psi.psiUtil.parents
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
public class IndentationRule :
Rule(
@@ -123,8 +123,8 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(
- indentSizeProperty,
- indentStyleProperty,
+ INDENT_SIZE_PROPERTY,
+ INDENT_STYLE_PROPERTY,
)
private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG
@@ -136,8 +136,8 @@
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
indentConfig = IndentConfig(
- indentStyle = editorConfigProperties.getEditorConfigValue(indentStyleProperty),
- tabWidth = editorConfigProperties.getEditorConfigValue(indentSizeProperty),
+ indentStyle = editorConfigProperties.getEditorConfigValue(INDENT_STYLE_PROPERTY),
+ tabWidth = editorConfigProperties.getEditorConfigValue(INDENT_SIZE_PROPERTY),
)
if (indentConfig.disabled) {
stopTraversalOfAST()
@@ -284,7 +284,7 @@
node.elementType == DESTRUCTURING_DECLARATION -> visitDestructuringDeclaration(node)
else -> {
- logger.trace { "No processing for ${node.elementType}: ${node.textWithEscapedTabAndNewline()}" }
+ LOGGER.trace { "No processing for ${node.elementType}: ${node.textWithEscapedTabAndNewline()}" }
}
}
}
@@ -739,7 +739,7 @@
childIndent = childIndent,
lastChildIndent = lastChildIndent,
).also { newIndentContext ->
- logger.trace {
+ LOGGER.trace {
val nodeIndentLevel = indentConfig.indentLevelFrom(newIndentContext.nodeIndent)
val childIndentLevel = indentConfig.indentLevelFrom(newIndentContext.childIndent)
"Create new indent context (same as parent) with level ($nodeIndentLevel, $childIndentLevel) for ${fromAstNode.elementType}: ${newIndentContext.nodes}"
@@ -753,7 +753,7 @@
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
) {
while (indentContextStack.peekLast()?.toASTNode == node) {
- logger.trace {
+ LOGGER.trace {
val indentContext = indentContextStack.peekLast()
val nodeIndentLevel = indentConfig.indentLevelFrom(indentContext.nodeIndent)
val childIndentLevel = indentConfig.indentLevelFrom(indentContext.childIndent)
@@ -762,7 +762,7 @@
indentContextStack
.removeLast()
.also {
- logger.trace {
+ LOGGER.trace {
val indentContext = indentContextStack.peekLast()
val nodeIndentLevel = indentConfig.indentLevelFrom(indentContext.nodeIndent)
val childIndentLevel = indentConfig.indentLevelFrom(indentContext.childIndent)
@@ -803,7 +803,7 @@
// Indentation was at correct level but contained invalid indent characters. This violation has already
// been emitted.
}
- logger.trace {
+ LOGGER.trace {
"Line $line: " + (if (!autoCorrect) "would have " else "") + "changed indentation to ${expectedIndentation.length} (from ${normalizedNodeIndent.length}) for ${node.elementType}: ${node.textWithEscapedTabAndNewline()}"
}
if (autoCorrect) {
@@ -844,7 +844,7 @@
this != null && this.elementType == OPEN_QUOTE && this.text == "\"\"\""
private fun ASTNode.processedButNoIndentationChangedNeeded() =
- logger.trace { "No indentation change required for $elementType: ${textWithEscapedTabAndNewline()}" }
+ LOGGER.trace { "No indentation change required for $elementType: ${textWithEscapedTabAndNewline()}" }
private fun ASTNode.expectedIndent(): String {
val lastIndexContext = indentContextStack.peekLast()
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/MaxLineLengthRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/MaxLineLengthRule.kt
index 9c1f936..bf15756 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/MaxLineLengthRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/MaxLineLengthRule.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.Rule
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.ast.ElementType
@@ -46,17 +46,17 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> = listOf(
- maxLineLengthProperty,
- ignoreBackTickedIdentifierProperty,
+ MAX_LINE_LENGTH_PROPERTY,
+ IGNORE_BACKTICKED_IDENTIFIER_PROPERTY,
)
- private var maxLineLength: Int = maxLineLengthProperty.defaultValue
+ private var maxLineLength: Int = MAX_LINE_LENGTH_PROPERTY.defaultValue
private var rangeTree = RangeTree()
private var ignoreBackTickedIdentifier by Delegates.notNull<Boolean>()
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
- ignoreBackTickedIdentifier = editorConfigProperties.getEditorConfigValue(ignoreBackTickedIdentifierProperty)
- maxLineLength = editorConfigProperties.getEditorConfigValue(maxLineLengthProperty)
+ ignoreBackTickedIdentifier = editorConfigProperties.getEditorConfigValue(IGNORE_BACKTICKED_IDENTIFIER_PROPERTY)
+ maxLineLength = editorConfigProperties.getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
}
override fun beforeVisitChildNodes(
@@ -116,19 +116,24 @@
?.let { it.firstChildNode.text == "\"\"\"" && it.textContains('\n') } == true
public companion object {
- internal const val KTLINT_IGNORE_BACKTICKED_IDENTIFIER_NAME = "ktlint_ignore_back_ticked_identifier"
- private const val PROPERTY_DESCRIPTION = "Defines whether the backticked identifier (``) should be ignored"
-
- public val ignoreBackTickedIdentifierProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
+ public val IGNORE_BACKTICKED_IDENTIFIER_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
- KTLINT_IGNORE_BACKTICKED_IDENTIFIER_NAME,
- PROPERTY_DESCRIPTION,
+ "ktlint_ignore_back_ticked_identifier",
+ "Defines whether the backticked identifier (``) should be ignored",
PropertyType.PropertyValueParser.BOOLEAN_VALUE_PARSER,
setOf(true.toString(), false.toString()),
),
defaultValue = false,
)
+
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("IGNORE_BACKTICKED_IDENTIFIER_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val ignoreBackTickedIdentifierProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
+ IGNORE_BACKTICKED_IDENTIFIER_PROPERTY
}
}
@@ -165,12 +170,12 @@
private fun totalLengthBacktickedElements(): Int {
return elements
.filterIsInstance(PsiElement::class.java)
- .filter { it.text.matches(isValueBetweenBackticks) }
+ .filter { it.text.matches(BACKTICKED_IDENTIFIER_REGEX) }
.sumOf(PsiElement::getTextLength)
}
private companion object {
- val isValueBetweenBackticks = Regex("`.*`")
+ val BACKTICKED_IDENTIFIER_REGEX = Regex("`.*`")
}
}
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/MultiLineIfElseRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/MultiLineIfElseRule.kt
index d787e46..f4a5c2f 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/MultiLineIfElseRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/MultiLineIfElseRule.kt
@@ -33,15 +33,15 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(
- DefaultEditorConfigProperties.indentSizeProperty,
- DefaultEditorConfigProperties.indentStyleProperty,
+ DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY,
+ DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY,
)
private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
indentConfig = IndentConfig(
- indentStyle = editorConfigProperties.getEditorConfigValue(DefaultEditorConfigProperties.indentStyleProperty),
- tabWidth = editorConfigProperties.getEditorConfigValue(DefaultEditorConfigProperties.indentSizeProperty),
+ indentStyle = editorConfigProperties.getEditorConfigValue(DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY),
+ tabWidth = editorConfigProperties.getEditorConfigValue(DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY),
)
}
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoUnusedImportsRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoUnusedImportsRule.kt
index 595e389..1c15d41 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoUnusedImportsRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoUnusedImportsRule.kt
@@ -135,7 +135,7 @@
importDirective.delete()
}
} else if (name != null && (!ref.map { it.text }.contains(name) || !isAValidImport(importPath)) &&
- !operatorSet.contains(name) &&
+ !OPERATOR_SET.contains(name) &&
!name.isComponentN() &&
!importPath.ignoreProvideDelegate()
) {
@@ -217,7 +217,7 @@
it.key.pathStr.removeBackticksAndTrim().contains(importPath)
}
- private fun String.isComponentN() = componentNRegex.matches(this)
+ private fun String.isComponentN() = COMPONENT_N_REGEX.matches(this)
private fun PsiElement.parentDotQualifiedExpression(): KtDotQualifiedExpression? {
val callOrThis = (parent as? KtCallExpression)?.takeIf { it.calleeExpression == this } ?: this
@@ -229,9 +229,9 @@
private data class Reference(val text: String, val inDotQualifiedExpression: Boolean)
private companion object {
- val componentNRegex = Regex("^component\\d+$")
+ val COMPONENT_N_REGEX = Regex("^component\\d+$")
- val operatorSet = setOf(
+ val OPERATOR_SET = setOf(
// unary
"unaryPlus", "unaryMinus", "not",
// inc/dec
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoWildcardImportsRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoWildcardImportsRule.kt
index fc84d16..d459ed8 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoWildcardImportsRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoWildcardImportsRule.kt
@@ -13,13 +13,13 @@
Rule("no-wildcard-imports"),
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> = listOf(
- packagesToUseImportOnDemandProperty,
+ IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND,
)
private lateinit var allowedWildcardImports: List<PatternEntry>
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
- allowedWildcardImports = editorConfigProperties.getEditorConfigValue(packagesToUseImportOnDemandProperty)
+ allowedWildcardImports = editorConfigProperties.getEditorConfigValue(IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND)
}
override fun beforeVisitChildNodes(
@@ -61,7 +61,7 @@
}
}
- private val packagesToUseImportOnDemandPropertyParser: (String, String?) -> PropertyType.PropertyValue<List<PatternEntry>> =
+ private val PACKAGES_TO_USE_ON_DEMAND_IMPORT_PROPERTY_PARSER: (String, String?) -> PropertyType.PropertyValue<List<PatternEntry>> =
{ _, value ->
when {
else -> try {
@@ -78,12 +78,12 @@
}
}
- public val packagesToUseImportOnDemandProperty: UsesEditorConfigProperties.EditorConfigProperty<List<PatternEntry>> =
+ public val IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND: UsesEditorConfigProperties.EditorConfigProperty<List<PatternEntry>> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType(
"ij_kotlin_packages_to_use_import_on_demand",
"Defines allowed wildcard imports",
- packagesToUseImportOnDemandPropertyParser,
+ PACKAGES_TO_USE_ON_DEMAND_IMPORT_PROPERTY_PARSER,
),
/**
* Default IntelliJ IDEA style: Use wildcard imports for packages in "java.util", "kotlin.android.synthetic" and
@@ -94,5 +94,13 @@
defaultValue = parseAllowedWildcardImports("java.util.*,kotlinx.android.synthetic.**"),
propertyWriter = { it.joinToString(separator = ",") },
)
+
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val packagesToUseImportOnDemandProperty: UsesEditorConfigProperties.EditorConfigProperty<List<PatternEntry>> =
+ IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND
}
}
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ParameterListWrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ParameterListWrappingRule.kt
index 6f242dc..bba585c 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ParameterListWrappingRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ParameterListWrappingRule.kt
@@ -2,9 +2,9 @@
import com.pinterest.ktlint.core.IndentConfig
import com.pinterest.ktlint.core.Rule
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentSizeProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentStyleProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.ast.ElementType.FUNCTION_LITERAL
@@ -36,19 +36,19 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(
- indentSizeProperty,
- indentStyleProperty,
- maxLineLengthProperty,
+ INDENT_SIZE_PROPERTY,
+ INDENT_STYLE_PROPERTY,
+ MAX_LINE_LENGTH_PROPERTY,
)
private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG
private var maxLineLength = -1
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
- maxLineLength = editorConfigProperties.getEditorConfigValue(maxLineLengthProperty)
+ maxLineLength = editorConfigProperties.getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
indentConfig = IndentConfig(
- indentStyle = editorConfigProperties.getEditorConfigValue(indentStyleProperty),
- tabWidth = editorConfigProperties.getEditorConfigValue(indentSizeProperty),
+ indentStyle = editorConfigProperties.getEditorConfigValue(INDENT_STYLE_PROPERTY),
+ tabWidth = editorConfigProperties.getEditorConfigValue(INDENT_SIZE_PROPERTY),
)
if (indentConfig.disabled) {
stopTraversalOfAST()
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/SpacingAroundAngleBracketsRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/SpacingAroundAngleBracketsRule.kt
index 11bc836..fd3416c 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/SpacingAroundAngleBracketsRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/SpacingAroundAngleBracketsRule.kt
@@ -28,7 +28,7 @@
val beforeLeftAngle = openingBracket.prevLeaf()
if (beforeLeftAngle?.elementType == WHITE_SPACE) {
// Ignore when the whitespace is preceded by certain keywords, e.g. fun <T> func(arg: T) {}
- if (!typesOkWithPrecedingWhitespace.contains(beforeLeftAngle.prevLeaf()?.elementType)) {
+ if (!ELEMENT_TYPES_ALLOWING_PRECEDING_WHITESPACE.contains(beforeLeftAngle.prevLeaf()?.elementType)) {
emit(beforeLeftAngle.startOffset, "Unexpected spacing before \"<\"", true)
if (autoCorrect) {
beforeLeftAngle.treeParent.removeChild(beforeLeftAngle)
@@ -91,6 +91,6 @@
}
private companion object {
- val typesOkWithPrecedingWhitespace = setOf(VAL_KEYWORD, VAR_KEYWORD, FUN_KEYWORD)
+ val ELEMENT_TYPES_ALLOWING_PRECEDING_WHITESPACE = setOf(VAL_KEYWORD, VAR_KEYWORD, FUN_KEYWORD)
}
}
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnCallSiteRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnCallSiteRule.kt
index 880b1eb..9941fe8 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnCallSiteRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnCallSiteRule.kt
@@ -41,7 +41,7 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> = listOf(
- allowTrailingCommaOnCallSiteProperty,
+ TRAILING_COMMA_ON_CALL_SITE_PROPERTY,
)
private var allowTrailingCommaOnCallSite by Delegates.notNull<Boolean>()
@@ -50,7 +50,7 @@
elementType in TYPES_ON_CALL_SITE && allowTrailingCommaOnCallSite
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
- allowTrailingCommaOnCallSite = editorConfigProperties.getEditorConfigValue(allowTrailingCommaOnCallSiteProperty)
+ allowTrailingCommaOnCallSite = editorConfigProperties.getEditorConfigValue(TRAILING_COMMA_ON_CALL_SITE_PROPERTY)
}
override fun beforeVisitChildNodes(
@@ -231,19 +231,17 @@
}
public companion object {
- internal const val ALLOW_TRAILING_COMMA_ON_CALL_SITE_NAME = "ij_kotlin_allow_trailing_comma_on_call_site"
- private const val ALLOW_TRAILING_COMMA_ON_CALL_SITE_DESCRIPTION =
- "Defines whether a trailing comma (or no trailing comma) should be enforced on the calling side," +
- "e.g. argument-list, when-entries, lambda-arguments, indices, etc."
private val BOOLEAN_VALUES_SET = setOf("true", "false")
- // TODO: Rename property to trailingCommaOnCallSite. The word 'allow' is misleading as the comma is
- // enforced when the property is enabled and prohibited when disabled.
- public val allowTrailingCommaOnCallSiteProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
+ public val TRAILING_COMMA_ON_CALL_SITE_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
- ALLOW_TRAILING_COMMA_ON_CALL_SITE_NAME,
- ALLOW_TRAILING_COMMA_ON_CALL_SITE_DESCRIPTION,
+ "ij_kotlin_allow_trailing_comma_on_call_site",
+ "Defines whether a trailing comma (or no trailing comma) should be enforced on the calling side," +
+ "e.g. argument-list, when-entries, lambda-arguments, indices, etc." +
+ "When set, IntelliJ IDEA uses this property to allow usage of a trailing comma by discretion " +
+ "of the developer. KtLint however uses this setting to enforce consistent usage of the " +
+ "trailing comma when set.",
PropertyValueParser.BOOLEAN_VALUE_PARSER,
BOOLEAN_VALUES_SET,
),
@@ -251,6 +249,14 @@
defaultAndroidValue = false,
)
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("TRAILING_COMMA_ON_CALL_SITE_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val allowTrailingCommaOnCallSiteProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
+ TRAILING_COMMA_ON_CALL_SITE_PROPERTY
+
private val TYPES_ON_CALL_SITE = TokenSet.create(
COLLECTION_LITERAL_EXPRESSION,
INDICES,
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRule.kt
index 0cef61c..21e93a7 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRule.kt
@@ -65,7 +65,7 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> = listOf(
- allowTrailingCommaProperty,
+ TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY,
)
private var allowTrailingComma by Delegates.notNull<Boolean>()
@@ -74,7 +74,7 @@
elementType in TYPES_ON_DECLARATION_SITE && allowTrailingComma
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
- allowTrailingComma = editorConfigProperties.getEditorConfigValue(allowTrailingCommaProperty)
+ allowTrailingComma = editorConfigProperties.getEditorConfigValue(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY)
}
override fun beforeVisitChildNodes(
@@ -418,21 +418,17 @@
}
public companion object {
-
- internal const val ALLOW_TRAILING_COMMA_NAME = "ij_kotlin_allow_trailing_comma"
- private const val ALLOW_TRAILING_COMMA_DESCRIPTION = "Defines whether a trailing comma (or no trailing comma)" +
- "should be enforced on the defining side," +
- "e.g. parameter-list, type-argument-list, lambda-value-parameters, enum-entries, etc."
-
private val BOOLEAN_VALUES_SET = setOf("true", "false")
- // TODO: Rename property to trailingCommaOnDeclarationSite. The word 'allow' is misleading as the comma is
- // enforced when the property is enabled and prohibited when disabled.
- public val allowTrailingCommaProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
+ public val TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
- ALLOW_TRAILING_COMMA_NAME,
- ALLOW_TRAILING_COMMA_DESCRIPTION,
+ "ij_kotlin_allow_trailing_comma",
+ "Defines whether a trailing comma (or no trailing comma) should be enforced on the defining " +
+ "side, e.g. parameter-list, type-argument-list, lambda-value-parameters, enum-entries, etc." +
+ "When set, IntelliJ IDEA uses this property to allow usage of a trailing comma by discretion " +
+ "of the developer. KtLint however uses this setting to enforce consistent usage of the " +
+ "trailing comma when set.",
PropertyValueParser.BOOLEAN_VALUE_PARSER,
BOOLEAN_VALUES_SET,
),
@@ -440,6 +436,14 @@
defaultAndroidValue = false,
)
+ @Deprecated(
+ message = "Marked for removal in KtLint 0.49",
+ replaceWith = ReplaceWith("TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY"),
+ )
+ @Suppress("ktlint:experimental:property-naming")
+ public val allowTrailingCommaProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
+ TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY
+
private val TYPES_ON_DECLARATION_SITE = TokenSet.create(
CLASS,
DESTRUCTURING_DECLARATION,
diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRule.kt
index 89a2fdc..dae60dd 100644
--- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRule.kt
+++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRule.kt
@@ -2,9 +2,9 @@
import com.pinterest.ktlint.core.IndentConfig
import com.pinterest.ktlint.core.Rule
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentSizeProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentStyleProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigProperties
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.ast.ElementType
@@ -68,7 +68,7 @@
import org.jetbrains.kotlin.psi.psiUtil.leaves
import org.jetbrains.kotlin.psi.psiUtil.siblings
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* This rule inserts missing newlines (e.g. between parentheses of a multi-line function call). This logic previously
@@ -83,9 +83,9 @@
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(
- indentSizeProperty,
- indentStyleProperty,
- maxLineLengthProperty,
+ INDENT_SIZE_PROPERTY,
+ INDENT_STYLE_PROPERTY,
+ MAX_LINE_LENGTH_PROPERTY,
)
private var line = 1
@@ -95,10 +95,10 @@
override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) {
line = 1
indentConfig = IndentConfig(
- indentStyle = editorConfigProperties.getEditorConfigValue(indentStyleProperty),
- tabWidth = editorConfigProperties.getEditorConfigValue(indentSizeProperty),
+ indentStyle = editorConfigProperties.getEditorConfigValue(INDENT_STYLE_PROPERTY),
+ tabWidth = editorConfigProperties.getEditorConfigValue(INDENT_SIZE_PROPERTY),
)
- maxLineLength = editorConfigProperties.getEditorConfigValue(maxLineLengthProperty)
+ maxLineLength = editorConfigProperties.getEditorConfigValue(MAX_LINE_LENGTH_PROPERTY)
}
override fun beforeVisitChildNodes(
@@ -169,7 +169,7 @@
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
) {
- val rElementType = matchingRToken[node.elementType]
+ val rElementType = MATCHING_RTOKEN_MAP[node.elementType]
var newlineInBetween = false
var parameterListInBetween = false
var numberOfArgs = 0
@@ -387,7 +387,7 @@
node as LeafPsiElement
node.rawInsertBeforeMe(LeafPsiElement(LITERAL_STRING_TEMPLATE_ENTRY, "\n"))
}
- logger.trace { "$line: " + (if (!autoCorrect) "would have " else "") + "inserted newline before (closing) \"\"\"" }
+ LOGGER.trace { "$line: " + (if (!autoCorrect) "would have " else "") + "inserted newline before (closing) \"\"\"" }
}
}
@@ -399,16 +399,16 @@
// return false
val nextCodeSibling = node.nextCodeSibling() // e.g. BINARY_EXPRESSION
var lToken = nextCodeSibling?.nextLeaf { it.isWhiteSpaceWithNewline() }?.prevCodeLeaf()
- if (lToken != null && lToken.elementType !in lTokenSet) {
+ if (lToken != null && lToken.elementType !in LTOKEN_SET) {
// special cases:
// x = y.f({ z ->
// })
// x = y.f(0, 1,
// 2, 3)
- lToken = lToken.prevLeaf { it.elementType in lTokenSet || it == node }
+ lToken = lToken.prevLeaf { it.elementType in LTOKEN_SET || it == node }
}
- if (lToken != null && lToken.elementType in lTokenSet) {
- val rElementType = matchingRToken[lToken.elementType]
+ if (lToken != null && lToken.elementType in LTOKEN_SET) {
+ val rElementType = MATCHING_RTOKEN_MAP[lToken.elementType]
val rToken = lToken.nextSibling { it.elementType == rElementType }
return rToken?.treeParent == lToken.treeParent
}
@@ -469,7 +469,7 @@
"""Missing newline before "${node.text}"""",
true,
)
- logger.trace { "$line: " + ((if (!autoCorrect) "would have " else "") + "inserted newline before ${node.text}") }
+ LOGGER.trace { "$line: " + ((if (!autoCorrect) "would have " else "") + "inserted newline before ${node.text}") }
if (autoCorrect) {
node.upsertWhitespaceBeforeMe("\n" + indent)
}
@@ -487,7 +487,7 @@
"""Missing newline after "${nodeAfterWhichNewlineIsRequired.text}"""",
true,
)
- logger.trace { "$line: " + (if (!autoCorrect) "would have " else "") + "inserted newline after ${nodeAfterWhichNewlineIsRequired.text}" }
+ LOGGER.trace { "$line: " + (if (!autoCorrect) "would have " else "") + "inserted newline after ${nodeAfterWhichNewlineIsRequired.text}" }
if (autoCorrect) {
val tempIndent = indent ?: (nodeToFix.lineIndent() + indentConfig.indent)
nodeToFix.upsertWhitespaceAfterMe("\n" + tempIndent)
@@ -588,11 +588,11 @@
}
private companion object {
- private val lTokenSet = TokenSet.create(LPAR, LBRACE, LBRACKET, LT)
- private val rTokenSet = TokenSet.create(RPAR, RBRACE, RBRACKET, GT)
- private val matchingRToken =
- lTokenSet.types.zip(
- rTokenSet.types,
+ private val LTOKEN_SET = TokenSet.create(LPAR, LBRACE, LBRACKET, LT)
+ private val RTOKEN_SET = TokenSet.create(RPAR, RBRACE, RBRACKET, GT)
+ private val MATCHING_RTOKEN_MAP =
+ LTOKEN_SET.types.zip(
+ RTOKEN_SET.types,
).toMap()
}
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/ArgumentListWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/ArgumentListWrappingRuleTest.kt
index 27ade7f..465d327 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/ArgumentListWrappingRuleTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/ArgumentListWrappingRuleTest.kt
@@ -1,6 +1,6 @@
package com.pinterest.ktlint.ruleset.standard
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.EOL_CHAR
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.MAX_LINE_LENGTH_MARKER
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule
@@ -83,7 +83,7 @@
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to 10)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)
.hasLintViolations(
LintViolation(1, 11, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(1, 14, "Argument should be on a separate line (unless all arguments can fit a single line)"),
@@ -162,7 +162,7 @@
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to 20)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 20)
.hasLintViolations(
LintViolation(13, 10, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(13, 19, "Argument should be on a separate line (unless all arguments can fit a single line)"),
@@ -298,7 +298,7 @@
val foo = foo(1, 2, 3, 4, 5, 6, 7, 8, 9)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to 20)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 20)
.hasNoLintViolations()
}
@@ -523,7 +523,7 @@
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to 33)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 33)
.hasLintViolations(
LintViolation(8, 23, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(8, 34, "Missing newline before \")\""),
@@ -555,7 +555,7 @@
argumentListWrappingRuleAssertThat(code)
// TODO: It is not clear how the length 65 is related to the lint errors below. Starting from length 66 the
// lint errors are not reported anymore.
- .withEditorConfigOverride(maxLineLengthProperty to 65)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 65)
.hasLintViolations(
LintViolation(4, 15, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(4, 70, "Missing newline before \")\""),
@@ -581,7 +581,7 @@
argumentListWrappingRuleAssertThat(code)
// TODO: With max line length of 43 or below, lint errors occur. It is not clear how that is related to
// example above
- .withEditorConfigOverride(maxLineLengthProperty to 44)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 44)
.hasNoLintViolations()
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/FinalNewlineRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/FinalNewlineRuleTest.kt
index a1d40ae..bb22846 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/FinalNewlineRuleTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/FinalNewlineRuleTest.kt
@@ -1,6 +1,6 @@
package com.pinterest.ktlint.ruleset.standard
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.insertNewLineProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INSERT_FINAL_NEWLINE_PROPERTY
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
@@ -109,7 +109,7 @@
}
private companion object {
- val FINAL_NEW_LINE_REQUIRED = insertNewLineProperty to true
- val FINAL_NEW_LINE_NOT_REQUIRED = insertNewLineProperty to false
+ val FINAL_NEW_LINE_REQUIRED = INSERT_FINAL_NEWLINE_PROPERTY to true
+ val FINAL_NEW_LINE_NOT_REQUIRED = INSERT_FINAL_NEWLINE_PROPERTY to false
}
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/IndentationRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/IndentationRuleTest.kt
index c25225b..0922040 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/IndentationRuleTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/IndentationRuleTest.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.ruleset.standard
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentSizeProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.indentStyleProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_SIZE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule
import com.pinterest.ktlint.test.LintViolation
import com.pinterest.ktlint.test.MULTILINE_STRING_QUOTE
@@ -1166,7 +1166,7 @@
}
""".trimIndent()
indentationRuleAssertThat(code)
- .withEditorConfigOverride(indentSizeProperty to 2)
+ .withEditorConfigOverride(INDENT_SIZE_PROPERTY to 2)
.hasLintViolations(
LintViolation(2, 1, "Unexpected indentation (3) (should be 2)"),
LintViolation(3, 1, "Unexpected indentation (4) (should be 2)"),
@@ -1225,7 +1225,7 @@
}
""".trimIndent()
indentationRuleAssertThat(code)
- .withEditorConfigOverride(indentSizeProperty to "unset")
+ .withEditorConfigOverride(INDENT_SIZE_PROPERTY to "unset")
.hasNoLintViolations()
}
@@ -2738,7 +2738,7 @@
}
""".trimIndent()
indentationRuleAssertThat(code)
- .withEditorConfigOverride(indentSizeProperty to 2)
+ .withEditorConfigOverride(INDENT_SIZE_PROPERTY to 2)
.hasLintViolations(
LintViolation(2, 1, "Unexpected tab character(s)"),
LintViolation(3, 1, "Unexpected tab character(s)"),
@@ -4761,7 +4761,7 @@
}
private companion object {
- val INDENT_STYLE_TAB = indentStyleProperty to PropertyType.IndentStyleValue.tab
+ val INDENT_STYLE_TAB = INDENT_STYLE_PROPERTY to PropertyType.IndentStyleValue.tab
}
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/MaxLineLengthRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/MaxLineLengthRuleTest.kt
index fd7f898..37b573b 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/MaxLineLengthRuleTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/MaxLineLengthRuleTest.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.ruleset.standard
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
-import com.pinterest.ktlint.ruleset.standard.MaxLineLengthRule.Companion.ignoreBackTickedIdentifierProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY
+import com.pinterest.ktlint.ruleset.standard.MaxLineLengthRule.Companion.IGNORE_BACKTICKED_IDENTIFIER_PROPERTY
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.EOL_CHAR
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.MAX_LINE_LENGTH_MARKER
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule
@@ -160,7 +160,7 @@
""".trimIndent()
maxLineLengthRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(ignoreBackTickedIdentifierProperty to true)
+ .withEditorConfigOverride(IGNORE_BACKTICKED_IDENTIFIER_PROPERTY to true)
// Note that no error was generated on line 2 with the long fun name but on another line
.hasLintViolationWithoutAutoCorrect(4, 1, "Exceeded max line length (37)")
}
@@ -177,7 +177,7 @@
""".trimIndent()
maxLineLengthRuleAssertThat(code)
.setMaxLineLength()
- .withEditorConfigOverride(ignoreBackTickedIdentifierProperty to true)
+ .withEditorConfigOverride(IGNORE_BACKTICKED_IDENTIFIER_PROPERTY to true)
.hasLintViolationsWithoutAutoCorrect(
// Note that no error was generated on line 2 with the long fun name but on another line
LintViolation(3, 1, "Exceeded max line length (37)"),
@@ -190,7 +190,7 @@
fun testLintOff() {
val code = "// some" + " long ".repeat(100) + "comment" // Total length of line is 7 + 600 + 7 = 614 characters
maxLineLengthRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to "off")
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to "off")
.hasNoLintViolations()
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoLineBreakBeforeAssignmentRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoLineBreakBeforeAssignmentRuleTest.kt
index d58e9db..4bb87d7 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoLineBreakBeforeAssignmentRuleTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoLineBreakBeforeAssignmentRuleTest.kt
@@ -5,8 +5,6 @@
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
-const val ruleId = "no-line-break-before-assignment"
-
class NoLineBreakBeforeAssignmentRuleTest {
private val noLineBreakBeforeAssignmentRuleAssertThat = assertThatRule { NoLineBreakBeforeAssignmentRule() }
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoWildcardImportsRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoWildcardImportsRuleTest.kt
index 252488b..a4699aa 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoWildcardImportsRuleTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoWildcardImportsRuleTest.kt
@@ -1,6 +1,6 @@
package com.pinterest.ktlint.ruleset.standard
-import com.pinterest.ktlint.ruleset.standard.NoWildcardImportsRule.Companion.packagesToUseImportOnDemandProperty
+import com.pinterest.ktlint.ruleset.standard.NoWildcardImportsRule.Companion.IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule
import com.pinterest.ktlint.test.LintViolation
import org.junit.jupiter.api.DisplayName
@@ -54,7 +54,7 @@
import react.dom.*
""".trimIndent()
noWildcardImportsRuleAssertThat(code)
- .withEditorConfigOverride(packagesToUseImportOnDemandProperty to "unset")
+ .withEditorConfigOverride(IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND to "unset")
.hasLintViolationsWithoutAutoCorrect(
LintViolation(3, 1, "Wildcard import"),
LintViolation(4, 1, "Wildcard import"),
@@ -71,7 +71,7 @@
import react.dom.*
""".trimIndent()
noWildcardImportsRuleAssertThat(code)
- .withEditorConfigOverride(packagesToUseImportOnDemandProperty to "react.*,react.dom.*")
+ .withEditorConfigOverride(IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND to "react.*,react.dom.*")
.hasLintViolationWithoutAutoCorrect(2, 1, "Wildcard import")
}
@@ -85,7 +85,7 @@
import react.dom.*
""".trimIndent()
noWildcardImportsRuleAssertThat(code)
- .withEditorConfigOverride(packagesToUseImportOnDemandProperty to "react.**")
+ .withEditorConfigOverride(IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND to "react.**")
.hasLintViolationWithoutAutoCorrect(2, 1, "Wildcard import")
}
@@ -97,7 +97,7 @@
import kotlinx.android.synthetic.main.layout_name.*
""".trimIndent()
noWildcardImportsRuleAssertThat(code)
- .withEditorConfigOverride(packagesToUseImportOnDemandProperty to "")
+ .withEditorConfigOverride(IJ_KOTLIN_PACKAGES_TO_USE_IMPORT_ON_DEMAND to "")
.hasLintViolationWithoutAutoCorrect(2, 1, "Wildcard import")
}
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/ParameterListWrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/ParameterListWrappingRuleTest.kt
index d5f7d54..4e60728 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/ParameterListWrappingRuleTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/ParameterListWrappingRuleTest.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.RuleProvider
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule
import com.pinterest.ktlint.test.LintViolation
import org.junit.jupiter.api.Test
@@ -55,7 +55,7 @@
)
""".trimIndent()
parameterListWrappingRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to 10)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)
.hasLintViolations(
LintViolation(1, 14, "Parameter should be on a separate line (unless all parameters can fit a single line)"),
LintViolation(1, 30, "Parameter should be on a separate line (unless all parameters can fit a single line)"),
@@ -71,7 +71,7 @@
class ClassAWithALongName()
""".trimIndent()
parameterListWrappingRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to 10)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)
.hasNoLintViolations()
}
@@ -165,7 +165,7 @@
}
""".trimIndent()
parameterListWrappingRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to 10)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)
.hasLintViolations(
LintViolation(1, 7, "Parameter should be on a separate line (unless all parameters can fit a single line)"),
LintViolation(1, 15, "Parameter should be on a separate line (unless all parameters can fit a single line)"),
@@ -220,7 +220,7 @@
}
""".trimIndent()
parameterListWrappingRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to 10)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)
.hasLintViolations(
LintViolation(2, 11, "Parameter should be on a separate line (unless all parameters can fit a single line)"),
LintViolation(6, 19, "Parameter should be on a separate line (unless all parameters can fit a single line)"),
@@ -310,7 +310,7 @@
) {}
""".trimIndent()
parameterListWrappingRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to 10)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)
.hasLintViolations(
LintViolation(1, 11, "Parameter should be on a separate line (unless all parameters can fit a single line)"),
LintViolation(1, 26, "Parameter should be on a separate line (unless all parameters can fit a single line)"),
@@ -476,7 +476,7 @@
)? = null
""".trimIndent()
parameterListWrappingRuleAssertThat(code)
- .withEditorConfigOverride(maxLineLengthProperty to 80)
+ .withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 80)
.hasLintViolations(
LintViolation(1, 22, "Parameter of nullable type should be on a separate line (unless the type fits on a single line)"),
LintViolation(1, 95, """Missing newline before ")""""),
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnCallSiteRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnCallSiteRuleTest.kt
index 19591b4..aa6612f 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnCallSiteRuleTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnCallSiteRuleTest.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.RuleProvider
-import com.pinterest.ktlint.ruleset.standard.TrailingCommaOnCallSiteRule.Companion.allowTrailingCommaOnCallSiteProperty
+import com.pinterest.ktlint.ruleset.standard.TrailingCommaOnCallSiteRule.Companion.TRAILING_COMMA_ON_CALL_SITE_PROPERTY
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule
import com.pinterest.ktlint.test.LintViolation
import org.junit.jupiter.api.Test
@@ -86,7 +86,7 @@
)
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to false)
.hasLintViolations(
LintViolation(1, 28, "Unnecessary trailing comma before \")\""),
LintViolation(4, 8, "Unnecessary trailing comma before \")\""),
@@ -121,7 +121,7 @@
)
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(4, 8, "Missing trailing comma before \")\""),
LintViolation(8, 8, "Missing trailing comma before \")\""),
@@ -151,7 +151,7 @@
> = emptyList()
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to false)
.hasLintViolations(
LintViolation(1, 23, "Unnecessary trailing comma before \">\""),
LintViolation(3, 11, "Unnecessary trailing comma before \">\""),
@@ -182,7 +182,7 @@
> = emptyList()
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(3, 11, "Missing trailing comma before \">\""),
LintViolation(6, 11, "Missing trailing comma before \">\""),
@@ -214,7 +214,7 @@
]
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to false)
.hasLintViolations(
LintViolation(2, 17, "Unnecessary trailing comma before \"]\""),
LintViolation(4, 6, "Unnecessary trailing comma before \"]\""),
@@ -247,7 +247,7 @@
]
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(4, 6, "Missing trailing comma before \"]\""),
LintViolation(7, 6, "Missing trailing comma before \"]\""),
@@ -295,7 +295,7 @@
val foo3: Int = 0
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to false)
.hasLintViolations(
LintViolation(3, 18, "Unnecessary trailing comma before \"]\""),
LintViolation(8, 6, "Unnecessary trailing comma before \"]\""),
@@ -368,7 +368,7 @@
val foo4: Int = 0
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(8, 6, "Missing trailing comma before \"]\""),
LintViolation(14, 6, "Missing trailing comma before \"]\""),
@@ -389,7 +389,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to true)
.hasNoLintViolations()
}
@@ -430,7 +430,7 @@
val fooBar = null
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(9, 16, "Missing trailing comma before \"]\""),
LintViolation(12, 19, "Missing trailing comma before \")\""),
@@ -464,7 +464,7 @@
annotation class Foo(val values: Array<KClass<*>>)
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(6, 19, "Missing trailing comma before \"]\""),
LintViolation(7, 6, "Missing trailing comma before \")\""),
@@ -483,7 +483,7 @@
val foo1 = setOf<Int>()
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to true)
.hasNoLintViolations()
}
@@ -510,7 +510,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaOnCallSiteProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_CALL_SITE_PROPERTY to true)
.hasNoLintViolations()
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRuleTest.kt
index 6c741aa..97c4642 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRuleTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/TrailingCommaOnDeclarationSiteRuleTest.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.RuleProvider
-import com.pinterest.ktlint.ruleset.standard.TrailingCommaOnDeclarationSiteRule.Companion.allowTrailingCommaProperty
+import com.pinterest.ktlint.ruleset.standard.TrailingCommaOnDeclarationSiteRule.Companion.TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY
import com.pinterest.ktlint.test.KtLintAssertThat
import com.pinterest.ktlint.test.LintViolation
import org.junit.jupiter.api.Nested
@@ -97,7 +97,7 @@
)
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to false)
.hasLintViolations(
LintViolation(1, 29, "Unnecessary trailing comma before \")\""),
LintViolation(3, 17, "Unnecessary trailing comma before \")\""),
@@ -128,7 +128,7 @@
)
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(3, 17, "Missing trailing comma before \")\""),
LintViolation(6, 17, "Missing trailing comma before \")\""),
@@ -162,7 +162,7 @@
> {}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to false)
.hasLintViolations(
LintViolation(1, 16, "Unnecessary trailing comma before \">\""),
LintViolation(4, 6, "Unnecessary trailing comma before \">\""),
@@ -197,7 +197,7 @@
> {}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(4, 6, "Missing trailing comma before \">\""),
LintViolation(8, 6, "Missing trailing comma before \">\""),
@@ -231,7 +231,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to false)
.hasLintViolations(
LintViolation(2, 9, "Unnecessary trailing comma before \"->\""),
LintViolation(3, 9, "Unnecessary trailing comma before \"->\""),
@@ -266,7 +266,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(3, 9, "Missing trailing comma before \"->\""),
LintViolation(6, 6, "Missing trailing comma before \"->\""),
@@ -300,7 +300,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(3, 33, "Missing trailing comma before \"->\""),
LintViolation(6, 18, "Missing trailing comma before \"->\""),
@@ -353,7 +353,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(3, 6, "Expected a newline between the trailing comma and \"->\""),
LintViolation(7, 6, "Expected a newline between the trailing comma and \"->\""),
@@ -396,7 +396,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to false)
.hasLintViolations(
LintViolation(4, 14, "Unnecessary trailing comma before \")\""),
LintViolation(7, 10, "Unnecessary trailing comma before \")\""),
@@ -439,7 +439,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(7, 10, "Missing trailing comma before \")\""),
LintViolation(11, 10, "Missing trailing comma before \")\""),
@@ -477,7 +477,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to false)
.hasLintViolations(
LintViolation(1, 44, "Unnecessary trailing comma before \"->\""),
LintViolation(4, 12, "Unnecessary trailing comma before \"->\""),
@@ -516,7 +516,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(4, 12, "Missing trailing comma before \"->\""),
LintViolation(9, 12, "Missing trailing comma before \"->\""),
@@ -550,7 +550,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(4, 29, "Missing trailing comma before \")\""),
LintViolation(6, 13, "Missing trailing comma before \")\""),
@@ -568,7 +568,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasNoLintViolations()
}
@@ -599,7 +599,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolations(
LintViolation(4, 6, "Missing trailing comma and newline before \"->\""),
LintViolation(6, 6, "Missing trailing comma and newline before \"->\""),
@@ -643,7 +643,7 @@
// trailing comma was added) which in turn resulted in not recognizing that the import of EnumThree actually
// was used.
.addAdditionalRuleProvider { NoUnusedImportsRule() }
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolation(9, 24, "Missing trailing comma before \")\"")
.isFormattedAs(formattedCode)
}
@@ -665,7 +665,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to false)
.hasLintViolation(3, 13, "Unnecessary trailing comma before \"}\"")
.isFormattedAs(formattedCode)
}
@@ -691,7 +691,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to false)
.hasLintViolation(3, 13, "Unnecessary trailing comma before \";\"")
.isFormattedAs(formattedCode)
}
@@ -705,7 +705,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to false)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to false)
.hasNoLintViolations()
}
@@ -720,7 +720,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasNoLintViolations()
}
@@ -733,7 +733,7 @@
)
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasNoLintViolations()
}
@@ -755,7 +755,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolation(3, 13, "Missing trailing comma before \";\"")
.isFormattedAs(formattedCode)
}
@@ -778,7 +778,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolation(3, 13, "Missing trailing comma before \";\"")
.isFormattedAs(formattedCode)
}
@@ -801,7 +801,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolation(3, 13, "Missing trailing comma before \";\"")
.isFormattedAs(formattedCode)
}
@@ -826,7 +826,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolation(3, 13, "Missing trailing comma before \";\"")
.isFormattedAs(formattedCode)
}
@@ -862,7 +862,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolation(10, 6, "Missing trailing comma before \"}\"")
.isFormattedAs(formattedCode)
}
@@ -884,7 +884,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolation(3, 13, "Missing trailing comma before \"}\"")
.isFormattedAs(formattedCode)
}
@@ -927,7 +927,7 @@
)
multiLineIfElseRuleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.isFormattedAs(formattedCode)
}
@@ -953,7 +953,7 @@
}
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasLintViolation(3, 15, "Missing trailing comma before \";\"")
.isFormattedAs(formattedCode)
}
@@ -977,7 +977,7 @@
)
""".trimIndent()
ruleAssertThat(code)
- .withEditorConfigOverride(allowTrailingCommaProperty to true)
+ .withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasNoLintViolations()
}
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRuleTest.kt
index 7a3fce4..beac82d 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRuleTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/WrappingRuleTest.kt
@@ -544,7 +544,7 @@
}
""".trimIndent()
wrappingRuleAssertThat(code)
- .withEditorConfigOverride(DefaultEditorConfigProperties.indentStyleProperty to tab)
+ .withEditorConfigOverride(DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY to tab)
.hasLintViolations(
LintViolation(2, 10, "Missing newline after \"(\""),
LintViolation(5, 18, "Missing newline before \")\""),
@@ -1179,7 +1179,7 @@
}
""".trimIndent()
wrappingRuleAssertThat(codeTabs)
- .withEditorConfigOverride(DefaultEditorConfigProperties.indentStyleProperty to tab)
+ .withEditorConfigOverride(DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY to tab)
.hasNoLintViolations()
}
@@ -1205,7 +1205,7 @@
}
""".trimIndent()
wrappingRuleAssertThat(code)
- .withEditorConfigOverride(DefaultEditorConfigProperties.indentStyleProperty to tab)
+ .withEditorConfigOverride(DefaultEditorConfigProperties.INDENT_STYLE_PROPERTY to tab)
.hasNoLintViolations()
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingEditorconfigTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingEditorconfigTest.kt
index f5f47c1..ee514e2 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingEditorconfigTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingEditorconfigTest.kt
@@ -12,7 +12,7 @@
val properties: EditorConfigProperties = emptyMap()
val rule = ImportOrderingRule()
with(rule) {
- val raw = properties.writeEditorConfigProperty(ImportOrderingRule.ideaImportsLayoutProperty, official)
+ val raw = properties.writeEditorConfigProperty(ImportOrderingRule.IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY, official)
assertThat(raw).isEqualTo("*,java.**,javax.**,kotlin.**,^")
}
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleAsciiTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleAsciiTest.kt
index 3c7b8fe..e268f04 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleAsciiTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleAsciiTest.kt
@@ -191,6 +191,6 @@
}
private companion object {
- val ASCII_IMPORT_ORDERING = ImportOrderingRule.ideaImportsLayoutProperty to "*"
+ val ASCII_IMPORT_ORDERING = ImportOrderingRule.IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "*"
}
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleCustomTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleCustomTest.kt
index b3a1899..d6e1845 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleCustomTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleCustomTest.kt
@@ -1,7 +1,7 @@
package com.pinterest.ktlint.ruleset.standard.importordering
import com.pinterest.ktlint.ruleset.standard.ImportOrderingRule
-import com.pinterest.ktlint.ruleset.standard.ImportOrderingRule.Companion.ideaImportsLayoutProperty
+import com.pinterest.ktlint.ruleset.standard.ImportOrderingRule.Companion.IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule
import org.junit.jupiter.api.Test
@@ -22,7 +22,7 @@
import kotlin.concurrent.Thread
""".trimIndent()
importOrderingRuleAssertThat(code)
- .withEditorConfigOverride(ideaImportsLayoutProperty to "^,|,*")
+ .withEditorConfigOverride(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "^,|,*")
.hasNoLintViolations()
}
@@ -50,7 +50,7 @@
import androidx.fragment.app.Fragment as F
""".trimIndent()
importOrderingRuleAssertThat(code)
- .withEditorConfigOverride(ideaImportsLayoutProperty to "*,|,^")
+ .withEditorConfigOverride(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "*,|,^")
.hasLintViolation(1, 1, "Imports must be ordered according to the pattern specified in .editorconfig")
.isFormattedAs(formattedCode)
}
@@ -82,7 +82,7 @@
import kotlin.concurrent.Thread
""".trimIndent()
importOrderingRuleAssertThat(code)
- .withEditorConfigOverride(ideaImportsLayoutProperty to "^,|,*")
+ .withEditorConfigOverride(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "^,|,*")
.hasLintViolation(1, 1, "Imports must be ordered according to the pattern specified in .editorconfig")
.isFormattedAs(formattedCode)
}
@@ -107,7 +107,7 @@
""".trimIndent()
importOrderingRuleAssertThat(code)
.withEditorConfigOverride(
- ideaImportsLayoutProperty to "android.**,|,org.junit.**,|,net.**,|,org.**,|,java.**,|,com.**,|,javax.**,|,*",
+ IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "android.**,|,org.junit.**,|,net.**,|,org.**,|,java.**,|,com.**,|,javax.**,|,*",
).hasNoLintViolations()
}
@@ -147,7 +147,7 @@
""".trimIndent()
importOrderingRuleAssertThat(code)
.withEditorConfigOverride(
- ideaImportsLayoutProperty to "android.**,|,org.junit.**,|,net.**,|,org.**,|,java.**,|,com.**,|,javax.**,|,*",
+ IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "android.**,|,org.junit.**,|,net.**,|,org.**,|,java.**,|,com.**,|,javax.**,|,*",
).hasLintViolation(1, 1, "Imports must be ordered according to the pattern specified in .editorconfig")
.isFormattedAs(formattedCode)
}
@@ -164,7 +164,7 @@
import android.view.View
""".trimIndent()
importOrderingRuleAssertThat(code)
- .withEditorConfigOverride(ideaImportsLayoutProperty to "java.**,|,|,|,kotlin.**,*")
+ .withEditorConfigOverride(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "java.**,|,|,|,kotlin.**,*")
.hasNoLintViolations()
}
@@ -180,7 +180,7 @@
import java.util.List as L
""".trimIndent()
importOrderingRuleAssertThat(code)
- .withEditorConfigOverride(ideaImportsLayoutProperty to "^kotlin.**,^android.**,android.**,|,*,^")
+ .withEditorConfigOverride(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "^kotlin.**,^android.**,android.**,|,*,^")
.hasNoLintViolations()
}
@@ -204,7 +204,7 @@
import kotlin.concurrent.Thread
""".trimIndent()
importOrderingRuleAssertThat(code)
- .withEditorConfigOverride(ideaImportsLayoutProperty to "^kotlin.**,^android.**,android.**,|,^,*")
+ .withEditorConfigOverride(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "^kotlin.**,^android.**,android.**,|,^,*")
.hasLintViolation(1, 1, "Imports must be ordered according to the pattern specified in .editorconfig")
.isFormattedAs(formattedCode)
}
@@ -220,7 +220,7 @@
import java.util.List
""".trimIndent()
importOrderingRuleAssertThat(code)
- .withEditorConfigOverride(ideaImportsLayoutProperty to "kotlin.io.Closeable.*,kotlin.**,*")
+ .withEditorConfigOverride(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "kotlin.io.Closeable.*,kotlin.**,*")
.hasNoLintViolations()
}
@@ -244,7 +244,7 @@
import java.util.List
""".trimIndent()
importOrderingRuleAssertThat(code)
- .withEditorConfigOverride(ideaImportsLayoutProperty to "kotlin.io.Closeable.*,kotlin.**,*")
+ .withEditorConfigOverride(IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "kotlin.io.Closeable.*,kotlin.**,*")
.isFormattedAs(formattedCode)
}
}
diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleIdeaTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleIdeaTest.kt
index c8e74ca..114b1e4 100644
--- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleIdeaTest.kt
+++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleIdeaTest.kt
@@ -235,6 +235,6 @@
}
private companion object {
- val IDEA_DEFAULT_IMPORT_ORDERING = ImportOrderingRule.ideaImportsLayoutProperty to "*,java.**,javax.**,kotlin.**,^"
+ val IDEA_DEFAULT_IMPORT_ORDERING = ImportOrderingRule.IJ_KOTLIN_IMPORTS_LAYOUT_PROPERTY to "*,java.**,javax.**,kotlin.**,^"
}
}
diff --git a/ktlint-ruleset-test/src/main/kotlin/com/pinterest/ruleset/test/DumpASTRule.kt b/ktlint-ruleset-test/src/main/kotlin/com/pinterest/ruleset/test/DumpASTRule.kt
index af330c6..dae0b01 100644
--- a/ktlint-ruleset-test/src/main/kotlin/com/pinterest/ruleset/test/DumpASTRule.kt
+++ b/ktlint-ruleset-test/src/main/kotlin/com/pinterest/ruleset/test/DumpASTRule.kt
@@ -19,7 +19,7 @@
) : Rule("dump") {
private companion object {
- val elementTypeSet = ElementType::class.members.map { it.name }.toSet()
+ val ELEMENT_TYPE_SET = ElementType::class.members.map { it.name }.toSet()
}
private var lineNumberColumnLength: Int = 0
@@ -95,7 +95,7 @@
if (KtTokens.KEYWORDS.contains(elementType) || KtTokens.SOFT_KEYWORDS.contains(elementType)) {
name = "${name}_KEYWORD"
}
- return if (elementTypeSet.contains(name)) name else elementType.className + "." + elementType
+ return if (ELEMENT_TYPE_SET.contains(name)) name else elementType.className + "." + elementType
}
private fun colorClassName(className: String): String {
diff --git a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt
index 7ce75b3..bdb135d 100644
--- a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt
+++ b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/KtLintAssertThat.kt
@@ -3,13 +3,12 @@
import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.RuleProvider
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.maxLineLengthProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.MAX_LINE_LENGTH_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigOverride
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.EOL_CHAR
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.MAX_LINE_LENGTH_MARKER
import org.assertj.core.api.AbstractAssert
-import org.assertj.core.api.AbstractSoftAssertions.assertAll
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.assertAll
@@ -87,7 +86,7 @@
?.indexOf(EOL_CHAR)
?.let { index ->
editorConfigProperties =
- editorConfigProperties + setOf(maxLineLengthProperty to (index + 1).toString())
+ editorConfigProperties + setOf(MAX_LINE_LENGTH_PROPERTY to (index + 1).toString())
} ?: throw MissingEolMarker()
return this
@@ -234,7 +233,7 @@
code = code,
filePath = filePath,
kotlinScript = kotlinScript,
- editorConfigOverride = EditorConfigOverride.emptyEditorConfigOverride,
+ editorConfigOverride = EditorConfigOverride.EMPTY_EDITOR_CONFIG_OVERRIDE,
additionalRuleProviders = additionalRuleProviders.toSet(),
)
} else {
@@ -304,7 +303,7 @@
private val code: String,
private val filePath: String?,
private val kotlinScript: Boolean,
- private val editorConfigOverride: EditorConfigOverride = EditorConfigOverride.emptyEditorConfigOverride,
+ private val editorConfigOverride: EditorConfigOverride = EditorConfigOverride.EMPTY_EDITOR_CONFIG_OVERRIDE,
/**
* The rules which have to be executed in addition to the main rule when linting/formatting the code. Note that
* lint errors for those rules are suppressed.
diff --git a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/RuleExtension.kt b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/RuleExtension.kt
index 9a2ebde..2e87434 100644
--- a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/RuleExtension.kt
+++ b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/RuleExtension.kt
@@ -10,7 +10,7 @@
import mu.KotlinLogging
import org.jetbrains.kotlin.utils.addToStdlib.ifTrue
-private val logger =
+private val LOGGER =
KotlinLogging
.logger {}
.setDefaultLoggerModifier { logger ->
@@ -45,7 +45,7 @@
.orEmpty()
.equals(KTLINT_UNIT_TEST_ON_PROPERTY, ignoreCase = true)
.ifTrue {
- logger.info { "Dump AST of code before processing as System environment variable $KTLINT_UNIT_TEST_DUMP_AST is set to 'on'" }
+ LOGGER.info { "Dump AST of code before processing as System environment variable $KTLINT_UNIT_TEST_DUMP_AST is set to 'on'" }
RuleProvider {
DumpASTRule(
// Write to STDOUT. The focus in a failed unit test should first go to the error in the rule that is
@@ -60,7 +60,7 @@
public fun Set<RuleProvider>.lint(
lintedFilePath: String? = null,
text: String,
- editorConfigOverride: EditorConfigOverride = EditorConfigOverride.emptyEditorConfigOverride,
+ editorConfigOverride: EditorConfigOverride = EditorConfigOverride.EMPTY_EDITOR_CONFIG_OVERRIDE,
userData: Map<String, String> = emptyMap(),
script: Boolean = false,
): List<LintError> {
@@ -82,7 +82,7 @@
public fun Set<RuleProvider>.format(
lintedFilePath: String?,
text: String,
- editorConfigOverride: EditorConfigOverride = EditorConfigOverride.emptyEditorConfigOverride,
+ editorConfigOverride: EditorConfigOverride = EditorConfigOverride.EMPTY_EDITOR_CONFIG_OVERRIDE,
userData: Map<String, String> = emptyMap(),
cb: (e: LintError, corrected: Boolean) -> Unit = { _, _ -> },
script: Boolean = false,
diff --git a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/RuleSetProviderTest.kt b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/RuleSetProviderTest.kt
index e0dedf4..6cea2d4 100644
--- a/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/RuleSetProviderTest.kt
+++ b/ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/RuleSetProviderTest.kt
@@ -31,13 +31,13 @@
val missingRules =
packageRules
.minus(providerRules.toSet())
- .joinToString(separator = separator)
+ .joinToString(separator = NEWLINE_AND_INDENT)
assertThat(missingRules)
- .withFailMessage("${ruleSetProvider::class.simpleName} is missing to provide the following rules:${separator}$missingRules")
+ .withFailMessage("${ruleSetProvider::class.simpleName} is missing to provide the following rules:${NEWLINE_AND_INDENT}$missingRules")
.isEmpty()
}
private companion object {
- const val separator = "\n\t"
+ const val NEWLINE_AND_INDENT = "\n\t"
}
}
diff --git a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/FileUtils.kt b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/FileUtils.kt
index 5e8e3d9..6a0aab1 100644
--- a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/FileUtils.kt
+++ b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/FileUtils.kt
@@ -25,17 +25,17 @@
import mu.KotlinLogging
import org.jetbrains.kotlin.util.prefixIfNot
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
-internal val workDir: String = File(".").canonicalPath
+internal val WORK_DIR: String = File(".").canonicalPath
-private val tildeRegex = Regex("^(!)?~")
+private val TILDE_REGEX = Regex("^(!)?~")
private const val NEGATION_PREFIX = "!"
-private val userHome = System.getProperty("user.home")
+private val USER_HOME = System.getProperty("user.home")
-private val defaultKotlinFileExtensions = setOf("kt", "kts")
-internal val defaultPatterns = defaultKotlinFileExtensions.map { "**/*.$it" }
+private val DEFAULT_KOTLIN_FILE_EXTENSIONS = setOf("kt", "kts")
+internal val DEFAULT_PATTERNS = DEFAULT_KOTLIN_FILE_EXTENSIONS.map { "**/*.$it" }
/**
* Transform the [patterns] to a sequence of files. Each element in [patterns] can be a glob, a file or directory path
@@ -65,7 +65,7 @@
val globs = expand(patternsExclusiveExistingFiles, rootDir)
val pathMatchers = if (globs.isEmpty()) {
- defaultPatterns
+ DEFAULT_PATTERNS
.map { getPathMatcher("glob:$it") }
.toSet()
} else {
@@ -82,7 +82,7 @@
.map { getPathMatcher(it.removePrefix(NEGATION_PREFIX)) }
}
- logger.debug {
+ LOGGER.debug {
"""
Start walkFileTree for rootDir: '$rootDir'
include:
@@ -107,7 +107,7 @@
.replace(File.separatorChar, '/'),
).also {
if (it != filePath) {
- logger.trace { "On WindowsOS transform '$filePath' to '$it'" }
+ LOGGER.trace { "On WindowsOS transform '$filePath' to '$it'" }
}
}
} else {
@@ -116,10 +116,10 @@
if (negatedPathMatchers.none { it.matches(path) } &&
pathMatchers.any { it.matches(path) }
) {
- logger.trace { "- File: $path: Include" }
+ LOGGER.trace { "- File: $path: Include" }
result.add(path)
} else {
- logger.trace { "- File: $path: Ignore" }
+ LOGGER.trace { "- File: $path: Ignore" }
}
return FileVisitResult.CONTINUE
}
@@ -129,17 +129,17 @@
dirAttr: BasicFileAttributes,
): FileVisitResult {
return if (Files.isHidden(dirPath)) {
- logger.trace { "- Dir: $dirPath: Ignore" }
+ LOGGER.trace { "- Dir: $dirPath: Ignore" }
FileVisitResult.SKIP_SUBTREE
} else {
- logger.trace { "- Dir: $dirPath: Traverse" }
+ LOGGER.trace { "- Dir: $dirPath: Traverse" }
FileVisitResult.CONTINUE
}
}
},
)
}
- logger.debug { "Discovered ${result.count()} files to be processed in $duration ms" }
+ LOGGER.debug { "Discovered ${result.count()} files to be processed in $duration ms" }
return result.asSequence()
}
@@ -163,7 +163,7 @@
.replace(File.separator, "/")
.also { transformedPath ->
if (it != transformedPath) {
- logger.trace { "On WindowsOS transform '$it' to '$transformedPath'" }
+ LOGGER.trace { "On WindowsOS transform '$it' to '$transformedPath'" }
}
}
} else {
@@ -192,14 +192,14 @@
resolvedPath
.expandPathToDefaultPatterns()
.also {
- logger.trace { "Expanding resolved directory path '$resolvedPath' to patterns: [$it]" }
+ LOGGER.trace { "Expanding resolved directory path '$resolvedPath' to patterns: [$it]" }
}
} else {
resolvedPath
.pathString
.expandDoubleStarPatterns()
.also {
- logger.trace { "Expanding resolved path '$resolvedPath` to patterns: [$it]" }
+ LOGGER.trace { "Expanding resolved path '$resolvedPath` to patterns: [$it]" }
}
}
} catch (e: InvalidPathException) {
@@ -208,7 +208,7 @@
pathWithoutNegationPrefix
.expandDoubleStarPatterns()
.also {
- logger.trace { "On WindowsOS: expanding unresolved path '$pathWithoutNegationPrefix` to patterns: [$it]" }
+ LOGGER.trace { "On WindowsOS: expanding unresolved path '$pathWithoutNegationPrefix` to patterns: [$it]" }
}
} else {
emptyList()
@@ -228,7 +228,7 @@
.prefixIfNot("**/")
.also { transformedPattern ->
if (transformedPattern != originalPattern) {
- logger.trace { "On WindowsOS, transform '$originalPattern' to '$transformedPattern'" }
+ LOGGER.trace { "On WindowsOS, transform '$originalPattern' to '$transformedPattern'" }
}
}
} else {
@@ -279,12 +279,12 @@
// that glob results in a pattern that will never be matched as the ".." reference will not occur in
// the filepath that is being checked with the regular expression.
if (parts.isEmpty()) {
- logger.warn {
+ LOGGER.warn {
"On WindowsOS the pattern '$this' can not be used as it refers to a path outside of the current directory"
}
return@normalizeWindowsPattern null
} else if (parts.peekLast().contains('*')) {
- logger.warn {
+ LOGGER.warn {
"On WindowsOS the pattern '$this' can not be used as '/..' follows the wildcard pattern ${parts.peekLast()}"
}
return@normalizeWindowsPattern null
@@ -301,7 +301,7 @@
}
private fun Path.expandPathToDefaultPatterns() =
- defaultKotlinFileExtensions
+ DEFAULT_KOTLIN_FILE_EXTENSIONS
.flatMap {
listOf(
"$this/*.$it",
@@ -317,7 +317,7 @@
internal fun JarFiles.toFilesURIList() = map {
val jarFile = File(it.expandTildeToFullPath())
if (!jarFile.exists()) {
- logger.error { "File $it does not exist" }
+ LOGGER.error { "File $it does not exist" }
exitProcess(1)
}
jarFile.toURI().toURL()
@@ -330,10 +330,10 @@
// Windows sometimes inserts `~` into paths when using short directory names notation, e.g. `C:\Users\USERNA~1\Documents
this
} else {
- replaceFirst(tildeRegex, userHome)
+ replaceFirst(TILDE_REGEX, USER_HOME)
.also {
if (it != this) {
- logger.trace { "On non-WindowsOS expand '$this' to '$it'" }
+ LOGGER.trace { "On non-WindowsOS expand '$this' to '$it'" }
}
}
}
@@ -346,7 +346,7 @@
internal fun File.location(
relative: Boolean,
-) = if (relative) this.toRelativeString(File(workDir)) else this.path
+) = if (relative) this.toRelativeString(File(WORK_DIR)) else this.path
/**
* Run lint over common kotlin file or kotlin script file.
diff --git a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/GenerateEditorConfigSubCommand.kt b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/GenerateEditorConfigSubCommand.kt
index c35014f..e1f1852 100644
--- a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/GenerateEditorConfigSubCommand.kt
+++ b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/GenerateEditorConfigSubCommand.kt
@@ -2,13 +2,13 @@
import com.pinterest.ktlint.core.KtLint
import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.codeStyleSetProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.CODE_STYLE_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigOverride
import com.pinterest.ktlint.core.initKtLintKLogger
import mu.KotlinLogging
import picocli.CommandLine
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
@CommandLine.Command(
description = [
@@ -40,7 +40,7 @@
ktlintCommand.debug,
ktlintCommand.disabledRules,
),
- editorConfigOverride = EditorConfigOverride.from(codeStyleSetProperty to codeStyle()),
+ editorConfigOverride = EditorConfigOverride.from(CODE_STYLE_PROPERTY to codeStyle()),
debug = ktlintCommand.debug,
cb = { _, _ -> },
),
@@ -51,7 +51,7 @@
// should not be confused with logging markers.
println("[*.{kt,kts}]\n$generatedEditorConfig")
} else {
- logger.info { "Nothing to add to .editorconfig file" }
+ LOGGER.info { "Nothing to add to .editorconfig file" }
}
}
diff --git a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/GitHookInstaller.kt b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/GitHookInstaller.kt
index f5edcd8..a532c5e 100644
--- a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/GitHookInstaller.kt
+++ b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/GitHookInstaller.kt
@@ -8,7 +8,7 @@
import kotlin.system.exitProcess
import mu.KotlinLogging
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
private const val DEFAULT_GIT_HOOKS_DIR = "hooks"
@@ -20,7 +20,7 @@
val gitHooksDir = try {
resolveGitHooksDir()
} catch (e: IOException) {
- logger.error { e.message }
+ LOGGER.error { e.message }
exitProcess(1)
}
@@ -33,7 +33,7 @@
gitHookFile.writeBytes(hookContent)
gitHookFile.setExecutable(true)
- logger.info {
+ LOGGER.info {
"""
${gitHookFile.path} is installed. Be aware that this hook assumes to find ktlint on the PATH. Either
ensure that ktlint is actually added to the path or expand the ktlint command in the hook with the path.
@@ -98,7 +98,7 @@
!actualHookContent.contentEquals(expectedHookContent)
) {
val backupFile = hooksDir.resolve("$gitHookName.ktlint-backup.${actualHookContent.toUniqueId()}")
- logger.info { "Existing git hook ${hookFile.path} is copied to ${backupFile.path}" }
+ LOGGER.info { "Existing git hook ${hookFile.path} is copied to ${backupFile.path}" }
hookFile.copyTo(backupFile, overwrite = true)
}
}
diff --git a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/KtlintCommandLine.kt b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/KtlintCommandLine.kt
index 45f59c0..353c3e0 100644
--- a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/KtlintCommandLine.kt
+++ b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/KtlintCommandLine.kt
@@ -11,8 +11,8 @@
import com.pinterest.ktlint.core.RuleProvider
import com.pinterest.ktlint.core.api.Baseline.Status.INVALID
import com.pinterest.ktlint.core.api.Baseline.Status.NOT_FOUND
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.codeStyleSetProperty
-import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.ktlintDisabledRulesProperty
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.CODE_STYLE_PROPERTY
+import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties.KTLINT_DISABLED_RULES_PROPERTY
import com.pinterest.ktlint.core.api.EditorConfigDefaults
import com.pinterest.ktlint.core.api.EditorConfigOverride
import com.pinterest.ktlint.core.api.EditorConfigOverride.Companion.plus
@@ -263,8 +263,8 @@
// Set default value to patterns only after the logger has been configured to avoid a warning about initializing
// the logger multiple times
if (patterns.isEmpty()) {
- logger.info { "Enable default patterns $defaultPatterns" }
- patterns = ArrayList(defaultPatterns)
+ logger.info { "Enable default patterns $DEFAULT_PATTERNS" }
+ patterns = ArrayList(DEFAULT_PATTERNS)
}
val start = System.currentTimeMillis()
@@ -292,11 +292,11 @@
)
val editorConfigOverride =
EditorConfigOverride
- .emptyEditorConfigOverride
+ .EMPTY_EDITOR_CONFIG_OVERRIDE
.applyIf(disabledRules.isNotBlank()) {
- plus(ktlintDisabledRulesProperty to disabledRules)
+ plus(KTLINT_DISABLED_RULES_PROPERTY to disabledRules)
}.applyIf(android) {
- plus(codeStyleSetProperty to android)
+ plus(CODE_STYLE_PROPERTY to android)
}
reporter.beforeAll()
diff --git a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/LoadRuleProviders.kt b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/LoadRuleProviders.kt
index 00cedcc..2f2c4fc 100644
--- a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/LoadRuleProviders.kt
+++ b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/LoadRuleProviders.kt
@@ -10,7 +10,7 @@
import java.util.ServiceLoader
import mu.KotlinLogging
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* Loads given list of paths to jar files. For files containing a [RuleSetProviderV2] or [RuleSetProvider] class, get
@@ -45,7 +45,7 @@
debug: Boolean,
): Map<String, Set<RuleProvider>> {
if (url != null && debug) {
- logger.debug { "JAR ruleset provided with path \"${url.path}\"" }
+ LOGGER.debug { "JAR ruleset provided with path \"${url.path}\"" }
}
return try {
ServiceLoader
@@ -63,7 +63,7 @@
getLegacyRuleProvidersFromJar(url)
} catch (e: ServiceConfigurationError) {
if (url != null) {
- logger.warn {
+ LOGGER.warn {
"""
JAR ${url.path}, provided as command line argument, does not contain a custom ruleset provider.
Check following:
@@ -105,7 +105,7 @@
}.also {
if (url != null) {
if (it.isEmpty()) {
- logger.warn {
+ LOGGER.warn {
"""
JAR ${url.path}, provided as command line argument, does not contain a custom ruleset provider.
Check following:
@@ -116,7 +116,7 @@
""".trimIndent()
}
} else if (it.values.isNotEmpty()) {
- logger.warn {
+ LOGGER.warn {
"JAR ${url.path}, provided as command line argument, contains a custom ruleset provider which " +
"will *NOT* be compatible with the next KtLint version (0.48). Contact the maintainer of " +
"this ruleset. This JAR is not maintained by the KtLint project."
diff --git a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/PrintASTSubCommand.kt b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/PrintASTSubCommand.kt
index 88b0fe2..120615e 100644
--- a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/PrintASTSubCommand.kt
+++ b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/PrintASTSubCommand.kt
@@ -3,8 +3,8 @@
import com.pinterest.ktlint.core.KtLint
import com.pinterest.ktlint.core.ParseException
import com.pinterest.ktlint.core.RuleProvider
-import com.pinterest.ktlint.core.api.EditorConfigDefaults.Companion.emptyEditorConfigDefaults
-import com.pinterest.ktlint.core.api.EditorConfigOverride.Companion.emptyEditorConfigOverride
+import com.pinterest.ktlint.core.api.EditorConfigDefaults.Companion.EMPTY_EDITOR_CONFIG_DEFAULTS
+import com.pinterest.ktlint.core.api.EditorConfigOverride.Companion.EMPTY_EDITOR_CONFIG_OVERRIDE
import com.pinterest.ktlint.core.initKtLintKLogger
import com.pinterest.ruleset.test.DumpASTRule
import java.io.File
@@ -13,7 +13,7 @@
import mu.KotlinLogging
import picocli.CommandLine
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
@CommandLine.Command(
description = [
@@ -61,7 +61,7 @@
fileName: String,
fileContent: String,
) {
- logger.debug {
+ LOGGER.debug {
"Analyzing " + if (fileName != KtLint.STDIN_FILE) {
File(fileName).location(ktlintCommand.relative)
} else {
@@ -76,8 +76,8 @@
ruleProviders = setOf(
RuleProvider { DumpASTRule(System.out, ktlintCommand.color) },
),
- editorConfigDefaults = emptyEditorConfigDefaults,
- editorConfigOverride = emptyEditorConfigOverride,
+ editorConfigDefaults = EMPTY_EDITOR_CONFIG_DEFAULTS,
+ editorConfigOverride = EMPTY_EDITOR_CONFIG_OVERRIDE,
debug = ktlintCommand.debug,
)
} catch (e: Exception) {
diff --git a/ktlint/src/test/kotlin/com/pinterest/ktlint/BaseCLITest.kt b/ktlint/src/test/kotlin/com/pinterest/ktlint/BaseCLITest.kt
index 1ec5010..8c87198 100644
--- a/ktlint/src/test/kotlin/com/pinterest/ktlint/BaseCLITest.kt
+++ b/ktlint/src/test/kotlin/com/pinterest/ktlint/BaseCLITest.kt
@@ -85,7 +85,7 @@
}
private fun prepareTestProject(testProjectName: String): Path {
- val testProjectPath = testProjectsPath.resolve(testProjectName)
+ val testProjectPath = TEST_PROJECTS_PATHS.resolve(testProjectName)
assert(Files.exists(testProjectPath)) {
"Test project $testProjectName does not exist!"
}
@@ -167,7 +167,7 @@
fun assertSourceFileWasFormatted(filePathInProject: String): AbstractAssert<*, *> {
val originalCode =
- testProjectsPath
+ TEST_PROJECTS_PATHS
.resolve(testProject.last())
.resolve(filePathInProject)
.toFile()
@@ -185,7 +185,7 @@
companion object {
private const val WAIT_INTERVAL_DURATION = 100L
private const val WAIT_INTERVAL_MAX_OCCURRENCES = 1000
- val testProjectsPath: Path = Paths.get("src", "test", "resources", "cli")
+ val TEST_PROJECTS_PATHS: Path = Paths.get("src", "test", "resources", "cli")
const val BASE_DIR_PLACEHOLDER = "__TEMP_DIR__"
}
}
diff --git a/ktlint/src/test/kotlin/com/pinterest/ktlint/internal/FileUtilsTest.kt b/ktlint/src/test/kotlin/com/pinterest/ktlint/internal/FileUtilsTest.kt
index be13780..51ac860 100644
--- a/ktlint/src/test/kotlin/com/pinterest/ktlint/internal/FileUtilsTest.kt
+++ b/ktlint/src/test/kotlin/com/pinterest/ktlint/internal/FileUtilsTest.kt
@@ -17,7 +17,7 @@
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
-private val logger = KotlinLogging.logger {}.initKtLintKLogger()
+private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()
/**
* Tests for [fileSequence] method.
@@ -248,7 +248,7 @@
@Test
fun `Given a (relative) directory path (but not a glob) from the workdir then find all files in that workdir and it subdirectories having the default kotlin extensions`() {
- logger.info {
+ LOGGER.info {
val patterns = "src/main/kotlin"
val dir = "${rootDir}project1".normalizePath()
"`Given a (relative) directory path (but not a glob) from the workdir then find all files in that workdir and it subdirectories having the default kotlin extensions`\n" +
@@ -388,7 +388,7 @@
.map { it.normalize().toString() }
.toList()
.also {
- logger.info {
+ LOGGER.info {
"Getting files with [patterns = $patterns] and [rootdir = $rootDir] returns [files = $it]"
}
}