pinterest / ktlint Goto Github PK
View Code? Open in Web Editor NEWAn anti-bikeshedding Kotlin linter with built-in formatter
Home Page: https://pinterest.github.io/ktlint/
License: MIT License
An anti-bikeshedding Kotlin linter with built-in formatter
Home Page: https://pinterest.github.io/ktlint/
License: MIT License
Ktlint Version: 0.4.0
If I pass in an a file as an argument that doesn't exist for example: /Users/jonathanleitschuh/work/git/plexxicontrol/PlexxiSwagger/ClientBindings/src/test/java/**/*.kt
I get the following very loud dump to standard error but no failure.
:PlexxiSwagger:ClientBindings:ktlintTest
Exception in thread "Thread-0" java.util.concurrent.ExecutionException: java.io.FileNotFoundException: /Users/jonathanleitschuh/work/git/plexxicontrol/PlexxiSwagger/ClientBindings/src/test/java (No such file or directory)
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at com.github.shyiko.ktlint.Main$parallel$consumer$1.run(Main.kt:329)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: /Users/jonathanleitschuh/work/git/plexxicontrol/PlexxiSwagger/ClientBindings/src/test/java (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at kotlin.io.FilesKt__FileReadWriteKt.readBytes(FileReadWrite.kt:52)
at kotlin.io.FilesKt__FileReadWriteKt.readText(FileReadWrite.kt:90)
at kotlin.io.FilesKt__FileReadWriteKt.readText$default(FileReadWrite.kt:90)
at com.github.shyiko.ktlint.Main$main$6$1$1.call(Main.kt:243)
at com.github.shyiko.ktlint.Main$main$6$1$1.call(Main.kt:43)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
... 1 more
I like that there is no failure but I think that this is a bit noisy of an exception to be dumping.
Perhaps a one line message if the file can't be found and then dump the full exception if the --debug
or --verbose
flag is set?
Seems like unused import check not aware of operator overloading.
import rx.lang.kotlin.plusAssign
- marked as unused by ktlint
actual usage in same file
presenterLifecycleSubscription += resetClicks.subscribe { resetSelection() }
I added in your feedback and made a full release of the plugin here:
https://github.com/JLLeitschuh/ktlint-gradle
Feel free to point people at this project in your project if you wish.
You have a great project! Hopefully this will make it easier for other users to consume.
I would like to have a command line parameter which would allow to disable certain rules so that I don't have to add comments to each file in a project.
Right now it looks like the only way to do that is to add a comment to each file where I need to disable a check, which is a bit intrusive I think.
One example is I would like to disable indentation rule, because I need it to behave differently in different contexts and ideally I would need to have different rules for different context which could be enabled/disabled.
I'm using KTLint for an Android app, on CircleCI, and I don't want to download the binary files every time. I'm successfully downloading and caching deps that are required for building the app, but when the ktlint
task runs, Gradle downloads more dependencies.
Is there a way I can force Gradle to download them up-front, and therefore get cached by the CI configuration?
The package has multiple imports from the org.jetbrains.kotlin.com.intellij namespace, but I can't seem to find how to resolve these in the Kotlin codebase.
For example:
Should refer to:
https://github.com/JetBrains/intellij-community/blob/master/platform/core-api/src/com/intellij/lang/ASTNode.java
The correct imports seem to be simply com.intellij without org.jetbrains.kotlin prepended. Am I missing something?
I followed all the steps for integrating ktlint into gradle
When adding the ktlint dependency to gradle, the following error occurs when building:
Execution failed for task ':compileFastDebugKotlin'
> com/intellij/ide/highlighter/JavaFileType
BUILD FAILED
Using gradle 2.1.2 and ktlint 0.1.0
The commands gradle ktlint
and gradle ktlintFormat
do work from the command line, only building fails.
While official stance of JetBrains (citation needed) is 4 it's seems like we're alienating considerable chunk of the community (Square, Trello, etc.) by not allowing indentation with 2 spaces.
So the question is: should we allow 2 spaces for indentation or adhere to the official recommendation?
ktlint formatter bug for semicolon in enums:
ONE("network_type_changed"),
TWO("technical_unexpected_api_error"),
THREE("technical_unexpected_api_response") ; << SEMICOLON REMOVED HERE, AND IT BREAKS CODE
override fun toString(): String = when (id) {
null -> name.toLowerCase()
else -> id
}
I wanted to allow users a bit more control over their build so I wrapped up your tool in a gradle plugin that I'll continue to develop as time goes on.
https://github.com/JLLeitschuh/ktlint-gradle
@shyiko I'm happy to add you as a contributor if you are interested.
ktlint changed catch (e:Exception)
to catch(e:Exception)
, which looks ugly and is not the style used at kotlinlang. https://kotlinlang.org/docs/reference/exceptions.html
Please use 👍 to upvote answers below (or add a new comment(s) if you have a different reason(s)).
The formatter is showing no errors, although errors exist.
Executing:
❯ ktlint -F --debug > ~/Desktop/format.txt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/main/kotlin/redux/Dispatcher.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/test/kotlin/redux/MiddlewareTest.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/test/kotlin/redux/StoreTest.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/main/kotlin/redux/Store.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/main/kotlin/redux/Middleware.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/main/kotlin/redux/Reducer.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/test/kotlin/redux/helpers/Reducers.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/test/kotlin/redux/helpers/ActionCreators.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/test/kotlin/redux/helpers/Todos.kt
[DEBUG] 766ms / 9file(s) / 0error(s)
and then:
❯ ktlint --debug > ~/Desktop/lint.txt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/test/kotlin/redux/helpers/ActionCreators.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/test/kotlin/redux/MiddlewareTest.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/test/kotlin/redux/StoreTest.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/main/kotlin/redux/Store.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/test/kotlin/redux/helpers/Todos.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/main/kotlin/redux/Dispatcher.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/main/kotlin/redux/Middleware.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/test/kotlin/redux/helpers/Reducers.kt
[DEBUG] Checking /Workspace/pardom/redux-kotlin/lib/src/main/kotlin/redux/Reducer.kt
[DEBUG] 625ms / 9file(s) / 222error(s)
Do you want to create a small organization that holds the ktlint project and gradle plugin?
As many projects end up stagnating when the core developers move on to other things, creating an organization makes it easier to give more people control over maintaining projects.
Pros:
Thoughts?
I was thinking just name the organization ktlint
. We'd both transfer ownership of our projects over to this org and update our readme's to reflect the link changes.
I would like to enforce a maximum line length on the files being linted. I'm partial to 100 characters, or even 120.
Steps to reproduce:
infixfunc.kt
package test
infix fun Int.infixfunc(x: Int): Int {
return x
}
error.kt
package test2
import test.infixfunc
class error {
init {
1 infixfunc 2
}
}
Error returned:
error.kt:3:1: Unused import
It's worth noting that using it as a standard extension works correctly.
Is there an easy way to disable specific rules?
I'm testing ktlint (inside spotless) on some random kotlin repos, and wildcard imports seem to be pretty common, and thus a barrier to initial adoption.
Please forgive my bikeshedding, but I beg to differ with the "no wildcards" rule. My primary argument is that intellij does add wildcard imports in the default configuration, and I think I should not have to configure intellij to play nice with ktlint. Adding // ktlint-disable no-wildcard-imports
is a very ugly workaround.
Another acceptable solution for me would be if the format action actually resolved wildcard imports into individual imports, which it does not as of version 0.7.0. I don't want to argue about what's better, I just want to have a consistent style without requiring manual intervention.
It says the first import is unused. It's wrong. Quick fix is there #6
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
class LinterFailure {
fun foo() {
val bar = mock(LinterFailure::class.java)
`when`(bar.foo())
}
}
Any chance on getting a small section on how to build ktlint from source?
Thanks!
I've been looking for a Kotlin linter for two reasons, one of which is accomplished with this library. The other reason I want a Kotlin linter is to create a companion linter for FP libraries. This linter would do things like:
val
.Maybe
instead of nullables when the type exists.For this reason, it would be useful to decouple the rules from the base linter/parser. Implementing libraries could then supply their own rules. Thoughts?
I'm basically using the sample config from the readme, except:
<phase>verify</phase>
.mvn antrun:run@ktlint
, not mvn verify
. (I'm assuming ktlint doesn't care about binaries, just source.)I've got kotlin-maven-plugin 1.0.6 in my project.
[INFO] --- maven-antrun-plugin:1.8:run (ktlint) @ server ---
[INFO] Executing tasksktlint:
[ktlint] Exception in thread "main" java.lang.ClassCastException: org.jetbrains.kotlin.lexer.KtKeywordToken cannot be cast to org.jetbrains.kotlin.com.intellij.psi.tree.IElementType
[ktlint] at com.gihub.shyiko.ktlint.ruleset.standard.SpacingAfterKeywordRule.(SpacingAfterKeywordRule.kt:22)
[ktlint] at com.gihub.shyiko.ktlint.ruleset.standard.StandardRuleSetProvider.get(StandardRuleSetProvider.kt:8)
[ktlint] at com.github.shyiko.ktlint.Main.main(Main.kt:186)
Suppose I have an extension method that adds an iterator to some type:
operator fun <T> Foo<T>?.iterator() {
...
}
In another package, I want to iterate using this in a for
loop:
import com.example.foo.iterator
...
val foo : Foo = ...
for (x in foo) {
...
}
With the import the code compiles and works, but ktlint fails with an "Unused import" error.
Without the import, the Kotlin compiler fails with "Error:(...) Kotlin: For-loop range must have an 'iterator()' method").
This probably happens with other operator
extension functions that are called implicitly, though I haven't tested.
Does anybody successfully ran ktlint with android?
i always have
Skipping task ':app:ktlint' as task onlyIf is false.
:app:ktlint SKIPPED
configuration same as in readme
Example:
import com.natpryce.konfig.PropertyGroup
import com.natpryce.konfig.getValue
import com.natpryce.konfig.stringType
interface EventConfiguration {
val url: String
companion object {
private object rabbitmq : PropertyGroup() {
val url by stringType // This is where getValue is used.
}
}
This is how getValue
is defined:
operator fun <G : PropertyGroup, T> ((PropertyLocation, String) -> T).getValue(group: G, property: KProperty<*>) =
group.key(property.name, this)
operator fun <SCOPE, T> ((PropertyLocation, String) -> T).getValue(scope: SCOPE?, property: KProperty<*>) =
Key(property.name, this)
Kt-lint thinks that import com.natpryce.konfig.getValue
is an unused import so you have to disable the check using // ktlint-disable
.
For this branch: pardom-zz/redux-kotlin#13
The spotless gradle plugin is pretty solid.
The only reason that I wrote my plugin was I needed it to be standalone.
I'm using spotless in a new project and it works really nicely.
I'm setting this up on a build server running OSX and having homebrew installation available would be awesome.
I'm trying to use the --stdin
flag but ktlint doesn't seem to be getting anything from standard in.
Here is a transcript of my terminal session:
francis::aether:ktlint.git [master %=] cat test.kt
import java.io.File
fun main(args: Array<String>) {
}
francis::aether:ktlint.git [master %=] ktlint --stdin --debug < test.kt
[DEBUG] Discovered ruleset "standard"
[DEBUG] Checking <text>
[DEBUG] 367ms / 0file(s) / 0error(s)
francis::aether:ktlint.git [master %=] ktlint --stdin --debug
[DEBUG] Discovered ruleset "standard"
import java.io.File
fun main(args: Array<String>) {
}
[DEBUG] Checking <text>
[DEBUG] 11032ms / 0file(s) / 0error(s)
I was expecting an unused import error but as you can see above, no error is produced.
Pretty much the same as #54 but with setValue
instead.
This list should contain setValue
.
Projects like gradle-script-kotlin should be lintable too.
Currently you get exceptions like these:
/Users/jonathanleitschuh/work/git/plexxicontrol/PlexxiInstall/PlexxiInstall.gradle.kts:8:1: Not a valid Kotlin file (expecting a top level declaration)
/Users/jonathanleitschuh/work/git/plexxicontrol/PlexxiDataSource/PlexxiDataSource.gradle.kts:1:1: Not a valid Kotlin file (expecting a top level declaration)
/Users/jonathanleitschuh/work/git/plexxicontrol/PlexxiCorePythonAPI/eggArtifacts.gradle.kts:17:1: Not a valid Kotlin file (expecting a top level declaration)
/Users/jonathanleitschuh/work/git/plexxicontrol/PlexxiCore/PlexxiCore.gradle.kts:12:1: Not a valid Kotlin file (expecting a top level declaration)
/Users/jonathanleitschuh/work/git/plexxicontrol/PlexxiControlConversion.gradle.kts:16:1: Not a valid Kotlin file (expecting a top level declaration)
/Users/jonathanleitschuh/work/git/plexxicontrol/PlexxiClientUpgrade/PlexxiClientUpgrade.gradle.kts:8:1: Not a valid Kotlin file (expecting a top level declaration)
/Users/jonathanleitschuh/work/git/plexxicontrol/PlexxiClient/psmCopy.gradle.kts:92:1: Not a valid Kotlin file (expecting a top level declaration)
/Users/jonathanleitschuh/work/git/plexxicontrol/codequality/ktLintBuild.gradle.kts:5:1: Not a valid Kotlin file (expecting a top level declaration)
/Users/jonathanleitschuh/work/git/plexxicontrol/codequality/checkStyle.gradle.kts:6:1: Not a valid Kotlin file (expecting a top level declaration)
ktlint error: Missing spacing after "}"
what ktlint expects: find { it.default ?: false } ?.phone
what idea reformat code do find { it.default ?: false }?.phone
idea reformat is right!
I read the note in the README:
No configuration. 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 from kotlinlang.org (+ we support additional 3rd party rulesets).
Can you budge in this case regarding the spaces or you want to keep it dead simple?
The official style guides are quiet about whether we should say override public
or public override
.
Does ktlint wanna enforce one true order?
I made up a standard order for KotlinPoet, but I’m not particular to it.
https://github.com/square/kotlinpoet/blob/master/src/main/java/com/squareup/kotlinpoet/KModifier.kt
When an import is only used in square brackets in the docs it will get removed by ktlint. For example:
package com.example
import android.provider.CalendarContract.Colors
/**
* [Colors]
*/
class Foo
will become:
package com.example
/**
* [Colors]
*/
class Foo
IntelliJ itself shows the import as used (or not as unused).
The following function appears in the Kotlin Reference:
fun reformat(str: String,
normalizeCase: Boolean = true,
upperCaseFirstLetter: Boolean = true,
divideByCamelHumps: Boolean = false,
wordSeparator: Char = ' ') {
...
}
If you copy this to a source file (and remove the ellipsis), ktlint
will complain:
src/main/kotlin/Foo.kt:3:1: Unexpected indentation (13)
src/main/kotlin/Foo.kt:4:1: Unexpected indentation (13)
src/main/kotlin/Foo.kt:5:1: Unexpected indentation (13)
src/main/kotlin/Foo.kt:6:1: Unexpected indentation (13)
This style also appears numerous times within the Kotlin compiler source, and when asked to reformat the code, this is the indentation style used by IntelliJ, so I think this error is incorrect.
This expression:
override val formatClass: Class<out Format<*>>
get() = super<MultiFileMixedTransform>.formatClass
generates:
RandomForestTransform.kt:25:24: Missing spacing after "<"
RandomForestTransform.kt:25:47: Missing spacing before ">"
which I believe is an error. I think it thinks the <
and >
are comparison operators rather than generics.
> Could not resolve all dependencies for configuration ':ktlint'.
> Could not find org.jetbrains.kotlin:kotlin-compiler-embeddable:1.1-M04.
Searched in the following locations:
http://dl.bintray.com/populov/maven/org/jetbrains/kotlin/kotlin-compiler-embeddable/1.1-M04/kotlin-compiler-embeddable-1.1-M04.pom
http://dl.bintray.com/populov/maven/org/jetbrains/kotlin/kotlin-compiler-embeddable/1.1-M04/kotlin-compiler-embeddable-1.1-M04.jar
https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-compiler-embeddable/1.1-M04/kotlin-compiler-embeddable-1.1-M04.pom
https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-compiler-embeddable/1.1-M04/kotlin-compiler-embeddable-1.1-M04.jar
Required by:
:joist-android:unspecified > com.github.shyiko:ktlint:0.4.0 > com.github.shyiko.ktlint:ktlint-core:0.4.0
This ticket is a parent for #27 #28 (PR available) #29 proposed by @iggymoran.
Cool formatter! What do you think about adding something along these lines:
public class KtLintStandard {
public KtLintStandard() {
// setup the default rules, and a default callback function
}
public String format(String input) { ... }
Spotless is a formatting "switchboard" that composes different formatters for different languages with different build systems. It has some value-add like up-to-date checking and automatically fixing minor idempotence glitches. Spotless understands a formatting rule as a "Function<String, String>", and it integrates third-party formatters like google-java-format and eclipse via reflection.
I tried to integrate your library in spotless #67, but it's very hard to instantiate via reflection. A shim such as the one proposed above would make it a lot easier! Once this change is made, it could be as easy as
plugins { id 'com.diffplug.gradle.spotless' }
spotless {
kotlin {
ktlint() // takes an arg if they want to set a specific version
}
}
For users to apply ktlint to their gradle projects with up-to-date-checking, and they could use other formatters for other languages. Also license enforcement, etc.
I have a file with this code:
fun repositoryConfigurer(repoHandler : RepositoryHandler) {
repoHandler.apply {
// ... ect...
}
}
var configureRepository : (RepositoryHandler) -> Unit by extraWrapped
configureRepository = this::repositoryConfigurer // Fails on this line
I get the following error:
/Users/jonathanleitschuh/work/git/plexxicontrol/sharedValues.gradle.kts:138:27: Not a valid Kotlin file (unexpected tokens (use ';' to separate expressions on the same line))
I'm using version: "0.3.0"
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.