query
On this page

readFile

builtins.readFile

Primop
Docs pulled from | This Revision | about 6 hours ago


Nix manual

Takes 1 arguments

path

Return the contents of the file path as a string.

Noogle detected

Aliases

Detected Type
readFile :: Path -> String

Implementation

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

src/libexpr/primops.cc:2100

static void prim_readFile(EvalState & state, const PosIdx pos, Value ** args, Value & v)
{
    auto path = state.realisePath(pos, *args[0]);
    auto s = path.readFile();
    if (s.find((char) 0) != std::string::npos)
        state.error<EvalError>("the contents of the file '%1%' cannot be represented as a Nix string", path)
            .atPos(pos)
            .debugThrow();
    StorePathSet refs;
    if (state.store->isInStore(path.path.abs())) {
        try {
            refs = state.store->queryPathInfo(state.store->toStorePath(path.path.abs()).first)->references;
        } catch (Error &) { // FIXME: should be InvalidPathError
        }
        // Re-scan references to filter down to just the ones that actually occur in the file.
        auto refsSink = PathRefScanSink::fromPaths(refs);
        refsSink << s;
        refs = refsSink.getResultPaths();
    }
    NixStringContext context;
    for (auto && p : std::move(refs)) {
        context.insert(
            NixStringContextElem::Opaque{
                .path = std::move((StorePath &&) p),
            });
    }
    v.mkString(s, context, state.mem);
}