Chapter 14Project Path Utility

Project

Overview

In this hands-on chapter, we build a tiny, allocator-friendly path helper that plays nicely with Zig’s standard library and works across platforms. We’ll develop it test-first—then also provide a small CLI demo so you can see actual output without a test harness. Along the way, we deliberately introduce a leak and watch Zig’s testing allocator catch it, then fix it and verify.

The goal is not to replace std.fs.path, but to practice API design, test-driven development (TDD), and leak-safe allocation in a realistic, bite-sized utility. See 13__testing-and-leak-detection.xml and path.zig.

Learning Goals

A small API surface

We’ll implement four helpers in the pathutil namespace:

  • joinAlloc(allocator, parts)[]u8: join components with a single separator, preserving an absolute root
  • basename(path)[]const u8: last component, ignoring trailing separators
  • dirpath(path)[]const u8: directory part, no trailing separators ("." for bare names, "/" for root)
  • extname(path)[]const u8 and changeExtAlloc(allocator, path, new_ext)[]u8

These functions emphasize predictable, teaching-friendly behavior; for production-grade edge cases, prefer std.fs.path.

Zig
const std = @import("std");

/// Tiny, allocator-friendly path utilities for didactic purposes.
/// Note: These do not attempt full platform semantics; they aim to be predictable
/// and portable for teaching. Prefer std.fs.path for production code.
pub const pathutil = struct {
    /// Join parts with exactly one separator between components.
    /// - Collapses duplicate separators at boundaries
    /// - Preserves a leading root (e.g. "/" on POSIX) if the first non-empty part starts with a separator
    /// - Does not resolve dot segments or drive letters
    pub fn joinAlloc(allocator: std.mem.Allocator, parts: []const []const u8) ![]u8 {
        var list: std.ArrayListUnmanaged(u8) = .{};
        defer list.deinit(allocator);

        const sep: u8 = std.fs.path.sep;
        var has_any: bool = false;

        for (parts) |raw| {
            if (raw.len == 0) continue;

            // Trim leading/trailing separators from this component
            var start: usize = 0;
            var end: usize = raw.len;
            while (start < end and isSep(raw[start])) start += 1;
            while (end > start and isSep(raw[end - 1])) end -= 1;

            const had_leading_sep = start > 0;
            const core = raw[start..end];

            if (!has_any) {
                if (had_leading_sep) {
                    // Preserve absolute root
                    try list.append(allocator, sep);
                    has_any = true;
                }
            } else {
                // Ensure exactly one separator between components if we have content already
                if (list.items.len == 0 or list.items[list.items.len - 1] != sep) {
                    try list.append(allocator, sep);
                }
            }

            if (core.len != 0) {
                try list.appendSlice(allocator, core);
                has_any = true;
            }
        }

        return list.toOwnedSlice(allocator);
    }

    /// Return the last path component. Trailing separators are ignored.
    /// Examples: "a/b/c" -> "c", "/a/b/" -> "b", "/" -> "/", "" -> "".
    pub fn basename(path: []const u8) []const u8 {
        if (path.len == 0) return path;

        // Skip trailing separators
        var end = path.len;
        while (end > 0 and isSep(path[end - 1])) end -= 1;
        if (end == 0) {
            // path was all separators; treat it as root
            return path[0..1];
        }

        // Find previous separator
        var i: isize = @intCast(end);
        while (i > 0) : (i -= 1) {
            if (isSep(path[@intCast(i - 1)])) break;
        }
        const start: usize = @intCast(i);
        return path[start..end];
    }

    /// Return the directory portion (without trailing separators).
    /// Examples: "a/b/c" -> "a/b", "a" -> ".", "/" -> "/".
    pub fn dirpath(path: []const u8) []const u8 {
        if (path.len == 0) return ".";

        // Skip trailing separators
        var end = path.len;
        while (end > 0 and isSep(path[end - 1])) end -= 1;
        if (end == 0) return path[0..1]; // all separators -> root

        // Find previous separator
        var i: isize = @intCast(end);
        while (i > 0) : (i -= 1) {
            const ch = path[@intCast(i - 1)];
            if (isSep(ch)) break;
        }
        if (i == 0) return ".";

        // Skip any trailing separators in the dir portion
        var d_end: usize = @intCast(i);
        while (d_end > 1 and isSep(path[d_end - 1])) d_end -= 1;
        if (d_end == 0) return path[0..1];
        return path[0..d_end];
    }

    /// Return the extension (without dot) of the last component or "" if none.
    /// Examples: "file.txt" -> "txt", "a.tar.gz" -> "gz", ".gitignore" -> "".
    pub fn extname(path: []const u8) []const u8 {
        const base = basename(path);
        if (base.len == 0) return base;
        if (base[0] == '.') {
            // Hidden file as first character '.' does not count as extension if there is no other dot
            if (std.mem.indexOfScalar(u8, base[1..], '.')) |idx2| {
                const idx = 1 + idx2;
                if (idx + 1 < base.len) return base[(idx + 1)..];
                return "";
            } else return "";
        }
        if (std.mem.lastIndexOfScalar(u8, base, '.')) |idx| {
            if (idx + 1 < base.len) return base[(idx + 1)..];
        }
        return "";
    }

    /// Return a newly-allocated path with the extension replaced by `new_ext` (no dot).
    /// If there is no existing extension, appends one if `new_ext` is non-empty.
    pub fn changeExtAlloc(allocator: std.mem.Allocator, path: []const u8, new_ext: []const u8) ![]u8 {
        const base = basename(path);
        const dir = dirpath(path);
        const sep: u8 = std.fs.path.sep;

        var base_core = base;
        if (std.mem.lastIndexOfScalar(u8, base, '.')) |idx| {
            if (!(idx == 0 and base[0] == '.')) {
                base_core = base[0..idx];
            }
        }

        const need_dot = new_ext.len != 0;
        const dir_has = dir.len != 0 and !(dir.len == 1 and dir[0] == '.' and base.len == path.len);
        // Compute length at runtime to avoid comptime_int dependency
        var new_len: usize = 0;
        if (dir_has) new_len += dir.len + 1;
        new_len += base_core.len;
        if (need_dot) new_len += 1 + new_ext.len;

        var out = try allocator.alloc(u8, new_len);
        errdefer allocator.free(out);

        var w: usize = 0;
        if (dir_has) {
            @memcpy(out[w..][0..dir.len], dir);
            w += dir.len;
            out[w] = sep;
            w += 1;
        }
        @memcpy(out[w..][0..base_core.len], base_core);
        w += base_core.len;
        if (need_dot) {
            out[w] = '.';
            w += 1;
            @memcpy(out[w..][0..new_ext.len], new_ext);
            w += new_ext.len;
        }
        return out;
    }
};

inline fn isSep(ch: u8) bool {
    return ch == std.fs.path.sep or isOtherSep(ch);
}

inline fn isOtherSep(ch: u8) bool {
    // Be forgiving in parsing: treat both '/' and '\\' as separators on any platform
    // but only emit std.fs.path.sep when joining.
    return ch == '/' or ch == '\\';
}

For pedagogy, we accept either '/' or '\\' as separators on any platform when parsing, but we always emit the local separator (std.fs.path.sep) when joining.

Try it: run the demo (visible output)

To keep output visible outside the test runner, here’s a tiny CLI that calls our helpers and prints the results.

Zig
const std = @import("std");
const pathutil = @import("path_util.zig").pathutil;

pub fn main() !void {
    var out_buf: [2048]u8 = undefined;
    var out_writer = std.fs.File.stdout().writer(&out_buf);
    const out = &out_writer.interface;

    // Demonstrate join
    const j1 = try pathutil.joinAlloc(std.heap.page_allocator, &.{ "a", "b", "c" });
    defer std.heap.page_allocator.free(j1);
    try out.print("join a,b,c => {s}\n", .{j1});

    const j2 = try pathutil.joinAlloc(std.heap.page_allocator, &.{ "/", "usr/", "/bin" });
    defer std.heap.page_allocator.free(j2);
    try out.print("join /,usr/,/bin => {s}\n", .{j2});

    // Demonstrate basename/dirpath
    const p = "/home/user/docs/report.txt";
    try out.print("basename({s}) => {s}\n", .{ p, pathutil.basename(p) });
    try out.print("dirpath({s}) => {s}\n", .{ p, pathutil.dirpath(p) });

    // Extension helpers
    try out.print("extname({s}) => {s}\n", .{ p, pathutil.extname(p) });
    const changed = try pathutil.changeExtAlloc(std.heap.page_allocator, p, "md");
    defer std.heap.page_allocator.free(changed);
    try out.print("changeExt({s}, md) => {s}\n", .{ p, changed });

    try out.flush();
}
Run
Shell
$ zig run chapters-data/code/14__project-path-utility-tdd/path_util_demo.zig
Output
Shell
join a,b,c => a/b/c
join /,usr/,/bin => /usr/bin
basename(/home/user/docs/report.txt) => report.txt
dirpath(/home/user/docs/report.txt) => /home/user/docs
extname(/home/user/docs/report.txt) => txt
changeExt(/home/user/docs/report.txt, md) => /home/user/docs/report.md

Test-first: codify behavior and edge cases

TDD helps clarify intent and lock down edge cases. We keep tests small and fast; they run with Zig’s testing allocator, which catches leaks by default. This chapter includes tests because the content plan calls for TDD; elsewhere we’ll favor zig run-style demos for visible output. See 13__testing-and-leak-detection.xml and testing.zig.

Zig
const std = @import("std");
const testing = std.testing;
const pathutil = @import("path_util.zig").pathutil;

fn ajoin(parts: []const []const u8) ![]u8 {
    return try pathutil.joinAlloc(testing.allocator, parts);
}

test "joinAlloc basic and absolute" {
    const p1 = try ajoin(&.{ "a", "b", "c" });
    defer testing.allocator.free(p1);
    try testing.expectEqualStrings("a" ++ [1]u8{std.fs.path.sep} ++ "b" ++ [1]u8{std.fs.path.sep} ++ "c", p1);

    const p2 = try ajoin(&.{ "/", "usr/", "/bin" });
    defer testing.allocator.free(p2);
    try testing.expectEqualStrings("/usr/bin", p2);

    const p3 = try ajoin(&.{ "", "a", "", "b" });
    defer testing.allocator.free(p3);
    try testing.expectEqualStrings("a" ++ [1]u8{std.fs.path.sep} ++ "b", p3);

    const p4 = try ajoin(&.{ "a/", "/b/" });
    defer testing.allocator.free(p4);
    try testing.expectEqualStrings("a" ++ [1]u8{std.fs.path.sep} ++ "b", p4);
}

test "basename and dirpath edges" {
    try testing.expectEqualStrings("c", pathutil.basename("a/b/c"));
    try testing.expectEqualStrings("b", pathutil.basename("/a/b/"));
    try testing.expectEqualStrings("/", pathutil.basename("////"));
    try testing.expectEqualStrings("", pathutil.basename(""));

    try testing.expectEqualStrings("a/b", pathutil.dirpath("a/b/c"));
    try testing.expectEqualStrings(".", pathutil.dirpath("a"));
    try testing.expectEqualStrings("/", pathutil.dirpath("////"));
}

test "extension and changeExtAlloc" {
    try testing.expectEqualStrings("txt", pathutil.extname("file.txt"));
    try testing.expectEqualStrings("gz", pathutil.extname("a.tar.gz"));
    try testing.expectEqualStrings("", pathutil.extname(".gitignore"));
    try testing.expectEqualStrings("", pathutil.extname("noext"));

    const changed1 = try pathutil.changeExtAlloc(testing.allocator, "a/b/file.txt", "md");
    defer testing.allocator.free(changed1);
    try testing.expectEqualStrings("a/b/file.md", changed1);

    const changed2 = try pathutil.changeExtAlloc(testing.allocator, "a/b/file", "md");
    defer testing.allocator.free(changed2);
    try testing.expectEqualStrings("a/b/file.md", changed2);

    const changed3 = try pathutil.changeExtAlloc(testing.allocator, "a/b/.profile", "txt");
    defer testing.allocator.free(changed3);
    try testing.expectEqualStrings("a/b/.profile.txt", changed3);
}
Run
Shell
$ zig test chapters-data/code/14__project-path-utility-tdd/path_util_test.zig
Output
Shell
All 3 tests passed.

Catch a deliberate leak → fix it

The testing allocator flags leaks at the end of a test. First, a failing example that forgets to free:

Zig
const std = @import("std");
const testing = std.testing;
const pathutil = @import("path_util.zig").pathutil;

test "deliberate leak caught by testing allocator" {
    const joined = try pathutil.joinAlloc(testing.allocator, &.{ "/", "tmp", "demo" });
    // Intentionally forget to free: allocator leak should be detected by the runner
    // defer testing.allocator.free(joined);
    try testing.expect(std.mem.endsWith(u8, joined, "demo"));
}
Run (expect failure)
Shell
$ zig test chapters-data/code/14__project-path-utility-tdd/leak_demo_fail.zig
Output (excerpt)
[gpa] (err): memory address 0x… leaked:
… path_util.zig:49:33: … in joinAlloc
… leak_demo_fail.zig:6:42: … in test.deliberate leak caught by testing allocator

All 1 tests passed.
1 errors were logged.
1 tests leaked memory.
error: the following test command failed with exit code 1:
…/test --seed=0x…

Then fix it with defer and watch the suite go green:

Zig
const std = @import("std");
const testing = std.testing;
const pathutil = @import("path_util.zig").pathutil;

test "fixed: no leak after adding defer free" {
    const joined = try pathutil.joinAlloc(testing.allocator, &.{ "/", "tmp", "demo" });
    defer testing.allocator.free(joined);
    try testing.expect(std.mem.endsWith(u8, joined, "demo"));
}
Run
Shell
$ zig test chapters-data/code/14__project-path-utility-tdd/leak_demo_fix.zig
Output
Shell
All 1 tests passed.

10__allocators-and-memory-management.xml, heap.zig

Notes & Caveats

  • For production path handling, consult std.fs.path for platform nuances (UNC paths, drive letters, special roots).
  • Prefer defer allocator.free(buf) immediately after successful allocations; it makes success and error paths correct by construction. 04__errors-resource-cleanup.xml
  • When you need visible output (tutorials, demos), prefer zig run examples; when you need guarantees (CI), prefer zig test. This chapter demonstrates both because it’s explicitly TDD-focused. 13__testing-and-leak-detection.xml

Exercises

  • Extend joinAlloc to elide . segments and collapse .. pairs in the middle (be careful near the root). Add tests for edge cases, then demo with zig run.
  • Add stem(path) that returns the basename without extension; verify behavior for .gitignore, multi-dot names, and trailing dots.
  • Write a tiny CLI that takes --change-ext md file1 file2 … and prints the results, using the page allocator and a buffered writer. 28__filesystem-and-io.xml

Alternatives & Edge Cases

  • On Windows, this teaching utility treats both '/' and '\\' as separators for input, but always prints the local separator. std.fs.path has richer semantics if you need exact Windows behavior.
  • Allocation failure handling: the demo uses std.heap.page_allocator and would abort on OOM; the tests use std.testing.allocator to systematically catch leaks. 10__allocators-and-memory-management.xml
  • If you embed these helpers into larger tools, thread the allocator through your APIs and keep ownership rules explicit; avoid global state. 36__style-and-best-practices.xml

Help make this chapter better.

Found a typo, rough edge, or missing explanation? Open an issue or propose a small improvement on GitHub.