diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 56ecc039e4..37743ea23c 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -9,8 +9,9 @@ If the PR solves an issue than provide a link to that issue. --> - [ ] PR description added - [ ] tests are added +- [ ] KtLint has been applied on source code itself and violations are fixed +- [ ] [documentation](https://pinterest.github.io/ktlint/) is updated - [ ] `CHANGELOG.md` is updated In case of adding a new rule: -- [ ] `README.md` is updated -- [ ] Rule has been applied on Ktlint itself and violations are fixed +- [ ] Rule is added to [rules documentation](https://pinterest.github.io/ktlint/rules/standard/) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2615842345..210b8fb28a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -126,7 +126,11 @@ The callback function provided as parameter to the format function is now called * When a glob is specified then ensure that it matches files in the current directory and not only in subdirectories of the current directory ([#1533](https://github.com/pinterest/ktlint/issue/1533)). * Execute `ktlint` cli on default kotlin extensions only when an (existing) path to a directory is given. ([#917](https://github.com/pinterest/ktlint/issue/917)). * Invoke callback on `format` function for all errors including errors that are autocorrected ([#1491](https://github.com/pinterest/ktlint/issues/1491)) - +* Add missing whitespace when else is on same line as true condition `multiline-if-else` ([#1560](https://github.com/pinterest/ktlint/issues/1560)) +* Fix multiline if-statements `multiline-if-else` ([#828](https://github.com/pinterest/ktlint/issues/828)) +* Prevent class cast exception on ".editorconfig" property `ktlint_code_style` ([#1559](https://github.com/pinterest/ktlint/issues/1559)) +* Handle trailing comma in enums `trailing-comma` ([#1542](https://github.com/pinterest/ktlint/pull/1542)) +* Split TrailingCommaRule ([#1555](https://github.com/pinterest/ktlint/pull/1555)) ### Changed @@ -1100,8 +1104,8 @@ path/to/file.kt path/to/another-file.kt 1:10 Unnecessary semicolon. ``` -- [string-template](https://ktlint.github.io/#rule-string-template), -[no-empty-class-body](https://ktlint.github.io/#rule-empty-class-body), +- [string-template](https://pinterest.github.io/ktlint/rules/standard/#string-template), +[no-empty-class-body](https://pinterest.github.io/ktlint/rules/standard/#no-empty-class-bodies), max-line-length ([#47](https://github.com/shyiko/ktlint/issues/47)), final-newline (activated only if `insert_final_newline` is set in `.editorconfig` (under `[*.{kt,kts}]`)) rules. - `--limit` CLI option (e.g. use `--limit=10` to limit the number of errors to display). @@ -1162,8 +1166,8 @@ set in `[*{kt,kts}]` section). ### Added -- [no-unit-return](https://ktlint.github.io/#rule-unit-return) rule. -- [modifier-order](https://ktlint.github.io/#rule-modifier-order) rule ([#42](https://github.com/shyiko/ktlint/issues/42)). +- [no-unit-return](https://pinterest.github.io/ktlint/rules/standard/#no-unit-as-return-type) rule. +- [modifier-order](https://pinterest.github.io/ktlint/rules/standard/#modifier-order) rule ([#42](https://github.com/shyiko/ktlint/issues/42)). - `else/catch/finally` on the same line as `}` check (now part of "keyword-spacing" rule). - `ktlint-intellij-idea-integration` binary for easy Intellij IDEA config injection. diff --git a/README.md b/README.md index 22c419cea9..34d612f17b 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- +

@@ -8,838 +8,29 @@ Join the chat at https://kotlinlang.slack.com Build status Maven Central -ktlint +ktlint

Kotlin linter in spirit of feross/standard (JavaScript) and gofmt (Go).

-## Features -- **No configuration.**[*](https://github.com/pinterest/ktlint#how-do-i-globally-disable-a-rule) Which means no decisions to make, nothing to argue about and no special files to manage. -While this might sound extreme, keep in mind that `ktlint` tries to capture (reflect) **official code style**[*](https://github.com/pinterest/ktlint/issues/284#issuecomment-425177186) from [kotlinlang.org](https://kotlinlang.org/docs/reference/coding-conventions.html) and [Android Kotlin Style Guide](https://android.github.io/kotlin-guides/style.html) -(+ [we respect your .editorconfig](#editorconfig) and support additional [ruleset](#creating-a-ruleset)|s). -- **Built-in formatter.** So that you wouldn't have to fix all style violations by hand. -- **Customizable output.** `plain` (+ `plain?group_by_file`), `format`, `json`, `html` and `checkstyle` reporters are available out-of-the-box. -It's also [easy to create your own](#creating-a-reporter). -- **A single executable jar with all dependencies included.** +## Key features -

-Installation | Usage | Integration with Maven / Gradle / IntelliJ IDEA / Emacs / Continuous Integration | Creating a ruleset | a reporter | Badge | FAQ -

- -## Standard rules - -- `annotation`: Annotation formatting - multiple annotations should be on a separate line than the annotated declaration; annotations with parameters should each be on separate lines; annotations should be followed by a space -- `argument-list-wrapping`: Argument list wrapping -- `chain-wrapping`: When wrapping chained calls `.`, `?.` and `?:` should be placed on the next line -- `comment-spacing`: The end of line comment sign `//` should be preceded and followed by exactly a space -- `enum-entry-name-case`: Enum entry names should be uppercase underscore-separated names -- `filename`: Files containing only one toplevel domain should be named according to that element. -- `final-newline`: Newline at the end of each file (enabled by default) - (set `insert_final_newline=false` in .editorconfig to disable (see [EditorConfig](#editorconfig) section for more)). -- `import-ordering`: Imports ordered consistently (see [Custom ktlint EditorConfig properties](#custom-ktlint-specific-editorconfig-properties) for more) -- `indent`: Indentation formatting - respects `.editorconfig` `indent_size` with no continuation indent (see [EditorConfig](#editorconfig) section for more) -- `max-line-length`: Ensures that lines do not exceed the given length of `.editorconfig` property `max_line_length` (see [EditorConfig](#editorconfig) section for more). This rule does not apply in a number of situations. For example, in the case a line exceeds the maximum line length due to and comment that disables ktlint rules than that comment is being ignored when validating the length of the line. The `.editorconfig` property `ktlint_ignore_back_ticked_identifier` can be set to ignore identifiers which are enclosed in backticks, which for example is very useful when you want to allow longer names for unit tests. -- `modifier-order`: Consistent order of modifiers -- `multiline-if-else`: Braces required for multiline if/else statements -- `no-blank-line-before-rbrace`: No blank lines before `}` -- `no-blank-lines-in-chained-method-calls`: No blank lines in chained method expressions -- `no-consecutive-blank-lines`: No consecutive blank lines -- `no-empty-class-body`: No empty (`{}`) class bodies -- `no-empty-first-line-in-method-block`: No leading empty lines in method blocks -- `no-line-break-after-else`: Disallows line breaks after the else keyword if that could lead to confusion, for example: - ```kotlin - if (conditionA()) { - doSomething() - } else - if (conditionB()) { - doAnotherThing() - } - ``` -- `no-line-break-before-assignment`: When a line is broken at an assignment (`=`) operator the break comes after the symbol -- `no-multi-spaces`: Except in indentation and in KDoc's it is not allowed to have multiple consecutive spaces -- `no-semi`: No semicolons (unless used to separate multiple statements on the same line) -- `no-trailing-spaces`: No trailing whitespaces -- `no-unit-return`: No `Unit` returns (`fun fn {}` instead of `fun fn: Unit {}`) -- `no-unused-imports`: No unused `import`s -- `no-wildcard-imports`: No wildcard `import`s expect imports listed in `.editorconfig` property `ij_kotlin_packages_to_use_import_on_demand` -- `package-name`: No underscores in package names -- `parameter-list-wrapping`: When class/function signature doesn't fit on a single line, each parameter must be on a separate line -- `string-template`: Consistent string templates (`$v` instead of `${v}`, `${p.v}` instead of `${p.v.toString()}`) -- `trailing-comma-on-call-site`: Consistent removal (default) or adding of trailing comma's (on call site) -- `trailing-comma-on-declaration-site`: Consistent removal (default) or adding of trailing comma's (on declaration site) - -### Spacing -- `annotation-spacing`: Annotations should be separated by a single line break -- `colon-spacing`: Consistent spacing around colon -- `comma-spacing`: Consistent spacing around comma -- `curly-spacing`: Consistent spacing around curly braces -- `dot-spacing`: Consistent spacing around dots -- `double-colon-spacing`: No spaces around `::` -- `keyword-spacing`: Consistent spacing around keywords -- `op-spacing`: Consistent spacing around operators -- `paren-spacing`: Consistent spacing around parenthesis -- `range-spacing`: Consistent spacing around range operators -- `spacing-around-angle-brackets`: No spaces around angle brackets -- `spacing-between-declarations-with-annotations`: Declarations with annotations should be separated by a blank line -- `spacing-between-declarations-with-comments`: Declarations with comments should be separated by a blank line -- `unary-op-spacing`: No spaces around unary operators - -## Experimental rules -New rules will be added into the [experimental ruleset](https://github.com/pinterest/ktlint/tree/master/ktlint-ruleset-experimental), which can be enabled -by passing the `--experimental` flag to `ktlint`. - -- `experimental:block-comment-initial-star-alignment`: Lines in a block comment which (exclusive the indentation) start with a `*` should have this `*` aligned with the `*` in the opening of the block comment. -- `experimental:discouraged-comment-location`: Detect discouraged comment locations (no autocorrect) -- `experimental:unnecessary-parentheses-before-trailing-lambda`: An empty parentheses block before a lambda is redundant. For example `some-string".count() { it == '-' }` -- `function-signature`: rewrites the function signature to a single line when possible (e.g. when not exceeding the `max_line_length` property) or a multiline signature otherwise. In case of function with a body expression, the body expression is placed on the same line as the function signature when not exceeding the `max_line_length` property. Optionally the function signature can be forced to be written as a multiline signature in case the function has more than a specified number of parameters (`.editorconfig' property `ktlint_function_signature_wrapping_rule_always_with_minimum_parameters`) - -### Spacing -- `experimental:fun-keyword-spacing`: Consistent spacing after the fun keyword -- `experimental:function-return-type-spacing`: Consistent spacing around the function return type -- `experimental:function-start-of-body-spacing`: Consistent spacing before start of function body -- `experimental:function-type-reference-spacing`: Consistent spacing in the type reference before a function -- `experimental:modifier-list-spacing`: Consistent spacing between modifiers in and after the last modifier in a modifier list -- `experimental:nullable-type-spacing`: No spaces in a nullable type -- `experimental:parameter-list-spacing`: Consistent spacing inside the parameter list -- `experimental:spacing-between-function-name-and-opening-parenthesis`: Consistent spacing between function name and opening parenthesis -- `experimental:type-parameter-list-spacing`: Spacing after a type parameter list in function and class declarations - -### Wrapping -- `experimental:comment-wrapping`: A block comment should start and end on a line that does not contain any other element. A block comment should not be used as end of line comment. -- `experimental:kdoc-wrapping`: A KDoc comment should start and end on a line that does not contain any other element. - -## EditorConfig - -Ktlint uses a limited set of `.editorconfig` properties for additional configuration. A sensible default value is provided for each property when not explicitly defined. Properties can be overridden, provided they are specified under `[*.{kt,kts}]`. Ktlint uses some properties defined by [.editorconfig](https://editorconfig.org/), IntelliJ IDEA and custom properties. - -### Disable rules - -By default, no rules are disabled. The property `disabled_rules` holds a comma separated list (without spaces). Rules which are not defined in the `standard` ruleset have to be prefixed. - -Example: -```ini -[*.{kt,kts}] -disabled_rules = some-standard-rule,experimental:some-experimental-rule,my-custom-ruleset:my-custom-rule -``` - -### Trailing comma - -Trailing comma's (both on call and declaration site) are disabled (e.g. not allowed) by. When enabling the properties, the trailing becomes mandatory where applicable. - -Example: -```ini -[*.{kt,kts}] -ij_kotlin_allow_trailing_comma = false -ij_kotlin_allow_trailing_comma_on_call_site = false -``` - -### Import layouts - -By default, the same imports are allowed as in IntelliJ IDEA. The import path can be a full path, e.g. "java.util.List.*" as well as wildcard path, e.g. "kotlin.**". - -The layout can be composed by the following symbols: -* "*" - wildcard. There must be at least one entry of a single wildcard to match all other imports. Matches anything after a specified symbol/import as well. -* "|" - blank line. Supports only single blank lines between imports. No blank line is allowed in the beginning or end of the layout. -* "^" - alias import, e.g. "^android.*" will match all android alias imports, "^" will match all other alias imports. - -Examples: -```kotlin -ij_kotlin_imports_layout=* # alphabetical with capital letters before lower case letters (e.g. Z before a), no blank lines -ij_kotlin_imports_layout=*,java.**,javax.**,kotlin.**,^ # default IntelliJ IDEA style, same as alphabetical, but with "java", "javax", "kotlin" and alias imports in the end of the imports list -ij_kotlin_imports_layout=android.**,|,^org.junit.**,kotlin.io.Closeable.*,|,*,^ # custom imports layout -``` - -Wildcard imports can be allowed for specific import paths (Comma-separated list, use "**" as wildcard for package and all subpackages). This setting overrides the no-wildcard-imports rule. This setting is best be used for allowing wildcard imports from libraries like Ktor where extension functions are used in a way that creates a lot of imports. - -```ini -[*.{kt,kts}] -ij_kotlin_packages_to_use_import_on_demand = java.util.*,kotlinx.android.synthetic.** -``` - -### Indent - -By default, indenting is done with 4 spaces per indent level. - -```ini -[*.{kt,kts}] -indent_size = 4 # possible values: number (e.g. 2), "unset" (makes ktlint ignore indentation completely) -indent_style = space # or "tab" -``` - -### Final newline - -By default, a final newline is required at the end of the file. - -```ini -[*.{kt,kts}] -insert_final_newline = true -``` - -### Code style - -By default, the `offical` Kotlin code style is applied. Alternatively, the code style can be set to `android`. Note that for the Android code style different default values might be applicable. - -```ini -[*.{kt,kts}] -ktlint_code_style = official # Or "android" -``` - -### Function signature - -By default, the number of parameters in a function signature is not relevant when rewriting the function signature. Only the maximum line length determines when a function signature should be written on a single line or with multiple lines. This setting can be used, to force a multiline function signature in case the function contain at least a number of parameters even in case the function signature would fit on a single line. - -```ini -[*.{kt,kts}] -ktlint_function_signature_rule_force_multiline_with_at_least_parameters= -1 # -1 to ignore the number of parameters or otherwise a positive number -``` - -### Ignore identifiers enclosed in backticks - -By default, the identifiers enclosed in backticks are not ignored. - -According to https://kotlinlang.org/docs/reference/coding-conventions.html#names-for-test-methods it is acceptable to write method names in natural language. When using natural language, the description tends to be longer. This property allows lines containing an identifier between backticks to be longer than the maximum line length. (Since 0.41.0) - -```kotlin -@Test -fun `Given a test with a very loooooooooooooooooooooong test description`() { - -} -``` - -```ini -[*.{kt,kts}] -ktlint_ignore_back_ticked_identifier = false -``` - -### Max line length - -By default, the maximum line length is not set. The `android` code style sets the max line length to 100 (per Android Kotlin Style Guide). - -```ini -[*.{kt,kts}] -max_line_length = -1 # Use "off" (or -1) to ignore max line length or a positive number to set max line length -``` - -### IntelliJ IDEA `.editorconfig` autoformat issue - -Unfortunately [IntelliJ IDEA](https://www.jetbrains.com/idea/) has `.editorconfig` [autoformat issue](https://youtrack.jetbrains.com/issue/IDEA-242506) -that adds additional space into glob statements. -For example, `[*{kt,kts}]` is formatted into `[*{kt, kts}]` ([original ktlint issue](https://github.com/pinterest/ktlint/issues/762)). -Such behaviour violates `.editorconfig` [specification](https://github.com/editorconfig/editorconfig/issues/148) and leads to ignoring this section when ktlint is parsing it. - -### Overriding Editorconfig properties for specific directories - -You could [override](https://editorconfig.org/#file-format-details) properties for specific directories inside your project: -```ini -[*.{kt,kts}] -disabled_rules=import-ordering - -# Note that in this case 'import-ordering' rule will be active and 'indent' will be disabled -[api/*.{kt,kts}] -disabled_rules=indent -``` - -## Online demo -You can try `ktlint` online [here](https://ktlint-demo.herokuapp.com/) using the standard or a custom ruleset without installing it to your PC. \ -To contribute or get more info, please visit the [GitHub repository](https://github.com/akuleshov7/diKTat-demo). - - -## Installation - -> Skip all the way to the "Integration" section if you don't plan to use `ktlint`'s command line interface. - -```sh -curl -sSLO https://github.com/pinterest/ktlint/releases/download/0.46.1/ktlint && - chmod a+x ktlint && - sudo mv ktlint /usr/local/bin/ -``` - -... or just download `ktlint` from the [releases](https://github.com/pinterest/ktlint/releases) page - -* `ktlint.asc` contains PGP signature which you can verify with: - * (Releases up through 0.31.0) `curl -sS https://keybase.io/shyiko/pgp_keys.asc | gpg --import && gpg --verify ktlint.asc` - * (Releases from 0.32.0 on) `curl -sS https://keybase.io/ktlint/pgp_keys.asc | gpg --import && gpg --verify ktlint.asc` - -On macOS ([or Linux](https://docs.brew.sh/Homebrew-on-Linux)) you can also use [brew](https://brew.sh/) - `brew install ktlint` - or [MacPorts](https://www.macports.org/) - `port install ktlint`. -On Arch Linux, you can install [ktlint](https://aur.archlinux.org/packages/ktlint/) AUR. - -> If you don't have curl installed - replace `curl -sL` with `wget -qO-`. - -> If you are behind a proxy see - -[curl](https://curl.haxx.se/docs/manpage.html#ENVIRONMENT) / -[wget](https://www.gnu.org/software/wget/manual/wget.html#Proxies) manpage. -Usually simple `http_proxy=http://proxy-server:port https_proxy=http://proxy-server:port curl -sL ...` is enough. - -## Command line usage - -```bash -# Get help about all available commands -$ ktlint --help - -# Check the style of all Kotlin files (ending with '.kt' or '.kts') inside the current dir (recursively). -# Hidden folders will be skipped. -$ ktlint - -# Check only certain locations starting from the current directory. -# -# Prepend ! to negate the pattern, KtLint uses .gitignore pattern style syntax. -# Globs are applied starting from the last one. -# -# Hidden folders will be skipped. -# Check all '.kt' files in 'src/' directory, but ignore files ending with 'Test.kt': -ktlint "src/**/*.kt" "!src/**/*Test.kt" -# Check all '.kt' files in 'src/' directory, but ignore 'generated' directory and its subdirectories: -ktlint "src/**/*.kt" "!src/**/generated/**" - -# Auto-correct style violations. -# If some errors cannot be fixed automatically they will be printed to stderr. -$ ktlint -F "src/**/*.kt" - -# Print style violations grouped by file. -$ ktlint --reporter=plain?group_by_file - -# Print style violations as usual + create report in checkstyle format, specifying report location. -$ ktlint --reporter=plain --reporter=checkstyle,output=ktlint-report-in-checkstyle-format.xml - -# Check against a baseline file. -$ ktlint --baseline=ktlint-baseline.xml - -# Install git hook to automatically check files for style violations on commit. -# Run "ktlint installGitPrePushHook" if you wish to run ktlint on push instead. -$ ktlint installGitPreCommitHook -``` - -> on Windows you'll have to use `java -jar ktlint ...`. - -`ktlint --help` for more. - -### Integration - -#### ... with [Maven](https://github.com/shyiko/mvnw) - -> pom.xml - -```xml -... - - org.apache.maven.plugins - maven-antrun-plugin - 1.8 - - - ktlint - verify - - - - - - - - - - - run - - - ktlint-format - - - - - - - - - run - - - - - com.pinterest - ktlint - 0.46.1 - - - - -... -``` - -> If you want ktlint to run before code compilation takes place - change `verify` to `validate` (see [Maven Build Lifecycle](https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html) for more). - -To check code style - `mvn antrun:run@ktlint` (it's also bound to `mvn verify`). -To run formatter - `mvn antrun:run@ktlint-format`. - -**Another option** is to use a dedicated Maven plugin - [gantsign/ktlint-maven-plugin](https://github.com/gantsign/ktlint-maven-plugin). - -#### ... with [Gradle](https://gradle.org/) - -#### (with a plugin - Recommended) - -Gradle plugins (in order of appearance): -- [jlleitschuh/ktlint-gradle](https://github.com/jlleitschuh/ktlint-gradle) -Gradle plugin that automatically creates check and format tasks for project Kotlin sources, -supports different kotlin plugins and Gradle build caching. - -- [jeremymailen/kotlinter-gradle](https://github.com/jeremymailen/kotlinter-gradle) -Gradle plugin featuring incremental build support, file reports, and `*.kts` source support. - -You might also want to take a look at [diffplug/spotless](https://github.com/diffplug/spotless/tree/master/plugin-gradle#applying-ktlint-to-kotlin-files) or [autostyle/autostyle](https://github.com/autostyle/autostyle/tree/master/plugin-gradle#applying-ktlint-to-kotlin-files) that have a built-in support for ktlint. In addition to linting/formatting kotlin code it allows you to keep license headers, markdown documentation, etc. in check. - -#### (without a plugin) - -> build.gradle - -```groovy -// kotlin-gradle-plugin must be applied for configuration below to work -// (see https://kotlinlang.org/docs/reference/using-gradle.html) - -apply plugin: 'java' - -repositories { - mavenCentral() -} - -configurations { - ktlint -} - -dependencies { - ktlint("com.pinterest:ktlint:0.46.1") { - attributes { - attribute(Bundling.BUNDLING_ATTRIBUTE, getObjects().named(Bundling, Bundling.EXTERNAL)) - } - } - // additional 3rd party ruleset(s) can be specified here - // just add them to the classpath (e.g. ktlint 'groupId:artifactId:version') and - // ktlint will pick them up -} - -task ktlint(type: JavaExec, group: "verification") { - description = "Check Kotlin code style." - classpath = configurations.ktlint - mainClass.set("com.pinterest.ktlint.Main") - args "src/**/*.kt" - // to generate report in checkstyle format prepend following args: - // "--reporter=plain", "--reporter=checkstyle,output=${buildDir}/ktlint.xml" - // to add a baseline to check against prepend following args: - // "--baseline=ktlint-baseline.xml" - // see https://github.com/pinterest/ktlint#usage for more -} -check.dependsOn ktlint - -task ktlintFormat(type: JavaExec, group: "formatting") { - description = "Fix Kotlin code style deviations." - classpath = configurations.ktlint - mainClass.set("com.pinterest.ktlint.Main") - args "-F", "src/**/*.kt" -} -``` - -To check code style - `gradle ktlint` (it's also bound to `gradle check`). -To run formatter - `gradle ktlintFormat`. - -See [Making your Gradle tasks incremental](https://proandroiddev.com/making-your-gradle-tasks-incremental-7f26e4ef09c3) by [Niklas Baudy](https://github.com/vanniktech) on how to make tasks above incremental. - - -#### (without a plugin) for Gradle Kotlin DSL (build.gradle.kts) - -> build.gradle.kts - -```kotlin -val ktlint by configurations.creating - -dependencies { - ktlint("com.pinterest:ktlint:0.46.1") { - attributes { - attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.EXTERNAL)) - } - } - // ktlint(project(":custom-ktlint-ruleset")) // in case of custom ruleset -} - -val outputDir = "${project.buildDir}/reports/ktlint/" -val inputFiles = project.fileTree(mapOf("dir" to "src", "include" to "**/*.kt")) - -val ktlintCheck by tasks.creating(JavaExec::class) { - inputs.files(inputFiles) - outputs.dir(outputDir) - - description = "Check Kotlin code style." - classpath = ktlint - mainClass.set("com.pinterest.ktlint.Main") - args = listOf("src/**/*.kt") -} - -val ktlintFormat by tasks.creating(JavaExec::class) { - inputs.files(inputFiles) - outputs.dir(outputDir) - - description = "Fix Kotlin code style deviations." - classpath = ktlint - mainClass.set("com.pinterest.ktlint.Main") - args = listOf("-F", "src/**/*.kt") -} -``` - -#### ... with [IntelliJ IDEA](https://www.jetbrains.com/idea/) - -> It is recommended to align the settings of IntelliJ IDEA's built-in formatter with ktlint. This reduces the chance that code which is formatted by ktlint conflicts with formatting by the IntelliJ IDEA built-in formatter. - -Choose any of options below to align the formatting settings of IntelliJ IDEA. - -##### Update code style of single project via ktlint (recommended) -Use ktlint to change the code style of a single project with any of the commands below. -```sh -# Run command below from root directory of project -ktlint applyToIDEAProject -``` -Or if you want to use android specific code style: - -```sh -# Run command below from root directory of project -ktlint --android applyToIDEAProject -``` - -##### Update global code style for all projects via ktlint -Use ktlint to change the code style of all projects with any of the commands below. -```sh -ktlint applyToIDEA -``` -Or if you want to use android specific code style: -```sh -ktlint --android applyToIDEA -``` - -##### Manually update `.editorconfig` - -Create or update the code style config with `.editorconfig` by setting properties below: -```ini -[{*.kt,*.kts}] -ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL - -ij_kotlin_line_comment_at_first_column = false -ij_kotlin_line_comment_add_space = true - -# These options can keep to use single name import -ij_kotlin_name_count_to_use_star_import = 2147483647 -ij_kotlin_name_count_to_use_star_import_for_members = 2147483647 - -ij_kotlin_keep_blank_lines_in_declarations = 1 -ij_kotlin_keep_blank_lines_in_code = 1 -ij_kotlin_keep_blank_lines_before_right_brace = 0 - -# optional but recommended -ij_kotlin_align_multiline_parameters = false - -# optional but recommended -ij_continuation_indent_size = 4 - -# Android specific rules -ij_kotlin_import_nested_classes = false -ij_kotlin_imports_layout = *,^ -``` - -##### Manually update the IntelliJ IDEA preferences - -Go to File -> Settings... -> Editor -- General -> Auto Import - - check `Kotlin` / `Optimize imports on the fly (for current project)`. -- Code Style -> Kotlin - - Set from... on the right -> (Predefined style) -> Kotlin style guide (Kotlin plugin 1.2.20+). - - open Code Generation tab - - uncheck `Line comment at first column`; - - select `Add a space at comment start`. - - open Imports tab - - select `Use single name import` (all of them); - - remove `import java.util.*` from `Packages to Use Import with '*'`. - - open Blank Lines tab - - change `Keep Maximum Blank Lines` / `In declarations` & `In code` to 1 and `Before '}'` to 0. - - (optional but recommended) open Wrapping and Braces tab - - uncheck `Function declaration parameters` (OR `Methods declartion parameters` for older version) / `Align when multiline`. - - (optional but recommended) open Tabs and Indents tab - - change `Continuation indent` to the same value as `Indent` (4 by default). -- Inspections - - change `Severity` level of `Unused import directive` and `Redundant semicolon` under `Kotlin` -> `Redundant constructs` to `ERROR`. - -#### ... with [GNU Emacs](https://www.gnu.org/software/emacs/) - -See [whirm/flycheck-kotlin](https://github.com/whirm/flycheck-kotlin). - -#### ... with [Vim](https://www.vim.org/) - -See [w0rp/ale](https://github.com/w0rp/ale). - -> Integrated with something else? Send a PR. - -#### ... with Continuous Integration - -See [Mega-Linter](https://nvuillam.github.io/mega-linter/): 70+ linters aggregated in a single tool for CI, including **ktlint** activated out of the box - -## Creating a ruleset - -> See also [Writing your first ktlint rule](https://medium.com/@vanniktech/writing-your-first-ktlint-rule-5a1707f4ca5b) by [Niklas Baudy](https://github.com/vanniktech). - -In a nutshell: "ruleset" is a JAR containing one or more [Rule](ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/Rule.kt)s gathered together in a [RuleSet](/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/RuleSet.kt). `ktlint` is relying on -[ServiceLoader](https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html) to discover all available "RuleSet"s -on the classpath (as a ruleset author, all you need to do is to include a `META-INF/services/com.pinterest.ktlint.core.RuleSetProvider` file -containing a fully qualified name of your [RuleSetProvider](ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/RuleSetProvider.kt) implementation). - -Once packaged in a JAR [e.g. via `./gradlew build`](https://github.com/pinterest/ktlint/issues/300#issuecomment-432408753) you can load it with - -```sh -# enable additional 3rd party ruleset by pointing ktlint to its location on the file system -$ ktlint -R /path/to/custom/rulseset.jar "src/test/**/*.kt" -``` - -Loading custom (3rd party) ruleset via built-in maven dependency resolver is deprecated, -see https://github.com/pinterest/ktlint/issues/451. - -A complete sample project (with tests and build files) is included in this repo under the [ktlint-ruleset-template](ktlint-ruleset-template) directory -(make sure to check [NoVarRuleTest](ktlint-ruleset-template/src/test/kotlin/yourpkgname/NoVarRuleTest.kt) as it contains some useful information). - -#### AST - -While writing/debugging [Rule](ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/Rule.kt)s it's often helpful to have an AST -printed out to see the structure rules have to work with. ktlint >= 0.15.0 has a `printAST` subcommand (or `--print-ast` flag for ktlint < 0.34.0) specifically for this purpose -(usage: `ktlint --color printAST `). -An example of the output is shown below. - -```sh -$ printf "fun main() {}" | ktlint --color printAST --stdin - -1: ~.psi.KtFile (~.psi.stubs.elements.KtFileElementType.kotlin.FILE) -1: ~.psi.KtPackageDirective (~.psi.stubs.elements.KtPlaceHolderStubElementType.PACKAGE_DIRECTIVE) "" -1: ~.psi.KtImportList (~.psi.stubs.elements.KtPlaceHolderStubElementType.IMPORT_LIST) "" -1: ~.psi.KtScript (~.psi.stubs.elements.KtScriptElementType.SCRIPT) -1: ~.psi.KtBlockExpression (~.KtNodeType.BLOCK) -1: ~.psi.KtNamedFunction (~.psi.stubs.elements.KtFunctionElementType.FUN) -1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtKeywordToken.fun) "fun" -1: ~.c.i.p.impl.source.tree.PsiWhiteSpaceImpl (~.c.i.p.tree.IElementType.WHITE_SPACE) " " -1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtToken.IDENTIFIER) "main" -1: ~.psi.KtParameterList - (~.psi.stubs.elements.KtPlaceHolderStubElementType.VALUE_PARAMETER_LIST) -1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.LPAR) "(" -1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.RPAR) ")" -1: ~.c.i.p.impl.source.tree.PsiWhiteSpaceImpl (~.c.i.p.tree.IElementType.WHITE_SPACE) " " -1: ~.psi.KtBlockExpression (~.KtNodeType.BLOCK) -1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.LBRACE) "{" -1: ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.RBRACE) "}" - - format: () "" - legend: ~ = org.jetbrains.kotlin, c.i.p = com.intellij.psi - -``` - -## Creating a reporter - -Take a look at [ktlint-reporter-plain](ktlint-reporter-plain). - -In short, all you need to do is to implement a -[Reporter](ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/Reporter.kt) and make it available by registering -a custom [ReporterProvider](ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/ReporterProvider.kt) using -`META-INF/services/com.pinterest.ktlint.core.ReporterProvider`. Pack all of that into a JAR and you're done. - -To load a custom (3rd party) reporter use `ktlint --reporter=name,artifact=/path/to/custom-ktlint-reporter.jar` -(see `ktlint --help` for more). - -Loading custom (3rd party) reporter via built-in maven dependency resolver is deprecated, -see https://github.com/pinterest/ktlint/issues/451. - -Third-party: -* [kryanod/ktlint-junit-reporter](https://github.com/kryanod/ktlint-junit-reporter) -* [musichin/ktlint-github-reporter](https://github.com/musichin/ktlint-github-reporter) -* [tobi2k/ktlint-gitlab-reporter](https://github.com/tobi2k/ktlint-gitlab-reporter) - -## Badge - -[![ktlint](https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg)](https://ktlint.github.io/) - -```md -[![ktlint](https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg)](https://ktlint.github.io/) -``` - -## FAQ - -### Why should I use ktlint? - -**Simplicity**. - -Spending time on configuration (& maintenance down the road) of hundred-line long style config file(s) is counter-productive. Instead of wasting your energy on something that has no business value - focus on what really matters (not debating whether to use tabs or spaces). - -By using ktlint you put the importance of code clarity and community conventions over personal preferences. This makes things easier for people reading your code as well as frees you from having to document & explain what style potential contributor(s) have to follow. - -ktlint is a single binary with both linter & formatter included. All you need is to drop it in (no need to get [overwhelmed](https://en.wikipedia.org/wiki/Decision_fatigue) while choosing among [dozens of code style options](https://checkstyle.sourceforge.net/checks.html)). - -### Can I have my own rules on top of ktlint? - -Absolutely, "no configuration" doesn't mean "no extensibility". You can add your own ruleset(s) to discover potential bugs, check for anti-patterns, etc. - -See [Creating A Ruleset](#creating-a-ruleset). - -### How do I suppress an errors for a line/block/file? - -> This is meant primarily as an escape latch for the rare cases when **ktlint** is not able -to produce the correct result (please report any such instances using [GitHub Issues](https://github.com/pinterest/ktlint/issues)). - -To disable a specific rule you'll need the rule identifier which is displayed at the end of the lint error. Note that when the rule id is prefixed with a rule set id like `experimental`, you will need to use that fully qualified rule id. - -An error can be suppressed using: - -* EOL comments -* Block comments -* @Suppress annotations - -From a consistency perspective seen, it might be best to **not** mix the (EOL/Block) comment style with the annotation style in the same project. - -Important notice: some rules like the `indent` rule do not yet support disabling of the rule per line of block. - -#### Disabling for one specific line using EOL comment - -An error for a specific rule on a specific line can be disabled with an EOL comment on that line: - -```kotlin -import package.* // ktlint-disable no-wildcard-imports -``` - -In case lint errors for different rules on the same line need to be ignored, then specify multiple rule ids (separated by a space): - -```kotlin -import package.* // ktlint-disable no-wildcard-imports other-rule-id -``` - -In case all lint errors on a line need to be ignored, then do not specify the rule id at all: - -```kotlin -import package.* // ktlint-disable -``` - -#### Disabling for a block of lines using Block comments - -An error for a specific rule in a block of lines can be disabled with an block comment like: - -```kotlin -/* ktlint-disable no-wildcard-imports */ -import package.a.* -import package.b.* -/* ktlint-enable no-wildcard-imports */ -``` - -In case lint errors for different rules in the same block of lines need to be ignored, then specify multiple rule ids (separated by a space): - -```kotlin -/* ktlint-disable no-wildcard-imports other-rule-id */ -import package.a.* -import package.b.* -/* ktlint-enable no-wildcard-imports,other-rule-id */ -``` - -Note that the `ktlint-enable` directive needs to specify the exact same rule-id's and in the same order as the `ktlint-disable` directive. - -In case all lint errors in a block of lines needs to be ignored, then do not specify the rule id at all: - -```kotlin -/* ktlint-disable */ -import package.a.* -import package.b.* -/* ktlint-enable */ -``` - -#### Disabling for a statement using @Suppress - -> As of ktlint version 0.46, it is possible to specify any ktlint rule id via the `@Suppress` annotation in order to suppress errors found by that rule. Note that some rules like `indent` still do not support disabling for parts of a file. - -An error for a specific rule on a specific line can be disabled with a `@Suppress` annotation: - -```kotlin -@Suppress("ktlint:max-line-length","ktlint:experimental:trailing-comma") -val foo = listOf( - "some really looooooooooooooooong string exceeding the max line length", - ) -``` - -Note that when using `@Suppress` each qualified rule id needs to be prefixed with `ktlint:`. - -To suppress the violations of all ktlint rules, use: -```kotlin -@Suppress("ktlint") -val foo = "some really looooooooooooooooong string exceeding the max line length" -``` - -Like with other `@Suppress` annotations, it can be placed on targets supported by the annotation. As of this it is possible to disable rules in the entire file with: -```kotlin -@file:Suppress("ktlint") // Suppressing all rules for the entire file -// or -@file:Suppress("ktlint:max-line-length","ktlint:experimental:trailing-comma") // Suppressing specific rules for the entire file -``` - - -### How do I globally disable a rule? -See the [EditorConfig section](https://github.com/pinterest/ktlint#editorconfig) for details on how to use the `disabled_rules` property. - -You may also pass a list of disabled rules via the `--disabled_rules` command line flag. It has the same syntax as the EditorConfig property. - -## Development - -> Make sure to read [CONTRIBUTING.md](CONTRIBUTING.md). - -```sh -git clone https://github.com/pinterest/ktlint && cd ktlint -./gradlew tasks # shows how to build, test, run, etc. project -``` - -> To open ktlint in Intellij IDEA: -File -> Open... (you may need to right-click on `pom.xml` (in the project dir) and then Maven -> Reimport). -You'll also need to set "Project SDK" to [1.8](https://github.com/shyiko/jabba#usage), "Project language level" to 8 in "Project Settings" (File -> Project Structure...). -To run `ktlint` - right-click on `ktlint/src/main/kotlin/com/pinterest/ktlint/Main.kt` -> Run. - -#### Access to the latest `master` snapshot - -Whenever a commit is added to the `master` branch a snapshot build is automatically uploaded to [Sonatype's snapshots repository](https://oss.sonatype.org/content/repositories/snapshots/com/pinterest/ktlint/). -If you are eager to try upcoming changes (that might or might not be included in the next stable release) you can do -so by changing version of ktlint to `-SNAPSHOT` + adding a repo: - -##### Maven - -```xml -... - - sonatype-snapshots - https://oss.sonatype.org/content/repositories/snapshots - - true - - - false - - -... -``` - -##### Gradle +- No configuration required +- Built-in Rule sets +- Built-in formatter +- `.editorconfig` support +- Several built-in reporters: `plain`, `json`, `html` and `checkstyle` +- Executable jar +- Allows extension with custom rule sets and reporters -```groovy -repositories { - maven { - url "https://oss.sonatype.org/content/repositories/snapshots" - } -} -``` +## Documentation -##### Kotlin development version snapshot +User guide -Additionally, project publishes snapshots build against latest kotlin development version. To use them, change version -of ktlint to `-kotlin-dev-SNAPSHOT`. -## Legal +### Legal This project is not affiliated with nor endorsed by JetBrains. All code, unless specified otherwise, is licensed under the [MIT](https://opensource.org/licenses/MIT) license. diff --git a/docs/extensions/badge.md b/docs/extensions/badge.md index cfb1833e30..40b87210b4 100644 --- a/docs/extensions/badge.md +++ b/docs/extensions/badge.md @@ -1,6 +1,6 @@ If you want to display a badge to show that your project is linted and formatted using `'ktlint` than you can add the -[![ktlint](https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg)](https://ktlint.github.io/) badge: +[![ktlint](https://img.shields.io/badge/ktlint%20code--style-%E2%9D%A4-FF4081)](https://pinterest.github.io/ktlint/) badge: ```md title="Ktlint code style badge" -[![ktlint](https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg)](https://ktlint.github.io/) +[![ktlint](https://img.shields.io/badge/ktlint%20code--style-%E2%9D%A4-FF4081)](https://pinterest.github.io/ktlint/) ``` diff --git a/docs/index.md b/docs/index.md index 02686d46dc..6807013165 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,7 +1,7 @@ # Welcome to Ktlint

- +

@@ -9,7 +9,7 @@ Join the chat at https://kotlinlang.slack.com Build status Maven Central -ktlint +ktlint

Kotlin linter in spirit of feross/standard (JavaScript) and gofmt (Go). diff --git a/docs/install/cli.md b/docs/install/cli.md index cae9b9515f..249ef3a5a2 100644 --- a/docs/install/cli.md +++ b/docs/install/cli.md @@ -52,18 +52,40 @@ On Arch Linux install package [ktlint AUR](https://aur.archlinux.org/ ## Command line usage -A good starting point is to read the help page: +### Rule set(s) -```shell title="Get help about all available commands" -ktlint --help -``` - -When no arguments are specified, the style of all Kotlin files (ending with '.kt' or '.kts') inside the current dir (recursively) are validated with the rules from the [standard ruleset](https://ktlint.github.io/rules/standard/). Hidden folders will be skipped. +When no arguments are specified, the style of all Kotlin files (ending with '.kt' or '.kts') inside the current dir (recursively) are validated with the rules from the [standard ruleset](https://pinterest.github.io/ktlint/rules/standard/). Hidden folders will be skipped. ```shell title="Default validation with standard ruleset" ktlint ``` +To validate with the [standard ruleset](https://pinterest.github.io/ktlint/rules/standard/) and the [experimental rulesset](https://pinterest.github.io/ktlint/rules/experimental/) run command below: + +```shell title="Validation with standard and experimental ruleset" +ktlint --experimental +``` + +To validate with a [custom ruleset](https://pinterest.github.io/ktlint/extensions/custom-rule-set/) run command below: + +```shell title="Validation with standard and a custom ruleset" +ktlint --ruleset=/path/to/custom-ruleset.jar +# or +ktlint -R /path/to/custom-ruleset.jar +``` + +### Format (autocorrect) + +Most style violations can be corrected automatically. Errors that can not be corrected, are printed to `stderr`. + +```shell title="Autocorrect style violations" +ktlint --format +# or +ktlint -F +``` + +### Globs + Globs can be used to specify more exactly what files and directories are to be validated. `ktlint` uses the [`.gitignore` pattern style syntax for globs](https://git-scm.com/docs/gitignore). Globs are processed from left to right. Prepend a glob with `!` to negate it. Hidden folders will be skipped. ```shell title="Check only certain locations starting from the current directory" @@ -74,11 +96,7 @@ ktlint "src/**/*.kt" "!src/**/*Test.kt" ktlint "src/**/*.kt" "!src/**/generated/**" ``` -Most style violations can be corrected automatically. Errors that can not be corrected, are printed to `stderr`. - -```shell title="Auto-correct style violations" -$ ktlint -F -``` +### Error reporting `ktlint` supports different type of reporters. When not specified the `plain` reporter is used. Optionally the `plain` reporter can group the violations per file. @@ -86,6 +104,8 @@ $ ktlint -F $ ktlint --reporter=plain?group_by_file ``` +Other built-in reporters are: `json`, `sarif`, `checkstyle`, and `html` + Style violations can be written to an output file which is convenient when multiple reporters are specified. In example below, the plain reporter is used to write to the console while the checkstyle reports is written to a file: ```shell title="Multiple reporters" @@ -98,6 +118,51 @@ If resolving all existing errors in a project is unwanted, it is possible to cre ktlint --baseline=ktlint-baseline.xml # Baseline is created when not existing ``` +### Rule configuration (`.editorconfig`) + +Some rules can be tweaked via the [`editorconfig file`](https://pinterest.github.io/ktlint/rules/configuration/). + +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 +# or +ktlint --experimental generateEditorConfig +# or +ktlint --experimental --ruleset=/path/to/custom-ruleset.jar generateEditorConfig +``` + +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. + +With command below, an `editorconfig` file of an alternative location can be used to configure ktlint: + +```shell title="Override '.editorconfig'" +ktlint --editorconfig=/path/to/.editorconfig +``` + +!!! warning "Overrides '.editorconfig' in project directory" + When specifying this option, all `.editorconfig` files in the project directory are being ignored. + +### Stdin && stdout + +With command below, the input is read from `stdin` and the violations are printed to `stderr`. + +```shell title="Lint from stdin" +ktlint --stdin +``` + +When combined with the `--format` option, the formatted code is written to `stdout` and the violations are printed to `stderr`: + +```shell title="Format from stdin and write to stdout" +ktlint --stdin -F +``` + +!!! tip Suppress error output + Output printed to `stderr` can be suppressed in different ways. To ignore all error output, add `2> /dev/null` to the end of the command line. Otherwise, specify a [reporter](#error-reporting) to write the error output to a file. + + +### Git hooks + Predefined git hooks can be installed, to automatically validate lint errors before commit or push. ```shell title="Install git pre-commit hook" @@ -108,5 +173,31 @@ ktlint installGitPreCommitHook ktlint installGitPrePushHook ``` +### Miscellaneous flags and commands + +`-a` or `--android`: Turn on Android Kotlin Style Guide compatibility. This flag is most likely to be removed in a future version. Use `.editorconfig ktlint_code_style`(https://pinterest.github.io/ktlint/rules/configuration/#code-style). + +`applyToIDEA` or `--apply-to-idea`: Update Intellij IDEA Kotlin codestyle settings (global) + +`applyToIDEAProject` or `--apply-to-idea-project`: Update Intellij IDEA project settings + +`--color` and `--color-name=`: Make output colorful and optionally set the color name to use. + +`--disabled_rules=`: A comma-separated list of rules to globally disable. To disable the standard ktlint rule-set use `--disabled_rules=standard`. This flag is most likely to be removed in a future version. Use `.editorconfig disabled_rules`(https://pinterest.github.io/ktlint/rules/configuration/#disabled-rules). + +`-h` or `--help`: Prints help information. + +`--limit=`: Maximum number of errors to show (default: show all) + +`printAST` or `--print-ast`: Prints AST (useful when writing/debugging rules) + +`--relative`: Print files relative to the working directory (e.g. dir/file.kt instead of /home/user/project/dir/file.kt) + +`-v`, `--verbose` or `--debug`: Turn on debug output. Also option `--trace` is available, but this is meant for ktlint library developers. + +`-V` or `--version`: Prints version information and exit. + +### Microsoft Windows users + !!! tip "Microsoft Windows" On Microsoft Windows you'll have to use `java -jar ktlint ...`. diff --git a/docs/install/integrations.md b/docs/install/integrations.md index fb066eb444..c876fe3fb5 100644 --- a/docs/install/integrations.md +++ b/docs/install/integrations.md @@ -22,7 +22,7 @@ See [cli usage](../cli) for arguments that can be supplied to `ktlint`. - + @@ -38,7 +38,7 @@ See [cli usage](../cli) for arguments that can be supplied to `ktlint`. classpathref="maven.plugin.classpath" classname="com.pinterest.ktlint.Main"> - + @@ -125,7 +125,7 @@ task ktlint(type: JavaExec, group: "verification") { classpath = configurations.ktlint mainClass.set("com.pinterest.ktlint.Main") args "src/**/*.kt" - // see https://ktlint.github.io/install/cli/#command-line-usage for more information + // see https://pinterest.github.io/ktlint/install/cli/#command-line-usage for more information } check.dependsOn ktlint @@ -134,7 +134,7 @@ task ktlintFormat(type: JavaExec, group: "formatting") { classpath = configurations.ktlint mainClass.set("com.pinterest.ktlint.Main") args "-F", "src/**/*.kt" - // see https://ktlint.github.io/install/cli/#command-line-usage for more information + // see https://pinterest.github.io/ktlint/install/cli/#command-line-usage for more information } ``` @@ -172,7 +172,7 @@ val ktlintCheck by tasks.creating(JavaExec::class) { description = "Check Kotlin code style." classpath = ktlint mainClass.set("com.pinterest.ktlint.Main") - // see https://ktlint.github.io/install/cli/#command-line-usage for more information + // see https://pinterest.github.io/ktlint/install/cli/#command-line-usage for more information args = listOf("src/**/*.kt") } @@ -183,7 +183,7 @@ val ktlintFormat by tasks.creating(JavaExec::class) { description = "Fix Kotlin code style deviations." classpath = ktlint mainClass.set("com.pinterest.ktlint.Main") - // see https://ktlint.github.io/install/cli/#command-line-usage for more information + // see https://pinterest.github.io/ktlint/install/cli/#command-line-usage for more information args = listOf("-F", "src/**/*.kt") } ``` 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 2b87ef4053..8440757d73 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 @@ -47,10 +47,24 @@ public interface UsesEditorConfigProperties { require(editorConfigProperties.contains(editorConfigProperty)) { "EditorConfigProperty '${editorConfigProperty.type.name}' may only be retrieved when it is registered in the editorConfigProperties." } - val codeStyle = getEditorConfigValue(codeStyleSetProperty, official) - return getEditorConfigValue(editorConfigProperty, codeStyle) + + return getEditorConfigValue(editorConfigProperty, getEditorConfigCodeStyle()) } + /** + * The code style property does not need to be defined in the [editorConfigProperties] of the class that defines + * this interface. Those classed should not need to be aware of the different coding styles except when setting + * different default values. As the property is not defined in the [editorConfigProperties] the value needs to + * be parsed explicitly to prevent class cast exceptions. + */ + private fun EditorConfigProperties.getEditorConfigCodeStyle() = + codeStyleSetProperty + .type + .parse( + get(codeStyleSetProperty.type.name)?.sourceValue + ).parsed + ?: official + /** * Get the value of [EditorConfigProperty] based on loaded [EditorConfigProperties] content for the current * [ASTNode]. @@ -61,8 +75,10 @@ public interface UsesEditorConfigProperties { "EditorConfigProperty '${editorConfigProperty.type.name}' may only be retrieved when it is registered in the editorConfigProperties." } val editorConfigPropertyValues = getUserData(KtLint.EDITOR_CONFIG_PROPERTIES_USER_DATA_KEY)!! - val codeStyle = editorConfigPropertyValues.getEditorConfigValue(codeStyleSetProperty, official) - return editorConfigPropertyValues.getEditorConfigValue(editorConfigProperty, codeStyle) + return editorConfigPropertyValues.getEditorConfigValue( + editorConfigProperty, + editorConfigPropertyValues.getEditorConfigCodeStyle() + ) } private fun EditorConfigProperties.getEditorConfigValue( 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 693e08a8c4..1491d1c7fc 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 @@ -38,12 +38,17 @@ internal object SuppressionLocatorBuilder { val hintsList = collect(rootNode) return if (hintsList.isEmpty()) { noSuppression - } else { offset, ruleId, isRoot -> + } else { + toSuppressedRegionsLocator(hintsList) + } + } + + private fun toSuppressedRegionsLocator(hintsList: List): SuppressionLocator = + { offset, ruleId, isRoot -> hintsList .filter { offset in it.range } .any { hint -> hint.disabledRules.isEmpty() || hint.disabledRules.contains(ruleId) } } - } /** * @param range zero-based range of lines where lint errors should be suppressed diff --git a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigGeneratorTest.kt b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigGeneratorTest.kt index 8a56ddda6c..152b84bedb 100644 --- a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigGeneratorTest.kt +++ b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/EditorConfigGeneratorTest.kt @@ -211,7 +211,7 @@ internal class EditorConfigGeneratorTest { autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit ) { - TODO("Not yet implemented") + throw UnsupportedOperationException("This method is not expected to be called") } } diff --git a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/RuleRunnerSorterTest.kt b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/RuleRunnerSorterTest.kt index b120a17660..b7bb00af6a 100644 --- a/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/RuleRunnerSorterTest.kt +++ b/ktlint-core/src/test/kotlin/com/pinterest/ktlint/core/internal/RuleRunnerSorterTest.kt @@ -215,7 +215,7 @@ class RuleRunnerSorterTest { ) } - @ParameterizedTest(name = "Rule id: {0}, expected result: {1}") + @ParameterizedTest(name = "Rule id: {0}") @ValueSource( strings = [ RULE_A, diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationSpacingRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationSpacingRule.kt index 5eda6f5311..ab17502d4b 100644 --- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationSpacingRule.kt +++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/AnnotationSpacingRule.kt @@ -73,7 +73,9 @@ class AnnotationSpacingRule : Rule("annotation-spacing") { val s = it.text // Ensure at least one occurrence of two line breaks s.indexOf("\n") != s.lastIndexOf("\n") - } else it.isPartOfComment() && !it.isCommentOnSameLineAsPrevLeaf() + } else { + it.isPartOfComment() && !it.isCommentOnSameLineAsPrevLeaf() + } } ) if (next != null) { 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 ac5c93f170..87ee66ffb6 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 @@ -1,17 +1,26 @@ package com.pinterest.ktlint.ruleset.standard +import com.pinterest.ktlint.core.IndentConfig import com.pinterest.ktlint.core.Rule +import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties +import com.pinterest.ktlint.core.api.EditorConfigProperties +import com.pinterest.ktlint.core.api.UsesEditorConfigProperties +import com.pinterest.ktlint.core.ast.ElementType.BLOCK import com.pinterest.ktlint.core.ast.ElementType.ELSE import com.pinterest.ktlint.core.ast.ElementType.ELSE_KEYWORD +import com.pinterest.ktlint.core.ast.ElementType.IF import com.pinterest.ktlint.core.ast.ElementType.LBRACE import com.pinterest.ktlint.core.ast.ElementType.RBRACE import com.pinterest.ktlint.core.ast.ElementType.RPAR import com.pinterest.ktlint.core.ast.ElementType.THEN +import com.pinterest.ktlint.core.ast.ElementType.WHITE_SPACE import com.pinterest.ktlint.core.ast.isPartOfComment +import com.pinterest.ktlint.core.ast.isWhiteSpace import com.pinterest.ktlint.core.ast.isWhiteSpaceWithoutNewline -import com.pinterest.ktlint.core.ast.prevLeaf +import com.pinterest.ktlint.core.ast.lineIndent +import com.pinterest.ktlint.core.ast.nextSibling +import com.pinterest.ktlint.core.ast.upsertWhitespaceBeforeMe import org.jetbrains.kotlin.com.intellij.lang.ASTNode -import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl import org.jetbrains.kotlin.psi.KtBlockExpression @@ -20,50 +29,100 @@ import org.jetbrains.kotlin.psi.psiUtil.leaves /** * https://kotlinlang.org/docs/reference/coding-conventions.html#formatting-control-flow-statements */ -class MultiLineIfElseRule : Rule("multiline-if-else") { +class MultiLineIfElseRule : + Rule("multiline-if-else"), + UsesEditorConfigProperties { + override val editorConfigProperties: List> = + listOf( + DefaultEditorConfigProperties.indentSizeProperty, + DefaultEditorConfigProperties.indentStyleProperty + ) + private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG + + override fun beforeFirstNode(editorConfigProperties: EditorConfigProperties) { + indentConfig = IndentConfig( + indentStyle = editorConfigProperties.getEditorConfigValue(DefaultEditorConfigProperties.indentStyleProperty), + tabWidth = editorConfigProperties.getEditorConfigValue(DefaultEditorConfigProperties.indentSizeProperty) + ) + } + override fun beforeVisitChildNodes( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit ) { if (node.elementType == THEN || node.elementType == ELSE) { - if (!node.treePrev.textContains('\n')) { // if (...) + if (node.firstChildNode?.elementType == BLOCK) { return } - if (node.firstChildNode?.firstChildNode?.elementType != LBRACE) { - emit(node.firstChildNode.startOffset, "Missing { ... }", true) - if (autoCorrect) { - autocorrect(node) + if (!node.treePrev.textContains('\n')) { + if (node.firstChildNode.elementType == IF) { + // Allow single line for: + // else if (...) + return + } + if (!node.treeParent.textContains('\n')) { + // Allow single line if statements as long as they are really simple (e.g. do not contain newlines) + // if (...) // no else statement + // if (...) else + return } } + + emit(node.firstChildNode.startOffset, "Missing { ... }", true) + if (autoCorrect) { + autocorrect(node) + } } } private fun autocorrect(node: ASTNode) { val prevLeaves = - node.leaves(forward = false).takeWhile { it.elementType !in listOf(RPAR, ELSE_KEYWORD) }.toList().reversed() + node + .leaves(forward = false) + .takeWhile { it.elementType !in listOf(RPAR, ELSE_KEYWORD) } + .toList() + .reversed() val nextLeaves = - node.leaves(forward = true).takeWhile { it.isWhiteSpaceWithoutNewline() || it.isPartOfComment() }.toList() - val rightBraceIndent = node.treeParent - .prevLeaf { it is PsiWhiteSpace && it.textContains('\n') }?.text.orEmpty() - .let { "\n${it.substringAfterLast("\n")}" } + node + .leaves(forward = true) + .takeWhile { it.isWhiteSpaceWithoutNewline() || it.isPartOfComment() } + .toList() + .dropLastWhile { it.isWhiteSpaceWithoutNewline() } - (node.treePrev as LeafPsiElement).rawReplaceWithText(" ") + prevLeaves + .firstOrNull() + .takeIf { it.isWhiteSpace() } + ?.let { + (it as LeafPsiElement).rawReplaceWithText(" ") + } KtBlockExpression(null).apply { val previousChild = node.firstChildNode node.replaceChild(node.firstChildNode, this) addChild(LeafPsiElement(LBRACE, "{")) - prevLeaves.forEach(::addChild) + addChild(PsiWhiteSpaceImpl("\n" + node.lineIndent() + indentConfig.indent)) + prevLeaves + .dropWhile { it.isWhiteSpace() } + .forEach(::addChild) addChild(previousChild) nextLeaves.forEach(::addChild) - addChild(PsiWhiteSpaceImpl(rightBraceIndent)) + addChild(PsiWhiteSpaceImpl("\n" + node.lineIndent())) addChild(LeafPsiElement(RBRACE, "}")) } // Make sure else starts on same line as newly inserted right brace - if (node.elementType == THEN && node.treeNext?.treeNext?.elementType == ELSE_KEYWORD) { - node.treeParent.replaceChild(node.treeNext, PsiWhiteSpaceImpl(" ")) + if (node.elementType == THEN) { + node + .nextSibling { !it.isPartOfComment() } + ?.let { nextSibling -> + if (nextSibling.elementType == ELSE_KEYWORD) { + (nextSibling as LeafPsiElement).upsertWhitespaceBeforeMe(" ") + } + if (nextSibling.elementType == WHITE_SPACE && nextSibling.text != " ") { + (nextSibling as LeafPsiElement).rawReplaceWithText(" ") + } + } } } } 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 8ad77b75bd..390935adc9 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 @@ -230,7 +230,7 @@ public class TrailingCommaOnCallSiteRule : /** * The trailing comma isn't needed, but exists */ - REDUNDANT, + REDUNDANT ; } 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 a2cc261141..282acad59e 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 @@ -6,6 +6,7 @@ import com.pinterest.ktlint.core.api.UsesEditorConfigProperties import com.pinterest.ktlint.core.ast.ElementType import com.pinterest.ktlint.core.ast.children import com.pinterest.ktlint.core.ast.containsLineBreakInRange +import com.pinterest.ktlint.core.ast.lineNumber import com.pinterest.ktlint.core.ast.prevCodeLeaf import com.pinterest.ktlint.core.ast.prevLeaf import kotlin.properties.Delegates @@ -15,8 +16,10 @@ import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.PsiElement import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet +import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression import org.jetbrains.kotlin.psi.KtDestructuringDeclaration +import org.jetbrains.kotlin.psi.KtEnumEntry import org.jetbrains.kotlin.psi.KtFunctionLiteral import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtValueArgumentList @@ -68,6 +71,7 @@ public class TrailingCommaOnDeclarationSiteRule : // Keep processing of element types in sync with Intellij Kotlin formatting settings. // https://github.com/JetBrains/intellij-kotlin/blob/master/formatter/src/org/jetbrains/kotlin/idea/formatter/trailingComma/util.kt when (node.elementType) { + ElementType.CLASS -> visitClass(node, emit, autoCorrect) ElementType.DESTRUCTURING_DECLARATION -> visitDestructuringDeclaration(node, autoCorrect, emit) ElementType.FUNCTION_LITERAL -> visitFunctionLiteral(node, autoCorrect, emit) ElementType.TYPE_PARAMETER_LIST -> visitTypeList(node, autoCorrect, emit) @@ -169,6 +173,56 @@ public class TrailingCommaOnDeclarationSiteRule : emit = emit ) } + private fun visitClass( + node: ASTNode, + emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, + autoCorrect: Boolean + ) { + val psi = node.psi + require(psi is KtClass) + + node + .takeIf { psi.isEnum() } + ?.findChildByType(ElementType.CLASS_BODY) + ?.takeUnless { + // Do nothing when last two entries are on same line as no trailing comma should be inserted + it.lastTwoEnumEntriesAreOnSameLine() + }?.let { classBody -> + val nodeAfterTrailingCommaPosition = classBody.findNodeAfterTrailingCommaPosition() + node.reportAndCorrectTrailingCommaNodeBefore( + inspectNode = nodeAfterTrailingCommaPosition, + isTrailingCommaAllowed = node.isTrailingCommaAllowed(), + autoCorrect = autoCorrect, + emit = emit + ) + } + } + + /** + * Determines the [ASTNode] before which the trailing comma is allowed. + * + * If the list of enumeration entries is terminated by a semicolon, that semicolon will be returned. Otherwise, the + * last element of the class. + */ + private fun ASTNode.findNodeAfterTrailingCommaPosition(): ASTNode { + val lastEnumEntry = children().last { it.psi is KtEnumEntry } + + val semicolonAfterLastEnumEntry = lastEnumEntry + .children() + .singleOrNull { it.elementType == ElementType.SEMICOLON } + + return semicolonAfterLastEnumEntry ?: lastChildNode + } + + private fun ASTNode.lastTwoEnumEntriesAreOnSameLine(): Boolean { + val lastTwoEnumEntries = + children() + .filter { it.psi is KtEnumEntry } + .toList() + .takeLast(2) + + return lastTwoEnumEntries.count() == 2 && lastTwoEnumEntries[0].lineNumber() == lastTwoEnumEntries[1].lineNumber() + } private fun ASTNode.reportAndCorrectTrailingCommaNodeBefore( inspectNode: ASTNode, @@ -221,6 +275,20 @@ public class TrailingCommaOnDeclarationSiteRule : prevNode.psi.parent.addAfter(newLine, prevNode.psi) } } + + if (inspectNode.treeParent.elementType == ElementType.ENUM_ENTRY) { + with(KtPsiFactory(prevNode.psi)) { + val parentIndent = (prevNode.psi.parent.prevLeaf() as? PsiWhiteSpace)?.text ?: "\n" + val newline = createWhiteSpace(parentIndent) + val enumEntry = inspectNode.treeParent.psi + enumEntry.apply { + add(newline) + removeChild(inspectNode) + parent.addAfter(createSemicolon(), this) + } + } + } + val comma = KtPsiFactory(prevNode.psi).createComma() prevNode.psi.parent.addAfter(comma, prevNode.psi) } @@ -337,6 +405,7 @@ public class TrailingCommaOnDeclarationSiteRule : ) private val TYPES_ON_DECLARATION_SITE = TokenSet.create( + ElementType.CLASS, ElementType.DESTRUCTURING_DECLARATION, ElementType.FUNCTION_LITERAL, ElementType.FUNCTION_TYPE, @@ -366,6 +435,6 @@ private enum class TrailingCommaState { /** * The trailing comma isn't needed, but exists */ - REDUNDANT, + REDUNDANT ; } diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/FilenameRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/FilenameRuleTest.kt index 3cb8f0375d..47001d2f3a 100644 --- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/FilenameRuleTest.kt +++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/FilenameRuleTest.kt @@ -56,7 +56,7 @@ class FilenameRuleTest { .hasLintViolationWithoutAutoCorrect(1, 1, "File name '$NON_PASCAL_CASE_NAME' should conform PascalCase") } - @ParameterizedTest(name = "Class type: {0}, expected result: {1}") + @ParameterizedTest(name = "Class type: {0}") @ValueSource( strings = [ "class Foo", diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/MultiLineIfElseRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/MultiLineIfElseRuleTest.kt index 2d2e8e0128..8ac7f2403d 100644 --- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/MultiLineIfElseRuleTest.kt +++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/MultiLineIfElseRuleTest.kt @@ -480,7 +480,9 @@ class MultiLineIfElseRuleTest { fun test(a: Int, b: Int, c: Int, d: Int, bar: Boolean) { foo( a, - if (bar) b else { + if (bar) { + b + } else { c }, d @@ -488,8 +490,83 @@ class MultiLineIfElseRuleTest { } """.trimIndent() multiLineIfElseRuleAssertThat(code) - // TODO: It is not consistent that argument "b" is not wrapped in a block while argument "c" is wrapped - .hasLintViolation(6, 13, "Missing { ... }") + .hasLintViolations( + LintViolation(5, 18, "Missing { ... }"), + LintViolation(6, 13, "Missing { ... }") + ).isFormattedAs(formattedCode) + } + + @Test + fun `Issue 1560 - Given an if statement with else keyword on same line as true branch`() { + val code = + """ + fun foo() = if (bar()) + "a" else + "b" + """.trimIndent() + val formattedCode = + """ + fun foo() = if (bar()) { + "a" + } else { + "b" + } + """.trimIndent() + multiLineIfElseRuleAssertThat(code) + .hasLintViolations( + LintViolation(2, 5, "Missing { ... }"), + LintViolation(3, 5, "Missing { ... }") + ).isFormattedAs(formattedCode) + } + + @Test + fun `Issue 828 - Given an if statement with multiline statement starting on same line as if`() { + val code = + """ + fun foo() { + if (true) 50 + .toString() + } + """.trimIndent() + val formattedCode = + """ + fun foo() { + if (true) { + 50 + .toString() + } + } + """.trimIndent() + multiLineIfElseRuleAssertThat(code) + .addAdditionalRuleProvider { IndentationRule() } + .hasLintViolation(2, 15, "Missing { ... }") .isFormattedAs(formattedCode) } + + @Test + fun `Issue 828 - Given an if statement with simple branches but the else branch is on a separate line`() { + val code = + """ + fun foo() { + if (true) 50 + else 55 + } + """.trimIndent() + val formattedCode = + """ + fun foo() { + if (true) { + 50 + } else { + 55 + } + } + """.trimIndent() + multiLineIfElseRuleAssertThat(code) + .addAdditionalRuleProvider { IndentationRule() } + .hasLintViolations( + LintViolation(2, 15, "Missing { ... }"), + LintViolation(3, 10, "Missing { ... }") + ).isFormattedAs(formattedCode) + } } diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoEmptyFirstLineInMethodBlockRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoEmptyFirstLineInMethodBlockRuleTest.kt index 5b18ec898f..4798fc0e26 100644 --- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoEmptyFirstLineInMethodBlockRuleTest.kt +++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/NoEmptyFirstLineInMethodBlockRuleTest.kt @@ -96,7 +96,7 @@ class NoEmptyFirstLineInMethodBlockRuleTest { fun fooBuilder() = object : Foo { override fun foo() { - TODO() + bar() } } """.trimIndent() 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 676892a941..24f1160f6e 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 @@ -4,6 +4,7 @@ import com.pinterest.ktlint.core.RuleProvider import com.pinterest.ktlint.ruleset.standard.TrailingCommaOnDeclarationSiteRule.Companion.allowTrailingCommaProperty import com.pinterest.ktlint.test.KtLintAssertThat import com.pinterest.ktlint.test.LintViolation +import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test class TrailingCommaOnDeclarationSiteRuleTest { @@ -559,4 +560,233 @@ class TrailingCommaOnDeclarationSiteRuleTest { .hasLintViolation(9, 24, "Missing trailing comma before \")\"") .isFormattedAs(formattedCode) } + + @Test + fun `Given that a trailing comma is is not allowed then remove comma after last enum member`() { + val code = + """ + enum class Shape { + SQUARE, + TRIANGLE, + } + """.trimIndent() + val formattedCode = + """ + enum class Shape { + SQUARE, + TRIANGLE + } + """.trimIndent() + ruleAssertThat(code) + .withEditorConfigOverride(allowTrailingCommaProperty to false) + .hasLintViolation(3, 13, "Unnecessary trailing comma before \"}\"") + .isFormattedAs(formattedCode) + } + + @Test + fun `Given that a trailing comma is not allowed then it is removed for enums terminated with semicolon`() { + val code = + """ + enum class Shape { + SQUARE, + TRIANGLE, + ; + fun print() = name() + } + """.trimIndent() + val formattedCode = + """ + enum class Shape { + SQUARE, + TRIANGLE + ; + fun print() = name() + } + """.trimIndent() + ruleAssertThat(code) + .withEditorConfigOverride(allowTrailingCommaProperty to false) + .hasLintViolation(3, 13, "Unnecessary trailing comma before \";\"") + .isFormattedAs(formattedCode) + } + + @Test + fun `Given that a trailing comma is not allowed then it is not removed for enums where last two entries are on same line`() { + val code = + """ + enum class Shape { + SQUARE, TRIANGLE, + } + """.trimIndent() + ruleAssertThat(code) + .withEditorConfigOverride(allowTrailingCommaProperty to false) + .hasNoLintViolations() + } + + @Nested + inner class MissingRequiredTrailingComma { + @Test + fun `Given that last two enumeration entries are on same line, do not add a trailing comma`() { + val code = + """ + enum class Shape { + SQUARE, TRIANGLE + } + """.trimIndent() + ruleAssertThat(code) + .withEditorConfigOverride(allowTrailingCommaProperty to true) + .hasNoLintViolations() + } + + @Test + fun `Given an enum is terminated by a semicolon and EOL comment without a trailing comma, then it is added `() { + val code = + """ + enum class Shape { + SQUARE, + TRIANGLE; // EOL Comment should be kept + } + """.trimIndent() + val formattedCode = + """ + enum class Shape { + SQUARE, + TRIANGLE, // EOL Comment should be kept + ; + } + """.trimIndent() + ruleAssertThat(code) + .withEditorConfigOverride(allowTrailingCommaProperty to true) + .hasLintViolation(3, 13, "Missing trailing comma before \";\"") + .isFormattedAs(formattedCode) + } + + @Test + fun `Given an enum is terminated by a semicolon and block comment, then it is added `() { + val code = + """ + enum class Shape { + SQUARE, + TRIANGLE; /* block comment should be kept */ + } + """.trimIndent() + val formattedCode = + """ + enum class Shape { + SQUARE, + TRIANGLE, /* block comment should be kept */ + ; + } + """.trimIndent() + ruleAssertThat(code) + .withEditorConfigOverride(allowTrailingCommaProperty to true) + .hasLintViolation(3, 13, "Missing trailing comma before \";\"") + .isFormattedAs(formattedCode) + } + + @Test + fun `Given an enum terminated by semicolon without a trailing comma then it is added`() { + val code = + """ + enum class Shape { + SQUARE, + TRIANGLE; + } + """.trimIndent() + val formattedCode = + """ + enum class Shape { + SQUARE, + TRIANGLE, + ; + } + """.trimIndent() + ruleAssertThat(code) + .withEditorConfigOverride(allowTrailingCommaProperty to true) + .hasLintViolation(3, 13, "Missing trailing comma before \";\"") + .isFormattedAs(formattedCode) + } + + @Test + fun `Given an enum without trailing-comma with other declarations following the enum entries then it is added`() { + val code = + """ + enum class Shape { + SQUARE, + TRIANGLE; + fun print() = name() + } + """.trimIndent() + val formattedCode = + """ + enum class Shape { + SQUARE, + TRIANGLE, + ; + fun print() = name() + } + """.trimIndent() + ruleAssertThat(code) + .withEditorConfigOverride(allowTrailingCommaProperty to true) + .hasLintViolation(3, 13, "Missing trailing comma before \";\"") + .isFormattedAs(formattedCode) + } + + @Test + fun `Given that a trailing comma is required then it is added for complicated enums`() { + val code = + """ + interface Printable { + fun print(): String + } + enum class Shape : Printable { + Square { + override fun print() = "■" + }, + Triangle { + override fun print() = "▲" + } + } + """.trimIndent() + val formattedCode = + """ + interface Printable { + fun print(): String + } + enum class Shape : Printable { + Square { + override fun print() = "■" + }, + Triangle { + override fun print() = "▲" + }, + } + """.trimIndent() + ruleAssertThat(code) + .withEditorConfigOverride(allowTrailingCommaProperty to true) + .hasLintViolation(10, 6, "Missing trailing comma before \"}\"") + .isFormattedAs(formattedCode) + } + + @Test + fun `Given that a trailing comma is required then add trailing comma after last enum member`() { + val code = + """ + enum class Shape { + SQUARE, + TRIANGLE + } + """.trimIndent() + val formattedCode = + """ + enum class Shape { + SQUARE, + TRIANGLE, + } + """.trimIndent() + ruleAssertThat(code) + .withEditorConfigOverride(allowTrailingCommaProperty to true) + .hasLintViolation(3, 13, "Missing trailing comma before \"}\"") + .isFormattedAs(formattedCode) + } + } } diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/internal/RemoveDiacriticsFromLettersTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/internal/RemoveDiacriticsFromLettersTest.kt index 960205eb1e..a242f28c2f 100644 --- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/internal/RemoveDiacriticsFromLettersTest.kt +++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/internal/RemoveDiacriticsFromLettersTest.kt @@ -5,7 +5,7 @@ import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource class RemoveDiacriticsFromLettersTest { - @ParameterizedTest(name = "Original character: {0}, expected result: {1}") + @ParameterizedTest(name = "Original character: {0}") @ValueSource( strings = [ "àáâäæãåā", 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 a9230fac69..6e489695c1 100644 --- a/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/KtlintCommandLine.kt +++ b/ktlint/src/main/kotlin/com/pinterest/ktlint/internal/KtlintCommandLine.kt @@ -126,7 +126,7 @@ internal class KtlintCommandLine { ) var disabledRules: String = "" - // todo: this should have been a command, not a flag (consider changing in 1.0.0) + // TODO: this should have been a command, not a flag (consider changing in 1.0.0) @Option( names = ["--format", "-F"], description = ["Fix any deviations from the code style"]