Repository: GoogleContainerTools/skaffold
Pull request #7866 (2022-09-18 16:50:31)

fix: backport Bazel build context fixes to v1
Fixes: #7864

**Description**
I've backported commits which fix the usage of `Bazel` artifact context. Now it's possible to put `skaffold.yaml` file to subfolder of bazel workspace and set context to a relative path.

Before:
```sh
skaffold-v1.39.2 version
v1.39.2

skaffold-v1.39.2 run -p k8s-usw2-dev-skaffold
WARN[0000] failed to detect active kubernetes cluster node platform. Specify the correct build platform in the `skaffold.yaml` file or using the `--platform` flag  subtask=-1 task=DevLoop
Generating tags...
 ...
(18:34:17) INFO: Build completed successfully, 1 total action
build [***] failed: reading image "bazel-out/darwin_arm64-dbg-ST-4a519fd6d3e4/bin/***r/docker.tar": open bazel-out/darwin_arm64-dbg-ST-4a519fd6d3e4/bin/***/docker.tar: no such file or directory

skaffold-v1.39.2-patched version
v1.39.2-2-gc8d606d52

skaffold-v1.39.2-patched run -p k8s-usw2-dev-skaffold
WARN[0000] failed to detect active kubernetes cluster node platform. Specify the correct build platform in the `skaffold.yaml` file or using the `--platform` flag  subtask=-1 task=DevLoop
Generating tags...
...
(18:34:45) INFO: Build completed successfully, 1 total action
Build [***] succeeded
Starting test...
Tags used in deployment:
...
Deployments stabilized in 3.686 seconds
You can also run [skaffold run --tail] to get the logs
```

codecov[bot]: # [Codecov](https://codecov.io/gh/GoogleContainerTools/skaffold/pull/7866?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=GoogleContainerTools) Report
> :exclamation: No coverage uploaded for pull request base (`v1@7ed1d72`). [Click here to learn what that means](https://docs.codecov.io/docs/error-reference?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=GoogleContainerTools#section-missing-base-commit).
> The diff coverage is `n/a`.

```diff
@@          Coverage Diff          @@
##             v1    #7866   +/-   ##
=====================================
  Coverage      ?   68.29%           
=====================================
  Files         ?      563           
  Lines         ?    26692           
  Branches      ?        0           
=====================================
  Hits          ?    18230           
  Misses        ?     7188           
  Partials      ?     1274           
```



:mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=GoogleContainerTools)

aaron-prindle: Thanks for the PR @mikekamornikov!  Currently I am restarting the Windows Integration Test job as there was a failure (but this is likely a flake unrelated to your changes).  Once I can verify this is a flake and we have all tests passing we can merge this.

Patch:
diff --git a/pkg/skaffold/build/bazel/build.go b/pkg/skaffold/build/bazel/build.go
index 4e3b57130..29d2930fd 100644
--- a/pkg/skaffold/build/bazel/build.go
+++ b/pkg/skaffold/build/bazel/build.go
@@ -23,6 +23,7 @@ import (
 	"io"
 	"os"
 	"os/exec"
+	"path/filepath"
 	"strings"
 
 	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker"
@@ -128,7 +129,19 @@ func bazelTarPath(ctx context.Context, workspace string, a *latest.BazelArtifact
 		return "", err
 	}
 
-	return strings.TrimSpace(string(buf)), nil
+	targetPath := strings.TrimSpace(string(buf))
+
+	cmd = exec.CommandContext(ctx, "bazel", "info", "execution_root")
+	cmd.Dir = workspace
+
+	buf, err = util.RunCmdOut(ctx, cmd)
+	if err != nil {
+		return "", err
+	}
+
+	execRoot := strings.TrimSpace(string(buf))
+
+	return filepath.Join(execRoot, targetPath), nil
 }
 
 func trimTarget(buildTarget string) string {


Test patch:
diff --git a/pkg/skaffold/build/bazel/build_test.go b/pkg/skaffold/build/bazel/build_test.go
index 5e376582a..0fc4a7e1a 100644
--- a/pkg/skaffold/build/bazel/build_test.go
+++ b/pkg/skaffold/build/bazel/build_test.go
@@ -18,7 +18,9 @@ package bazel
 
 import (
 	"context"
+	"fmt"
 	"io/ioutil"
+	"path/filepath"
 	"testing"
 
 	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker"
@@ -33,7 +35,7 @@ func TestBuildBazel(t *testing.T) {
 		t.NewTempDir().Mkdir("bin").Chdir()
 		t.Override(&util.DefaultExecCommand, testutil.CmdRun("bazel build //:app.tar --color=no").AndRunOut(
 			"bazel cquery //:app.tar --output starlark --starlark:expr target.files.to_list()[0].path",
-			"bin/app.tar"))
+			"bin/app.tar").AndRunOut("bazel info execution_root", ""))
 		testutil.CreateFakeImageTar("bazel:app", "bin/app.tar")
 
 		artifact := &latest.Artifact{
@@ -52,6 +54,29 @@ func TestBuildBazel(t *testing.T) {
 	})
 }
 
+func TestBazelTarPathPrependExecutionRoot(t *testing.T) {
+	testutil.Run(t, "", func(t *testutil.T) {
+		t.Override(&util.DefaultExecCommand, testutil.CmdRun("bazel build //:app.tar --color=no").AndRunOut(
+			"bazel cquery //:app.tar --output starlark --starlark:expr target.files.to_list()[0].path",
+			"app.tar").AndRunOut("bazel info execution_root", ".."))
+		testutil.CreateFakeImageTar("bazel:app", "../app.tar")
+
+		artifact := &latest.Artifact{
+			Workspace: "..",
+			ArtifactType: latest.ArtifactType{
+				BazelArtifact: &latest.BazelArtifact{
+					BuildTarget: "//:app.tar",
+				},
+			},
+		}
+
+		builder := NewArtifactBuilder(fakeLocalDaemon(), &mockConfig{}, false)
+		_, err := builder.Build(context.Background(), ioutil.Discard, artifact, "img:tag", platform.Matcher{})
+
+		t.CheckNoError(err)
+	})
+}
+
 func TestBuildBazelFailInvalidTarget(t *testing.T) {
 	testutil.Run(t, "", func(t *testutil.T) {
 		artifact := &latest.Artifact{
@@ -70,11 +95,27 @@ func TestBuildBazelFailInvalidTarget(t *testing.T) {
 }
 
 func TestBazelTarPath(t *testing.T) {
-	testutil.Run(t, "", func(t *testutil.T) {
+	testutil.Run(t, "EmptyExecutionRoot", func(t *testutil.T) {
+		osSpecificPath := filepath.Join("absolute", "path", "bin")
+		t.Override(&util.DefaultExecCommand, testutil.CmdRunOut(
+			"bazel cquery //:skaffold_example.tar --output starlark --starlark:expr target.files.to_list()[0].path --arg1 --arg2",
+			fmt.Sprintf("%s\n", osSpecificPath),
+		).AndRunOut("bazel info execution_root", ""))
+
+		bazelBin, err := bazelTarPath(context.Background(), ".", &latest.BazelArtifact{
+			BuildArgs:   []string{"--arg1", "--arg2"},
+			BuildTarget: "//:skaffold_example.tar",
+		})
+
+		t.CheckNoError(err)
+		t.CheckDeepEqual(osSpecificPath, bazelBin)
+	})
+	testutil.Run(t, "AbsoluteExecutionRoot", func(t *testutil.T) {
+		osSpecificPath := filepath.Join("var", "tmp", "bazel-execution-roots", "abcdefg", "execroot", "workspace_name")
 		t.Override(&util.DefaultExecCommand, testutil.CmdRunOut(
 			"bazel cquery //:skaffold_example.tar --output starlark --starlark:expr target.files.to_list()[0].path --arg1 --arg2",
-			"/absolute/path/bin\n",
-		))
+			"bazel-bin/darwin-fastbuild-ST-confighash/path/to/bin\n",
+		).AndRunOut("bazel info execution_root", osSpecificPath))
 
 		bazelBin, err := bazelTarPath(context.Background(), ".", &latest.BazelArtifact{
 			BuildArgs:   []string{"--arg1", "--arg2"},
@@ -82,7 +123,8 @@ func TestBazelTarPath(t *testing.T) {
 		})
 
 		t.CheckNoError(err)
-		t.CheckDeepEqual("/absolute/path/bin", bazelBin)
+		expected := filepath.Join(osSpecificPath, "bazel-bin", "darwin-fastbuild-ST-confighash", "path", "to", "bin")
+		t.CheckDeepEqual(expected, bazelBin)
 	})
 }