Clone of https://github.com/NixOS/nixpkgs.git (to stress-test knotserver)
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 isStringLike
16 substring
17 stringLength
18 optionalString
19 escapeShellArgs
20 concatMap
21 ;
22
23 isNonCaStorePath =
24 x:
25 if isStringLike x then
26 let
27 str = toString x;
28 in
29 builtins.substring 0 1 str == "/" && (dirOf str == builtins.storeDir)
30 else
31 false;
32in
33if replacements == [ ] then
34 drv
35else
36 let
37 drvName =
38 if isNonCaStorePath drv then
39 # Reconstruct the name from the actual store path if available.
40 substring 33 (stringLength (baseNameOf drv)) (baseNameOf drv)
41 else if drv ? drvAttrs.name then
42 # Try to get the name from the derivation arguments otherwise (for floating or deferred derivations).
43 drv.drvAttrs.name
44 + (
45 let
46 outputName = drv.outputName or "out";
47 in
48 optionalString (outputName != "out") "-${outputName}"
49 )
50 else
51 throw "cannot reconstruct the derivation name from ${drv}";
52 in
53 runCommandLocal drvName { nativeBuildInputs = [ nix.out ]; } ''
54 createRewriteScript() {
55 while [ $# -ne 0 ]; do
56 oldBasename="$(basename "$1")"
57 newBasename="$(basename "$2")"
58 shift 2
59 if [ ''${#oldBasename} -ne ''${#newBasename} ]; then
60 echo "cannot rewrite $oldBasename to $newBasename: length does not match" >&2
61 exit 1
62 fi
63 echo "s|$oldBasename|$newBasename|g" >> rewrite.sed
64 done
65 }
66 createRewriteScript ${
67 escapeShellArgs (
68 [
69 drv
70 (placeholder "out")
71 ]
72 ++ concatMap (
73 { oldDependency, newDependency }:
74 [
75 oldDependency
76 newDependency
77 ]
78 ) replacements
79 )
80 }
81 nix-store --dump ${drv} | sed -f rewrite.sed | nix-store --restore $out
82 ''