Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions lib/customisation.nix
Original file line number Diff line number Diff line change
Expand Up @@ -296,4 +296,30 @@ rec {
};
in self;



/* Apply a function to an attrset of potential args, automatically filtering
the set to those the function can accept.
NOTE: This is strictly meant to be used with functions that accept attrsets
as their argument, and is best suited for use with `setFunctionArgs'.

nix-repl> lib.applyArgs ( { x, y }: x + y ) { x = 1; y = 2; z = -1; }
3
*/
applyArgs = f: args: let
fn = if lib.isFunction f then f else import f;
in fn ( builtins.intersectAttrs ( lib.functionArgs fn ) args );


/* Non-overridable form of `callPackageWith'.
Applying matching args from `auto' with `args' to function/file `f'.

nix-repl> f = lib.callWith { x = 1; y = 2; z = -1; } ( { x, y }: x + y )
nix-repl> f { x = 3; }
5
*/
callWith = auto: f: args: let
fn = if lib.isFunction f then f else import f;
in fn ( ( builtins.intersectAttrs ( lib.functionArgs fn ) auto ) // args );

}
2 changes: 1 addition & 1 deletion lib/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ let
noDepEntry fullDepEntry packEntry stringAfter;
inherit (self.customisation) overrideDerivation makeOverridable
callPackageWith callPackagesWith extendDerivation hydraJob
makeScope makeScopeWithSplicing;
makeScope makeScopeWithSplicing applyArgs callWith;
inherit (self.derivations) lazyDerivation;
inherit (self.meta) addMetaAttrs dontDistribute setName updateName
appendToName mapDerivationAttrset setPrio lowPrio lowPrioSet hiPrio
Expand Down
29 changes: 29 additions & 0 deletions lib/tests/misc.nix
Original file line number Diff line number Diff line change
Expand Up @@ -1419,4 +1419,33 @@ runTests {
expr = (with types; either int (listOf (either bool str))).description;
expected = "signed integer or list of (boolean or string)";
};

testApplyArgsFormal = {
expr = applyArgs ( { x, y }: x + y ) { x = 1; y = 2; z = -1; };
expected = 3;
};

testApplyArgsInformal = {
expr = applyArgs ( args: ( args.x or 1 ) + ( args.y or 2 ) ) {
x = 3;
y = 4;
z = -1;
};
expected = 3;
};

testCallWithFormal = {
expr = callWith { x = 1; y = 2; z = -1; } ( { x, y }: x + y ) { x = 3; };
expected = 5;
};

testCallWithInformal = {
expr = callWith { x = 1; y = 2; z = -1; } ( args: args.x + args.y ) {
x = 3;
y = 4;
z = -2;
};
expected = 7;
};

}