Skip to content

Commit

Permalink
Download Buildifier Binary (bazelbuild#6625)
Browse files Browse the repository at this point in the history
Adds support to automatically download the buildifier binary if it is not installed.
  • Loading branch information
LeFrosch authored Oct 10, 2024
1 parent 41e93fc commit 5ac22de
Show file tree
Hide file tree
Showing 6 changed files with 403 additions and 23 deletions.
2 changes: 1 addition & 1 deletion base/src/META-INF/blaze-base.xml
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@
language="BUILD"
implementationClass="com.google.idea.blaze.base.run.producers.BuildFileRunLineMarkerContributor"/>
<actionConfigurationCustomizer implementation="com.google.idea.blaze.base.plugin.BlazeHideMakeActions"/>
<notificationGroup displayType="BALLOON" id="BuildifierBinaryMissing"/>
<notificationGroup displayType="BALLOON" id="Buildifier"/>
<notificationGroup displayType="BALLOON" id="AddToProject" />
<notificationGroup displayType="STICKY_BALLOON" id="QuerySyncPromo" />
<notificationGroup displayType="BALLOON" id="QuerySyncBuild" />
Expand Down
Original file line number Diff line number Diff line change
@@ -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> OS_KEY = new Key<>("OS_KEY");

/**
* Key for {@link TestModeFlags} to mock the CpuArch.
*/
static final Key<CpuArch> 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;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,11 @@ public final class BuildifierFormattingService extends AsyncDocumentFormattingSe
static final FeatureRolloutExperiment useNewBuildifierFormattingService =
new FeatureRolloutExperiment("formatter.api.buildifier");

static final Supplier<Optional<String>> 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);
Expand All @@ -75,7 +72,7 @@ public ImmutableSet<Feature> getFeatures() {
public boolean canFormat(PsiFile file) {
return useNewBuildifierFormattingService.isEnabled()
&& file instanceof BuildFile
&& binaryPath.get().isPresent();
&& getBinary().isPresent();
}

private static Optional<String> getBinary() {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Boolean> NOTIFICATION_DOWNLOAD_SHOWN_KEY = new Key<>("buildifier.notification.download");
private static final Key<Boolean> 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<Boolean> 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<Boolean> key) {
PropertiesComponent.getInstance().setValue(key.toString(), true);
}
}
Loading

0 comments on commit 5ac22de

Please sign in to comment.