query
On this page

readDir

lib.readDir

Primop
Docs pulled from | This Revision | 1 day ago


Nix manual

Takes 1 arguments

path

Return the contents of the directory path as a set mapping directory entries to the corresponding file type. For instance, if directory A contains a regular file B and another directory C, then builtins.readDir ./A returns the set

{ B = "regular"; C = "directory"; }

The possible values for the file type are "regular", "directory", "symlink" and "unknown".

Noogle detected

Aliases

Detected Type
readDir :: Path -> AttrSet

Implementation

This function is implemented in c++ and is part of the native nix runtime.

src/libexpr/primops.cc:2405

static void prim_readDir(EvalState & state, const PosIdx pos, Value ** args, Value & v)
{
    auto path = state.realisePath(pos, *args[0]);

    // Retrieve directory entries for all nodes in a directory.
    // This is similar to `getFileType` but is optimized to reduce system calls
    // on many systems.
    auto entries = path.readDirectory();
    auto attrs = state.buildBindings(entries.size());

    // If we hit unknown directory entry types we may need to fallback to
    // using `getFileType` on some systems.
    // In order to reduce system calls we make each lookup lazy by using
    // `builtins.readFileType` application.
    Value * readFileType = nullptr;

    for (auto & [name, type] : entries) {
        if (!type) {
            auto & attr = attrs.alloc(name);
            // Some filesystems or operating systems may not be able to return
            // detailed node info quickly in this case we produce a thunk to
            // query the file type lazily.
            auto epath = state.allocValue();
            epath->mkPath(path / name, state.mem);
            if (!readFileType)
                readFileType = &state.getBuiltin("readFileType");
            attr.mkApp(readFileType, epath);
        } else {
            // This branch of the conditional is much more likely.
            // Here we just stringize the directory entry type.
            // N.B. const_cast here is ok, because these values will never be modified, since
            // only thunks are mutable - other types do not change once constructed.
            attrs.insert(state.symbols.create(name), const_cast<Value *>(&fileTypeToString(state, *type)));
        }
    }

    v.mkAttrs(attrs);
}

Implementation

The following is the current implementation of this function.

readDir