Skip to content

Example: Path Relativization and Joining (demo.os.path_rel)

This example demonstrates how to use the ddn.os.path.Path struct for joining paths, normalizing, checking ancestry, computing relative paths, and manipulating file names and extensions.


Source: demo/os/path_rel.d

/**
 * Demo: joining and relativization with ddn.os.path.Path
 *
 * Run:
 *   ./demo.sh demo-os-path_rel
 * or:
 *   dub run --single demo/os/path_rel.d
 */
module demo.os.path_rel;

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

void main() {
  writeln("=== ddn.os.path joining/relative demo ===");

  // Join using operator and joinpath variadic
  auto p = Path("/usr") / "local" / "bin";
  writeln("joined: ", p.str());

  auto q = Path("/var").joinpath("log", "app", "..", "log", "app.log").normalize();
  writeln("normalized: ", q.str());

  // Check ancestry and compute relative path
  auto base = Path("/var");
  writeln("isRelativeTo(/var): ", q.isRelativeTo(base));
  auto rel = q.relativeTo(base);
  writeln("relative to /var: ", rel.str());

  // withStem / withSuffix helpers
  auto f = Path("archive.tar.gz");
  writeln("name=", f.name(), " stem=", f.stem(), " suffix=", f.suffix());
  writeln("withStem('pkg'): ", f.withStem("pkg").str());
  writeln("withSuffix('.xz'): ", f.withSuffix(".xz").str());

  writeln("=== End rel demo ===");
}

What This Example Shows

  • Joining Paths:
    Use / operator or joinpath to join path segments.
  • Normalization:
    Use .normalize() to resolve .. and redundant segments.
  • Relativization:
    Use .relativeTo(base) to compute the relative path from a base.
  • Ancestry Check:
    Use .isRelativeTo(base) to check if a path is a descendant of another.
  • File Name Manipulation:
    Use .name(), .stem(), .suffix(), .withStem(), and .withSuffix() for file name and extension operations.

Example Output

=== ddn.os.path joining/relative demo ===
joined: /usr/local/bin
normalized: /var/log/app.log
isRelativeTo(/var): true
relative to /var: log/app.log
name=archive.tar.gz stem=archive.tar suffix=.gz
withStem('pkg'): pkg.tar.gz
withSuffix('.xz'): archive.tar.xz
=== End rel demo ===

See Also