Skip to content

Commit

Permalink
Support ktlint 0.50.0 and drop support for 0.47.0
Browse files Browse the repository at this point in the history
Closes #1741
  • Loading branch information
magneticflux- committed Jul 8, 2023
1 parent d245b60 commit 3bafa6a
Show file tree
Hide file tree
Showing 14 changed files with 299 additions and 181 deletions.
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ 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
* Bump default `ktlint` version to latest `0.49.1` -> `0.50.0`.([#1741](https://github.com/diffplug/spotless/issues/1741))
* Dropped support for `ktlint 0.47.x` following our policy of supporting two breaking changes at a time.
### Changes
* Bump default `cleanthat` version to latest `2.13` -> `2.16`. ([#1725](https://github.com/diffplug/spotless/pull/1725))
### Fixed
Expand Down
12 changes: 7 additions & 5 deletions lib/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ 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 = [
'0.47.0',
'0.48.0',
'0.49.0',
'0.50.0',
]
targetSourceSetName = 'ktlint'
}
Expand Down Expand Up @@ -95,16 +95,18 @@ dependencies {
strictly '1.7' // for JDK 8 compatibility
}
}
// ktlint
compatKtLint0Dot47Dot0CompileOnly 'com.pinterest.ktlint:ktlint-core:0.47.0'
compatKtLint0Dot47Dot0CompileOnly 'com.pinterest.ktlint:ktlint-ruleset-experimental:0.47.0'
compatKtLint0Dot47Dot0CompileOnly 'com.pinterest.ktlint:ktlint-ruleset-standard:0.47.0'
// ktlint oldest supported version
compatKtLint0Dot48Dot0CompileAndTestOnly 'com.pinterest.ktlint:ktlint-core:0.48.0'
compatKtLint0Dot48Dot0CompileAndTestOnly 'com.pinterest.ktlint:ktlint-ruleset-experimental:0.48.0'
compatKtLint0Dot48Dot0CompileAndTestOnly 'com.pinterest.ktlint:ktlint-ruleset-standard:0.48.0'
// ktlint previous supported version
compatKtLint0Dot49Dot0CompileAndTestOnly 'com.pinterest.ktlint:ktlint-rule-engine:0.49.0'
compatKtLint0Dot49Dot0CompileAndTestOnly 'com.pinterest.ktlint:ktlint-ruleset-standard:0.49.0'
compatKtLint0Dot49Dot0CompileAndTestOnly 'org.slf4j:slf4j-api:2.0.0'
// ktlint latest supported version
compatKtLint0Dot50Dot0CompileAndTestOnly 'com.pinterest.ktlint:ktlint-rule-engine:0.50.0'
compatKtLint0Dot50Dot0CompileAndTestOnly 'com.pinterest.ktlint:ktlint-ruleset-standard:0.50.0'
compatKtLint0Dot50Dot0CompileAndTestOnly 'org.slf4j:slf4j-api:2.0.0'
// palantirJavaFormat
palantirJavaFormatCompileOnly 'com.palantir.javaformat:palantir-java-format:1.1.0' // this version needs to stay compilable against Java 8 for CI Job testNpm
// scalafmt
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
/*
* Copyright 2023 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.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pinterest.ktlint.rule.engine.api.Code;
import com.pinterest.ktlint.rule.engine.api.EditorConfigDefaults;
import com.pinterest.ktlint.rule.engine.api.EditorConfigOverride;
import com.pinterest.ktlint.rule.engine.api.KtLintRuleEngine;
import com.pinterest.ktlint.rule.engine.api.LintError;
import com.pinterest.ktlint.rule.engine.core.api.Rule;
import com.pinterest.ktlint.rule.engine.core.api.RuleId;
import com.pinterest.ktlint.rule.engine.core.api.RuleProvider;
import com.pinterest.ktlint.rule.engine.core.api.RuleSetId;
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CodeStyleEditorConfigPropertyKt;
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfigProperty;
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EndOfLinePropertyKt;
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.IndentSizeEditorConfigPropertyKt;
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.IndentStyleEditorConfigPropertyKt;
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.InsertFinalNewLineEditorConfigPropertyKt;
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MaxLineLengthEditorConfigPropertyKt;
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.RuleExecution;
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.RuleExecutionEditorConfigPropertyKt;
import com.pinterest.ktlint.ruleset.standard.StandardRuleSetProvider;

import kotlin.Pair;
import kotlin.Unit;
import kotlin.jvm.functions.Function2;

public class KtLintCompat0Dot50Dot0Adapter implements KtLintCompatAdapter {

private static final Logger logger = LoggerFactory.getLogger(KtLintCompat0Dot50Dot0Adapter.class);

private static final List<EditorConfigProperty<?>> DEFAULT_EDITOR_CONFIG_PROPERTIES;

static {
List<EditorConfigProperty<?>> list = new ArrayList<>();
list.add(CodeStyleEditorConfigPropertyKt.getCODE_STYLE_PROPERTY());
list.add(EndOfLinePropertyKt.getEND_OF_LINE_PROPERTY());
list.add(IndentSizeEditorConfigPropertyKt.getINDENT_SIZE_PROPERTY());
list.add(IndentStyleEditorConfigPropertyKt.getINDENT_STYLE_PROPERTY());
list.add(InsertFinalNewLineEditorConfigPropertyKt.getINSERT_FINAL_NEWLINE_PROPERTY());
list.add(MaxLineLengthEditorConfigPropertyKt.getMAX_LINE_LENGTH_PROPERTY());
list.add(RuleExecutionEditorConfigPropertyKt.getEXPERIMENTAL_RULES_EXECUTION_PROPERTY());
DEFAULT_EDITOR_CONFIG_PROPERTIES = Collections.unmodifiableList(list);
}

static class FormatterCallback implements Function2<LintError, Boolean, Unit> {

@Override
public Unit invoke(LintError lint, Boolean corrected) {
if (!corrected) {
KtLintCompatReporting.report(lint.getLine(), lint.getCol(), lint.getRuleId().getValue(), lint.getDetail());
}
return Unit.INSTANCE;
}
}

@Override
public String format(final String text, Path path, final boolean isScript,
final boolean useExperimental,
Path editorConfigPath, final Map<String, String> userData,
final Map<String, Object> editorConfigOverrideMap) {
final FormatterCallback formatterCallback = new FormatterCallback();

Set<RuleProvider> allRuleProviders = new LinkedHashSet<>(
new StandardRuleSetProvider().getRuleProviders());

// TODO: Should we keep `useExperimental` now that ktlint uses an EditorConfig property for this purpose?
if (useExperimental) {
String experimentalRulesPropertyName = RuleExecutionEditorConfigPropertyKt.getEXPERIMENTAL_RULES_EXECUTION_PROPERTY().getName();
Object experimentalOverride = editorConfigOverrideMap.get(experimentalRulesPropertyName);
if (experimentalOverride != null) {
logger.warn("`useExperimental` parameter is `true` and `ktlint_experimental` property is set, `useExperimental` will take priority!");
editorConfigOverrideMap.put(experimentalRulesPropertyName, "enabled");
}
}

EditorConfigOverride editorConfigOverride;
if (editorConfigOverrideMap.isEmpty()) {
editorConfigOverride = EditorConfigOverride.Companion.getEMPTY_EDITOR_CONFIG_OVERRIDE();
} else {
editorConfigOverride = createEditorConfigOverride(allRuleProviders.stream().map(
RuleProvider::createNewRuleInstance).collect(Collectors.toList()),
editorConfigOverrideMap);
}
EditorConfigDefaults editorConfig;
if (editorConfigPath == null || !Files.exists(editorConfigPath)) {
editorConfig = EditorConfigDefaults.Companion.getEMPTY_EDITOR_CONFIG_DEFAULTS();
} else {
editorConfig = EditorConfigDefaults.Companion.load(editorConfigPath, Collections.emptySet());
}

return new KtLintRuleEngine(
allRuleProviders,
editorConfig,
editorConfigOverride,
true,
false,
path.getFileSystem())
.format(Code.Companion.fromPath(path), formatterCallback);
}

/**
* Create EditorConfigOverride from user provided parameters.
*/
private static EditorConfigOverride createEditorConfigOverride(final List<Rule> rules, Map<String, Object> editorConfigOverrideMap) {
// Get properties from rules in the rule sets
Stream<EditorConfigProperty<?>> ruleProperties = rules.stream()
.flatMap(rule -> rule.getUsesEditorConfigProperties().stream());

// Create a mapping of properties to their names based on rule properties and default properties
Map<String, EditorConfigProperty<?>> supportedProperties = Stream
.concat(ruleProperties, DEFAULT_EDITOR_CONFIG_PROPERTIES.stream())
.distinct()
.collect(Collectors.toMap(EditorConfigProperty::getName, property -> property));

// Create config properties based on provided property names and values
@SuppressWarnings("unchecked")
Pair<EditorConfigProperty<?>, ?>[] properties = editorConfigOverrideMap.entrySet().stream()
.map(entry -> {
EditorConfigProperty<?> property = supportedProperties.get(entry.getKey());
if (property != null) {
return new Pair<>(property, entry.getValue());
} else if (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 = RuleExecutionEditorConfigPropertyKt.createRuleSetExecutionEditorConfigProperty(id, RuleExecution.disabled);
} else {
// convert ktlint_{ruleset}_{rulename} to RuleId
RuleId id = new RuleId(parts[0] + ":" + parts[1]);
property = RuleExecutionEditorConfigPropertyKt.createRuleExecutionEditorConfigProperty(id, RuleExecution.disabled);
}
return new Pair<>(property, entry.getValue());
} else {
return null;
}
})
.filter(Objects::nonNull)
.toArray(Pair[]::new);

return EditorConfigOverride.Companion.from(properties);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,19 @@ public class KtlintFormatterFunc implements FormatterFunc.NeedsFile {
public KtlintFormatterFunc(String version, boolean isScript, boolean useExperimental, FileSignature editorConfigPath, Map<String, String> userData,
Map<String, Object> editorConfigOverrideMap) {
int minorVersion = Integer.parseInt(version.split("\\.")[1]);
if (minorVersion >= 49) {
if (minorVersion >= 50) {
// Fixed `RuleId` and `RuleSetId` issues
// New argument to `EditorConfigDefaults.Companion.load(...)` for custom property type parsing
// New argument to `new KtLintRuleEngine(...)` to fail on usage of `treeCopyHandler` extension point
this.adapter = new KtLintCompat0Dot50Dot0Adapter();
} else if (minorVersion == 49) {
// Packages and modules moved around (`ktlint-core` -> `ktlint-rule-engine`)
// Experimental ruleset was replaced by implementing `Rule.Experimental` and checking the `ktlint_experimental` `.editorconfig` property
// `RuleId` and `RuleSetId` became inline classes (mangled to be unrepresentable in Java source code, so reflection is needed), tracked here: https://github.com/pinterest/ktlint/issues/2041
this.adapter = new KtLintCompat0Dot49Dot0Adapter();
} else if (minorVersion == 48) {
} else {
// ExperimentalParams lost two constructor arguments, EditorConfigProperty moved to its own class
this.adapter = new KtLintCompat0Dot48Dot0Adapter();
} else {
// rename RuleSet to RuleProvider
this.adapter = new KtLintCompat0Dot47Dot0Adapter();
}
this.editorConfigPath = editorConfigPath;
this.useExperimental = useExperimental;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class KtLintStep {
// prevent direct instantiation
private KtLintStep() {}

private static final String DEFAULT_VERSION = "0.49.1";
private static final String DEFAULT_VERSION = "0.50.0";
static final String NAME = "ktlint";
static final String PACKAGE = "com.pinterest";
static final String MAVEN_COORDINATE = PACKAGE + ":ktlint:";
Expand Down
Loading

0 comments on commit 3bafa6a

Please sign in to comment.