Skip to content

Commit 38b8144

Browse files
authored
patchpkg: lookPath helper to find nix binaries (#2247)
When running inside a Nix derivation the PATH is completely empty, so functions like `exec.Command("bash")` don't work. To make dealing with this easier, add a helper function that looks for an environment variable named after the command and returns `$cmd/bin/cmd` (e.g., `bash` becomes `$bash/bin/bash`). This will automatically find build-time dependencies that are added as attributes to the derivation.
1 parent 0fdfc67 commit 38b8144

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

internal/patchpkg/builder.go

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,7 @@ func (d *DerivationBuilder) Build(ctx context.Context, pkgStorePath string) erro
6767
}
6868
}
6969

70-
bash := filepath.Join(os.Getenv("bash"), "bin/bash")
71-
cmd := exec.CommandContext(ctx, bash, "-s")
70+
cmd := exec.CommandContext(ctx, lookPath("bash"), "-s")
7271
cmd.Stdin = bytes.NewReader(glibcPatchScript)
7372
cmd.Stdout = os.Stdout
7473
cmd.Stderr = os.Stderr
@@ -152,5 +151,24 @@ func allFiles(fsys fs.FS, root string) iter.Seq2[string, fs.DirEntry] {
152151
}
153152
}
154153

154+
// lookPath is like [exec.lookPath], but first checks if there's an environment
155+
// variable with the name prog. If there is, it returns $prog/bin/prog instead
156+
// of consulting PATH.
157+
//
158+
// For example, lookPath would be able to find bash and patchelf in the
159+
// following derivation:
160+
//
161+
// derivation {
162+
// inherit (nixpkgs.legacyPackages.x86_64-linux) bash patchelf;
163+
// builder = devbox;
164+
// }
165+
func lookPath(prog string) string {
166+
pkgPath := os.Getenv(prog)
167+
if pkgPath == "" {
168+
return prog
169+
}
170+
return filepath.Join(pkgPath, "bin", prog)
171+
}
172+
155173
func isExecutable(mode fs.FileMode) bool { return mode&0o111 != 0 }
156174
func isSymlink(mode fs.FileMode) bool { return mode&fs.ModeSymlink != 0 }

0 commit comments

Comments
 (0)