treewide: replace hardcoded runfiles paths

We hardcoded some of the runfiles paths to find specific files. This replaces the hardcoded paths by a call to rlocationpath. This prevents running a target without the correct dependencies at build time instead of at runtime

Change-Id: I7ce56935ac80be6b28b824ccb0781ab401bd6521
Reviewed-on: https://review.monogon.dev/c/monogon/+/3301
Reviewed-by: Serge Bazanski <serge@monogon.tech>
Tested-by: Jenkins CI
diff --git a/go/qcow2/BUILD.bazel b/go/qcow2/BUILD.bazel
index 07afa58..c4806eb 100644
--- a/go/qcow2/BUILD.bazel
+++ b/go/qcow2/BUILD.bazel
@@ -3,16 +3,19 @@
 go_library(
     name = "qcow2",
     srcs = ["qcow2.go"],
+    data = [
+        "@qemu//:qemu-img",
+    ],
     importpath = "source.monogon.dev/go/qcow2",
     visibility = ["//visibility:public"],
+    x_defs = {
+        "xQemuImgPath": "$(rlocationpath @qemu//:qemu-img )",
+    },
 )
 
 go_test(
     name = "qcow2_test",
     srcs = ["qcow2_test.go"],
-    data = [
-        "@qemu//:qemu-img",
-    ],
     embed = [":qcow2"],
     deps = ["@io_bazel_rules_go//go/runfiles:go_default_library"],
 )
diff --git a/go/qcow2/qcow2_test.go b/go/qcow2/qcow2_test.go
index 3b987c0..9dc230a 100644
--- a/go/qcow2/qcow2_test.go
+++ b/go/qcow2/qcow2_test.go
@@ -10,13 +10,27 @@
 	"github.com/bazelbuild/rules_go/go/runfiles"
 )
 
+var (
+	// These are filled by bazel at linking time with the canonical path of
+	// their corresponding file. Inside the init function we resolve it
+	// with the rules_go runfiles package to the real path.
+	xQemuImgPath string
+)
+
+func init() {
+	var err error
+	for _, path := range []*string{
+		&xQemuImgPath,
+	} {
+		*path, err = runfiles.Rlocation(*path)
+		if err != nil {
+			panic(err)
+		}
+	}
+}
+
 // TestGenerate exercises the Generate function for a variety of image sizes.
 func TestGenerate(t *testing.T) {
-	qemuImg, err := runfiles.Rlocation("qemu/qemu-img")
-	if err != nil {
-		t.Fatalf("Could not locate qemu-img: %v", err)
-	}
-
 	// Test all orders of magnitude from 1KiB to 1PiB.
 	for i := 20; i < 50; i++ {
 		t.Run(fmt.Sprintf("%d", 1<<i), func(t *testing.T) {
@@ -33,7 +47,7 @@
 				t.Fatalf("Close: %v", err)
 			}
 
-			cmd := exec.Command(qemuImg, "check", path)
+			cmd := exec.Command(xQemuImgPath, "check", path)
 			if err := cmd.Run(); err != nil {
 				t.Fatalf("qemu-img check failed: %v", err)
 			}