diff --git a/base/src/META-INF/blaze-base.xml b/base/src/META-INF/blaze-base.xml
index be581d52e83..d3477e574b3 100644
--- a/base/src/META-INF/blaze-base.xml
+++ b/base/src/META-INF/blaze-base.xml
@@ -381,7 +381,7 @@
language="BUILD"
implementationClass="com.google.idea.blaze.base.run.producers.BuildFileRunLineMarkerContributor"/>
-
+
diff --git a/base/src/com/google/idea/blaze/base/buildmodifier/BuildifierDownloader.java b/base/src/com/google/idea/blaze/base/buildmodifier/BuildifierDownloader.java
new file mode 100644
index 00000000000..f538818bf5a
--- /dev/null
+++ b/base/src/com/google/idea/blaze/base/buildmodifier/BuildifierDownloader.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2024 The Bazel Authors. 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.google.idea.blaze.base.buildmodifier;
+
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.PathManager;
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.progress.ProgressManager;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Key;
+import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.testFramework.TestModeFlags;
+import com.intellij.util.ObjectUtils;
+import com.intellij.util.containers.ContainerUtil;
+import com.intellij.util.download.DownloadableFileService;
+import com.intellij.util.system.CpuArch;
+import com.intellij.util.system.OS;
+import com.intellij.util.ui.EDT;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.VisibleForTesting;
+
+public final class BuildifierDownloader {
+
+ private static final Logger LOG = Logger.getInstance(BuildifierDownloader.class);
+
+ /**
+ * Key for {@link TestModeFlags} to mock the OS version.
+ */
+ static final Key OS_KEY = new Key<>("OS_KEY");
+
+ /**
+ * Key for {@link TestModeFlags} to mock the CpuArch.
+ */
+ static final Key CPU_ARCH_KEY = new Key<>("CPU_ARCH_KEY");
+
+ /**
+ * Hardcoded buildifier version, update it to bump the version.
+ */
+ private static final String BUILDIFIER_VERSION = "7.1.2";
+
+ private static final Path DOWNLOAD_PATH = PathManager.getPluginsDir().resolve("buildifier");
+ private static final String DOWNLOAD_URL = "https://github.com/bazelbuild/buildtools/releases/download";
+
+ public static boolean canDownload() {
+ return getDownloadUrl() != null;
+ }
+
+ public static @Nullable File downloadWithProgress(Project project) {
+ return ProgressManager.getInstance().runProcessWithProgressSynchronously(
+ BuildifierDownloader::downloadSync,
+ "Downloading: " + getFileName(),
+ true,
+ project
+ );
+ }
+
+ @VisibleForTesting
+ public static @Nullable File downloadSync() {
+ try {
+ return download();
+ } catch (Exception e) {
+ LOG.error("download failed", e);
+ return null;
+ }
+ }
+
+ private static File download() throws IOException {
+ LOG.assertTrue(!EDT.isCurrentThreadEdt(), "runs on background thread");
+ LOG.assertTrue(!ApplicationManager.getApplication().isReadAccessAllowed(), "runs without read lock");
+
+ if (!Files.exists(DOWNLOAD_PATH)) {
+ Files.createDirectories(DOWNLOAD_PATH);
+ }
+
+ final var fileName = getFileName();
+ final var file = DOWNLOAD_PATH.resolve(fileName);
+ Files.deleteIfExists(file);
+
+ final var url = getDownloadUrl();
+ if (url == null) {
+ throw new IOException("cannot create download url");
+ }
+
+ final var service = DownloadableFileService.getInstance();
+ final var description = service.createFileDescription(url, fileName);
+ final var downloader = service.createDownloader(List.of(description), fileName);
+
+ final var results = downloader.download(DOWNLOAD_PATH.toFile());
+ final var result = ContainerUtil.getFirstItem(results);
+ if (result == null) {
+ throw new IOException("download failed");
+ }
+
+ final var resultFile = result.getFirst();
+ FileUtil.setExecutable(resultFile);
+
+ return resultFile;
+ }
+
+ private static String getFileName() {
+ final var version = BUILDIFIER_VERSION.replace('.', '_');
+
+ if (getOS() == OS.Windows) {
+ return String.format("buildifier_%s.exe", version);
+ } else {
+ return String.format("buildifier_%s", version);
+ }
+ }
+
+ private static OS getOS() {
+ return ObjectUtils.coalesce(TestModeFlags.get(OS_KEY), OS.CURRENT);
+ }
+
+ private static CpuArch getCpuArch() {
+ return ObjectUtils.coalesce(TestModeFlags.get(CPU_ARCH_KEY), CpuArch.CURRENT);
+ }
+
+ private static @Nullable String getPlatformIdentifier() {
+ return switch (getOS()) {
+ case Windows -> "windows";
+ case macOS -> "darwin";
+ case Linux -> "linux";
+ default -> null;
+ };
+ }
+
+ private static @Nullable String getArchitectureIdentifier() {
+ return switch (getCpuArch()) {
+ case X86_64 -> "amd64";
+ case ARM64 -> "arm64";
+ default -> null;
+ };
+ }
+
+ private static @Nullable String getDownloadUrl() {
+ final var platform = getPlatformIdentifier();
+ final var arch = getArchitectureIdentifier();
+
+ if (platform == null || arch == null) {
+ return null;
+ }
+
+ // example: https://github.com/bazelbuild/buildtools/releases/download/v7.1.2/buildifier-darwin-amd64
+ final var url = String.format(
+ "%s/v%s/buildifier-%s-%s",
+ DOWNLOAD_URL,
+ BUILDIFIER_VERSION,
+ platform,
+ arch
+ );
+
+ if (getOS() == OS.Windows) {
+ return url + ".exe";
+ } else {
+ return url;
+ }
+ }
+}
diff --git a/base/src/com/google/idea/blaze/base/buildmodifier/BuildifierFormattingService.java b/base/src/com/google/idea/blaze/base/buildmodifier/BuildifierFormattingService.java
index 4fa727abbcc..2ee564d7557 100644
--- a/base/src/com/google/idea/blaze/base/buildmodifier/BuildifierFormattingService.java
+++ b/base/src/com/google/idea/blaze/base/buildmodifier/BuildifierFormattingService.java
@@ -41,14 +41,11 @@ public final class BuildifierFormattingService extends AsyncDocumentFormattingSe
static final FeatureRolloutExperiment useNewBuildifierFormattingService =
new FeatureRolloutExperiment("formatter.api.buildifier");
- static final Supplier> binaryPath = Suppliers.memoize(() -> getBinary());
-
@Override
@Nullable
protected FormattingTask createFormattingTask(AsyncFormattingRequest request) {
BuildFile buildFile = (BuildFile) request.getContext().getContainingFile();
- return binaryPath
- .get()
+ return getBinary()
.map(binary -> BuildFileFormatter.getCommandLineArgs(binary, buildFile))
.map(args -> new BuildifierFormattingTask(request, args))
.orElse(null);
@@ -75,7 +72,7 @@ public ImmutableSet getFeatures() {
public boolean canFormat(PsiFile file) {
return useNewBuildifierFormattingService.isEnabled()
&& file instanceof BuildFile
- && binaryPath.get().isPresent();
+ && getBinary().isPresent();
}
private static Optional getBinary() {
diff --git a/base/src/com/google/idea/blaze/base/buildmodifier/BuildifierNotification.java b/base/src/com/google/idea/blaze/base/buildmodifier/BuildifierNotification.java
new file mode 100644
index 00000000000..6e64f4d51e3
--- /dev/null
+++ b/base/src/com/google/idea/blaze/base/buildmodifier/BuildifierNotification.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright 2024 The Bazel Authors. 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.google.idea.blaze.base.buildmodifier;
+
+import com.google.idea.blaze.base.settings.BlazeUserSettings;
+import com.intellij.ide.BrowserUtil;
+import com.intellij.ide.util.PropertiesComponent;
+import com.intellij.notification.Notification;
+import com.intellij.notification.NotificationAction;
+import com.intellij.notification.NotificationGroup;
+import com.intellij.notification.NotificationGroupManager;
+import com.intellij.notification.NotificationType;
+import com.intellij.notification.Notifications;
+import com.intellij.openapi.actionSystem.AnActionEvent;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Key;
+import org.jetbrains.annotations.NotNull;
+
+public final class BuildifierNotification {
+
+ private static final String GITHUB_URL = "https://github.com/bazelbuild/buildtools/";
+
+ private static final String NOTIFICATION_GROUP_ID = "Buildifier";
+ private static final String NOTIFICATION_DOWNLOAD_TITLE = "Download Buildifier";
+ private static final String NOTIFICATION_DOWNLOAD_QUESTION = "Would you like to download the buildifier formatter?";
+ private static final String NOTIFICATION_DOWNLOAD_SUCCESS = "Buildifier download was successful.";
+ private static final String NOTIFICATION_DOWNLOAD_FAILURE = "Buildifier download failed. Please install it manually.";
+ private static final String NOTIFICATION_NOTFOUND_FAILURE = "Could not find buildifier binary. Please install it manually.";
+
+ private static final Key NOTIFICATION_DOWNLOAD_SHOWN_KEY = new Key<>("buildifier.notification.download");
+ private static final Key NOTIFICATION_NOTFOUND_SHOWN_KEY = new Key<>("buildifier.notification.notfound");
+
+ private static final NotificationGroup NOTIFICATION_GROUP =
+ NotificationGroupManager.getInstance().getNotificationGroup(NOTIFICATION_GROUP_ID);
+
+ public static void showDownloadNotification() {
+ if (!shouldShowNotification(NOTIFICATION_DOWNLOAD_SHOWN_KEY)) {
+ return;
+ }
+
+ final var notification = NOTIFICATION_GROUP.createNotification(
+ NOTIFICATION_DOWNLOAD_TITLE,
+ NOTIFICATION_DOWNLOAD_QUESTION,
+ NotificationType.INFORMATION
+ ).setSuggestionType(true);
+
+ notification.addAction(
+ new NotificationAction("Download") {
+ @Override
+ public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) {
+ notification.expire();
+ install(e.getProject());
+ }
+ }
+ );
+
+ notification.addAction(
+ NotificationAction.createSimple("Dismiss", () -> {
+ notification.expire();
+ dismissNotification(NOTIFICATION_DOWNLOAD_SHOWN_KEY);
+ }
+ )
+ );
+
+ Notifications.Bus.notify(notification);
+ }
+
+ public static void showNotFoundNotification() {
+ if (!shouldShowNotification(NOTIFICATION_NOTFOUND_SHOWN_KEY)) {
+ return;
+ }
+
+ final var notification = NOTIFICATION_GROUP.createNotification(
+ NOTIFICATION_NOTFOUND_FAILURE,
+ NotificationType.ERROR
+ );
+
+ notification.addAction(
+ NotificationAction.createSimple("Open GitHub Page", () -> BrowserUtil.open(GITHUB_URL))
+ );
+
+ notification.addAction(
+ NotificationAction.createSimple("Dismiss", () -> {
+ notification.expire();
+ dismissNotification(NOTIFICATION_NOTFOUND_SHOWN_KEY);
+ }
+ )
+ );
+
+ Notifications.Bus.notify(notification);
+ }
+
+ private static void install(Project project) {
+ final var file = BuildifierDownloader.downloadWithProgress(project);
+
+ if (file == null) {
+ NOTIFICATION_GROUP.createNotification(
+ NOTIFICATION_DOWNLOAD_TITLE,
+ NOTIFICATION_DOWNLOAD_FAILURE,
+ NotificationType.ERROR
+ ).addAction(
+ NotificationAction.createSimple("Open GitHub Page", () -> BrowserUtil.open(GITHUB_URL))
+ ).notify(project);
+ } else {
+ NOTIFICATION_GROUP.createNotification(
+ NOTIFICATION_DOWNLOAD_TITLE,
+ NOTIFICATION_DOWNLOAD_SUCCESS,
+ NotificationType.INFORMATION
+ ).notify(project);
+
+ BlazeUserSettings.getInstance().setBuildifierBinaryPath(file.getAbsolutePath());
+ }
+ }
+
+ private static boolean shouldShowNotification(Key key) {
+ // dismiss is a persisted property
+ if (PropertiesComponent.getInstance().getBoolean(key.toString(), false)) {
+ return false;
+ }
+
+ // show the notification only once per application start
+ final var application = ApplicationManager.getApplication();
+ if (key.get(application, false)) {
+ return false;
+ }
+
+ application.putUserData(key, true);
+ return true;
+ }
+
+ private static void dismissNotification(Key key) {
+ PropertiesComponent.getInstance().setValue(key.toString(), true);
+ }
+}
diff --git a/base/src/com/google/idea/blaze/base/buildmodifier/DefaultBuildifierBinaryProvider.java b/base/src/com/google/idea/blaze/base/buildmodifier/DefaultBuildifierBinaryProvider.java
index a23e22b2d5e..9ed2e766b8e 100644
--- a/base/src/com/google/idea/blaze/base/buildmodifier/DefaultBuildifierBinaryProvider.java
+++ b/base/src/com/google/idea/blaze/base/buildmodifier/DefaultBuildifierBinaryProvider.java
@@ -15,12 +15,8 @@
*/
package com.google.idea.blaze.base.buildmodifier;
-import com.google.idea.blaze.base.settings.Blaze;
import com.google.idea.blaze.base.settings.BlazeUserSettings;
import com.intellij.execution.configurations.PathEnvironmentVariableUtil;
-import com.intellij.notification.NotificationGroupManager;
-import com.intellij.notification.NotificationType;
-import com.intellij.notification.Notifications;
import java.io.File;
import javax.annotation.Nullable;
@@ -43,19 +39,12 @@ public String getBuildifierBinaryPath() {
return relativeBinaryFile.getPath();
}
- notifyError(
- "Could not find the buildifier binary. Please install buildifier via the instructions at"
- + " https://github.com/bazelbuild/buildtools/tree/master/buildifier#readme and point"
- + " to it in the "
- + Blaze.guessBuildSystemName()
- + " settings.");
- return null;
- }
+ if (BuildifierDownloader.canDownload()) {
+ BuildifierNotification.showDownloadNotification();
+ } else {
+ BuildifierNotification.showNotFoundNotification();
+ }
- public static void notifyError(String content) {
- Notifications.Bus.notify(
- NotificationGroupManager.getInstance()
- .getNotificationGroup("BuildifierBinaryMissing")
- .createNotification(content, NotificationType.ERROR));
+ return null;
}
}
diff --git a/base/tests/integrationtests/com/google/idea/blaze/base/buildmodifier/BuildifierDownloaderTest.java b/base/tests/integrationtests/com/google/idea/blaze/base/buildmodifier/BuildifierDownloaderTest.java
new file mode 100644
index 00000000000..66597605ede
--- /dev/null
+++ b/base/tests/integrationtests/com/google/idea/blaze/base/buildmodifier/BuildifierDownloaderTest.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2016 The Bazel Authors. 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.google.idea.blaze.base.buildmodifier;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.intellij.testFramework.LightPlatformTestCase;
+import com.intellij.testFramework.TestModeFlags;
+import com.intellij.util.system.CpuArch;
+import com.intellij.util.system.OS;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link BuildifierDownloader}. */
+@RunWith(JUnit4.class)
+public class BuildifierDownloaderTest extends LightPlatformTestCase {
+
+ @Override
+ protected boolean runInDispatchThread() {
+ return false;
+ }
+
+ @Test
+ public void testMacArm64() {
+ doTest(OS.macOS, CpuArch.ARM64);
+ }
+
+ @Test
+ public void testMacAmd64() {
+ doTest(OS.macOS, CpuArch.X86_64);
+ }
+
+ @Test
+ public void testLinuxArm64() {
+ doTest(OS.Linux, CpuArch.ARM64);
+ }
+
+ @Test
+ public void testLinuxAmd64() {
+ doTest(OS.Linux, CpuArch.X86_64);
+ }
+
+ @Test
+ public void testWindowsAmd64() {
+ doTest(OS.Windows, CpuArch.X86_64);
+ }
+
+ private void doTest(OS os, CpuArch arch) {
+ TestModeFlags.set(BuildifierDownloader.OS_KEY, os);
+ TestModeFlags.set(BuildifierDownloader.CPU_ARCH_KEY, arch);
+
+ assertThat(BuildifierDownloader.downloadSync()).isNotNull();
+ }
+}