pinterest / ktlint

An anti-bikeshedding Kotlin linter with built-in formatter
https://pinterest.github.io/ktlint/
MIT License
6.23k stars 512 forks source link

Unable to autocorrect trailing comma #2794

Closed ccjernigan closed 1 month ago

ccjernigan commented 1 month ago

Expected Behavior

ktlint --format should be able to autocorrect violations

Observed Behavior

07:48:17.149 [pool-1-thread-7] WARN com.pinterest.ktlint.rule.engine.internal.CodeFormatter -- Format was not able to resolve all violations which (theoretically) can be autocorrected in file

Steps to Reproduce

  1. Add some code like this
    private fun breakKtlint(int: Int,) {
    }
  2. Run ktlint --format

Your Environment

paul-dingemans commented 1 month ago

The given code sample does not reproduce the problem, given .editorconfig below:

root = true

[*.{kt,kts}]
ktlint_code_style = ktlint_official
ktlint_standard = enabled
ktlint_experimental = enabled

Please provide additional information to reproduce.

ccjernigan commented 1 month ago

Ah, this is my .editorconfig

root = true

[*.{kt,kts}]
ktlint_standard_trailing-comma-on-call-site = disabled
ktlint_standard_trailing-comma-on-declaration-site = disabled
ktlint_standard_function-naming = disabled # Disabled because of Compose

Given the rule is disabled, #2794 is probably invalid (or perhaps the error message could be more clear) but #2795 is probably valid.

paul-dingemans commented 1 month ago

Ok tnx. Reproducable with:

root = true

[*.{kt,kts}]
ktlint_standard_trailing-comma-on-declaration-site = disabled

The problem is caused by the parameter-list-spacing rule. It requires a whitespace after each comma but this does not make sense for a trailing comma. The output of lint:

src/main/kotlin/Foo.kt:1:33: Whitespace after ',' is missing (standard:parameter-list-spacing)
20:27:12.345 [main] WARN com.pinterest.ktlint.cli.internal.KtlintCommandLine -- Lint has found errors than can be autocorrected using 'ktlint --format'

Summary error count (descending) by rule:
  standard:parameter-list-spacing: 1

When format is run, the violation above is found and resolved. But as a result of this fix, the function-signature, which runs later, removes this space but leaves the comma. After both rules have run, the result is identical to the original file. So actually ktlint finds and resolves two lint violations. This is repeated three times with identical results (this also does not make sense) which results in message Format was not able to resolve all violations which (theoretically) can be autocorrected in file.