1{
2 lib,
3 runCommandLocal,
4 nix,
5}:
6
7# Replace some direct dependencies of drv, not recursing into the dependency tree.
8# You likely want to use replaceDependencies instead, unless you plan to implement your own recursion mechanism.
9{
10 drv,
11 replacements ? [ ],
12}:
13let
14 inherit (lib)
15 isStorePath
16 substring
17 stringLength
18 optionalString
19 escapeShellArgs
20 concatMap
21 ;
22in
23if replacements == [ ] then
24 drv
25else
26 let
27 drvName =
28 if isStorePath drv then
29 # Reconstruct the name from the actual store path if available.
30 substring 33 (stringLength (baseNameOf drv)) (baseNameOf drv)
31 else if drv ? drvAttrs.name then
32 # Try to get the name from the derivation arguments otherwise (for floating or deferred derivations).
33 drv.drvAttrs.name
34 + (
35 let
36 outputName = drv.outputName or "out";
37 in
38 optionalString (outputName != "out") "-${outputName}"
39 )
40 else
41 throw "cannot reconstruct the derivation name from ${drv}";
42 in
43 runCommandLocal drvName { nativeBuildInputs = [ nix.out ]; } ''
44 createRewriteScript() {
45 while [ $# -ne 0 ]; do
46 oldBasename="$(basename "$1")"
47 newBasename="$(basename "$2")"
48 shift 2
49 if [ ''${#oldBasename} -ne ''${#newBasename} ]; then
50 echo "cannot rewrite $oldBasename to $newBasename: length does not match" >&2
51 exit 1
52 fi
53 echo "s|$oldBasename|$newBasename|g" >> rewrite.sed
54 done
55 }
56 createRewriteScript ${
57 escapeShellArgs (
58 [
59 drv
60 (placeholder "out")
61 ]
62 ++ concatMap (
63 { oldDependency, newDependency }:
64 [
65 oldDependency
66 newDependency
67 ]
68 ) replacements
69 )
70 }
71 nix-store --dump ${drv} | sed -f rewrite.sed | nix-store --restore $out
72 ''