Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove deprecated cli parameters --experimental, --code-style, --disabled-rules #2411

Merged
merged 7 commits into from
Dec 3, 2023
10 changes: 5 additions & 5 deletions documentation/snapshot/docs/install/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,17 +138,17 @@ By default, the `info` log level is used meaning that all log lines at level `in

Some rules can be tweaked via the [`editorconfig file`](../../rules/configuration-ktlint/).

A scaffold of the `.editorconfig file` can be generated with command below. Note: that the generated file only contains configuration settings which are actively used by the [rules which are loaded](#rule-sets):
A scaffold of the `.editorconfig` file can be generated with command below. Note: that the generated file only contains configuration settings which are actively used by the [rules which are loaded](#rule-sets):

```shell title="Generate .editorconfig"
ktlint generateEditorConfig
ktlint generateEditorConfig ktlint_official
# or
ktlint generateEditorConfig
ktlint generateEditorConfig ktlint_official
# or
ktlint --ruleset=/path/to/custom-ruleset.jar generateEditorConfig
ktlint --ruleset=/path/to/custom-ruleset.jar generateEditorConfig ktlint_official
```

Normally this file is located in the root of your project directory. In case the file is located in a sub folder of the project, the settings of that file only applies to that subdirectory and its folders (recursively). Ktlint automatically detects and reads all `.editorconfig` files in your project.
Normally the `.editorconfig` file is located in the root of your project directory. In case the file is located in a sub folder of the project, the settings of that file only applies to that subdirectory and its folders (recursively). Ktlint automatically detects and reads all `.editorconfig` files in your project.

Use command below, to specify a default `editorconfig`. In case a property is not defined in any `.editorconfig` file on the path to the file, the value from the default file is used. The path may point to any valid file or directory. The path can be relative or absolute. Depending on your OS, the "~" at the beginning of a path is replaced by the user home directory.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.pinterest.ktlint.logger.api.initKtLintKLogger
import com.pinterest.ktlint.rule.engine.api.EditorConfigOverride
import com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue
import io.github.oshai.kotlinlogging.KotlinLogging
import picocli.CommandLine
import java.nio.file.Paths
Expand All @@ -12,13 +13,26 @@ private val LOGGER = KotlinLogging.logger {}.initKtLintKLogger()

@CommandLine.Command(
description = [
"Generate kotlin style section for '.editorconfig' file.",
"Output should be copied manually to the '.editorconfig' file.",
"Generate kotlin style section for '.editorconfig' file. Output should be copied manually to the '.editorconfig' file.",
],
mixinStandardHelpOptions = true,
versionProvider = KtlintVersionProvider::class,
)
internal class GenerateEditorConfigSubCommand : Runnable {
// No default value is set as users should explicitly choose one of the code styles. In this way, it is more clear that the generated
// content is determined by the chosen value. If a default (ktlint_official) is set, and the user has not specified the code style, the
// user might not be aware that the value of the other properties are dependent on the code style.
@CommandLine.Parameters(
arity = "1",
paramLabel = "code-style",
description = [
"Code style to be used when generating the '.editorconfig'. Value should be one of 'ktlint_official' (recommended), " +
"'intellij_idea' or 'android_studio'.",
],
converter = [CodeStyleValueConverter::class],
)
var codeStyle: CodeStyleValue? = null

@CommandLine.ParentCommand
private lateinit var ktlintCommand: KtlintCommandLine

Expand All @@ -28,15 +42,10 @@ internal class GenerateEditorConfigSubCommand : Runnable {
override fun run() {
commandSpec.commandLine().printCommandLineHelpOrVersionUsage()

if (ktlintCommand.codeStyle == null) {
System.err.println("Option --code-style must be set as to generate the '.editorconfig' correctly")
exitKtLintProcess(1)
}

val ktLintRuleEngine =
KtLintRuleEngine(
ruleProviders = ktlintCommand.ruleProviders(),
editorConfigOverride = EditorConfigOverride.from(CODE_STYLE_PROPERTY to ktlintCommand.codeStyle),
editorConfigOverride = EditorConfigOverride.from(CODE_STYLE_PROPERTY to codeStyle),
isInvokedFromCli = true,
)
val generatedEditorConfig = ktLintRuleEngine.generateKotlinEditorConfigSection(Paths.get("."))
Expand All @@ -54,3 +63,15 @@ internal class GenerateEditorConfigSubCommand : Runnable {
internal const val COMMAND_NAME = "generateEditorConfig"
}
}

private class CodeStyleValueConverter : CommandLine.ITypeConverter<CodeStyleValue> {
@Throws(Exception::class)
override fun convert(value: String?): CodeStyleValue =
when (value?.lowercase()?.replace("-", "_")) {
null -> CODE_STYLE_PROPERTY.defaultValue
"ktlint_official" -> CodeStyleValue.ktlint_official
"android_studio" -> CodeStyleValue.android_studio
"intellij_idea" -> CodeStyleValue.intellij_idea
else -> throw IllegalArgumentException("Invalid code style value")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,24 @@ package com.pinterest.ktlint.cli.internal
import picocli.CommandLine

@CommandLine.Command(
description = [
"Install git hook to automatically check files for style violations on commit",
],
description = ["Install git hook to automatically check files for style violations on commit"],
mixinStandardHelpOptions = true,
versionProvider = KtlintVersionProvider::class,
)
internal class GitPreCommitHookSubCommand : Runnable {
@CommandLine.ParentCommand
private lateinit var ktlintCommand: KtlintCommandLine

@CommandLine.Spec
private lateinit var commandSpec: CommandLine.Model.CommandSpec

override fun run() {
commandSpec.commandLine().printCommandLineHelpOrVersionUsage()

if (ktlintCommand.codeStyle == null) {
System.err.println("Option --code-style must be set as to generate the git pre commit hook correctly")
exitKtLintProcess(1)
}

GitHookInstaller.installGitHook("pre-commit") {
"""
#!/bin/sh

# <https://github.com/pinterest/ktlint> pre-commit hook

git diff --name-only -z --cached --relative -- '*.kt' '*.kts' | ktlint --code-style=${ktlintCommand.codeStyle} --relative --patterns-from-stdin=''
git diff --name-only -z --cached --relative -- '*.kt' '*.kts' | ktlint --relative --patterns-from-stdin=''
""".trimIndent().toByteArray()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,24 @@ package com.pinterest.ktlint.cli.internal
import picocli.CommandLine

@CommandLine.Command(
description = [
"Install git hook to automatically check files for style violations before push",
],
description = ["Install git hook to automatically check files for style violations before push"],
mixinStandardHelpOptions = true,
versionProvider = KtlintVersionProvider::class,
)
internal class GitPrePushHookSubCommand : Runnable {
@CommandLine.ParentCommand
private lateinit var ktlintCommand: KtlintCommandLine

@CommandLine.Spec
private lateinit var commandSpec: CommandLine.Model.CommandSpec

override fun run() {
commandSpec.commandLine().printCommandLineHelpOrVersionUsage()

if (ktlintCommand.codeStyle == null) {
System.err.println("Option --code-style must be set as to generate the git pre push hook correctly")
exitKtLintProcess(1)
}

GitHookInstaller.installGitHook("pre-push") {
"""
#!/bin/sh

# <https://github.com/pinterest/ktlint> pre-push hook

git diff --name-only -z HEAD "origin/${'$'}(git rev-parse --abbrev-ref HEAD)" -- '*.kt' '*.kts' | ktlint --code-style=${ktlintCommand.codeStyle} --relative --patterns-from-stdin=''
git diff --name-only -z HEAD "origin/${'$'}(git rev-parse --abbrev-ref HEAD)" -- '*.kt' '*.kts' | ktlint --relative --patterns-from-stdin=''
""".trimIndent().toByteArray()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,8 @@ import com.pinterest.ktlint.rule.engine.api.EditorConfigOverride.Companion.plus
import com.pinterest.ktlint.rule.engine.api.KtLintParseException
import com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine
import com.pinterest.ktlint.rule.engine.api.KtLintRuleException
import com.pinterest.ktlint.rule.engine.core.api.RuleId
import com.pinterest.ktlint.rule.engine.core.api.RuleProvider
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CODE_STYLE_PROPERTY
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleValue
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EXPERIMENTAL_RULES_EXECUTION_PROPERTY
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.RuleExecution
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.createRuleExecutionEditorConfigProperty
import com.pinterest.ktlint.rule.engine.core.api.propertyTypes
Expand Down Expand Up @@ -61,7 +58,7 @@ private lateinit var logger: KLogger
headerHeading =
"""
An anti-bikeshedding Kotlin linter with built-in formatter.
(https://github.com/pinterest/ktlint).
(https://pinterest.github.io/ktlint/latest/).

Usage:
ktlint <flags> [patterns]
Expand Down Expand Up @@ -105,14 +102,10 @@ internal class KtlintCommandLine {
// Ensure that the code-style can be set on sub commands and is visible in the help documentation
scope = CommandLine.ScopeType.INHERIT,
names = ["--code-style"],
description = [
"Defines the code style (ktlint_official, intellij_idea or android_studio) to be used for formatting the code. This option " +
"is deprecated, and will be removed in Ktlint 1.1. The code style has to be defined as '.editorconfig' property " +
"'ktlint_code_style'.",
],
converter = [CodeStyleValueConverter::class],
// Keep as hidden option, so that a customized error can be printed when still used.
hidden = true,
)
@Deprecated("Marked for removal in Ktlint 1.1")
@Deprecated("Remove in Ktlint 1.2 (or later) as some users will skip multiple versions.")
var codeStyle: CodeStyleValue? = null

@Option(
Expand All @@ -129,13 +122,9 @@ internal class KtlintCommandLine {

@Option(
names = ["--disabled_rules"],
description = [
"Comma-separated list of rules to globally disable. This option is deprecated, and will be removed in Ktlint 1.1. The " +
"disabled rules have to be defined as '.editorconfig' properties. See " +
"https://pinterest.github.io/ktlint/1.0.0/faq/#how-do-i-enable-or-disable-a-rule",
],
hidden = true,
)
@Deprecated("Marked for removal in Ktlint 1.1")
@Deprecated("Remove in Ktlint 1.2 (or later) as some users will skip multiple versions.")
var disabledRules: String = ""

@Option(
Expand Down Expand Up @@ -207,13 +196,9 @@ internal class KtlintCommandLine {

@Option(
names = ["--experimental"],
description = [
"Enable experimental rules. This option is deprecated, and will be removed in Ktlint 1.1. The experimental flag has to be " +
"set as '.editorconfig' property 'ktlint_experimental'. See " +
"https://pinterest.github.io/ktlint/1.0.0/faq/#how-do-i-enable-or-disable-a-rule-set",
],
hidden = true,
)
@Deprecated("Marked for removal in Ktlint 1.1")
@Deprecated("Remove in Ktlint 1.2 (or later) as some users will skip multiple versions.")
var experimental: Boolean = false

@Option(
Expand Down Expand Up @@ -241,41 +226,35 @@ internal class KtlintCommandLine {
get() = Level.DEBUG.isGreaterOrEqual(minLogLevel)
private set

private fun disabledRulesEditorConfigOverrides() =
disabledRules
.split(",")
.filter { it.isNotBlank() }
.map {
// For backwards compatibility, prefix the rule id with the standard rule set id when missing
RuleId.prefixWithStandardRuleSetIdWhenMissing(it)
}.map { RuleId(it).createRuleExecutionEditorConfigProperty() to RuleExecution.disabled }
.toTypedArray()

fun run() {
if (experimental) {
logger.error {
"Parameter `--experimental is ignored. The experimental rules have to be enabled via '.editorconfig' property " +
"'ktlint_experimental = enabled'."
}
exitKtLintProcess(2)
}

if (disabledRules.isNotBlank()) {
logger.error {
"Parameter '--disabled-rules' is ignored. The disabled rules have to be defined as '.editorconfig' properties. " +
"See https://pinterest.github.io/ktlint/1.0.0/faq/#how-do-i-enable-or-disable-a-rule"
}
exitKtLintProcess(3)
}

if (codeStyle != null) {
logger.error {
"Parameter '--code-style=${codeStyle?.name}' is ignored. The code style should be defined as '.editorconfig' " +
"property 'ktlint_code_style='."
}
exitKtLintProcess(4)
}

val editorConfigOverride =
EditorConfigOverride
.EMPTY_EDITOR_CONFIG_OVERRIDE
.applyIf(experimental) {
logger.warn {
"Parameter `--experimental is deprecated, and will be removed in Ktlint 1.1. The experimental flag has to be " +
"set as '.editorconfig' property 'ktlint_experimental = enabled'. See " +
"https://pinterest.github.io/ktlint/1.0.0/faq/#how-do-i-enable-or-disable-a-rule-set"
}
plus(EXPERIMENTAL_RULES_EXECUTION_PROPERTY to RuleExecution.enabled)
}.applyIf(disabledRules.isNotBlank()) {
logger.warn {
"Parameter `--disabled-rules is deprecated, and will be removed in Ktlint 1.1. The disabled rules have to be " +
"defined as '.editorconfig' properties. See " +
"https://pinterest.github.io/ktlint/1.0.0/faq/#how-do-i-enable-or-disable-a-rule"
}
plus(*disabledRulesEditorConfigOverrides())
}.applyIf(codeStyle != null) {
logger.warn {
"Parameter `--code-style=${codeStyle?.name} is deprecated. The code style should be defined as '.editorconfig' " +
"property 'ktlint_code_style'."
}
plus(CODE_STYLE_PROPERTY to codeStyle)
}.applyIf(stdin) {
.applyIf(stdin) {
logger.debug {
"Add editor config override to disable 'filename' rule which can not be used in combination with reading from " +
"<stdin>"
Expand Down Expand Up @@ -743,18 +722,6 @@ internal class KtlintCommandLine {
}
}

private class CodeStyleValueConverter : CommandLine.ITypeConverter<CodeStyleValue> {
@Throws(Exception::class)
override fun convert(value: String?): CodeStyleValue =
when (value?.lowercase()?.replace("-", "_")) {
null -> CODE_STYLE_PROPERTY.defaultValue
"ktlint_official" -> CodeStyleValue.ktlint_official
"android_studio" -> CodeStyleValue.android_studio
"intellij_idea" -> CodeStyleValue.intellij_idea
else -> throw IllegalArgumentException("Invalid code style value")
}
}

private class LogLevelConverter : CommandLine.ITypeConverter<Level> {
@Throws(Exception::class)
override fun convert(value: String?): Level =
Expand Down
Loading