Skip to content
Merged
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
1 change: 0 additions & 1 deletion gradle-open-java-format/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// GRADLE_PUBLISH_SECRET. It applies java-gradle-plugin and maven-publish itself, and once the signing
// plugin is applied it signs what it uploads.
apply plugin: 'com.gradle.plugin-publish'
apply plugin: 'groovy'
apply plugin: 'signing'
apply plugin: 'open-java-format.publishing-conventions'

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@

package com.palantir.javaformat.gradle;

import static java.util.Comparator.reverseOrder;

import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Comparator;
import java.util.function.Predicate;
import java.util.stream.Stream;

Expand Down Expand Up @@ -88,7 +89,7 @@ private static void delete(Path dir) throws IOException {
return;
}
try (Stream<Path> paths = Files.walk(dir)) {
for (var path : paths.sorted(Comparator.reverseOrder()).toList()) {
for (var path : paths.sorted(reverseOrder()).toList()) {
Files.deleteIfExists(path);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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.palantir.javaformat.gradle;

import groovy.util.Node;
import java.lang.module.ModuleDescriptor;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

final class ConfigureJavaFormatterXml {

static void configureJavaFormat(Node rootNode, List<URI> uris) {
var settings = matchOrCreateChild(rootNode, "component", Map.of("name", "PalantirJavaFormatSettings"));
// enable
attributes(matchOrCreateChild(settings, "option", Map.of("name", "enabled")))
.put("value", "true");
// configure classpath
var classPath = matchOrCreateChild(settings, "option", Map.of("name", "implementationClassPath"));
var listItems = matchOrCreateChild(classPath, "list", Map.of());
listItems.children().clear();
for (var uri : uris) {
listItems.appendNode("option", new LinkedHashMap<>(Map.of("value", uri.toString())));
}
// Earlier versions wrote the native binary for openjavaformat.native.formatter=true. The IDE plugin has a
// setting of its own for that now, useNativeImage, which is left alone, and no longer reads this option.
matchChild(settings, "option", Map.of("name", "nativeImageClassPath"))
.ifPresent(option -> option.parent().remove(option));
}

static void configureWorkspaceXml(Node rootNode) {
configureFormatOnSave(rootNode);
configureOptimizeOnSave(rootNode);
}

// Lists an IDEA plugin as required by the project, so IntelliJ offers to install or update it. The other
// required plugins stay, and so does a higher min-version for this one, such as a developer's own choice.
static void configureExternalDependencies(Node rootNode, String pluginId, String minVersion) {
var externalDependencies = matchOrCreateChild(rootNode, "component", Map.of("name", "ExternalDependencies"));
var plugin = matchOrCreateChild(externalDependencies, "plugin", Map.of("id", pluginId));
var existing = plugin.attribute("min-version");
var required = ModuleDescriptor.Version.parse(minVersion);
if (existing == null
|| ModuleDescriptor.Version.parse(existing.toString()).compareTo(required) < 0) {
attributes(plugin).put("min-version", minVersion);
}
}

private static void configureFormatOnSave(Node rootNode) {
configureOnSaveAction(matchOrCreateChild(rootNode, "component", Map.of("name", "FormatOnSaveOptions")));
}

private static void configureOptimizeOnSave(Node rootNode) {
configureOnSaveAction(matchOrCreateChild(rootNode, "component", Map.of("name", "OptimizeOnSaveOptions")));
}

private static void configureOnSaveAction(Node onSaveOptions) {
// In IntelliJ <2023.3.7, the myRunOnSave option is default false.
// In IntelliJ >=2023.3.7, it is default true, and if it is set to true IntelliJ will remove it from the XML
// the next time the file is saved or the actions on save options window is saved.
// So to cover all cases, we always write it out and ensure it is true
var myRunOnSave = matchOrCreateChild(onSaveOptions, "option", Map.of("name", "myRunOnSave"));
attributes(myRunOnSave).put("value", "true");

// In IntelliJ <2023.3.7, the myAllFileTypesSelected option is default true.
// In IntelliJ >=2023.3.7, it is default false, and if it is set to false IntelliJ will remove it from the XML
// the next time the file is saved or the actions on save options window is saved.
// People may have manually set this to true, so we respect that setting is so. However, if it doesn't exist,
// we make sure it is explicitly set false to work in all IntelliJ versions.
matchOrCreateChild(onSaveOptions, "option", Map.of("name", "myAllFileTypesSelected"), Map.of("value", "false"));

// Ensure that is per-file type settings are enabled, we ensure JAVA is part of the list.
var mySelectedFileTypes = matchOrCreateChild(onSaveOptions, "option", Map.of("name", "mySelectedFileTypes"));
var set = matchOrCreateChild(mySelectedFileTypes, "set", Map.of());
matchOrCreateChild(set, "option", Map.of("value", "JAVA"));
}

private static Node matchOrCreateChild(Node base, String name, Map<String, String> attributes) {
return matchOrCreateChild(base, name, attributes, Map.of());
}

// A new child gets the defaults too; an existing one is left as it is.
private static Node matchOrCreateChild(
Node base, String name, Map<String, String> attributes, Map<String, String> defaults) {
return matchChild(base, name, attributes).orElseGet(() -> {
// The node keeps this map and the callers put values in it, so it has to be mutable.
var newAttributes = new LinkedHashMap<>(attributes);
newAttributes.putAll(defaults);
return base.appendNode(name, newAttributes);
});
}

private static Optional<Node> matchChild(Node base, String name, Map<String, String> attributes) {
// The children with that name, in a NodeList.
var children = (List<?>) base.get(name);
return children.stream()
.map(Node.class::cast)
.filter(child -> attributes(child).entrySet().containsAll(attributes.entrySet()))
.findFirst();
}

// Node.attributes() is a raw Map.
private static Map<Object, Object> attributes(Node node) {
return node.attributes();
}

private ConfigureJavaFormatterXml() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@

package com.palantir.javaformat.gradle;

import static com.google.common.base.Preconditions.checkState;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Comparator.comparing;
import static java.util.regex.Pattern.MULTILINE;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterators;
import com.google.common.collect.Range;
Expand Down Expand Up @@ -49,11 +50,11 @@ final class FormatDiff {
private static final Pattern SEPARATOR = Pattern.compile("diff --git");

// "+++ b/witchcraft-example-stateless/src/main/java/com/palantir/witchcraftexample/WitchcraftExampleResource.java"
private static final Pattern FILENAME = Pattern.compile("^\\+\\+\\+ (.+?)/(?<filename>.+)\\n", Pattern.MULTILINE);
private static final Pattern FILENAME = Pattern.compile("^\\+\\+\\+ (.+?)/(?<filename>.+)\\n", MULTILINE);

// "@@ -25,6 +26,19 @@ public final class WitchcraftExampleServer {"
private static final Pattern HUNK =
Pattern.compile("^@@.*\\+(?<startLineOneIndexed>\\d+)(,(?<numLines>\\d+))?", Pattern.MULTILINE);
Pattern.compile("^@@.*\\+(?<startLineOneIndexed>\\d+)(,(?<numLines>\\d+))?", MULTILINE);

public static void formatDiff(Path dirToFormat, FormatterService formatter)
throws IOException, InterruptedException {
Expand Down Expand Up @@ -132,7 +133,7 @@ private static String gitCommand(Path dir, String... args) throws IOException, I
Process process =
new ProcessBuilder().command(args).directory(dir.toFile()).start();

Preconditions.checkState(process.waitFor(30, TimeUnit.SECONDS), "git diff took too long to terminate");
checkState(process.waitFor(30, TimeUnit.SECONDS), "git diff took too long to terminate");
if (process.exitValue() != 0) {
throw new RuntimeException("Expected return code of 0 but got " + process.exitValue()
+ "\n stdout: " + new String(process.getInputStream().readAllBytes(), UTF_8)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

package com.palantir.javaformat.gradle;

import static java.util.stream.Collectors.joining;

import com.google.common.collect.Iterables;
import com.palantir.javaformat.java.FormatterService;
import java.io.File;
Expand All @@ -26,7 +28,6 @@
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.stream.Collectors;
import org.gradle.api.GradleException;

/**
Expand Down Expand Up @@ -111,7 +112,7 @@ private static void checkJavacIsExportedTo(ClassLoader formatterClassLoader) {
}
String addExports = JAVAC_PACKAGES.stream()
.map(javacPackage -> "--add-exports jdk.compiler/" + javacPackage + "=ALL-UNNAMED")
.collect(Collectors.joining(" "));
.collect(joining(" "));
throw new GradleException("""
open-java-format cannot run inside this Gradle JVM: module jdk.compiler does not export %s to it. \
Set one of these in gradle.properties:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

package com.palantir.javaformat.gradle;

import static java.util.stream.Collectors.toUnmodifiableSet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -28,7 +30,6 @@
import java.util.HexFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
Expand Down Expand Up @@ -107,7 +108,7 @@ private static void makeExecutable(Path file) throws IOException {
PosixFilePermission.OWNER_EXECUTE,
PosixFilePermission.GROUP_EXECUTE,
PosixFilePermission.OTHERS_EXECUTE))
.collect(Collectors.toUnmodifiableSet()));
.collect(toUnmodifiableSet()));
}

/** An image as it was when it was hashed: replaced in place, it changes size or time. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@

package com.palantir.javaformat.gradle;

import com.google.common.base.Preconditions;
import java.util.Collections;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Collections.singletonList;

import javax.inject.Inject;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
Expand All @@ -33,8 +34,8 @@ public abstract class NativeImageFormatProviderPlugin implements Plugin<Project>

@Override
public void apply(Project rootProject) {
Preconditions.checkState(
rootProject == rootProject.getRootProject(),
checkState(
rootProject.equals(rootProject.getRootProject()),
"May only apply dev.openjavaformat.java-format-provider to the root project");

Provider<NativePlatform> platform = NativePlatform.current(getProviderFactory());
Expand All @@ -44,7 +45,7 @@ public void apply(Project rootProject) {
conf.setCanBeConsumed(false);
conf.setCanBeResolved(true);
conf.defaultDependencies(deps -> {
deps.addAllLater(platform.map(p -> Collections.singletonList(rootProject
deps.addAllLater(platform.map(p -> singletonList(rootProject
.getDependencies()
.create(String.format(
"dev.openjavaformat:open-java-format-native:%s:%s@%s",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@

package com.palantir.javaformat.gradle;

import com.google.common.base.Preconditions;
import static com.google.common.base.Preconditions.checkState;

import java.util.stream.Stream;
import org.gradle.StartParameter;
import org.gradle.api.Plugin;
Expand All @@ -29,8 +30,8 @@ public abstract class PalantirJavaFormatIdeaPlugin implements Plugin<Project> {

@Override
public void apply(Project rootProject) {
Preconditions.checkState(
rootProject == rootProject.getRootProject(),
checkState(
rootProject.equals(rootProject.getRootProject()),
"May only apply dev.openjavaformat.java-format-idea to the root project");

rootProject.getPlugins().apply(PalantirJavaFormatProviderPlugin.class);
Expand Down
Loading
Loading