Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
file-system.hh File Reference

Utilities for working with the file system and file paths. More...

#include "nix/util/fun.hh"
#include "nix/util/types.hh"
#include "nix/util/file-descriptor.hh"
#include "nix/util/file-path.hh"
#include "nix/util/deleter.hh"
#include <filesystem>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <functional>
#include <optional>

Go to the source code of this file.

Classes

struct  nix::OpenNewFileForWriteParams
class  nix::AutoDelete
class  nix::DirectoryIterator
 A directory iterator that can be used to iterate over the contents of a directory. It is similar to std::filesystem::directory_iterator but throws NixError on failure instead of std::filesystem::filesystem_error. More...

Macros

#define S_IFLNK   0120000
#define S_ISLNK(m)

Typedefs

using nix::PosixStat
typedef std::unique_ptr< DIR, Deleter< closedir > > nix::AutoCloseDir
typedef fun< bool(const std::string &path)> nix::PathFilter

Enumerations

enum struct  nix::FinalSymlink : bool { DontFollow = false , Follow = true }
enum struct  FsSync { Yes , No }

Functions

std::filesystem::path nix::absPath (const std::filesystem::path &path0, const std::filesystem::path *dir, bool resolveSymlinks)
std::filesystem::path nix::canonPath (const std::filesystem::path &path, bool resolveSymlinks)
std::string_view nix::baseNameOf (std::string_view path)
bool nix::isInDir (const std::filesystem::path &path, const std::filesystem::path &dir)
bool nix::isDirOrInDir (const std::filesystem::path &path, const std::filesystem::path &dir)
PosixStat nix::lstat (const std::filesystem::path &path)
PosixStat nix::stat (const std::filesystem::path &path)
std::optional< PosixStat > nix::maybeLstat (const std::filesystem::path &path)
std::optional< PosixStat > nix::maybeStat (const std::filesystem::path &path)
bool nix::pathExists (const std::filesystem::path &path)
bool nix::pathAccessible (const std::filesystem::path &path)
std::filesystem::path nix::readLink (const std::filesystem::path &path)
std::filesystem::path nix::descriptorToPath (Descriptor fd)
Result< AutoCloseFD, NativeError > nix::openDirectory (const std::filesystem::path &path, FinalSymlink finalSymlink=FinalSymlink::Follow)
Result< AutoCloseFD, NativeError > nix::openDirectoryTraversable (const std::filesystem::path &path, FinalSymlink finalSymlink=FinalSymlink::Follow)
Result< AutoCloseFD, NativeError > nix::openFileReadonly (const std::filesystem::path &path, FinalSymlink finalSymlink=FinalSymlink::Follow)
Result< AutoCloseFD, NativeError > nix::openNewFileForWrite (const std::filesystem::path &path, mode_t mode, OpenNewFileForWriteParams params)
std::string nix::readFile (const std::filesystem::path &path)
void nix::readFile (const std::filesystem::path &path, Sink &sink, bool memory_map)
void nix::writeFile (const std::filesystem::path &path, std::string_view s, mode_t mode, FsSync sync, FinalSymlink finalSymlink)
void nix::writeFile (const std::filesystem::path &path, Source &source, mode_t mode, FsSync sync, FinalSymlink finalSymlink)
void nix::writeFile (Descriptor fd, Source &source, FsSync sync, const std::filesystem::path *origPath)
void nix::writeFile (Descriptor fd, std::string_view s, FsSync sync, const std::filesystem::path *origPath)
void nix::syncParent (const std::filesystem::path &path)
void nix::recursiveSync (const std::filesystem::path &path)
void nix::deletePath (const std::filesystem::path &path)
void nix::deletePath (const std::filesystem::path &path, uint64_t &bytesFreed)
void nix::createDirs (const std::filesystem::path &path)
void nix::createDir (const std::filesystem::path &path, mode_t mode=0755)
void nix::setWriteTime (const std::filesystem::path &path, time_t accessedTime, time_t modificationTime, std::optional< bool > isSymlink=std::nullopt)
void nix::setWriteTime (const std::filesystem::path &path, const PosixStat &st)
void nix::createSymlink (const std::filesystem::path &target, const std::filesystem::path &link)
void nix::replaceSymlink (const std::filesystem::path &target, const std::filesystem::path &link)
void nix::copyFile (const std::filesystem::path &from, const std::filesystem::path &to, bool contents)
std::filesystem::path nix::createTempDir (const std::filesystem::path &tmpRoot, const std::string &prefix, mode_t mode)
AutoCloseFD nix::createAnonymousTempFile ()
std::pair< AutoCloseFD, std::filesystem::path > nix::createTempFile (const std::filesystem::path &root, const std::filesystem::path &prefix)
std::pair< AutoCloseFD, std::filesystem::path > nix::createTempFile (const std::filesystem::path &prefix)
std::filesystem::path nix::defaultTempDir ()
bool nix::isExecutableFileAmbient (const std::filesystem::path &exe)
std::filesystem::path nix::makeTempPath (const std::filesystem::path &root, const std::string &suffix)
bool nix::chmodIfNeeded (const std::filesystem::path &path, mode_t mode, mode_t mask)
void nix::chmod (const std::filesystem::path &path, mode_t mode)
void nix::chown (const std::filesystem::path &path, uid_t owner, gid_t group)
void nix::unlink (const std::filesystem::path &path)
void nix::unlinkIfExists (const std::filesystem::path &path)
void nix::tryUnlink (const std::filesystem::path &path)
void nix::movePath (const std::filesystem::path &src, const std::filesystem::path &dst)
 Move/rename path 'src' to 'dst'.
void nix::renameFile (const std::filesystem::path &src, const std::filesystem::path &dst)
 Thin wrapper around ::rename that throws SystemError on errors.

Detailed Description

Utilities for working with the file system and file paths.

Please try to use file-system-at.hh instead of this where possible, for the reasons given in the documentation of that header.

Macro Definition Documentation

◆ S_IFLNK

#define S_IFLNK   0120000

Polyfill for MinGW

Windows does in fact support symlinks, but the C runtime interfaces predate this. We define S_IFLNK and S_ISLNK so that our lstat implementation can properly indicate symlinks by setting these mode bits when it detects a reparse point.

◆ S_ISLNK

#define S_ISLNK ( m)
Value:
(((m) & S_IFMT) == S_IFLNK)
#define S_IFLNK
Definition file-system.hh:41

Typedef Documentation

◆ PathFilter

typedef fun<bool(const std::string & path)> nix::PathFilter

Used in various places.

Todo
type

◆ PosixStat

Initial value:
struct ::stat

struct stat is not 64-bit everywhere on Windows.

Enumeration Type Documentation

◆ FinalSymlink

enum struct nix::FinalSymlink : bool
strong

Type-safe boolean for whether to follow the final symlink component.

Function Documentation

◆ absPath()

std::filesystem::path nix::absPath ( const std::filesystem::path & path,
const std::filesystem::path * dir = nullptr,
bool resolveSymlinks = false )
Returns
An absolutized path, resolving paths relative to the specified directory, or the current directory otherwise. The path is also canonicalised.

In the process of being deprecated for std::filesystem::absolute.

◆ baseNameOf()

std::string_view nix::baseNameOf ( std::string_view path)
Returns
the base name of the given canonical path, i.e., everything following the final / (trailing slashes are removed).

In the process of being deprecated for std::filesystem::path::filename.

◆ canonPath()

std::filesystem::path nix::canonPath ( const std::filesystem::path & path,
bool resolveSymlinks = false )

Canonicalise a path by removing all . or .. components and double or trailing slashes. Optionally resolves all symlink components such that each component of the resulting path is not a symbolic link.

In the process of being deprecated for std::filesystem::path::lexically_normal (for the resolveSymlinks = false case), and std::filesystem::weakly_canonical (for the resolveSymlinks = true case).

◆ chmod()

void nix::chmod ( const std::filesystem::path & path,
mode_t mode )

Set permissions on a path, throwing an exception on error.

Parameters
pathPath to the file to change the permissions for.
modeNew file mode.
Todo
stop using this and start using fchmodatTryNoFollow (or a different wrapper) to avoid TOCTOU issues.

◆ chmodIfNeeded()

bool nix::chmodIfNeeded ( const std::filesystem::path & path,
mode_t mode,
mode_t mask = S_IRWXU|S_IRWXG|S_IRWXO )

Change permissions of a file only if necessary.

Skip chmod call if the directory already has the requested permissions. This is to avoid failing when the executing user lacks permissions to change the directory's permissions even if it would be no-op.

Parameters
pathPath to the file to change the permissions for.
modeNew file mode.
maskUsed for checking if the file already has requested permissions.
Returns
true if permissions changed, false otherwise.

◆ chown()

void nix::chown ( const std::filesystem::path & path,
uid_t owner,
gid_t group )

Change ownership of a file, throwing an exception on error.

Parameters
pathPath to the file to change the ownership for.
ownerNew owner user ID.
groupNew owner group ID.

◆ copyFile()

void nix::copyFile ( const std::filesystem::path & from,
const std::filesystem::path & to,
bool contents )

Recursively copy the content of oldPath to newPath.

Todo
Delete this. This function is prone to TOCTOU races and follows symlinks in the destination.

If contents is set, always create a regular file, even if the source is a link.

◆ createAnonymousTempFile()

AutoCloseFD nix::createAnonymousTempFile ( )

Create an anonymous readable/writable temporary file, returning a file handle. On UNIX there resulting file isn't linked to any path on the filesystem.

◆ createDir()

void nix::createDir ( const std::filesystem::path & path,
mode_t mode = 0755 )

Create a single directory.

◆ createDirs()

void nix::createDirs ( const std::filesystem::path & path)

Create a directory and all its parents, if necessary.

Wrapper around std::filesystem::create_directories to handle exceptions.

◆ createSymlink()

void nix::createSymlink ( const std::filesystem::path & target,
const std::filesystem::path & link )

Create a symlink.

◆ createTempDir()

std::filesystem::path nix::createTempDir ( const std::filesystem::path & tmpRoot = "",
const std::string & prefix = "nix",
mode_t mode = 0755 )

Create a temporary directory.

◆ createTempFile() [1/2]

std::pair< AutoCloseFD, std::filesystem::path > nix::createTempFile ( const std::filesystem::path & prefix = "nix")

Create a temporary file, returning a file handle and its path.

◆ createTempFile() [2/2]

std::pair< AutoCloseFD, std::filesystem::path > nix::createTempFile ( const std::filesystem::path & root,
const std::filesystem::path & prefix )

Create a temporary file at a root, returning a file handle and its path.

◆ defaultTempDir()

std::filesystem::path nix::defaultTempDir ( )

Return TMPDIR, or the default temporary directory if unset or empty. Uses GetTempPathW on windows which respects TMP, TEMP, USERPROFILE env variables. Does not resolve symlinks and the returned path might not be directory or exist at all.

◆ deletePath() [1/2]

void nix::deletePath ( const std::filesystem::path & path)

Delete a path; i.e., in the case of a directory, it is deleted recursively. It's not an error if the path does not exist. The second variant returns the number of bytes and blocks freed.

◆ deletePath() [2/2]

void nix::deletePath ( const std::filesystem::path & path,
uint64_t & bytesFreed )
Parameters
[out]bytesFreedEstimation of how many bytes of disk space have been reclaimed. Initialised to zero internally, so the caller doesn't need to initialise it.

◆ descriptorToPath()

std::filesystem::path nix::descriptorToPath ( Descriptor fd)

Get the path associated with a file descriptor.

Note
One MUST only use this for error handling, because it creates TOCTOU issues. We don't mind if error messages point to out of date paths (that is a rather trivial TOCTOU — the error message is best effort) but for anything else we do.
this function will clobber errno (Unix) / "last error" (Windows), so care must be used to get those error codes, then call this, then build a SysError / WinError with the saved error code.

◆ isDirOrInDir()

bool nix::isDirOrInDir ( const std::filesystem::path & path,
const std::filesystem::path & dir )

Check whether 'path' is equal to 'dir' or a descendant of 'dir'. Both paths must be canonicalized.

◆ isExecutableFileAmbient()

bool nix::isExecutableFileAmbient ( const std::filesystem::path & exe)

Interpret exe as a location in the ambient file system and return whether it resolves to a file that is executable.

◆ isInDir()

bool nix::isInDir ( const std::filesystem::path & path,
const std::filesystem::path & dir )

Check whether 'path' is a descendant of 'dir'. Both paths must be canonicalized.

◆ lstat()

PosixStat nix::lstat ( const std::filesystem::path & path)

Get status of path.

◆ makeTempPath()

std::filesystem::path nix::makeTempPath ( const std::filesystem::path & root,
const std::string & suffix = ".tmp" )

Return temporary path constructed by appending a suffix to a root path.

The constructed path looks like <root><suffix>-<pid>-<unique>. To create a path nested in a directory, provide a suffix starting with /.

◆ maybeLstat()

std::optional< PosixStat > nix::maybeLstat ( const std::filesystem::path & path)

lstat the given path if it exists.

Returns
std::nullopt if the path doesn't exist, or an optional containing the result of lstat otherwise

◆ movePath()

void nix::movePath ( const std::filesystem::path & src,
const std::filesystem::path & dst )

Move/rename path 'src' to 'dst'.

Temporarily makes 'src' writable if it's a directory and we're not root (to be able to update the directory's parent link "..").

Atomically replaces the destination if it exists. Does not follow symlinks if dst is a symlink.

◆ openDirectory()

Result< AutoCloseFD, NativeError > nix::openDirectory ( const std::filesystem::path & path,
FinalSymlink finalSymlink = FinalSymlink::Follow )

Open a Descriptor with read-only access to the given directory.

Parameters
finalSymlinkIf DontFollow, fail if the path is a symlink.
Returns
The descriptor, or on failure the native error code.

◆ openDirectoryTraversable()

Result< AutoCloseFD, NativeError > nix::openDirectoryTraversable ( const std::filesystem::path & path,
FinalSymlink finalSymlink = FinalSymlink::Follow )

Open a Descriptor to the given directory only for traversing it: using it as the base of *at calls, or fstating it.

Unlike nix::openDirectory(), this needs only search (traverse) permission on the directory, not read (list) permission, where the OS allows asking for that. In exchange, the descriptor may not support listing the directory or fsyncing it.

Parameters
finalSymlinkIf DontFollow, fail if the path is a symlink.
Returns
The descriptor, or on failure the native error code.

◆ openFileReadonly()

Result< AutoCloseFD, NativeError > nix::openFileReadonly ( const std::filesystem::path & path,
FinalSymlink finalSymlink = FinalSymlink::Follow )

Open a Descriptor with read-only access to the given file.

Note
For directories use nix::openDirectory().
Returns
The descriptor, or on failure the native error code.

◆ openNewFileForWrite()

Result< AutoCloseFD, NativeError > nix::openNewFileForWrite ( const std::filesystem::path & path,
mode_t mode,
OpenNewFileForWriteParams params )

Open a Descriptor for write access or create it if it doesn't exist or truncate existing depending on nix::OpenNewFileForWriteParams::truncateExisting.

Parameters
modePOSIX permission bits. Ignored on Windows.
Returns
The descriptor, or on failure the native error code.
Todo
Reparse points on Windows.

◆ pathAccessible()

bool nix::pathAccessible ( const std::filesystem::path & path)

A version of pathExists that returns false on a permission error. Useful for inferring default paths across directories that might not be readable.

Returns
true iff the given path can be accessed and exists

◆ pathExists()

bool nix::pathExists ( const std::filesystem::path & path)
Returns
true iff the given path exists.

◆ readFile()

std::string nix::readFile ( const std::filesystem::path & path)

Read the contents of a file into a string.

◆ readLink()

std::filesystem::path nix::readLink ( const std::filesystem::path & path)

Read the contents (target) of a symbolic link. The result is not in any way canonicalised.

◆ recursiveSync()

void nix::recursiveSync ( const std::filesystem::path & path)

Flush a file or entire directory tree to disk.

◆ renameFile()

void nix::renameFile ( const std::filesystem::path & src,
const std::filesystem::path & dst )

Thin wrapper around ::rename that throws SystemError on errors.

Unlike nix::movePath(), doesn't attempt to make the source writable if it's a directory.

◆ replaceSymlink()

void nix::replaceSymlink ( const std::filesystem::path & target,
const std::filesystem::path & link )

Atomically create or replace a symlink.

◆ setWriteTime() [1/2]

void nix::setWriteTime ( const std::filesystem::path & path,
const PosixStat & st )

Convenience wrapper that takes all arguments from the PosixStat.

◆ setWriteTime() [2/2]

void nix::setWriteTime ( const std::filesystem::path & path,
time_t accessedTime,
time_t modificationTime,
std::optional< bool > isSymlink = std::nullopt )

Set the access and modification times of the given path, not following symlinks.

Parameters
accessedTimeSpecified in seconds.
modificationTimeSpecified in seconds.
isSymlinkWhether the file in question is a symlink. Used for fallback code where we don't have lutimes or similar. if std::optional is passed, the information will be recomputed if it is needed. Race conditions are possible so be careful!

◆ stat()

PosixStat nix::stat ( const std::filesystem::path & path)

Get status of path following symlinks.

◆ syncParent()

void nix::syncParent ( const std::filesystem::path & path)

Flush a path's parent directory to disk.

◆ tryUnlink()

void nix::tryUnlink ( const std::filesystem::path & path)

Try to remove a file, ignoring errors.

Parameters
pathPath to the file to try to remove.

◆ unlink()

void nix::unlink ( const std::filesystem::path & path)

Remove a file, throwing an exception on error.

Parameters
pathPath to the file to remove.

◆ unlinkIfExists()

void nix::unlinkIfExists ( const std::filesystem::path & path)

Remove a file, throwing an exception on error. ENOENT is ignored.

Parameters
pathPath to the file to remove.

◆ writeFile()

void nix::writeFile ( const std::filesystem::path & path,
std::string_view s,
mode_t mode = 0666,
FsSync sync = FsSync::No,
FinalSymlink finalSymlink = FinalSymlink::Follow )

Write a string to a file.