選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

483 行
14 KiB

  1. { lib }:
  2. # Operations on attribute sets.
  3. let
  4. inherit (builtins) head tail length;
  5. inherit (lib.trivial) and;
  6. inherit (lib.strings) concatStringsSep;
  7. inherit (lib.lists) fold concatMap concatLists;
  8. in
  9. rec {
  10. inherit (builtins) attrNames listToAttrs hasAttr isAttrs getAttr;
  11. /* Return an attribute from nested attribute sets.
  12. Example:
  13. x = { a = { b = 3; }; }
  14. attrByPath ["a" "b"] 6 x
  15. => 3
  16. attrByPath ["z" "z"] 6 x
  17. => 6
  18. */
  19. attrByPath = attrPath: default: e:
  20. let attr = head attrPath;
  21. in
  22. if attrPath == [] then e
  23. else if e ? ${attr}
  24. then attrByPath (tail attrPath) default e.${attr}
  25. else default;
  26. /* Return if an attribute from nested attribute set exists.
  27. Example:
  28. x = { a = { b = 3; }; }
  29. hasAttrByPath ["a" "b"] x
  30. => true
  31. hasAttrByPath ["z" "z"] x
  32. => false
  33. */
  34. hasAttrByPath = attrPath: e:
  35. let attr = head attrPath;
  36. in
  37. if attrPath == [] then true
  38. else if e ? ${attr}
  39. then hasAttrByPath (tail attrPath) e.${attr}
  40. else false;
  41. /* Return nested attribute set in which an attribute is set.
  42. Example:
  43. setAttrByPath ["a" "b"] 3
  44. => { a = { b = 3; }; }
  45. */
  46. setAttrByPath = attrPath: value:
  47. if attrPath == [] then value
  48. else listToAttrs
  49. [ { name = head attrPath; value = setAttrByPath (tail attrPath) value; } ];
  50. /* Like `attrByPath' without a default value. If it doesn't find the
  51. path it will throw.
  52. Example:
  53. x = { a = { b = 3; }; }
  54. getAttrFromPath ["a" "b"] x
  55. => 3
  56. getAttrFromPath ["z" "z"] x
  57. => error: cannot find attribute `z.z'
  58. */
  59. getAttrFromPath = attrPath: set:
  60. let errorMsg = "cannot find attribute `" + concatStringsSep "." attrPath + "'";
  61. in attrByPath attrPath (abort errorMsg) set;
  62. /* Return the specified attributes from a set.
  63. Example:
  64. attrVals ["a" "b" "c"] as
  65. => [as.a as.b as.c]
  66. */
  67. attrVals = nameList: set: map (x: set.${x}) nameList;
  68. /* Return the values of all attributes in the given set, sorted by
  69. attribute name.
  70. Example:
  71. attrValues {c = 3; a = 1; b = 2;}
  72. => [1 2 3]
  73. */
  74. attrValues = builtins.attrValues or (attrs: attrVals (attrNames attrs) attrs);
  75. /* Given a set of attribute names, return the set of the corresponding
  76. attributes from the given set.
  77. Example:
  78. getAttrs [ "a" "b" ] { a = 1; b = 2; c = 3; }
  79. => { a = 1; b = 2; }
  80. */
  81. getAttrs = names: attrs: genAttrs names (name: attrs.${name});
  82. /* Collect each attribute named `attr' from a list of attribute
  83. sets. Sets that don't contain the named attribute are ignored.
  84. Example:
  85. catAttrs "a" [{a = 1;} {b = 0;} {a = 2;}]
  86. => [1 2]
  87. */
  88. catAttrs = builtins.catAttrs or
  89. (attr: l: concatLists (map (s: if s ? ${attr} then [s.${attr}] else []) l));
  90. /* Filter an attribute set by removing all attributes for which the
  91. given predicate return false.
  92. Example:
  93. filterAttrs (n: v: n == "foo") { foo = 1; bar = 2; }
  94. => { foo = 1; }
  95. */
  96. filterAttrs = pred: set:
  97. listToAttrs (concatMap (name: let v = set.${name}; in if pred name v then [(nameValuePair name v)] else []) (attrNames set));
  98. /* Filter an attribute set recursively by removing all attributes for
  99. which the given predicate return false.
  100. Example:
  101. filterAttrsRecursive (n: v: v != null) { foo = { bar = null; }; }
  102. => { foo = {}; }
  103. */
  104. filterAttrsRecursive = pred: set:
  105. listToAttrs (
  106. concatMap (name:
  107. let v = set.${name}; in
  108. if pred name v then [
  109. (nameValuePair name (
  110. if isAttrs v then filterAttrsRecursive pred v
  111. else v
  112. ))
  113. ] else []
  114. ) (attrNames set)
  115. );
  116. /* Apply fold functions to values grouped by key.
  117. Example:
  118. foldAttrs (n: a: [n] ++ a) [] [{ a = 2; } { a = 3; }]
  119. => { a = [ 2 3 ]; }
  120. */
  121. foldAttrs = op: nul: list_of_attrs:
  122. fold (n: a:
  123. fold (name: o:
  124. o // { ${name} = op n.${name} (a.${name} or nul); }
  125. ) a (attrNames n)
  126. ) {} list_of_attrs;
  127. /* Recursively collect sets that verify a given predicate named `pred'
  128. from the set `attrs'. The recursion is stopped when the predicate is
  129. verified.
  130. Type:
  131. collect ::
  132. (AttrSet -> Bool) -> AttrSet -> [x]
  133. Example:
  134. collect isList { a = { b = ["b"]; }; c = [1]; }
  135. => [["b"] [1]]
  136. collect (x: x ? outPath)
  137. { a = { outPath = "a/"; }; b = { outPath = "b/"; }; }
  138. => [{ outPath = "a/"; } { outPath = "b/"; }]
  139. */
  140. collect = pred: attrs:
  141. if pred attrs then
  142. [ attrs ]
  143. else if isAttrs attrs then
  144. concatMap (collect pred) (attrValues attrs)
  145. else
  146. [];
  147. /* Utility function that creates a {name, value} pair as expected by
  148. builtins.listToAttrs.
  149. Example:
  150. nameValuePair "some" 6
  151. => { name = "some"; value = 6; }
  152. */
  153. nameValuePair = name: value: { inherit name value; };
  154. /* Apply a function to each element in an attribute set. The
  155. function takes two arguments --- the attribute name and its value
  156. --- and returns the new value for the attribute. The result is a
  157. new attribute set.
  158. Example:
  159. mapAttrs (name: value: name + "-" + value)
  160. { x = "foo"; y = "bar"; }
  161. => { x = "x-foo"; y = "y-bar"; }
  162. */
  163. mapAttrs = builtins.mapAttrs or
  164. (f: set:
  165. listToAttrs (map (attr: { name = attr; value = f attr set.${attr}; }) (attrNames set)));
  166. /* Like `mapAttrs', but allows the name of each attribute to be
  167. changed in addition to the value. The applied function should
  168. return both the new name and value as a `nameValuePair'.
  169. Example:
  170. mapAttrs' (name: value: nameValuePair ("foo_" + name) ("bar-" + value))
  171. { x = "a"; y = "b"; }
  172. => { foo_x = "bar-a"; foo_y = "bar-b"; }
  173. */
  174. mapAttrs' = f: set:
  175. listToAttrs (map (attr: f attr set.${attr}) (attrNames set));
  176. /* Call a function for each attribute in the given set and return
  177. the result in a list.
  178. Example:
  179. mapAttrsToList (name: value: name + value)
  180. { x = "a"; y = "b"; }
  181. => [ "xa" "yb" ]
  182. */
  183. mapAttrsToList = f: attrs:
  184. map (name: f name attrs.${name}) (attrNames attrs);
  185. /* Like `mapAttrs', except that it recursively applies itself to
  186. attribute sets. Also, the first argument of the argument
  187. function is a *list* of the names of the containing attributes.
  188. Type:
  189. mapAttrsRecursive ::
  190. ([String] -> a -> b) -> AttrSet -> AttrSet
  191. Example:
  192. mapAttrsRecursive (path: value: concatStringsSep "-" (path ++ [value]))
  193. { n = { a = "A"; m = { b = "B"; c = "C"; }; }; d = "D"; }
  194. => { n = { a = "n-a-A"; m = { b = "n-m-b-B"; c = "n-m-c-C"; }; }; d = "d-D"; }
  195. */
  196. mapAttrsRecursive = mapAttrsRecursiveCond (as: true);
  197. /* Like `mapAttrsRecursive', but it takes an additional predicate
  198. function that tells it whether to recursive into an attribute
  199. set. If it returns false, `mapAttrsRecursiveCond' does not
  200. recurse, but does apply the map function. It is returns true, it
  201. does recurse, and does not apply the map function.
  202. Type:
  203. mapAttrsRecursiveCond ::
  204. (AttrSet -> Bool) -> ([String] -> a -> b) -> AttrSet -> AttrSet
  205. Example:
  206. # To prevent recursing into derivations (which are attribute
  207. # sets with the attribute "type" equal to "derivation"):
  208. mapAttrsRecursiveCond
  209. (as: !(as ? "type" && as.type == "derivation"))
  210. (x: ... do something ...)
  211. attrs
  212. */
  213. mapAttrsRecursiveCond = cond: f: set:
  214. let
  215. recurse = path: set:
  216. let
  217. g =
  218. name: value:
  219. if isAttrs value && cond value
  220. then recurse (path ++ [name]) value
  221. else f (path ++ [name]) value;
  222. in mapAttrs g set;
  223. in recurse [] set;
  224. /* Generate an attribute set by mapping a function over a list of
  225. attribute names.
  226. Example:
  227. genAttrs [ "foo" "bar" ] (name: "x_" + name)
  228. => { foo = "x_foo"; bar = "x_bar"; }
  229. */
  230. genAttrs = names: f:
  231. listToAttrs (map (n: nameValuePair n (f n)) names);
  232. /* Check whether the argument is a derivation. Any set with
  233. { type = "derivation"; } counts as a derivation.
  234. Example:
  235. nixpkgs = import <nixpkgs> {}
  236. isDerivation nixpkgs.ruby
  237. => true
  238. isDerivation "foobar"
  239. => false
  240. */
  241. isDerivation = x: isAttrs x && x ? type && x.type == "derivation";
  242. /* Converts a store path to a fake derivation. */
  243. toDerivation = path:
  244. let
  245. path' = builtins.storePath path;
  246. res =
  247. { type = "derivation";
  248. name = builtins.unsafeDiscardStringContext (builtins.substring 33 (-1) (baseNameOf path'));
  249. outPath = path';
  250. outputs = [ "out" ];
  251. out = res;
  252. outputName = "out";
  253. };
  254. in res;
  255. /* If `cond' is true, return the attribute set `as',
  256. otherwise an empty attribute set.
  257. Example:
  258. optionalAttrs (true) { my = "set"; }
  259. => { my = "set"; }
  260. optionalAttrs (false) { my = "set"; }
  261. => { }
  262. */
  263. optionalAttrs = cond: as: if cond then as else {};
  264. /* Merge sets of attributes and use the function f to merge attributes
  265. values.
  266. Example:
  267. zipAttrsWithNames ["a"] (name: vs: vs) [{a = "x";} {a = "y"; b = "z";}]
  268. => { a = ["x" "y"]; }
  269. */
  270. zipAttrsWithNames = names: f: sets:
  271. listToAttrs (map (name: {
  272. inherit name;
  273. value = f name (catAttrs name sets);
  274. }) names);
  275. /* Implementation note: Common names appear multiple times in the list of
  276. names, hopefully this does not affect the system because the maximal
  277. laziness avoid computing twice the same expression and listToAttrs does
  278. not care about duplicated attribute names.
  279. Example:
  280. zipAttrsWith (name: values: values) [{a = "x";} {a = "y"; b = "z";}]
  281. => { a = ["x" "y"]; b = ["z"] }
  282. */
  283. zipAttrsWith = f: sets: zipAttrsWithNames (concatMap attrNames sets) f sets;
  284. /* Like `zipAttrsWith' with `(name: values: values)' as the function.
  285. Example:
  286. zipAttrs [{a = "x";} {a = "y"; b = "z";}]
  287. => { a = ["x" "y"]; b = ["z"] }
  288. */
  289. zipAttrs = zipAttrsWith (name: values: values);
  290. /* Does the same as the update operator '//' except that attributes are
  291. merged until the given predicate is verified. The predicate should
  292. accept 3 arguments which are the path to reach the attribute, a part of
  293. the first attribute set and a part of the second attribute set. When
  294. the predicate is verified, the value of the first attribute set is
  295. replaced by the value of the second attribute set.
  296. Example:
  297. recursiveUpdateUntil (path: l: r: path == ["foo"]) {
  298. # first attribute set
  299. foo.bar = 1;
  300. foo.baz = 2;
  301. bar = 3;
  302. } {
  303. #second attribute set
  304. foo.bar = 1;
  305. foo.quz = 2;
  306. baz = 4;
  307. }
  308. returns: {
  309. foo.bar = 1; # 'foo.*' from the second set
  310. foo.quz = 2; #
  311. bar = 3; # 'bar' from the first set
  312. baz = 4; # 'baz' from the second set
  313. }
  314. */
  315. recursiveUpdateUntil = pred: lhs: rhs:
  316. let f = attrPath:
  317. zipAttrsWith (n: values:
  318. let here = attrPath ++ [n]; in
  319. if tail values == []
  320. || pred here (head (tail values)) (head values) then
  321. head values
  322. else
  323. f here values
  324. );
  325. in f [] [rhs lhs];
  326. /* A recursive variant of the update operator ‘//’. The recursion
  327. stops when one of the attribute values is not an attribute set,
  328. in which case the right hand side value takes precedence over the
  329. left hand side value.
  330. Example:
  331. recursiveUpdate {
  332. boot.loader.grub.enable = true;
  333. boot.loader.grub.device = "/dev/hda";
  334. } {
  335. boot.loader.grub.device = "";
  336. }
  337. returns: {
  338. boot.loader.grub.enable = true;
  339. boot.loader.grub.device = "";
  340. }
  341. */
  342. recursiveUpdate = lhs: rhs:
  343. recursiveUpdateUntil (path: lhs: rhs:
  344. !(isAttrs lhs && isAttrs rhs)
  345. ) lhs rhs;
  346. /* Returns true if the pattern is contained in the set. False otherwise.
  347. Example:
  348. matchAttrs { cpu = {}; } { cpu = { bits = 64; }; }
  349. => true
  350. */
  351. matchAttrs = pattern: attrs: assert isAttrs pattern;
  352. fold and true (attrValues (zipAttrsWithNames (attrNames pattern) (n: values:
  353. let pat = head values; val = head (tail values); in
  354. if length values == 1 then false
  355. else if isAttrs pat then isAttrs val && matchAttrs pat val
  356. else pat == val
  357. ) [pattern attrs]));
  358. /* Override only the attributes that are already present in the old set
  359. useful for deep-overriding.
  360. Example:
  361. overrideExisting {} { a = 1; }
  362. => {}
  363. overrideExisting { b = 2; } { a = 1; }
  364. => { b = 2; }
  365. overrideExisting { a = 3; b = 2; } { a = 1; }
  366. => { a = 1; b = 2; }
  367. */
  368. overrideExisting = old: new:
  369. mapAttrs (name: value: new.${name} or value) old;
  370. /* Get a package output.
  371. If no output is found, fallback to `.out` and then to the default.
  372. Example:
  373. getOutput "dev" pkgs.openssl
  374. => "/nix/store/9rz8gxhzf8sw4kf2j2f1grr49w8zx5vj-openssl-1.0.1r-dev"
  375. */
  376. getOutput = output: pkg:
  377. if pkg.outputUnspecified or false
  378. then pkg.${output} or pkg.out or pkg
  379. else pkg;
  380. getBin = getOutput "bin";
  381. getLib = getOutput "lib";
  382. getDev = getOutput "dev";
  383. /* Pick the outputs of packages to place in buildInputs */
  384. chooseDevOutputs = drvs: builtins.map getDev drvs;
  385. /*** deprecated stuff ***/
  386. zipWithNames = zipAttrsWithNames;
  387. zip = builtins.trace
  388. "lib.zip is deprecated, use lib.zipAttrsWith instead" zipAttrsWith;
  389. }