build-support: remove assertMsg, throwIf, and throwIfNot usage (#524535)

This commit is contained in:
Philip Taron
2026-05-28 18:09:32 +00:00
committed by GitHub
28 changed files with 168 additions and 158 deletions

View File

@@ -39,9 +39,9 @@ rec {
src,
...
}:
assert lib.assertMsg (
assert
name == null
) "The `name` argument is deprecated. Use `pname` and `version` instead to construct the name.";
|| throw "The `name` argument is deprecated. Use `pname` and `version` instead to construct the name.";
pkgs.runCommand "${pname}-${version}-extracted"
{
nativeBuildInputs = [ appimage-exec ];

View File

@@ -64,9 +64,7 @@ let
let
matches = (builtins.length (builtins.split "\\{}" prog) - 1) / 2;
in
lib.assertMsg (
matches == 1
) "compressor ${ext} needs to have exactly one '{}', found ${toString matches}";
matches == 1 || throw "compressor ${ext} needs to have exactly one '{}', found ${toString matches}";
mkCmd =
ext: prog:
assert validProg ext prog;

View File

@@ -71,8 +71,7 @@ lib.extendMkDerivation {
if autoPubspecLock == null then
throw "The pubspecLock argument is required. If import-from-derivation is allowed (it isn't in Nixpkgs), you can set autoPubspecLock to the path to a pubspec.lock instead."
else
assert lib.assertMsg (builtins.pathExists autoPubspecLock)
"The pubspec.lock file could not be found!";
assert builtins.pathExists autoPubspecLock || throw "The pubspec.lock file could not be found!";
lib.importJSON (
runCommand "${lib.getName args}-pubspec-lock-json" {
nativeBuildInputs = [ yq ];

View File

@@ -94,8 +94,9 @@ let
mkPathDependencySource =
name: details:
assert lib.assertMsg details.description.relative
"Only relative paths are supported - ${name} has an absolue path!";
assert
details.description.relative
|| throw "Only relative paths are supported - ${name} has an absolue path!";
(
if lib.isDerivation src then
src

View File

@@ -655,9 +655,12 @@ rec {
checked =
lib.warnIf (contents != null)
"in docker image ${name}: The contents parameter is deprecated. Change to copyToRoot if the contents are designed to be copied to the root filesystem, such as when you use `buildEnv` or similar between contents and your packages. Use copyToRoot = buildEnv { ... }; or similar if you intend to add packages to /bin."
lib.throwIf
(contents != null && copyToRoot != null)
"in docker image ${name}: You can not specify both contents and copyToRoot.";
(
if (contents != null && copyToRoot != null) then
throw "in docker image ${name}: You can not specify both contents and copyToRoot."
else
x: x
);
rootContents = if copyToRoot == null then contents else copyToRoot;
@@ -1030,11 +1033,12 @@ rec {
debug ? false,
}:
assert (
lib.assertMsg (layeringPipeline == null -> maxLayers > 1)
"the maxLayers argument of dockerTools.buildLayeredImage function must be greather than 1 (current value: ${toString maxLayers})"
(layeringPipeline == null -> maxLayers > 1)
|| throw "the maxLayers argument of dockerTools.buildLayeredImage function must be greather than 1 (current value: ${toString maxLayers})"
);
assert (
lib.assertMsg (enableFakechroot -> !stdenv.hostPlatform.isDarwin) ''
(enableFakechroot -> !stdenv.hostPlatform.isDarwin)
|| throw ''
cannot use `enableFakechroot` because `proot` is not portable to Darwin. Workarounds:
- use `fakeRootCommands` with the restricted `fakeroot` environment
- cross-compile your packages
@@ -1271,11 +1275,11 @@ rec {
command ? null,
run ? null,
}:
assert lib.assertMsg (!(drv.drvAttrs.__structuredAttrs or false))
"streamNixShellImage: Does not work with the derivation ${drv.name} because it uses __structuredAttrs";
assert lib.assertMsg (
command == null || run == null
) "streamNixShellImage: Can't specify both command and run";
assert
!(drv.drvAttrs.__structuredAttrs or false)
|| throw "streamNixShellImage: Does not work with the derivation ${drv.name} because it uses __structuredAttrs";
assert
command == null || run == null || throw "streamNixShellImage: Can't specify both command and run";
let
# A binary that calls the command to build the derivation

View File

@@ -24,9 +24,8 @@ lib.makeOverridable (
}@args:
assert (
lib.assertMsg (lib.xor (tag == null) (
rev == null
)) "fetchFromBitbucket requires one of either `rev` or `tag` to be provided (not both)."
lib.xor (tag == null) (rev == null)
|| throw "fetchFromBitbucket requires one of either `rev` or `tag` to be provided (not both)."
);
let

View File

@@ -177,7 +177,8 @@ lib.makeOverridable (
sparseCheckoutText =
# Changed to throw on 2023-06-04
assert (
lib.assertMsg (lib.isList finalAttrs.sparseCheckout) "Please provide directories/patterns for sparse checkout as a list of strings. Passing a (multi-line) string is not supported any more."
lib.isList finalAttrs.sparseCheckout
|| throw "Please provide directories/patterns for sparse checkout as a list of strings. Passing a (multi-line) string is not supported any more."
);
assert finalAttrs.nonConeMode -> (finalAttrs.sparseCheckout != [ ]);
# git-sparse-checkout(1) says:

View File

@@ -59,9 +59,8 @@ decorate (
}@args:
assert (
lib.assertMsg (lib.xor (tag == null) (
rev == null
)) "fetchFromGitHub requires one of either `rev` or `tag` to be provided (not both)."
lib.xor (tag == null) (rev == null)
|| throw "fetchFromGitHub requires one of either `rev` or `tag` to be provided (not both)."
);
let

View File

@@ -14,9 +14,8 @@ lib.makeOverridable (
}@args:
assert (
lib.assertMsg (lib.xor (tag == null) (
rev == null
)) "fetchFromGitiles requires one of either `rev` or `tag` to be provided (not both)."
lib.xor (tag == null) (rev == null)
|| throw "fetchFromGitiles requires one of either `rev` or `tag` to be provided (not both)."
);
let

View File

@@ -27,9 +27,8 @@ lib.makeOverridable (
}@args:
assert (
lib.assertMsg (lib.xor (tag == null) (
rev == null
)) "fetchFromGitLab requires one of either `rev` or `tag` to be provided (not both)."
lib.xor (tag == null) (rev == null)
|| throw "fetchFromGitLab requires one of either `rev` or `tag` to be provided (not both)."
);
let
@@ -65,43 +64,46 @@ lib.makeOverridable (
fetcher = if useFetchGit then fetchgit else fetchzip;
privateAttrs = lib.optionalAttrs private (
lib.throwIfNot (protocol == "https") "private token login is only supported for https" {
netrcPhase = ''
if [ -z "''$${varBase}USERNAME" -o -z "''$${varBase}PASSWORD" ]; then
echo "Error: Private fetchFromGitLab requires the nix building process (nix-daemon in multi user mode) to have the ${varBase}USERNAME and ${varBase}PASSWORD env vars set." >&2
exit 1
fi
''
+ (
if useFetchGit then
# GitLab supports HTTP Basic Authentication only when Git is used:
# https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html#project-access-tokens
''
cat > netrc <<EOF
machine ${domain}
login ''$${varBase}USERNAME
password ''$${varBase}PASSWORD
EOF
''
else
# Access via the GitLab API requires a custom header and does not work
# with HTTP Basic Authentication:
# https://docs.gitlab.com/ee/api/#personalprojectgroup-access-tokens
''
# needed because fetchurl always sets --netrc-file if a netrcPhase is present
touch netrc
if protocol != "https" then
throw "private token login is only supported for https"
else
{
netrcPhase = ''
if [ -z "''$${varBase}USERNAME" -o -z "''$${varBase}PASSWORD" ]; then
echo "Error: Private fetchFromGitLab requires the nix building process (nix-daemon in multi user mode) to have the ${varBase}USERNAME and ${varBase}PASSWORD env vars set." >&2
exit 1
fi
''
+ (
if useFetchGit then
# GitLab supports HTTP Basic Authentication only when Git is used:
# https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html#project-access-tokens
''
cat > netrc <<EOF
machine ${domain}
login ''$${varBase}USERNAME
password ''$${varBase}PASSWORD
EOF
''
else
# Access via the GitLab API requires a custom header and does not work
# with HTTP Basic Authentication:
# https://docs.gitlab.com/ee/api/#personalprojectgroup-access-tokens
''
# needed because fetchurl always sets --netrc-file if a netrcPhase is present
touch netrc
cat > private-token <<EOF
PRIVATE-TOKEN: ''$${varBase}PASSWORD
EOF
curlOpts="$curlOpts --header @./private-token"
''
);
netrcImpureEnvVars = [
"${varBase}USERNAME"
"${varBase}PASSWORD"
];
}
cat > private-token <<EOF
PRIVATE-TOKEN: ''$${varBase}PASSWORD
EOF
curlOpts="$curlOpts --header @./private-token"
''
);
netrcImpureEnvVars = [
"${varBase}USERNAME"
"${varBase}PASSWORD"
];
}
);
gitRepoUrl = "${protocol}://${domain}/${slug}.git";

View File

@@ -30,14 +30,18 @@ lib.extendMkDerivation {
outputHashAlgo = if finalAttrs.hash != null && finalAttrs.hash != "" then null else "sha256";
outputHashMode = "recursive";
outputHash = lib.throwIf (hash != null && sha256 != null) "Only one of sha256 or hash can be set" (
if finalAttrs.hash != null then
finalAttrs.hash
else if sha256 != null then
sha256
outputHash =
if (hash != null && sha256 != null) then
throw "Only one of sha256 or hash can be set"
else
""
);
(
if finalAttrs.hash != null then
finalAttrs.hash
else if sha256 != null then
sha256
else
""
);
inherit url rev hash;
inherit preferLocalBuild;

View File

@@ -38,10 +38,10 @@ in
let
inherit (args') stripLen extraPrefix;
in
lib.throwIfNot (excludes == [ ] || includes == [ ])
"fetchpatch: cannot use excludes and includes simultaneously"
fetchurl
(
if excludes != [ ] && includes != [ ] then
throw "fetchpatch: cannot use excludes and includes simultaneously"
else
fetchurl (
{
nativeBuildInputs = [ patchutils ] ++ nativeBuildInputs;
postFetch = ''

View File

@@ -10,9 +10,9 @@ lib.makeOverridable (
...
}@args:
assert lib.assertMsg (lib.xor (tag != null) (
rev != null
)) "fetchFromRadicle requires one of either `rev` or `tag` to be provided (not both).";
assert
lib.xor (tag != null) (rev != null)
|| throw "fetchFromRadicle requires one of either `rev` or `tag` to be provided (not both).";
let
namespacePrefix = lib.optionalString (node != null) "refs/namespaces/${node}/";

View File

@@ -12,9 +12,8 @@ lib.makeOverridable (
...
}@args:
assert lib.assertMsg (
!args ? rev && !args ? tag
) "fetchRadiclePatch does not accept `rev` or `tag` arguments.";
assert
(!args ? rev && !args ? tag) || throw "fetchRadiclePatch does not accept `rev` or `tag` arguments.";
fetchFromRadicle (
{

View File

@@ -28,9 +28,8 @@ makeOverridable (
}@args:
assert (
lib.assertMsg (lib.xor (tag == null) (
rev == null
)) "fetchFromSourcehut requires one of either `rev` or `tag` to be provided (not both)."
lib.xor (tag == null) (rev == null)
|| throw "fetchFromSourcehut requires one of either `rev` or `tag` to be provided (not both)."
);
assert (

View File

@@ -83,12 +83,16 @@ let
else
[ ];
in
assert lib.assertMsg (config != { } -> backend == "transmission") ''
json config for configuring fetchtorrent only works with the transmission backend
'';
assert lib.assertMsg (backend == "transmission" -> flatten') ''
`flatten = false` is only supported by the rqbit backend for fetchtorrent
'';
assert
(config != { } -> backend == "transmission")
|| throw ''
json config for configuring fetchtorrent only works with the transmission backend
'';
assert
(backend == "transmission" -> flatten')
|| throw ''
`flatten = false` is only supported by the rqbit backend for fetchtorrent
'';
runCommand name
{
inherit meta;

View File

@@ -34,7 +34,8 @@ let
keywordsSection =
let
mustBeAList = attr: attrName: lib.throwIfNot (lib.isList attr) "'${attrName}' must be a list" attr;
mustBeAList =
attr: attrName: if !(lib.isList attr) then throw "'${attrName}' must be a list" else attr;
in
{
"Name" = name;

View File

@@ -60,17 +60,17 @@ in
pnpm-fixup-state-db;
in
# pnpmWorkspace was deprecated, so throw if it's used.
assert (lib.throwIf (args ? pnpmWorkspace)
"fetchPnpmDeps: `pnpmWorkspace` is no longer supported, please migrate to `pnpmWorkspaces`."
) true;
assert
!args ? pnpmWorkspace
|| throw "fetchPnpmDeps: `pnpmWorkspace` is no longer supported, please migrate to `pnpmWorkspaces`.";
assert (lib.throwIf (fetcherVersion == null)
"fetchPnpmDeps: `fetcherVersion` is not set, see https://nixos.org/manual/nixpkgs/stable/#javascript-pnpm-fetcherVersion."
) true;
assert
fetcherVersion != null
|| throw "fetchPnpmDeps: `fetcherVersion` is not set, see https://nixos.org/manual/nixpkgs/stable/#javascript-pnpm-fetcherVersion.";
assert (lib.throwIf (!(builtins.elem fetcherVersion supportedFetcherVersions))
"fetchPnpmDeps `fetcherVersion` is not set to a supported value (${lib.concatStringsSep ", " (map toString supportedFetcherVersions)}), see https://nixos.org/manual/nixpkgs/stable/#javascript-pnpm-fetcherVersion."
) true;
assert
builtins.elem fetcherVersion supportedFetcherVersions
|| throw "fetchPnpmDeps `fetcherVersion` is not set to a supported value (${lib.concatStringsSep ", " (map toString supportedFetcherVersions)}), see https://nixos.org/manual/nixpkgs/stable/#javascript-pnpm-fetcherVersion.";
lib.warnIf (fetcherVersion < 3)
"fetchPnpmDeps: `fetcherVersion = ${toString fetcherVersion}` is deprecated and scheduled for removal in the 26.11 release. Please migrate `${pname}` to `fetcherVersion = 3` and regenerate the hash. See https://nixos.org/manual/nixpkgs/stable/#javascript-pnpm-fetcherVersion."

View File

@@ -19,11 +19,10 @@
...
}@args:
lib.throwIf (args ? minimalOCamlVersion && lib.versionOlder ocaml.version args.minimalOCamlVersion)
"${pname}-${version} is not available for OCaml ${ocaml.version}"
stdenv.mkDerivation
(
if (args ? minimalOCamlVersion && lib.versionOlder ocaml.version args.minimalOCamlVersion) then
throw "${pname}-${version} is not available for OCaml ${ocaml.version}"
else
stdenv.mkDerivation (
{
dontAddStaticConfigureFlags = true;

View File

@@ -24,24 +24,20 @@ let
phpDrv = finalAttrs.php or php;
composer = finalAttrs.composer or phpDrv.packages.composer-local-repo-plugin;
in
assert (lib.assertMsg (previousAttrs ? src) "mkComposerRepository expects src argument.");
assert previousAttrs ? src || throw "mkComposerRepository expects src argument.";
assert previousAttrs ? vendorHash || throw "mkComposerRepository expects vendorHash argument.";
assert previousAttrs ? version || throw "mkComposerRepository expects version argument.";
assert previousAttrs ? pname || throw "mkComposerRepository expects pname argument.";
assert (
lib.assertMsg (previousAttrs ? vendorHash) "mkComposerRepository expects vendorHash argument."
);
assert (lib.assertMsg (previousAttrs ? version) "mkComposerRepository expects version argument.");
assert (lib.assertMsg (previousAttrs ? pname) "mkComposerRepository expects pname argument.");
assert (
lib.assertMsg (previousAttrs ? composerNoDev) "mkComposerRepository expects composerNoDev argument."
previousAttrs ? composerNoDev || throw "mkComposerRepository expects composerNoDev argument."
);
assert (
lib.assertMsg (
previousAttrs ? composerNoPlugins
) "mkComposerRepository expects composerNoPlugins argument."
previousAttrs ? composerNoPlugins
|| throw "mkComposerRepository expects composerNoPlugins argument."
);
assert (
lib.assertMsg (
previousAttrs ? composerNoScripts
) "mkComposerRepository expects composerNoScripts argument."
previousAttrs ? composerNoScripts
|| throw "mkComposerRepository expects composerNoScripts argument."
);
{
composerNoDev = previousAttrs.composerNoDev or true;

View File

@@ -25,9 +25,9 @@ let
dontCheckForBrokenSymlinks ? true,
...
}@args:
assert (lib.assertMsg (args ? pname) "mkComposerVendor expects pname argument.");
assert (lib.assertMsg (args ? version) "mkComposerVendor expects version argument.");
assert (lib.assertMsg (args ? src) "mkComposerVendor expects src argument.");
assert args ? pname || throw "mkComposerVendor expects pname argument.";
assert args ? version || throw "mkComposerVendor expects version argument.";
assert args ? src || throw "mkComposerVendor expects src argument.";
{
name = "${args.pname}-composer-vendor-${args.version}";

View File

@@ -87,9 +87,9 @@ let
};
in
assert lib.assertMsg (lib.all (
u: lib.hasPrefix pname u.name
) units) "Unit names must be prefixed with the service name";
assert
lib.all (u: lib.hasPrefix pname u.name) units
|| throw "Unit names must be prefixed with the service name";
stdenv.mkDerivation {
pname = "${pname}-img";

View File

@@ -4669,7 +4669,7 @@ rec {
# Not rate-limited, CDN URL.
url = "https://static.crates.io/crates/${crateConfig.crateName}/${crateConfig.crateName}-${crateConfig.version}.crate";
sha256 =
assert (lib.assertMsg (crateConfig ? sha256) "Missing sha256 for ${name}");
assert crateConfig ? sha256 || throw "Missing sha256 for ${name}";
crateConfig.sha256;
});
extraRustcOpts =

View File

@@ -78,8 +78,9 @@ lib.extendMkDerivation {
...
}@args:
assert lib.assertMsg useFetchCargoVendor
"buildRustPackage: `useFetchCargoVendor` is nonoptional and enabled by default as of 25.05, remove it";
assert
useFetchCargoVendor
|| throw "buildRustPackage: `useFetchCargoVendor` is nonoptional and enabled by default as of 25.05, remove it";
assert lib.warnIf (args ? useFetchCargoVendor)
"buildRustPackage: `useFetchCargoVendor` is nonoptional and enabled by default as of 25.05, remove it"

View File

@@ -120,9 +120,11 @@ let
checksum =
pkg.checksum or parsedLockFile.metadata."checksum ${pkg.name} ${pkg.version} (${pkg.source})";
in
assert lib.assertMsg (checksum != null) ''
Package ${pkg.name} does not have a checksum.
'';
assert
checksum != null
|| throw ''
Package ${pkg.name} does not have a checksum.
'';
fetchurl {
name = "crate-${pkg.name}-${pkg.version}.tar.gz";
url = "${downloadUrl}/${pkg.name}/${pkg.version}/download";

View File

@@ -30,7 +30,7 @@ makeSetupHook {
# depsTargetTargetPropagated will essentially be buildInputs when wrapGAppsHook3 is placed into nativeBuildInputs
# the librsvg and gtk3 above should be removed but kept to not break anything that implicitly depended on its binaries
depsTargetTargetPropagated =
assert (lib.assertMsg (!targetPackages ? raw) "wrapGAppsHook3 must be in nativeBuildInputs");
assert (!targetPackages ? raw || throw "wrapGAppsHook3 must be in nativeBuildInputs");
lib.optionals isGraphical [
# librsvg provides a module for gdk-pixbuf to allow rendering
# SVG icons. Most icon themes are SVG-based and so are some

View File

@@ -54,8 +54,9 @@ optionalDeprecationWarning stdenvNoCC.mkDerivation (
// args
// lib.optionalAttrs (args ? substitutions) {
substitutions =
assert lib.assertMsg (lib.isList args.substitutions)
''pkgs.substitute: For "${name}", `substitutions` is passed, which is expected to be a list, but it's a ${builtins.typeOf args.substitutions} instead.'';
assert
lib.isList args.substitutions
|| throw ''pkgs.substitute: For "${name}", `substitutions` is passed, which is expected to be a list, but it's a ${builtins.typeOf args.substitutions} instead.'';
lib.escapeShellArgs args.substitutions;
}
)

View File

@@ -131,12 +131,14 @@ rec {
preferLocalBuild
;
destination =
assert lib.assertMsg (destination != "" -> (lib.hasPrefix "/" destination && destination != "/")) ''
destination must be an absolute path, relative to the derivation's out path,
got '${destination}' instead.
assert
(destination != "" -> (lib.hasPrefix "/" destination && destination != "/"))
|| throw ''
destination must be an absolute path, relative to the derivation's out path,
got '${destination}' instead.
Ensure that the path starts with a / and specifies at least the filename.
'';
Ensure that the path starts with a / and specifies at least the filename.
'';
destination;
passAsFile = [ "text" ] ++ derivationArgs.passAsFile or [ ];
@@ -184,8 +186,9 @@ rec {
writeText =
name: text:
# TODO: To fully deprecate, replace the assertion with `lib.isString` and remove the warning
assert lib.assertMsg (lib.strings.isConvertibleWithToString text)
"pkgs.writeText ${lib.strings.escapeNixString name}: The second argument should be a string, but it's a ${builtins.typeOf text} instead.";
assert
lib.strings.isConvertibleWithToString text
|| throw "pkgs.writeText ${lib.strings.escapeNixString name}: The second argument should be a string, but it's a ${builtins.typeOf text} instead.";
lib.warnIf (!lib.isString text)
"pkgs.writeText ${lib.strings.escapeNixString name}: The second argument should be a string, but it's a ${builtins.typeOf text} instead, which is deprecated. Use `toString` to convert the value to a string first."
writeTextFile
@@ -534,9 +537,9 @@ rec {
finalAttrs:
args@{
name ?
assert lib.assertMsg (
finalAttrs ? pname && finalAttrs ? version
) "symlinkJoin requires either a `name` OR `pname` and `version`";
assert
(finalAttrs ? pname && finalAttrs ? version)
|| throw "symlinkJoin requires either a `name` OR `pname` and `version`";
"${finalAttrs.pname}-${finalAttrs.version}",
paths,
stripPrefix ? "",
@@ -546,11 +549,13 @@ rec {
failOnMissing ? stripPrefix == "",
...
}:
assert lib.assertMsg (stripPrefix != "" -> (hasPrefix "/" stripPrefix && stripPrefix != "/")) ''
stripPrefix must be either an empty string (disable stripping behavior), or relative path prefixed with /.
assert
(stripPrefix != "" -> (hasPrefix "/" stripPrefix && stripPrefix != "/"))
|| throw ''
stripPrefix must be either an empty string (disable stripping behavior), or relative path prefixed with /.
Ensure that the path starts with / and specifies path to the subdirectory.
'';
Ensure that the path starts with / and specifies path to the subdirectory.
'';
let
mapPaths =
f:
@@ -1012,12 +1017,9 @@ rec {
src,
...
}@args:
assert lib.assertMsg (
!args ? meta
) "applyPatches will not merge 'meta', change it in 'src' instead";
assert lib.assertMsg (
!args ? passthru
) "applyPatches will not merge 'passthru', change it in 'src' instead";
assert !args ? meta || throw "applyPatches will not merge 'meta', change it in 'src' instead";
assert
!args ? passthru || throw "applyPatches will not merge 'passthru', change it in 'src' instead";
let
keepAttrs = names: lib.filterAttrs (name: val: lib.elem name names);
# enables tools like nix-update to determine what src attributes to replace