const std = @import("std"); /// Collapses '.' and '..' by text alone. A leading '/' survives; a '..' that /// would climb past the start is kept, because M1-PROJ-005 accepts such paths /// when the target is otherwise valid. pub fn normalizePath(arena: std.mem.Allocator, path: []const u8) std.mem.Allocator.Error![]const u8 { const absolute = path.len > 0 and path[0] == '/'; var parts: std.ArrayList([]const u8) = .empty; var it = std.mem.splitScalar(u8, path, '/'); while (it.next()) |part| { if (part.len == 0 or std.mem.eql(u8, part, ".")) continue; if (std.mem.eql(u8, part, "..")) { const climbable = parts.items.len > 0 and !std.mem.eql(u8, parts.items[parts.items.len - 1], ".."); if (climbable) { _ = parts.pop(); continue; } // "/.." is "/", so an absolute path simply drops it. if (absolute) continue; } try parts.append(arena, part); } var out: std.ArrayList(u8) = .empty; if (absolute) try out.append(arena, '/'); for (parts.items, 0..) |part, i| { if (i > 0) try out.append(arena, '/'); try out.appendSlice(arena, part); } return out.items; } // -- tests ------------------------------------------------------------------- const expectEqualStrings = std.testing.expectEqualStrings; test "lexical normalization collapses . and .. without touching the filesystem" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const alloc = arena.allocator(); try expectEqualStrings("a/b", try normalizePath(alloc, "a/./b")); try expectEqualStrings("a", try normalizePath(alloc, "a/b/..")); try expectEqualStrings("", try normalizePath(alloc, "a/..")); try expectEqualStrings("../b", try normalizePath(alloc, "../b")); try expectEqualStrings("/a/b", try normalizePath(alloc, "/a/./c/../b")); try expectEqualStrings("a/b", try normalizePath(alloc, "a//b/")); }