Giter Site home page Giter Site logo

pinterest / ktlint Goto Github PK

View Code? Open in Web Editor NEW
6.0K 55.0 497.0 15.98 MB

An anti-bikeshedding Kotlin linter with built-in formatter

Home Page: https://pinterest.github.io/ktlint/

License: MIT License

Shell 0.14% Kotlin 99.85% Batchfile 0.02%
kotlin lint linter

ktlint's People

Contributors

3flex avatar adammtgreenberg avatar akuleshov7 avatar arturbosch avatar atulgpt avatar avinash3699 avatar cable729 avatar chao2zhang avatar charbgr avatar gabrielittner avatar goooler avatar ilya-gh avatar izeye avatar jaredsburrows avatar jelloranger avatar jlleitschuh avatar mateuszkwiecinski avatar mydogtom avatar paul-dingemans avatar paulwoitaschek avatar renovate[bot] avatar romtsn avatar shashachu avatar shyiko avatar sowmyav24 avatar t-kameyama avatar tapchicoma avatar yokotaso avatar yukukotani avatar z3d1k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ktlint's Issues

Klint succeeds loudly if a file it is fed does not exist

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?

False positive unused import for operator overloads

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() }

Allow to disable rules globally

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.

Dependencies not downloaded until ktlint task is run with Gradle

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?

Problematic imports

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:

https://github.com/shyiko/ktlint/blob/master/ktlint-ruleset-standard/src/main/kotlin/com/github/shyiko/ktlint/ruleset/standard/SpacingAfterKeywordRule.kt#L4

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?

Gradle build error

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

screenshot from 2016-07-28 13-18-03

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.

Poll: Should we support 2 spaces indentation?

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?

Enum semicolon error

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
    }

Formatter isn't modifying files or documentation is unclear.

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)

lint.txt

Interested in creating an organization?

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:

  • If either of us drops off the face of the earth then the other can continue to maintain or at least merge PR's.
  • Combined access for new contributors that become interested in the projects and we want to provide maintainer access to.

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.

Max line length

I would like to enforce a maximum line length on the files being linted. I'm partial to 100 characters, or even 120.

Infix extension functions throw "Unused import" errors

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.

Easy way to disable specific rules?

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.

Wildcard imports

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.

Doesn't handle escaped imports properly

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())
    }
}

Extract linter to library dependency

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:

  • Enforce use of val.
  • Require functions to be pure.
  • Use 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?

Maven plugin dies with ClassCastException

I'm basically using the sample config from the readme, except:

  1. I commented out <phase>verify</phase>.
  2. I'm executing with mvn antrun:run@ktlint, not mvn verify. (I'm assuming ktlint doesn't care about binaries, just source.)
  3. Using maven-antrun-plugin:1.8, not 1.7.

I've got kotlin-maven-plugin 1.0.6 in my project.

[INFO] --- maven-antrun-plugin:1.8:run (ktlint) @ server ---
[INFO] Executing tasks

ktlint:
[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)

"Unused import" incorrectly triggered if import is used implicitly

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.

Android Gradle not working

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

If `getValue` is declared as an extension method ktlint thinks its unused

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.

Mention spotless plugin in readme

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.

Reading from standard in broken?

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.

Add support for `kts` files

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)

Missing spacing after "}" conflict with "?"

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!

Allow 2 spaces instead of 4

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?

Imports only used in docs

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).

"Unexpected indentation" on wrapped function declarations

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.

incorrect op-spacing on generics

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.

0.4.0 depends on upstream Kotlin 1.1 M04, which no longer available in Maven Central

> 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

Shim class to make creating a formatter easier (also Spotless integration)

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.

Gradle script kotlin not valid file `this::method`

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"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.