diff --git a/lib/default.nix b/lib/default.nix index 8fea4b8ad6374..d60aba2f09241 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -119,7 +119,7 @@ let hiPrioSet getLicenseFromSpdxId getExe; inherit (self.filesystem) pathType pathIsDirectory pathIsRegularFile; inherit (self.sources) cleanSourceFilter - cleanSource sourceByRegex sourceFilesBySuffices + cleanSource sourceByRegex sourceFilesBySuffices sourceSubdirs commitIdFromGitRepo cleanSourceWith pathHasContext canCleanSource pathIsGitRepo; inherit (self.modules) evalModules setDefaultModuleLocation diff --git a/lib/path/default.nix b/lib/path/default.nix index a4a08668ae62e..bdcc4760798f1 100644 --- a/lib/path/default.nix +++ b/lib/path/default.nix @@ -149,6 +149,24 @@ in /* No rec! Add dependencies on this file at the top. */ { ${subpathInvalidReason subpath}''; path + ("/" + subpath); + /* + Test whether one path is a child of another. + This is just based on the string values of the provided paths. + It does not access the filesystem. + + Type: sourceLike -> Path|String -> Path|String -> bool + + Examples: + path.hasPrefix "foo" "foo/bar" # => true + path.hasPrefix "foo" "foo" # => true + path.hasPrefix "food" "foo" => false + path.hasPrefix "foo/bar" "foo" # => false + */ + hasPrefix = parent: child: + assert lib.isPath parent; + assert lib.isPath child; + lib.hasPrefix "${toString parent}/" "${toString child}/"; + /* Whether a value is a valid subpath string. - The value is a string diff --git a/lib/sources.nix b/lib/sources.nix index d990777c6fcc7..dbcb50183d7d0 100644 --- a/lib/sources.nix +++ b/lib/sources.nix @@ -156,6 +156,27 @@ let in type == "directory" || lib.any (ext: lib.hasSuffix ext base) exts; in cleanSourceWith { inherit filter src; }; + /* + Filter a source directory down to only a specified list of + subdirectories. + + Type: sourceLike -> [String] -> Source + + Example: + sourceSubdirs src [ "host/rootfs" "scripts" ] + */ + sourceSubdirs = src: subdirs: lib.cleanSourceWith { + filter = path: _type: + lib.any (subdir: + let + subdir' = lib.path.append (src.origSrc or src) subdir; + path' = /. + path; + in + lib.path.hasPrefix path' subdir' || lib.path.hasPrefix subdir' path' + ) subdirs; + inherit src; + }; + pathIsGitRepo = path: (_commitIdFromGitRepoOrError path)?value; /* @@ -286,6 +307,7 @@ in { sourceByRegex sourceFilesBySuffices + sourceSubdirs trace ;