lib.fetchers: optimize normalizeHash and withNormalizedHash via min-scoping

This commit is contained in:
nicoo 2024-09-16 09:05:29 +00:00
parent 0518f4d245
commit f470dc703c

View File

@ -66,29 +66,32 @@ rec {
normalizeHash = { normalizeHash = {
hashTypes ? [ "sha256" ], hashTypes ? [ "sha256" ],
required ? true, required ? true,
}: args: }:
with builtins; with lib;
let let
hNames = [ "hash" ] ++ hashTypes; hNames = [ "hash" ] ++ hashTypes;
hAttrs = genAttrs hNames (const {});
# The argument hash, as a {name, value} pair
h =
let _h = attrsToList (intersectAttrs (genAttrs hNames (const {})) args); in
if _h == [] then
throwIf required "fetcher called without `hash`" null
else if tail _h != [] then
throw "fetcher called with mutually-incompatible arguments: ${concatMapStringsSep ", " (a: a.name) _h}"
else
head _h
;
in in
if args ? "outputHash" then with builtins; with lib;
args args:
else if args ? "outputHash" then
removeAttrs args hNames // (optionalAttrs (h != null) { args
outputHash = h.value; else
outputHashAlgo = if h.name == "hash" then null else h.name; let
}) # The argument hash, as a {name, value} pair
h =
let _h = attrsToList (intersectAttrs hAttrs args); in
if _h == [] then
throwIf required "fetcher called without `hash`" null
else if tail _h != [] then
throw "fetcher called with mutually-incompatible arguments: ${concatMapStringsSep ", " (a: a.name) _h}"
else
head _h
;
in
removeAttrs args hNames // (optionalAttrs (h != null) {
outputHash = h.value;
outputHashAlgo = if h.name == "hash" then null else h.name;
})
; ;
/** /**
@ -148,13 +151,17 @@ rec {
let let
hAttrs = genAttrs ([ "hash" ] ++ hashTypes) (const {}); hAttrs = genAttrs ([ "hash" ] ++ hashTypes) (const {});
fArgs = functionArgs fetcher; fArgs = functionArgs fetcher;
required = !fArgs.outputHash;
normalize = normalizeHash {
inherit hashTypes;
required = !fArgs.outputHash;
};
in in
# The o.g. fetcher must *only* accept outputHash and outputHashAlgo # The o.g. fetcher must *only* accept outputHash and outputHashAlgo
assert fArgs ? outputHash && fArgs ? outputHashAlgo; assert fArgs ? outputHash && fArgs ? outputHashAlgo;
assert intersectAttrs fArgs hAttrs == {}; assert intersectAttrs fArgs hAttrs == {};
setFunctionArgs setFunctionArgs
(args: fetcher (normalizeHash { inherit hashTypes required; } args)) (args: fetcher (normalize args))
(removeAttrs fArgs [ "outputHash" "outputHashAlgo" ] // { hash = !required; }); (removeAttrs fArgs [ "outputHash" "outputHashAlgo" ] // { hash = fArgs.outputHash; });
} }