diff --git a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/SpotlessInterop.java b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/SpotlessInterop.java index 7aa4f3221..78ab851c2 100644 --- a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/SpotlessInterop.java +++ b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/SpotlessInterop.java @@ -38,7 +38,7 @@ * {@link com.palantir.javaformat.gradle.PalantirJavaFormatSpotlessPlugin} even if spotless is not on the classpath. */ public abstract class SpotlessInterop implements Action { - 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 diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/EmbeddedNativeImage.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/EmbeddedNativeImage.java index 7fb8b33cd..38f236502 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/EmbeddedNativeImage.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/EmbeddedNativeImage.java @@ -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-"; diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java index 5e3f5f931..1309fc397 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java @@ -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> implementationCache = - Caffeine.newBuilder().maximumSize(1).build(FormatterProvider::createFormatter); + Caffeine.newBuilder().maximumSize(1).build(this::createFormatter); private final Supplier> embeddedNativeImage; private final Supplier> inProcessUnavailable; @@ -69,7 +69,7 @@ Optional get(Project project, PalantirJavaFormatSettings setti settings, FormatterSelection.in(project, inProcessUnavailable, embeddedNativeImage)))); } - private static Optional createFormatter(FormatterCacheKey cacheKey) { + private Optional createFormatter(FormatterCacheKey cacheKey) { return Optional.of( switch (cacheKey.selection()) { case FormatterSelection.NativeImage nativeImage -> { @@ -85,7 +85,7 @@ private static Optional 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 @@ -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 @@ -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)); @@ -133,7 +133,7 @@ private static String fallbackMessage(FormatterSelection.Fallback fallback) { }; } - private static List implementationClasspath(FormatterCacheKey cacheKey) { + private List implementationClasspath(FormatterCacheKey cacheKey) { return getImplementationUrls(cacheKey.implementationClassPath(), cacheKey.useBundledImplementation()); } @@ -150,32 +150,27 @@ private static List getProvidedImplementationUrls(List implementation /** The jars of the formatter bundled with the plugin, in the directory impl next to the plugin's own lib. */ static List 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 getImplementationUrls( + private List getImplementationUrls( Optional> 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 listDirAsUrlsUnchecked(Path dir) { diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java index 0fedcc3d1..f2a99ce99 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java @@ -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); @@ -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; private final PendingFormat pendingFormat; @@ -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; } @@ -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 replacementsCollection) { List replacements = new ArrayList<>(replacementsCollection); replacements.sort(comparing((Replacement r) -> r.getReplaceRange().lowerEndpoint()) diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java index a2d468a79..0d328b0e7 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java @@ -27,6 +27,7 @@ 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, @@ -34,7 +35,7 @@ * 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. @@ -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); @@ -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); @@ -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"); } }; } @@ -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) {