Skip to content

Commit

Permalink
[prettier] Add support for prettier v3 plugin changes (#1802 fixes #1798
Browse files Browse the repository at this point in the history
)
  • Loading branch information
nedtwigg authored Sep 9, 2023
2 parents 614e75b + 3754eb1 commit 7631fb0
Show file tree
Hide file tree
Showing 17 changed files with 324 additions and 59 deletions.
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (

## [Unreleased]

### Fixed
* Added support for plugins when using Prettier version `3.0.0` and newer. ([#1802](https://github.com/diffplug/spotless/pull/1802))

## [2.41.0] - 2023-08-29
### Added
* Add a `jsonPatch` step to `json` formatter configurations. This allows patching of JSON documents using [JSON Patches](https://jsonpatch.com). ([#1753](https://github.com/diffplug/spotless/pull/1753))
Expand Down
18 changes: 17 additions & 1 deletion lib/src/main/java/com/diffplug/spotless/npm/JsonEscaper.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -34,6 +34,22 @@ public static String jsonEscape(Object val) {
if (val instanceof String) {
return jsonEscape((String) val);
}
if (ListableAdapter.canAdapt(val)) {
// create an array
StringBuilder sb = new StringBuilder();
sb.append('[');
boolean first = true;
for (Object o : ListableAdapter.adapt(val)) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(jsonEscape(o));
}
sb.append(']');
return sb.toString();
}
return val.toString();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -28,33 +28,46 @@

import com.diffplug.spotless.ThrowingEx;

public class SimpleJsonWriter {
class JsonWriter {

private final LinkedHashMap<String, Object> valueMap = new LinkedHashMap<>();

public static SimpleJsonWriter of(Map<String, ?> values) {
SimpleJsonWriter writer = new SimpleJsonWriter();
public static JsonWriter of(Map<String, ?> values) {
JsonWriter writer = new JsonWriter();
writer.putAll(values);
return writer;
}

SimpleJsonWriter putAll(Map<String, ?> values) {
JsonWriter putAll(Map<String, ?> values) {
verifyValues(values);
this.valueMap.putAll(values);
return this;
}

SimpleJsonWriter put(String name, Object value) {
JsonWriter put(String name, Object value) {
verifyValues(Collections.singletonMap(name, value));
this.valueMap.put(name, value);
return this;
}

private void verifyValues(Map<String, ?> values) {
if (values.values()
.stream()
.anyMatch(val -> !(val instanceof String || val instanceof JsonRawValue || val instanceof Number || val instanceof Boolean))) {
throw new IllegalArgumentException("Only values of type 'String', 'JsonRawValue', 'Number' and 'Boolean' are supported. You provided: " + values.values());
for (Object value : values.values()) {
verifyValue(value);
}
}

private void verifyValue(Object val) {
if (val == null) {
return;
}
if (ListableAdapter.canAdapt(val)) {
for (Object o : ListableAdapter.adapt(val)) {
verifyValue(o);
}
return;
}
if (!(val instanceof String || val instanceof JsonRawValue || val instanceof Number || val instanceof Boolean)) {
throw new IllegalArgumentException("Only values of type 'String', 'JsonRawValue', 'Number' and 'Boolean' are supported. You provided: " + val);
}
}

Expand Down
58 changes: 58 additions & 0 deletions lib/src/main/java/com/diffplug/spotless/npm/ListableAdapter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* 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.npm;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import javax.annotation.Nonnull;

class ListableAdapter<T> implements Iterable<T> {

private final List<T> delegate;

@SuppressWarnings("unchecked")
private ListableAdapter(Object delegate) {
Objects.requireNonNull(delegate);
if (!canAdapt(delegate)) {
throw new IllegalArgumentException("Cannot create ListableAdapter from " + delegate.getClass() + ". Use canAdapt() to check first.");
}
if (delegate instanceof List) {
this.delegate = (List<T>) delegate;
} else if (delegate.getClass().isArray()) {
this.delegate = Arrays.asList((T[]) delegate);
} else {
throw new IllegalArgumentException("Cannot create IterableAdapter from " + delegate.getClass());
}
}

static <T> Iterable<T> adapt(Object delegate) {
return new ListableAdapter<>(delegate);
}

@Override
@Nonnull
public Iterator<T> iterator() {
return delegate.iterator();
}

static boolean canAdapt(Object delegate) {
Objects.requireNonNull(delegate);
return delegate instanceof List || delegate.getClass().isArray();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ public String resolveConfig(File prettierConfigPath, Map<String, Object> prettie
jsonProperties.put("prettier_config_path", prettierConfigPath.getAbsolutePath());
}
if (prettierConfigOptions != null) {
jsonProperties.put("prettier_config_options", SimpleJsonWriter.of(prettierConfigOptions).toJsonRawValue());

jsonProperties.put("prettier_config_options", JsonWriter.of(prettierConfigOptions).toJsonRawValue());
}
return restClient.postJson("/prettier/config-options", jsonProperties);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2021 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -40,7 +40,7 @@ static SimpleRestClient forBaseUrl(String baseUrl) {
}

String postJson(String endpoint, Map<String, Object> jsonParams) throws SimpleRestException {
final SimpleJsonWriter jsonWriter = SimpleJsonWriter.of(jsonParams);
final JsonWriter jsonWriter = JsonWriter.of(jsonParams);
final String jsonString = jsonWriter.toJsonString();

return postJson(endpoint, jsonString);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ private Map<String, Object> unifyOptions() {
Map<String, Object> unified = new HashMap<>();
if (!this.inlineTsFmtSettings.isEmpty()) {
File targetFile = new File(this.buildDir, "inline-tsfmt.json");
SimpleJsonWriter.of(this.inlineTsFmtSettings).toJsonFile(targetFile);
JsonWriter.of(this.inlineTsFmtSettings).toJsonFile(targetFile);
unified.put("tsfmt", true);
unified.put("tsfmtFile", targetFile.getAbsolutePath());
} else if (this.configFile != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public String format(String fileContent, Map<String, Object> configOptions) {
Map<String, Object> jsonProperties = new LinkedHashMap<>();
jsonProperties.put("file_content", fileContent);
if (configOptions != null && !configOptions.isEmpty()) {
jsonProperties.put("config_options", SimpleJsonWriter.of(configOptions).toJsonRawValue());
jsonProperties.put("config_options", JsonWriter.of(configOptions).toJsonRawValue());
}

return restClient.postJson("/tsfmt/format", jsonProperties);
Expand Down
3 changes: 3 additions & 0 deletions plugin-gradle/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (

## [Unreleased]

### Fixed
* Added support for plugins when using Prettier version `3.0.0` and newer. ([#1802](https://github.com/diffplug/spotless/pull/1802))

## [6.21.0] - 2023-08-29
### Added
* Add a `jsonPatch` step to `json` formatter configurations. This allows patching of JSON documents using [JSON Patches](https://jsonpatch.com). ([#1753](https://github.com/diffplug/spotless/pull/1753))
Expand Down
2 changes: 2 additions & 0 deletions plugin-gradle/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1024,10 +1024,12 @@ Since spotless uses the actual npm prettier package behind the scenes, it is pos
spotless {
java {
prettier(['prettier': '2.8.8', 'prettier-plugin-java': '2.2.0']).config(['parser': 'java', 'tabWidth': 4])
// prettier(['prettier': '3.0.3', 'prettier-plugin-java': '2.3.0']).config(['parser': 'java', 'tabWidth': 4, 'plugins': ['prettier-plugin-java']]) // Prettier v3 requires additional 'plugins' config
}
format 'php', {
target 'src/**/*.php'
prettier(['prettier': '2.8.8', '@prettier/plugin-php': '0.19.6']).config(['parser': 'php', 'tabWidth': 3])
// prettier(['prettier': '3.0.3', '@prettier/plugin-php': '0.20.1']).config(['parser': 'php', 'tabWidth': 3, 'plugins': ['@prettier/plugin-php']]) // Prettier v3 requires additional 'plugins' config
}
}
```
Expand Down
Loading

0 comments on commit 7631fb0

Please sign in to comment.