Skip to content

Filtering Files

By default, import-tree includes files that:

  1. Have the .nix suffix
  2. Do not have /_ in their path (underscore-prefixed directories are ignored)

You can narrow this down with filters, or replace the defaults entirely.

filter takes a predicate function string -> bool applied to each file’s path:

# Only import files containing ".mod." in their name
import-tree.filter (lib.hasInfix ".mod.") ./modules

filterNot is the inverse — exclude files matching the predicate:

# Skip any file with "experimental" in the path
import-tree.filterNot (lib.hasInfix "experimental") ./modules

Multiple filters combine with logical AND — a file must pass all of them:

lib.pipe import-tree [
(i: i.filter (lib.hasInfix "/desktop/"))
(i: i.filter (lib.hasSuffix "bar.nix"))
(i: i ./modules)
]

This selects only files under a desktop/ directory whose name ends in bar.nix.

match takes a regular expression. The regex is tested against the full path using builtins.match:

# Only files named like "word_word.nix"
import-tree.match ".*/[a-z]+_[a-z]+\.nix" ./modules

matchNot excludes files matching the regex:

# Skip files with numeric names
import-tree.matchNot ".*/[0-9]+\.nix" ./modules

All filter types compose together:

(import-tree.match ".*_.*\.nix").filter (lib.hasInfix "/src/") ./tree

This finds files matching the regex and containing /src/ in their path.

initFilter replaces the built-in .nix + no-/_ filter entirely. Use it to discover non-Nix files or change the ignore convention:

# Find .txt files instead of .nix files
import-tree.initFilter (lib.hasSuffix ".txt") ./dir
# Find .nix files but use /ignored/ instead of /_
import-tree.initFilter (p: lib.hasSuffix ".nix" p && !lib.hasInfix "/ignored/" p)
Contribute Community Sponsor