From 2f4de64c494e714b5dc6e7e33192313d55464292 Mon Sep 17 00:00:00 2001 From: Dmytro Kashyn <50216138+dkashyn-sfdc@users.noreply.github.com> Date: Mon, 26 Feb 2024 14:14:13 -0500 Subject: [PATCH] Use path to workspace root as `pwd` for `buildifier` (#6158) --- .../base/buildmodifier/BuildFileFormatter.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/base/src/com/google/idea/blaze/base/buildmodifier/BuildFileFormatter.java b/base/src/com/google/idea/blaze/base/buildmodifier/BuildFileFormatter.java index 8803597cbd8..5278f8f8b63 100644 --- a/base/src/com/google/idea/blaze/base/buildmodifier/BuildFileFormatter.java +++ b/base/src/com/google/idea/blaze/base/buildmodifier/BuildFileFormatter.java @@ -29,6 +29,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.TextRange; import java.io.BufferedReader; +import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Path; @@ -125,7 +126,19 @@ private static Iterable pathArg(@Nullable BuildFile buildFile) { @Nullable private static String formatText( String buildifierBinaryPath, BuildFile buildFile, String inputText) throws IOException { - Process process = new ProcessBuilder(getCommandLineArgs(buildifierBinaryPath, buildFile)).start(); + // We need to be in a proper directory to respect default buildifier config placement convention + // see https://github.com/bazelbuild/buildtools/blob/03bf520394afefdf48c558187b2d76b8b4b60ef1/buildifier/buildifier.go#L85 + // `a file named '.buildifier.json' at the root of the workspace (e.g., in the same directory as the WORKSPACE file)` + File buildifierWorkingDir = null; + + WorkspaceRoot workspaceRoot = BazelWorkspaceRootProvider.INSTANCE.findWorkspaceRoot(buildFile.getFile()); + if (workspaceRoot != null) { + buildifierWorkingDir = workspaceRoot.directory(); + } + + Process process = new ProcessBuilder(getCommandLineArgs(buildifierBinaryPath, buildFile)) + .directory(buildifierWorkingDir) + .start(); process.getOutputStream().write(inputText.getBytes(UTF_8)); process.getOutputStream().close();