Skip to content

Commit

Permalink
Merge remote-tracking branch 'ktlint/master' into split
Browse files Browse the repository at this point in the history
  • Loading branch information
chao2zhang committed Aug 5, 2022
2 parents 45f70b2 + 49efdba commit 9a62167
Show file tree
Hide file tree
Showing 21 changed files with 631 additions and 909 deletions.
5 changes: 3 additions & 2 deletions .github/PULL_REQUEST_TEMPLATE.md
Expand Up @@ -9,8 +9,9 @@ If the PR solves an issue than provide a link to that issue. -->
<!-- Following checklist maybe skipped in some cases -->
- [ ] 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/)
14 changes: 9 additions & 5 deletions CHANGELOG.md
Expand Up @@ -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

Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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.

Expand Down
835 changes: 13 additions & 822 deletions README.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions 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/)
```
4 changes: 2 additions & 2 deletions docs/index.md
@@ -1,15 +1,15 @@
# Welcome to Ktlint

<h1 align="center">
<a href="https://ktlint.github.io/">
<a href="https://pinterest.github.io/ktlint/">
<img src="https://cloud.githubusercontent.com/assets/370176/26518284/38b680da-4262-11e7-8d27-2b9e849fb55f.png"/>
</a>
</h1>
<p align="center">
<a href="https://kotlinlang.slack.com/messages/CKS3XG0LS"><img src="https://img.shields.io/badge/slack-@kotlinlang/ktlint-yellow.svg?logo=slack" alt="Join the chat at https://kotlinlang.slack.com"/></a>
<a href="https://github.com/pinterest/ktlint/actions?query=workflow%3A%22Snapshot+Publish%22"><img src="https://github.com/pinterest/ktlint/workflows/Snapshot%20Publish/badge.svg" alt="Build status"></a>
<a href="https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.pinterest%22%20AND%20a%3A%22ktlint%22"><img src="https://img.shields.io/maven-central/v/com.pinterest/ktlint.svg" alt="Maven Central"></a>
<a href="https://ktlint.github.io/"><img src="https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg" alt="ktlint"></a>
<a href="https://pinterest.github.io/ktlint/"><img src="https://img.shields.io/badge/ktlint%20code--style-%E2%9D%A4-FF4081.svg" alt="ktlint"></a>
</p>
<p align="center">
<a href="https://kotlinlang.org/">Kotlin</a> linter in spirit of <a href="https://github.com/feross/standard">feross/standard</a> (JavaScript) and <a href="https://golang.org/cmd/gofmt/">gofmt</a> (Go).
Expand Down
113 changes: 102 additions & 11 deletions docs/install/cli.md
Expand Up @@ -52,18 +52,40 @@ On Arch Linux install package [ktlint <sup>AUR</sup>](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"
Expand All @@ -74,18 +96,16 @@ 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.

```shell title="Style violation grouped by file"
$ 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"
Expand All @@ -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"
Expand All @@ -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=<colorName>`: Make output colorful and optionally set the color name to use.

`--disabled_rules=<disabledRules>`: 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=<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 ...`.
12 changes: 6 additions & 6 deletions docs/install/integrations.md
Expand Up @@ -22,7 +22,7 @@ See [cli usage](../cli) for arguments that can be supplied to `ktlint`.
<java taskname="ktlint" dir="${basedir}" fork="true" failonerror="true"
classpathref="maven.plugin.classpath" classname="com.pinterest.ktlint.Main">
<arg value="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 -->
</java>
</target>
</configuration>
Expand All @@ -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">
<arg value="-F"/>
<arg value="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 -->
</java>
</target>
</configuration>
Expand Down Expand Up @@ -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
Expand All @@ -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
}
```

Expand Down Expand Up @@ -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")
}

Expand All @@ -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")
}
```
Expand Down
Expand Up @@ -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].
Expand All @@ -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 <T> EditorConfigProperties.getEditorConfigValue(
Expand Down
Expand Up @@ -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<SuppressionHint>): 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
Expand Down
Expand Up @@ -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")
}
}

Expand Down
Expand Up @@ -215,7 +215,7 @@ class RuleRunnerSorterTest {
)
}

@ParameterizedTest(name = "Rule id: {0}, expected result: {1}")
@ParameterizedTest(name = "Rule id: {0}")
@ValueSource(
strings = [
RULE_A,
Expand Down
Expand Up @@ -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) {
Expand Down

0 comments on commit 9a62167

Please sign in to comment.