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
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
* {@link com.palantir.javaformat.gradle.PalantirJavaFormatSpotlessPlugin} even if spotless is not on the classpath.
*/
public abstract class SpotlessInterop implements Action<JavaExtension> {
private static final Logger logger = Logging.getLogger(SpotlessInterop.class);
private final Logger logger = Logging.getLogger(SpotlessInterop.class);

// Generated source directories, which are not formatted: a file is in one when its path in the project directory
// matches **/build/generated*/**, **/src/generated*/**, **/generated_*src/**, **/generated_*Src/** or
Expand All @@ -59,7 +59,7 @@
@Inject
protected abstract ObjectFactory getObjects();

@Inject

Check warning on line 62 in gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/SpotlessInterop.java

View workflow job for this annotation

GitHub Actions / build

[InjectOnConstructorOfAbstractClass] Constructors on abstract classes are never directly @Inject'ed, only the constructors of their subclasses can be @Inject'ed.
public SpotlessInterop(
File projectDir,
SourceSetContainer sourceSets,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
*/
@Service(Service.Level.APP)
final class EmbeddedNativeImage {
private static final Logger log = Logger.getInstance(EmbeddedNativeImage.class);
private final Logger log = Logger.getInstance(EmbeddedNativeImage.class);

private static final String MAVEN_CENTRAL = "https://repo1.maven.org/maven2";
private static final String TEMPORARY_PREFIX = "download-";
Expand Down Expand Up @@ -232,7 +232,7 @@
HttpRequests.request(url).productNameAsUserAgent().saveToFile(download, indicator);
return download;
});
if (!sha256(download).equalsIgnoreCase(expected.strip().split("\\s+")[0])) {

Check warning on line 235 in open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/EmbeddedNativeImage.java

View workflow job for this annotation

GitHub Actions / build

[StringSplitter] String.split(String) has surprising behavior
throw new IOException("the checksum of the download does not match Maven Central's");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@
import static java.util.Optional.ofNullable;

final class FormatterProvider {
private static final Logger log = Logger.getInstance(FormatterProvider.class);
private final Logger log = Logger.getInstance(FormatterProvider.class);

// Cache to avoid resolving the formatter every time we want to format from IntelliJ
private final LoadingCache<FormatterCacheKey, Optional<FormatterService>> implementationCache =
Caffeine.newBuilder().maximumSize(1).build(FormatterProvider::createFormatter);
Caffeine.newBuilder().maximumSize(1).build(this::createFormatter);

private final Supplier<Optional<Path>> embeddedNativeImage;
private final Supplier<Optional<String>> inProcessUnavailable;
Expand All @@ -69,7 +69,7 @@ Optional<FormatterService> get(Project project, PalantirJavaFormatSettings setti
settings, FormatterSelection.in(project, inProcessUnavailable, embeddedNativeImage))));
}

private static Optional<FormatterService> createFormatter(FormatterCacheKey cacheKey) {
private Optional<FormatterService> createFormatter(FormatterCacheKey cacheKey) {
return Optional.of(
switch (cacheKey.selection()) {
case FormatterSelection.NativeImage nativeImage -> {
Expand All @@ -85,7 +85,7 @@ private static Optional<FormatterService> createFormatter(FormatterCacheKey cach
});
}

private static FormatterService inProcess(FormatterCacheKey cacheKey) {
private FormatterService inProcess(FormatterCacheKey cacheKey) {
log.info("open-java-format: using in-process formatter (Java " + System.getProperty("java.version") + ") with "
+ classpathName(cacheKey) + " classpath");
// Loaded with the first file, in the background, and not here: this can be the UI thread. What cannot be
Expand All @@ -96,10 +96,10 @@ private static FormatterService inProcess(FormatterCacheKey cacheKey) {
InProcessFormatters.IDE,
classpath,
new BootstrappingFormatterService(ideRuntime.java(), ideRuntime.javaVersion(), classpath),
FormatterProvider::couldNotFormatInProcess);
this::couldNotFormatInProcess);
}

private static void couldNotFormatInProcess(Throwable failure) {
private void couldNotFormatInProcess(Throwable failure) {
var message = "open-java-format: cannot format inside the IDE, formatting in a JVM of its own";
if (InProcessFormatters.IDE.unavailable().isPresent()) {
// The formatter does not load or link in this IDE, which it should: an error, so that it goes to the
Expand All @@ -113,7 +113,7 @@ private static void couldNotFormatInProcess(Throwable failure) {
// The JVM gets the "--add-exports" it needs to reach javac. By default it is the IDE's own runtime rather than
// the project SDK: every IDE this plugin supports runs on Java 21 or later, which the formatter needs, while a
// project SDK can be any version.
private static FormatterService separateJvm(Path java, int javaVersion, FormatterCacheKey cacheKey) {
private FormatterService separateJvm(Path java, int javaVersion, FormatterCacheKey cacheKey) {
log.info("open-java-format: using Java-based formatter on " + java + " (Java " + javaVersion + ") with "
+ classpathName(cacheKey) + " classpath");
return new BootstrappingFormatterService(java, javaVersion, implementationClasspath(cacheKey));
Expand All @@ -133,7 +133,7 @@ private static String fallbackMessage(FormatterSelection.Fallback fallback) {
};
}

private static List<Path> implementationClasspath(FormatterCacheKey cacheKey) {
private List<Path> implementationClasspath(FormatterCacheKey cacheKey) {
return getImplementationUrls(cacheKey.implementationClassPath(), cacheKey.useBundledImplementation());
}

Expand All @@ -150,32 +150,27 @@ private static List<Path> getProvidedImplementationUrls(List<URI> implementation

/** The jars of the formatter bundled with the plugin, in the directory impl next to the plugin's own lib. */
static List<Path> getBundledImplementationUrls() {
Path implDir = ofNullable(FormattingService.EP_NAME.findExtension(PalantirJavaFormatFormattingService.class))
return listDirAsUrlsUnchecked(bundledImplementationDir());
}

private static Path bundledImplementationDir() {
return ofNullable(FormattingService.EP_NAME.findExtension(PalantirJavaFormatFormattingService.class))
.flatMap(PalantirJavaFormatFormattingService::getPluginDescriptor)
.map(PluginDescriptor::getPluginPath)
.orElseThrow(() -> new NoSuchElementException("The platform has not set the plugin descriptor"))
.resolve("impl");

log.debug("Using open-java-format implementation bundled with plugin: " + implDir);

return listDirAsUrlsUnchecked(implDir);
}

private static List<Path> getImplementationUrls(
private List<Path> getImplementationUrls(
Optional<List<URI>> implementationClassPath, boolean useBundledImplementation) {
if (useBundledImplementation) {
log.debug("Using open-java-format implementation bundled with plugin");
return getBundledImplementationUrls();
if (useBundledImplementation || implementationClassPath.isEmpty()) {
var implDir = bundledImplementationDir();
log.debug("Using open-java-format implementation bundled with plugin: " + implDir);
return listDirAsUrlsUnchecked(implDir);
}
return implementationClassPath
.map(classpath -> {
log.debug("Using open-java-format implementation defined by URIs: " + classpath);
return getProvidedImplementationUrls(classpath);
})
.orElseGet(() -> {
log.debug("Using open-java-format implementation bundled with plugin");
return getBundledImplementationUrls();
});
var classpath = implementationClassPath.orElseThrow();
log.debug("Using open-java-format implementation defined by URIs: " + classpath);
return getProvidedImplementationUrls(classpath);
}

private static List<Path> listDirAsUrlsUnchecked(Path dir) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,12 @@
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.jspecify.annotations.Nullable;

class PalantirJavaFormatFormattingService extends AsyncDocumentFormattingService implements PluginAware {
private static final Logger logger = Logger.getInstance(PalantirJavaFormatFormattingService.class);
private final Logger logger = Logger.getInstance(PalantirJavaFormatFormattingService.class);
private final FormatterProvider formatterProvider = new FormatterProvider(
() -> EmbeddedNativeImage.getInstance().installedPath(), InProcessFormatters.IDE::unavailable);
private final ImportOptimizer importOptimizer = new PalantirJavaFormatImportOptimizer(this);
Expand Down Expand Up @@ -210,7 +211,7 @@ public void documentChanged(DocumentEvent event) {
}
}

private static final class PalantirJavaFormatFormattingTask implements FormattingTask {
private final class PalantirJavaFormatFormattingTask implements FormattingTask {
private final AsyncFormattingRequest request;
private final Optional<FormatterService> formatterService;
private final PendingFormat pendingFormat;
Expand Down Expand Up @@ -249,25 +250,32 @@ private boolean format() {
if (logger.isDebugEnabled()) {
logger.debug(String.format(
"Received request to format file=%s, length=%s with ranges=%s",
ofNullable(request.getIOFile())
.map(file -> file.toPath().toString())
.orElse("null"),
preFormatText.length(),
request.getFormattingRanges()));
filePath(request), preFormatText.length(), request.getFormattingRanges()));
}

var start = System.nanoTime();
// Note: I attempted to implement this using getFormatReplacements and elide an update when
// there were no replacements. There is a bug in the underlying formatter where it _always_
// returns a change. Thus we must perform a content aware diff / branching.
String formattedText = applyReplacements(
preFormatText, formatterService.get().getFormatReplacements(preFormatText, toRanges(request)));
if (pendingFormat.finishFormatting()) {
var fixesImports = pendingFormat.finishFormatting();
if (fixesImports) {
formattedText = formatterService.get().fixImports(formattedText);
}
var changed = !preFormatText.equals(formattedText);
if (logger.isDebugEnabled()) {
logger.debug(String.format(
"Formatted file=%s in %s ms, imports fixed too: %s, text changed: %s",
filePath(request),
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start),
fixesImports,
changed));
}

// The Javadoc of this API says that you should set it to null when the document is unchanged
// We should not be trying to format a document that is already formatted
if (preFormatText.equals(formattedText)) {
if (!changed) {
request.onTextReady(null);
return false;
}
Expand Down Expand Up @@ -299,6 +307,12 @@ private boolean format() {
return false;
}

private static String filePath(AsyncFormattingRequest request) {
return ofNullable(request.getIOFile())
.map(file -> file.toPath().toString())
.orElse("null");
}

static String applyReplacements(String input, Collection<Replacement> replacementsCollection) {
List<Replacement> replacements = new ArrayList<>(replacementsCollection);
replacements.sort(comparing((Replacement r) -> r.getReplaceRange().lowerEndpoint())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,15 @@
import com.intellij.psi.PsiFile;
import com.palantir.javaformat.intellij.PalantirJavaFormatFormattingService.PendingFormat;
import com.palantir.javaformat.java.FormatterException;
import java.util.concurrent.TimeUnit;

/**
* Optimizes imports as the command line fixes them, with {@code FormatterService.fixImports}: the unused ones removed,
* the others sorted. The IDE takes it instead of its own {@code JavaImportOptimizer} for every way of optimizing
* imports, since {@link PalantirJavaFormatFormattingService} has {@code OPTIMIZE_IMPORTS}.
*/
final class PalantirJavaFormatImportOptimizer implements ImportOptimizer {
private static final Logger logger = Logger.getInstance(PalantirJavaFormatImportOptimizer.class);
private final Logger logger = Logger.getInstance(PalantirJavaFormatImportOptimizer.class);

// Changes nothing. An explicit Optimize Imports shows the message in its hint, instead of "No unused imports
// found"; on the fly nothing shows it.
Expand Down Expand Up @@ -67,11 +68,16 @@ public boolean supports(PsiFile file) {
public Runnable processFile(PsiFile file) {
Project project = file.getProject();
Document document = PsiDocumentManager.getInstance(project).getDocument(file);
if (document == null || leftToPendingFormat(document)) {
if (document == null) {
debug(file, "skipped, the file has no document");
return EmptyRunnable.getInstance();
}
if (leftToPendingFormat(document, file)) {
return EmptyRunnable.getInstance();
}
if (!PalantirJavaFormatFormattingService.isTrusted(project)) {
// Safe mode is a normal state, and on the fly this runs on every highlighting pass: no warning, no balloon.
debug(file, "skipped, the project is not trusted");
return UNTRUSTED_PROJECT;
}
var formatter = formattingService.getFormatter(project);
Expand All @@ -86,7 +92,17 @@ public Runnable processFile(PsiFile file) {
String text = document.getText();
String fixedText;
try {
var start = System.nanoTime();
fixedText = formatter.get().fixImports(text);
if (logger.isDebugEnabled()) {
debug(
file,
String.format(
"fixImports ran in %s ms, length=%s, text changed: %s",
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start),
text.length(),
!fixedText.equals(text)));
}
} catch (FormatterException e) {
// A syntax error in the file, not a fault of the plugin: an error would go to its error reports.
logger.warn(String.format("Failed to optimize imports of file %s", file.getName()), e);
Expand All @@ -110,8 +126,11 @@ public Runnable processFile(PsiFile file) {
return () -> {
// The document can have changed since: typed into, or given the text of a formatting request. Or a request
// can have started formatting it meanwhile, which takes the imports over.
if (StringUtil.equals(document.getImmutableCharSequence(), text) && !leftToPendingFormat(document)) {
if (!StringUtil.equals(document.getImmutableCharSequence(), text)) {
debug(file, "dropped the fixed imports, the document changed meanwhile");
} else if (!leftToPendingFormat(document, file)) {
document.setText(fixedText);
debug(file, "applied the fixed imports");
}
};
}
Expand All @@ -120,9 +139,29 @@ public Runnable processFile(PsiFile file) {
* Whether a formatting request is pending on the document: one that is still formatting fixes the imports itself,
* and one whose text is not applied yet would lose it if the document changed now.
*/
private static boolean leftToPendingFormat(Document document) {
private boolean leftToPendingFormat(Document document, PsiFile file) {
PendingFormat pendingFormat = PendingFormat.of(document);
return pendingFormat != null && (pendingFormat.handOverImports() || pendingFormat.isUnapplied());
if (pendingFormat == null) {
return false;
}
if (pendingFormat.handOverImports()) {
debug(file, "handed over to the formatting request in progress, which fixes them after formatting");
return true;
}
if (pendingFormat.isUnapplied()) {
debug(file, "skipped, a formatting request has finished and its text is not applied yet");
return true;
}
return false;
}

private void debug(PsiFile file, String message) {
if (logger.isDebugEnabled()) {
var virtualFile = file.getVirtualFile();
logger.debug(String.format(
"Optimizing imports of file=%s: %s",
virtualFile == null ? file.getName() : virtualFile.getPath(), message));
}
}

private static void reportError(Project project, String title, String message) {
Expand Down
Loading