Skip to content

ddn.os.path

Overview

The ddn.os.path module provides a robust, cross-platform API for filesystem path manipulation in D, inspired by Python's pathlib. It offers the high-level Path struct and related utilities for working with file and directory paths in a safe, expressive, and idiomatic D style.


Installation

To use ddn.os.path, ensure your project depends on the DDN library. If using DUB, add the following to your dub.sdl or dub.json:

dependency "ddn" version=">=1.0.0"

Then, import the module in your D code:

import ddn.os.path;

Usage

Typical usage involves creating Path objects, joining and normalizing paths, performing filesystem operations, and using globbing for file discovery:

import ddn.os.path;
import std.stdio;

void main() {
    auto p = Path("foo/bar.txt");
    writeln("Path: ", p.str());
    writeln("Exists? ", p.exists());
    writeln("Parent: ", p.parent().str());
    writeln("Stem: ", p.stem());
    writeln("Suffix: ", p.suffix());

    // Create directory and file
    auto dir = Path("foo");
    if (!dir.exists()) dir.mkdir();
    p.writeText("Hello, world!");

    // Read file
    auto contents = p.readText();
    writeln("Contents: ", contents);

    // Globbing
    foreach (file; dir.glob("*.txt")) {
        writeln("Found text file: ", file.str());
    }
}

Module

module ddn.os.path;

Struct: Path

Represents a filesystem path and provides a rich set of methods for manipulation and querying.

Fields

  • private string _path — The underlying path string.

Constructors

  • this(string path)
    Constructs a Path from a string.

Properties

  • string str() const — Returns the string representation of the path.
  • string name() const — Returns the final component of the path.
  • string stem() const — Returns the filename without its extension.
  • string suffix() const — Returns the last file extension (including the dot).
  • string[] suffixes() const — Returns all file extensions as an array.
  • Path parent() const — Returns the parent directory as a Path.
  • string asUri() const — Returns the file URI as a string.
  • string drive() const — Returns the drive component (Windows only).
  • string root() const — Returns the root component of the path.
  • string anchor() const — Returns the anchor (drive + root on Windows, root on POSIX).

Methods

Path Manipulation

  • Path join(string other) const — Joins this path with another string segment.
  • Path joinpath(T...)(T args) const — Joins this path with one or more segments (string or Path).
  • Path opBinary(string op : "/")(string other) const — Operator overload for joining with /.
  • Path opBinary(string op : "/")(Path other) const — Operator overload for joining with /.
  • Path withName(string newName) const — Returns a new Path with the name replaced.
  • Path withStem(string newStem) const — Returns a new Path with the stem replaced.
  • Path withSuffix(string newSuffix) const — Returns a new Path with the last suffix replaced.
  • Path absolute() const — Returns the absolute path.
  • Path normalize() const — Returns the normalized version of this path.
  • Path norm() const — Alias for normalize().
  • Path expandUser() const — Expands a leading ~ to the user's home directory.
  • Path expandVars() const — Expands environment variables in the path string.

Filesystem Queries

  • bool exists() const — Checks if the path exists.
  • bool isFile() const — Checks if the path is a file.
  • bool isDir() const — Checks if the path is a directory.
  • bool isSymlink() const — Checks if the path is a symbolic link.
  • bool isBlockDevice() const — Checks if the path is a block device (POSIX only).
  • bool isCharDevice() const — Checks if the path is a character device (POSIX only).
  • bool isFifo() const — Checks if the path is a FIFO (named pipe, POSIX only).
  • bool isSocket() const — Checks if the path is a socket (POSIX only).
  • bool isReservedDeviceName() const — Checks if the path is a reserved device name (Windows only).
  • bool isRelativeTo(Path other) const — Checks if this path is relative to another.
  • bool isRelativeTo(string other) const — Checks if this path is relative to another (string overload).
  • Path relativeTo(Path other) const — Returns the relative path from another base Path.
  • Path relativeTo(string other) const — Returns the relative path from another base (string overload).
  • bool samefile(Path other) const — Checks if both paths refer to the same file.
  • static bool sameOpenFile(int fd1, int fd2) — Checks if two file descriptors refer to the same file.
  • static bool sameOpenFile(File f1, File f2) — Checks if two File objects refer to the same file.

Filesystem Operations

  • void mkdir(bool parents = false) const — Creates a directory (optionally recursively).
  • void remove(bool recursive = false) const — Removes the file or directory.
  • void rename(string target) const — Renames this path to the target path.
  • void replace(string target) const — Atomically replaces the target with this path.
  • void symlinkTo(string target) const — Creates a symbolic link at this path pointing to the target.
  • void hardlinkTo(string target) const — Creates a hard link at this path pointing to the target.
  • void chmod(uint mode) const — Changes file permissions (POSIX only).
  • void lchmod(uint mode) const — Changes file permissions, not following symlinks (POSIX only).
  • void chown(int uid, int gid) const — Changes file owner and group (POSIX only).
  • void lchown(int uid, int gid) const — Changes file owner and group, not following symlinks (POSIX only).
  • string owner() const — Returns the owner username (POSIX only).
  • string group() const — Returns the group name (POSIX only).
  • void touch(bool existOk = true, Nullable!uint mode = Nullable!uint.init, Nullable!SysTime times = Nullable!SysTime.init) const — Creates the file if it does not exist.

File I/O

  • string readText(string encoding = "utf-8", string errors = "strict", string newline = null) const — Reads the file as text.
  • ubyte[] readBytes() const — Reads the file as bytes.
  • void writeText(string content, string encoding = "utf-8", string errors = "strict", string newline = null, bool atomic = false) const — Writes text to the file.
  • void writeBytes(const(ubyte)[] content, bool atomic = false) const — Writes bytes to the file.

Directory and Globbing

  • Path[] iterDir() const — Returns an array of immediate children as Paths.
  • auto iterdir() const — Returns a lazy input range of immediate children as Paths.
  • Path[] glob(string pattern) const — Returns paths matching the glob pattern.
  • Path[] rglob(string pattern) const — Recursively finds files matching the glob pattern.
  • string readLink() const — Reads the target of a symbolic link.

Directory Walking

  • WalkEntry[] walk(bool topDown = true, bool followSymlinks = false, bool delegate(const Path) dirFilter = null) const — Recursively walks the directory tree.

Static Methods

  • static Path home() — Returns the home directory as a Path.
  • static Path cwd() — Returns the current working directory as a Path.

Additional Types

WalkEntry

Represents a directory walk result (root, dirs, files).

FileTimes

Represents file access and modification times.


Examples

Path Construction and Joining

auto p = Path("foo") / "bar" / "baz.txt";
auto joined = Path("foo").joinpath("bar", "baz.txt");

Normalization and Relativization

auto normalized = Path("foo/../bar").normalize();
auto rel = Path("/usr/local/bin").relativeTo(Path("/usr"));

File and Directory Operations

auto p = Path("data.txt");
if (!p.exists()) {
    p.writeText("Hello!");
}
auto txt = p.readText();

Globbing

foreach (file; Path("src").glob("**/*.d")) {
    // Do something with each .d file
}

Directory Walking

foreach (entry; Path("src").walk()) {
    writeln("Dir: ", entry.root.str());
    foreach (f; entry.files) writeln("  File: ", f.str());
}

Exceptions

PathError

Base class for all path-related exceptions thrown by this module.

class PathError : Exception

NotFoundError

Thrown when a path component is missing (ENOENT/ENOTDIR).

class NotFoundError : PathError

PermissionError

Thrown when access is denied (EACCES/EPERM).

class PermissionError : PathError

See Also


License

SPDX-License-Identifier: BSD-3-Clause