Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ This document is intended for Spotless developers.
We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `1.27.0`).

## [Unreleased]
### Added
- Support ktlint `2.x` (Maven group `io.github.ktlint.core`), e.g. `ktlint("2.0.0-ALPHA-5")`. The default version stays `1.8.0`. Note that ktlint `2.x` renamed some rules (e.g. `no-semi` is now `semicolon`) and only runs custom rule sets built for ktlint `2.x`. ([#3156](https://github.com/diffplug/spotless/issues/3156))
### Fixed
- Fix npm/node executable discovery treating a directory (e.g. an `npm` folder inside `NODE_PATH`) as an executable. ([#3190](https://github.com/diffplug/spotless/issues/3190))

Expand Down
3 changes: 3 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ durian = "1.2.0"
selfie = "3.1.2"
jackson = "2.23.0"
ktlint = "1.8.0"
ktlint2 = "2.0.0-ALPHA-5"
javaparser = "3.28.2"

[libraries]
Expand All @@ -22,6 +23,8 @@ jackson-dataformat-yaml = { module = "com.fasterxml.jackson.dataformat:jackson-d

ktlint-rule-engine = { module = "com.pinterest.ktlint:ktlint-rule-engine", version.ref = "ktlint" }
ktlint-ruleset-standard = { module = "com.pinterest.ktlint:ktlint-ruleset-standard", version.ref = "ktlint" }
ktlint2-rule-engine = { module = "io.github.ktlint.core:ktlint-rule-engine", version.ref = "ktlint2" }
ktlint2-ruleset-standard = { module = "io.github.ktlint.core:ktlint-ruleset-standard", version.ref = "ktlint2" }

javaparser-core = { module = "com.github.javaparser:javaparser-core", version.ref = "javaparser" }
javaparser-symbol-solver-core = { module = "com.github.javaparser:javaparser-symbol-solver-core", version.ref = "javaparser" }
Expand Down
14 changes: 12 additions & 2 deletions lib/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ versionCompatibility {
// we will support no more than 2 breaking changes at a time = 3 incompatible versions
// we will try to drop down to only one version if a stable API can be maintained for a full
// year
versions = listOf("1.0.0")
versions = listOf("1.0.0", "2.0.0")
targetSourceSetName = "ktlint"
}
namespaces.register("Diktat") {
Expand Down Expand Up @@ -165,10 +165,14 @@ dependencies {
"ktfmtCompileOnly"(libs.ktfmt)
"ktfmtCompileOnly"(pinnedLibs.google.java.format) // for JDK 8 compatibility
"ktfmtCompileOnly"(libs.jsr305)
// ktlint latest supported version
// ktlint 1.x (com.pinterest.ktlint)
"compatKtLint1Dot0Dot0CompileAndTestOnly"(libs.ktlint.rule.engine)
"compatKtLint1Dot0Dot0CompileAndTestOnly"(libs.ktlint.ruleset.standard)
"compatKtLint1Dot0Dot0CompileAndTestOnly"(libs.slf4j.api)
// ktlint 2.x (io.github.ktlint.core)
"compatKtLint2Dot0Dot0CompileAndTestOnly"(libs.ktlint2.rule.engine)
"compatKtLint2Dot0Dot0CompileAndTestOnly"(libs.ktlint2.ruleset.standard)
"compatKtLint2Dot0Dot0CompileAndTestOnly"(libs.slf4j.api)
// palantirJavaFormat
"palantirJavaFormatCompileOnly"(
pinnedLibs.palantir.java.format,
Expand Down Expand Up @@ -201,6 +205,12 @@ tasks.withType<Test>().configureEach {
failOnNoDiscoveredTests = false
}

// the adapter test tasks registered by the version-compatibility plugin default to JUnit 4,
// which silently discovers none of our JUnit 5 tests
tasks.withType<Test>().matching { it.name.startsWith("testCompat") }.configureEach {
useJUnitPlatform()
}

tasks.jar {
for (glue in needsGlue) {
from(sourceSets.getByName(glue).output.classesDirs)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
* Copyright 2026 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.glue.ktlint.compat;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import io.github.ktlint.core.cli.ruleset.core.api.RuleSetV2Provider;
import io.github.ktlint.core.rule.engine.api.Code;
import io.github.ktlint.core.rule.engine.api.EditorConfigDefaults;
import io.github.ktlint.core.rule.engine.api.EditorConfigOverride;
import io.github.ktlint.core.rule.engine.api.KtLintRuleEngine;
import io.github.ktlint.core.rule.engine.api.LintError;
import io.github.ktlint.core.rule.engine.core.api.AutocorrectDecision;
import io.github.ktlint.core.rule.engine.core.api.RuleId;
import io.github.ktlint.core.rule.engine.core.api.RuleSetId;
import io.github.ktlint.core.rule.engine.core.api.RuleV2Provider;
import io.github.ktlint.core.rule.engine.core.api.RuleV2ProviderKt;
import io.github.ktlint.core.rule.engine.core.api.editorconfig.CodeStyleEditorConfigPropertyKtKt;
import io.github.ktlint.core.rule.engine.core.api.editorconfig.EditorConfigProperty;
import io.github.ktlint.core.rule.engine.core.api.editorconfig.EndOfLinePropertyKt;
import io.github.ktlint.core.rule.engine.core.api.editorconfig.IndentSizeEditorConfigPropertyKt;
import io.github.ktlint.core.rule.engine.core.api.editorconfig.IndentStyleEditorConfigPropertyKt;
import io.github.ktlint.core.rule.engine.core.api.editorconfig.InsertFinalNewLineEditorConfigPropertyKt;
import io.github.ktlint.core.rule.engine.core.api.editorconfig.MaxLineLengthEditorConfigPropertyKt;
import io.github.ktlint.core.rule.engine.core.api.editorconfig.RuleExecution;
import io.github.ktlint.core.rule.engine.core.api.editorconfig.RuleExecutionEditorConfigPropertyKtKt;
import kotlin.Pair;

/**
* Adapter for ktlint 2.x, which moved from {@code com.pinterest.ktlint} to {@code io.github.ktlint.core}.
*/
public class KtLintCompat2Dot0Dot0Adapter implements KtLintCompatAdapter {

private static final List<EditorConfigProperty<?>> DEFAULT_EDITOR_CONFIG_PROPERTIES = List.of(
CodeStyleEditorConfigPropertyKtKt.getCODE_STYLE_PROPERTY(),
EndOfLinePropertyKt.getEND_OF_LINE_PROPERTY(),
IndentSizeEditorConfigPropertyKt.getINDENT_SIZE_PROPERTY(),
IndentStyleEditorConfigPropertyKt.getINDENT_STYLE_PROPERTY(),
InsertFinalNewLineEditorConfigPropertyKt.getINSERT_FINAL_NEWLINE_PROPERTY(),
MaxLineLengthEditorConfigPropertyKt.getMAX_LINE_LENGTH_PROPERTY(),
RuleExecutionEditorConfigPropertyKtKt.getEXPERIMENTAL_RULES_EXECUTION_PROPERTY());

@Override
public String format(
String unix,
Path path,
Path editorConfigPath,
Map<String, Object> editorConfigOverrideMap) {
Set<RuleV2Provider> allRuleProviders = loadRuleProviders();

EditorConfigDefaults editorConfig = EditorConfigDefaults.Companion.load(editorConfigPath, RuleV2ProviderKt.propertyTypes(allRuleProviders));
EditorConfigOverride editorConfigOverride;
if (editorConfigOverrideMap.isEmpty()) {
editorConfigOverride = EditorConfigOverride.Companion.getEMPTY_EDITOR_CONFIG_OVERRIDE();
} else {
editorConfigOverride = createEditorConfigOverride(editorConfig, allRuleProviders, editorConfigOverrideMap);
}

// create Code and then set the content to match previous steps in the Spotless pipeline
Code code = Code.Companion.fromPath(path);
KtLintCompatAdapter.setCodeContent(code, unix);

// ktlint 2.x asks for the autocorrect decision while a rule is still executing, and wraps any exception thrown there,
// so violations are collected and only reported once formatting has finished
List<LintError> uncorrected = new ArrayList<>();
String formatted = new KtLintRuleEngine(
allRuleProviders,
editorConfig,
editorConfigOverride,
path.getFileSystem())
.format(
code,
true,
lint -> {
uncorrected.add(lint);
return kotlin.Unit.INSTANCE;
},
lint -> {
if (!lint.getCanBeAutoCorrected()) {
uncorrected.add(lint);
}
return AutocorrectDecision.ALLOW_AUTOCORRECT;
});
if (!uncorrected.isEmpty()) {
LintError lint = uncorrected.get(0);
KtLintCompatReporting.report(lint.getLine(), lint.getCol(), lint.getRuleId().getValue(), lint.getDetail());
}
return formatted;
}

private static Set<RuleV2Provider> loadRuleProviders() {
return ServiceLoader.load(RuleSetV2Provider.class, RuleSetV2Provider.class.getClassLoader())
.stream()
.flatMap(loader -> loader.get().getRuleProviders().stream())
.collect(Collectors.toUnmodifiableSet());
}

/**
* Create EditorConfigOverride from user provided parameters.
*/
private static EditorConfigOverride createEditorConfigOverride(final EditorConfigDefaults editorConfig, final Set<RuleV2Provider> ruleProviders, Map<String, Object> editorConfigOverrideMap) {
// Create a mapping of properties to their names based on rule properties and default properties
Map<String, EditorConfigProperty<?>> supportedProperties = Stream
.concat(ruleProviders.stream().flatMap(provider -> provider.getUsesEditorConfigProperties().stream()), DEFAULT_EDITOR_CONFIG_PROPERTIES.stream())
.distinct()
.collect(Collectors.toMap(EditorConfigProperty::getName, property -> property, (first, second) -> first));

Map<String, Object> overrides = new LinkedHashMap<>(editorConfigOverrideMap);
// Spotless keeps intellij_idea as default code style, as it did for ktlint 1.x
boolean isCodeStyleDefinedInEditorConfig = editorConfig.getValue().getSections().stream()
.anyMatch(section -> section.getProperties().containsKey("ktlint_code_style"));
if (!isCodeStyleDefinedInEditorConfig && !overrides.containsKey("ktlint_code_style")) {
overrides.put("ktlint_code_style", "intellij_idea");
}

// Create config properties based on provided property names and values
@SuppressWarnings("unchecked")
Pair<EditorConfigProperty<?>, ?>[] properties = overrides.entrySet().stream()
.map(entry -> {
EditorConfigProperty<?> property = supportedProperties.get(entry.getKey());

if (property == null && entry.getKey().startsWith("ktlint_")) {
String[] parts = entry.getKey().substring(7).split("_", 2);
if (parts.length == 1) {
// convert ktlint_{ruleset} to RuleSetId
RuleSetId id = new RuleSetId(parts[0]);
property = RuleExecutionEditorConfigPropertyKtKt.createRuleSetExecutionEditorConfigProperty(id, RuleExecution.ENABLED);
} else {
// convert ktlint_{ruleset}_{rulename} to RuleId
RuleId id = new RuleId(parts[0] + ":" + parts[1]);
property = RuleExecutionEditorConfigPropertyKtKt.createRuleExecutionEditorConfigProperty(id, RuleExecution.ENABLED);
}
}

if (property == null) {
return null;
} else {
return new Pair<>(property, entry.getValue());
}
})
.filter(Objects::nonNull)
.toArray(Pair[]::new);

return EditorConfigOverride.Companion.from(properties);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2021-2025 DiffPlug
* Copyright 2021-2026 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -23,6 +23,7 @@
import com.diffplug.spotless.FormatterFunc;
import com.diffplug.spotless.Lint;
import com.diffplug.spotless.glue.ktlint.compat.KtLintCompat1Dot0Dot0Adapter;
import com.diffplug.spotless.glue.ktlint.compat.KtLintCompat2Dot0Dot0Adapter;
import com.diffplug.spotless.glue.ktlint.compat.KtLintCompatAdapter;
import com.diffplug.spotless.glue.ktlint.compat.KtLintCompatReporting;

Expand All @@ -37,7 +38,9 @@ public KtlintFormatterFunc(
Map<String, Object> editorConfigOverrideMap) {
String[] versions = version.split("\\.");
int majorVersion = Integer.parseInt(versions[0]);
if (majorVersion == 1) {
if (majorVersion >= 2) {
this.adapter = new KtLintCompat2Dot0Dot0Adapter();
} else if (majorVersion == 1) {
this.adapter = new KtLintCompat1Dot0Dot0Adapter();
} else {
throw new IllegalStateException("Ktlint versions < 1.0.0 not supported!");
Expand Down
15 changes: 13 additions & 2 deletions lib/src/main/java/com/diffplug/spotless/kotlin/KtLintStep.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public final class KtLintStep implements Serializable {
private static final String NAME = "ktlint";
private static final String MAVEN_COORDINATE_0_DOT = "com.pinterest:ktlint:";
private static final String MAVEN_COORDINATE_1_DOT = "com.pinterest.ktlint:ktlint-cli:";
private static final String MAVEN_COORDINATE_2_DOT = "io.github.ktlint.core:ktlint-cli:";

private final JarState.Promised jarState;
@Nullable private final FileSignature.Promised config;
Expand Down Expand Up @@ -73,15 +74,25 @@ public static FormatterStep create(String version,
List<String> customRuleSets) {
Objects.requireNonNull(version, "version");
Objects.requireNonNull(provisioner, "provisioner");
String ktlintCoordinate = (version.startsWith("0.") ? MAVEN_COORDINATE_0_DOT : MAVEN_COORDINATE_1_DOT) + version;
Set<String> mavenCoordinates = new HashSet<>(customRuleSets);
mavenCoordinates.add(ktlintCoordinate);
mavenCoordinates.add(ktlintCoordinate(version));
return FormatterStep.create(NAME,
new KtLintStep(version, JarState.promise(() -> JarState.from(mavenCoordinates, provisioner)), editorConfig, editorConfigOverride),
KtLintStep::equalityState,
State::createFormat);
}

private static String ktlintCoordinate(String version) {
if (version.startsWith("0.")) {
return MAVEN_COORDINATE_0_DOT + version;
} else if (version.startsWith("1.")) {
return MAVEN_COORDINATE_1_DOT + version;
} else {
// ktlint 2.x moved from the com.pinterest.ktlint group to io.github.ktlint.core
return MAVEN_COORDINATE_2_DOT + version;
}
}

public static String defaultVersion() {
return KotlinBuildConfig.VERSION_KTLINT;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Copyright 2026 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.glue.ktlint.compat;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

public class KtLintCompat2Dot0Dot0AdapterTest {
@Test
public void testDefaults(@TempDir Path path) throws IOException {
KtLintCompat2Dot0Dot0Adapter adapter = new KtLintCompat2Dot0Dot0Adapter();
var content = loadAndWriteText(path, "EmptyClassBody.kt");
final Path filePath = Path.of(path.toString(), "EmptyClassBody.kt");

Map<String, Object> editorConfigOverrideMap = new HashMap<>();

String formatted = adapter.format(content, filePath, null, editorConfigOverrideMap);
assertEquals("class EmptyClassBody\n", formatted);
}

@Test
public void testEditorConfigCanDisable(@TempDir Path path) throws IOException {
KtLintCompat2Dot0Dot0Adapter adapter = new KtLintCompat2Dot0Dot0Adapter();
var content = loadAndWriteText(path, "FailsNoSemicolons.kt");
final Path filePath = Path.of(path.toString(), "FailsNoSemicolons.kt");

Map<String, Object> editorConfigOverrideMap = new HashMap<>();
editorConfigOverrideMap.put("indent_style", "tab");
// ktlint 2.x renamed the 'no-semi' rule to 'semicolon'
editorConfigOverrideMap.put("ktlint_standard_semicolon", "disabled");

String formatted = adapter.format(content, filePath, null, editorConfigOverrideMap);
assertEquals("class FailsNoSemicolons {\n\tval i = 0;\n}\n", formatted);
}

@Test
public void testUnfixableViolationIsReportedWithLineAndRuleId(@TempDir Path path) throws IOException {
KtLintCompat2Dot0Dot0Adapter adapter = new KtLintCompat2Dot0Dot0Adapter();
var content = loadAndWriteText(path, "FailsWildcardImport.kt");
final Path filePath = Path.of(path.toString(), "FailsWildcardImport.kt");

Map<String, Object> editorConfigOverrideMap = new HashMap<>();

KtLintCompatReporting.KtlintSpotlessException e = assertThrows(KtLintCompatReporting.KtlintSpotlessException.class,
() -> adapter.format(content, filePath, null, editorConfigOverrideMap));
assertEquals(3, e.line);
assertEquals("standard:no-wildcard-imports", e.ruleId);
assertEquals("Wildcard import", e.detail);
}

private static String loadAndWriteText(Path path, String name) throws IOException {
try (InputStream is = KtLintCompat2Dot0Dot0AdapterTest.class.getResourceAsStream("/" + name)) {
Files.copy(is, path.resolve(name));
}
return Files.readString(path.resolve(name));
}
}
3 changes: 3 additions & 0 deletions lib/src/testCompatKtLint2Dot0Dot0/resources/EmptyClassBody.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class EmptyClassBody {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class FailsNoSemicolons {
val i = 0;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package demo

import java.io.*

val file = File("x")
2 changes: 2 additions & 0 deletions plugin-gradle/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `3.27.0`).

## [Unreleased]
### Added
- Support ktlint `2.x` (Maven group `io.github.ktlint.core`), e.g. `ktlint("2.0.0-ALPHA-5")`. The default version stays `1.8.0`. Note that ktlint `2.x` renamed some rules (e.g. `no-semi` is now `semicolon`) and only runs custom rule sets built for ktlint `2.x`. ([#3156](https://github.com/diffplug/spotless/issues/3156))
### Fixed
- Fix npm/node executable discovery treating a directory (e.g. an `npm` folder inside `NODE_PATH`) as an executable. ([#3190](https://github.com/diffplug/spotless/issues/3190))
- Fix `Cannot set the value of task ... property 'taskService'` when Spotless is applied to sibling projects but not to their parent, a regression since `8.3.0`. Applying it to the root project with `apply false` is no longer necessary. ([#2877](https://github.com/diffplug/spotless/issues/2877))
Expand Down
Loading
Loading