Skip to content

Commit

Permalink
Add 'detekt' static code analyzer for Kotlin
Browse files Browse the repository at this point in the history
Another option to format Kotlin and KotlinScript files.

See: https://github.com/arturbosch/detekt
Resolves: diffplug#143
  • Loading branch information
saschpe committed Mar 19, 2019
1 parent 54e4d10 commit 6697ed3
Show file tree
Hide file tree
Showing 13 changed files with 422 additions and 41 deletions.
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ You might be looking for:

**WARNING: xml formatter in this version may be vulnerable to XXE attacks, fixed in 1.20.0 (see [#358](https://github.com/diffplug/spotless/issues/358)).**

* Added support for Kotlin via [detekt](https://github.com/arturbosch/detekt) ([#XXX](https://github.com/diffplug/spotless/pull/XXX))
* Security fix: Updated groovy, c/c++, and eclipse WTP formatters so that they download their source jars securely using `https` rather than `http` ([#360](https://github.com/diffplug/spotless/issues/360)).
* Updated default eclipse-jdt from 4.9.0 to 4.10.0 ([#368](https://github.com/diffplug/spotless/pull/368))

Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ lib('java.GoogleJavaFormatStep') +'{{yes}} | {{yes}}
lib('java.ImportOrderStep') +'{{yes}} | {{yes}} | {{no}} |',
lib('java.RemoveUnusedImportsStep') +'{{yes}} | {{yes}} | {{no}} |',
extra('java.EclipseFormatterStep') +'{{yes}} | {{yes}} | {{no}} |',
lib('kotlin.DetektStep') +'{{yes}} | {{yes}} | {{no}} |',
lib('kotlin.KtLintStep') +'{{yes}} | {{yes}} | {{no}} |',
lib('markdown.FreshMarkStep') +'{{yes}} | {{no}} | {{no}} |',
lib('npm.PrettierFormatterStep') +'{{yes}} | {{no}} | {{no}} |',
Expand Down Expand Up @@ -71,6 +72,7 @@ extra('wtp.EclipseWtpFormatterStep') +'{{yes}} | {{yes}}
| [`java.ImportOrderStep`](lib/src/main/java/com/diffplug/spotless/java/ImportOrderStep.java) | :+1: | :+1: | :white_large_square: |
| [`java.RemoveUnusedImportsStep`](lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java) | :+1: | :+1: | :white_large_square: |
| [`java.EclipseFormatterStep`](lib-extra/src/main/java/com/diffplug/spotless/extra/java/EclipseFormatterStep.java) | :+1: | :+1: | :white_large_square: |
| [`kotlin.DetektStep`](lib/src/main/java/com/diffplug/spotless/kotlin/DetektStep.java) | :+1: | :+1: | :white_large_square: |
| [`kotlin.KtLintStep`](lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java) | :+1: | :+1: | :white_large_square: |
| [`markdown.FreshMarkStep`](lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java) | :+1: | :white_large_square: | :white_large_square: |
| [`npm.PrettierFormatterStep`](lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java) | :+1: | :white_large_square: | :white_large_square: |
Expand All @@ -85,6 +87,7 @@ extra('wtp.EclipseWtpFormatterStep') +'{{yes}} | {{yes}}

## Acknowledgements

- Thanks to [Sascha Peilicke](https://github.com/saschpe) for [adding support for Detekt](https://github.com/diffplug/spotless/pull/XXX)
- Thanks to [Simon Gamma](https://github.com/simschla) for [adding support for npm-based formatters](https://github.com/diffplug/spotless/pull/283), including `prettier` and `tsfmt`.
- Thanks to [Frank Vennemeyer](https://github.com/fvgh) for [Groovy support via greclipse](https://github.com/diffplug/spotless/issues/13), [C++ support via CDT](https://github.com/diffplug/spotless/issues/232), [XML support via WTP](https://github.com/diffplug/spotless/pull/241) and a huge body of work with other eclipse-based formatters.
- Thanks to [Konstantin Lutovich](https://github.com/lutovich) for [implementing the maven plugin](https://github.com/diffplug/spotless/pull/188).
Expand Down
160 changes: 160 additions & 0 deletions lib/src/main/java/com/diffplug/spotless/kotlin/DetektStep.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
* Copyright 2016 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.spotless.kotlin;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.diffplug.spotless.*;

/**
* Wraps up [detekt](https://github.com/arturbosch/detekt) as a FormatterStep.
*/
public class DetektStep {
private DetektStep() {
}

private static final String DEFAULT_VERSION = "1.0.0-RC14";
private static final String NAME = "detekt";
private static final String MAVEN_COORDINATE = "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:";

public static FormatterStep create(Provisioner provisioner) {
return create(defaultVersion(), provisioner);
}

public static FormatterStep create(String version, Provisioner provisioner) {
return create(version, provisioner, "");
}

public static FormatterStep create(String version, Provisioner provisioner, String configFile) {
return create(version, provisioner, false, configFile);
}

public static FormatterStep createForScript(String version, Provisioner provisioner) {
return create(version, provisioner, true, "");
}

public static FormatterStep createForScript(String version, Provisioner provisioner, String configFile) {
return create(version, provisioner, true, configFile);
}

private static FormatterStep create(String version, Provisioner provisioner, boolean isScript, String configFile) {
Objects.requireNonNull(version, "version");
Objects.requireNonNull(provisioner, "provisioner");
return FormatterStep.createLazy(NAME,
() -> new DetektStep.State(version, provisioner, isScript, configFile),
DetektStep.State::createFormat);
}

public static String defaultVersion() {
return DEFAULT_VERSION;
}

static final class State implements Serializable {
/**
* Are the files being linted Kotlin script files.
*/
private final boolean isScript;
private final String configFile;
/**
* The jar that contains the eclipse formatter.
*/
final JarState jarState;

State(String version, Provisioner provisioner, boolean isScript, String configFile) throws IOException {
this.configFile = configFile;
this.isScript = isScript;
this.jarState = JarState.from(MAVEN_COORDINATE + version, provisioner);
}

FormatterFunc createFormat() throws Exception {
ClassLoader classLoader = jarState.getClassLoader();

Class<?> detektFacadeClass = classLoader.loadClass("io.gitlab.arturbosch.detekt.core.DetektFacade");
Object detektFacadeCompanion = detektFacadeClass.getDeclaredField("INSTANCE").get(null);

Class<?> processSettingsClass = classLoader.loadClass("io.gitlab.arturbosch.detekt.core.ProcessingSettings");
Method createMethod = detektFacadeClass.getMethod("create", processSettingsClass);

// TODO: Parse config file...
//Class<?> configClass = classLoader.loadClass("io.gitlab.arturbosch.detekt.api.Config");

Constructor processSettingsClassConstructor = processSettingsClass.getDeclaredConstructor(List.class);

// TODO: Paths...
ArrayList<Path> paths = new ArrayList<>();

Object processSettings = processSettingsClassConstructor.newInstance(paths);

// Create 'DetektFacade' instance..
Object detektFacade = createMethod.invoke(detektFacadeCompanion, processSettings);


return input -> {
Object detektion = detektFacadeClass.getMethod("run").invoke(null);

// TODO: Convert to printable string..
return "";
};

/*// first, we get the standard rules
Class<?> standardRuleSetProviderClass = classLoader.loadClass("com.github.shyiko.ktlint.ruleset.standard.StandardRuleSetProvider");
Object standardRuleSet = standardRuleSetProviderClass.getMethod("get").invoke(standardRuleSetProviderClass.newInstance());
Iterable<?> ruleSets = Collections.singletonList(standardRuleSet);
// next, we create an error callback which throws an assertion error when the format is bad
Class<?> function2Interface = classLoader.loadClass("kotlin.jvm.functions.Function2");
Class<?> lintErrorClass = classLoader.loadClass("com.github.shyiko.ktlint.core.LintError");
Method detailGetter = lintErrorClass.getMethod("getDetail");
Method lineGetter = lintErrorClass.getMethod("getLine");
Method colGetter = lintErrorClass.getMethod("getCol");
Object formatterCallback = Proxy.newProxyInstance(classLoader, new Class[]{function2Interface},
(proxy, method, args) -> {
Object lintError = args[0]; // com.github.shyiko.ktlint.core.LintError
boolean corrected = (Boolean) args[1];
if (!corrected) {
String detail = (String) detailGetter.invoke(lintError);
int line = (Integer) lineGetter.invoke(lintError);
int col = (Integer) colGetter.invoke(lintError);
throw new AssertionError("Error on line: " + line + ", column: " + col + "\n" + detail);
}
return null;
});
// grab the KtLint singleton
Class<?> ktlintClass = classLoader.loadClass("com.github.shyiko.ktlint.core.KtLint");
Object ktlint = ktlintClass.getDeclaredField("INSTANCE").get(null);
// and its format method
String formatterMethodName = isScript ? "formatScript" : "format";
Method formatterMethod = ktlintClass.getMethod(formatterMethodName, String.class, Iterable.class, Map.class, function2Interface);
return input -> {
try {
return (String) formatterMethod.invoke(ktlint, input, ruleSets, userData, formatterCallback);
} catch (InvocationTargetException e) {
throw ThrowingEx.unwrapCause(e);
}
};*/
}
}
}
32 changes: 32 additions & 0 deletions plugin-gradle/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ Spotless can check and apply formatting to any plain-text file, using simple rul
* Google's [google-java-format](https://github.com/google/google-java-format)
* [Groovy Eclipse](#groovy-eclipse)'s groovy code formatter
* [FreshMark](https://github.com/diffplug/freshmark) (markdown with variables)
* [detekt](https://github.com/arturbosch/detekt)
* [ktlint](https://github.com/shyiko/ktlint)
* [scalafmt](https://github.com/olafurpg/scalafmt)
* [DBeaver sql format](https://dbeaver.jkiss.org/)
Expand Down Expand Up @@ -250,6 +251,37 @@ spotless {
}
```

<a name="detekt"></a>

## Applying [detekt](https://github.com/arturbosch/detekt) to Kotlin files

```gradle
spotless {
kotlin {
// optionally takes a version
detekt()
// Optional configration file can be set as such:
detekt().config("my-detekt-baseline.xml")
// also supports license headers
licenseHeader '/* Licensed under Apache-2.0 */' // License header
licenseHeaderFile 'path-to-license-file' // License header file
}
kotlinGradle {
// same as kotlin, but for .gradle.kts files (defaults to '*.gradle.kts')
target '*.gradle.kts', 'additionalScripts/*.gradle.kts'
detekt()
// Optional configration file can be set as such:
detekt().config("my-detekt-baseline.xml")
// doesn't support licenseHeader, because scripts don't have a package statement
// to clearly mark where the license should go
}
}
```

<a name="ktlint"></a>

## Applying [ktlint](https://github.com/shyiko/ktlint) to Kotlin files
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.gradle.api.tasks.SourceSet;

import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.kotlin.DetektStep;
import com.diffplug.spotless.kotlin.KtLintStep;

public class KotlinExtension extends FormatExtension implements HasBuiltinDelimiterForLicense {
Expand All @@ -46,40 +47,79 @@ public LicenseHeaderConfig licenseHeaderFile(Object licenseHeaderFile) {
return licenseHeaderFile(licenseHeaderFile, LICENSE_HEADER_DELIMITER);
}

/** Adds the specified version of [ktlint](https://github.com/shyiko/ktlint). */
public KotlinFormatExtension ktlint(String version) {
/**
* Adds the specified version of [detekt](https://github.com/arturbosch/detekt).
*/
public KotlinDetektFormatExtension detekt(String version) {
Objects.requireNonNull(version);
return new KotlinFormatExtension(version, Collections.emptyMap());
return new KotlinDetektFormatExtension(this, version, "");
}

public KotlinFormatExtension ktlint() {
return ktlint(KtLintStep.defaultVersion());
public KotlinDetektFormatExtension detekt() {
return detekt(DetektStep.defaultVersion());
}

public class KotlinFormatExtension {
public static class KotlinDetektFormatExtension {
private final String version;
private String configFile;
private final FormatExtension formatExtension;

KotlinDetektFormatExtension(FormatExtension formatExtension, String version, String configFile) {
this.version = version;
this.configFile = configFile;
this.formatExtension = formatExtension;
formatExtension.addStep(createStep());
}

public void config(String configFile) {
this.configFile = configFile;
formatExtension.replaceStep(createStep());
}

private FormatterStep createStep() {
return DetektStep.create(version, GradleProvisioner.fromProject(formatExtension.getProject()), configFile);
}
}

/**
* Adds the specified version of [ktlint](https://github.com/shyiko/ktlint).
*/
public KotlinKtlintFormatExtension ktlint(String version) {
Objects.requireNonNull(version);
return new KotlinKtlintFormatExtension(this, version, Collections.emptyMap());
}

public KotlinKtlintFormatExtension ktlint() {
return ktlint(KtLintStep.defaultVersion());
}

public static class KotlinKtlintFormatExtension {
private final String version;
private Map<String, String> userData;
private final FormatExtension formatExtension;

KotlinFormatExtension(String version, Map<String, String> config) {
KotlinKtlintFormatExtension(FormatExtension formatExtension, String version, Map<String, String> config) {
this.version = version;
this.userData = config;
addStep(createStep());
this.formatExtension = formatExtension;
formatExtension.addStep(createStep());
}

public void userData(Map<String, String> userData) {
// Copy the map to a sorted map because up-to-date checking is based on binary-equals of the serialized
// representation.
this.userData = userData;
replaceStep(createStep());
formatExtension.replaceStep(createStep());
}

private FormatterStep createStep() {
return KtLintStep.create(version, GradleProvisioner.fromProject(getProject()), userData);
return KtLintStep.create(version, GradleProvisioner.fromProject(formatExtension.getProject()), userData);
}
}

/** If the user hasn't specified the files yet, we'll assume he/she means all of the kotlin files. */
/**
* If the user hasn't specified the files yet, we'll assume he/she means all of the kotlin files.
*/
@Override
protected void setupTask(SpotlessTask task) {
if (target == null) {
Expand Down
Loading

0 comments on commit 6697ed3

Please # to comment.