| 1 | //! POSIX paths are arbitrary sequences of `u8` with no particular encoding. |
| 2 | //! |
| 3 | //! Windows paths are arbitrary sequences of `u16` (WTF-16). |
| 4 | //! For cross-platform APIs that deal with sequences of `u8`, Windows |
| 5 | //! paths are encoded by Zig as [WTF-8](https://wtf-8.codeberg.page/). |
| 6 | //! WTF-8 is a superset of UTF-8 that allows encoding surrogate codepoints, |
| 7 | //! which enables lossless roundtripping when converting to/from WTF-16 |
| 8 | //! (as long as the WTF-8 encoded surrogate codepoints do not form a pair). |
| 9 | //! |
| 10 | //! WASI paths are sequences of valid Unicode scalar values, |
| 11 | //! which means that WASI is unable to handle paths that cannot be |
| 12 | //! encoded as well-formed UTF-8/UTF-16. |
| 13 | //! https://github.com/WebAssembly/wasi-filesystem/issues/17#issuecomment-1430639353 |
| 14 | |
| 15 | const builtin = @import("builtin"); |
| 16 | const native_os = builtin.target.os.tag; |
| 17 | |
| 18 | const std = @import("../std.zig"); |
| 19 | const assert = std.debug.assert; |
| 20 | const testing = std.testing; |
| 21 | const mem = std.mem; |
| 22 | const Allocator = std.mem.Allocator; |
| 23 | const eqlIgnoreCaseWtf8 = std.os.windows.eqlIgnoreCaseWtf8; |
| 24 | const eqlIgnoreCaseWtf16 = std.os.windows.eqlIgnoreCaseWtf16; |
| 25 | |
| 26 | pub const sep_windows: u8 = '\\'; |
| 27 | pub const sep_posix: u8 = '/'; |
| 28 | pub const sep = switch (native_os) { |
| 29 | .windows, .uefi => sep_windows, |
| 30 | else => sep_posix, |
| 31 | }; |
| 32 | |
| 33 | pub const sep_str_windows = "\\"; |
| 34 | pub const sep_str_posix = "/"; |
| 35 | pub const sep_str = switch (native_os) { |
| 36 | .windows, .uefi => sep_str_windows, |
| 37 | else => sep_str_posix, |
| 38 | }; |
| 39 | |
| 40 | pub const delimiter_windows: u8 = ';'; |
| 41 | pub const delimiter_posix: u8 = ':'; |
| 42 | pub const delimiter = if (native_os == .windows) delimiter_windows else delimiter_posix; |
| 43 | |
| 44 | /// Returns if the given byte is a valid path separator |
| 45 | pub fn isSep(byte: u8) bool { |
| 46 | return switch (native_os) { |
| 47 | .windows => byte == '/' or byte == '\\', |
| 48 | .uefi => byte == '\\', |
| 49 | else => byte == '/', |
| 50 | }; |
| 51 | } |
| 52 | |
| 53 | pub const PathType = enum { |
| 54 | windows, |
| 55 | uefi, |
| 56 | posix, |
| 57 | |
| 58 | /// Returns true if `c` is a valid path separator for the `path_type`. |
| 59 | /// If `T` is `u16`, `c` is assumed to be little-endian. |
| 60 | pub inline fn isSep(comptime path_type: PathType, comptime T: type, c: T) bool { |
| 61 | return switch (path_type) { |
| 62 | .windows => c == mem.nativeToLittle(T, '/') or c == mem.nativeToLittle(T, '\\'), |
| 63 | .posix => c == mem.nativeToLittle(T, '/'), |
| 64 | .uefi => c == mem.nativeToLittle(T, '\\'), |
| 65 | }; |
| 66 | } |
| 67 | }; |
| 68 | |
| 69 | /// This is different from mem.join in that the separator will not be repeated if |
| 70 | /// it is found at the end or beginning of a pair of consecutive paths. |
| 71 | fn joinSepMaybeZ(allocator: Allocator, separator: u8, comptime sepPredicate: fn (u8) bool, paths: []const []const u8, zero: bool) ![]u8 { |
| 72 | if (paths.len == 0) return if (zero) try allocator.dupe(u8, &[1]u8{0}) else &[0]u8{}; |
| 73 | |
| 74 | // Find first non-empty path index. |
| 75 | const first_path_index = blk: { |
| 76 | for (paths, 0..) |path, index| { |
| 77 | if (path.len == 0) continue else break :blk index; |
| 78 | } |
| 79 | |
| 80 | // All paths provided were empty, so return early. |
| 81 | return if (zero) try allocator.dupe(u8, &[1]u8{0}) else &[0]u8{}; |
| 82 | }; |
| 83 | |
| 84 | // Calculate length needed for resulting joined path buffer. |
| 85 | const total_len = blk: { |
| 86 | var sum: usize = paths[first_path_index].len; |
| 87 | var prev_path = paths[first_path_index]; |
| 88 | assert(prev_path.len > 0); |
| 89 | var i: usize = first_path_index + 1; |
| 90 | while (i < paths.len) : (i += 1) { |
| 91 | const this_path = paths[i]; |
| 92 | if (this_path.len == 0) continue; |
| 93 | const prev_sep = sepPredicate(prev_path[prev_path.len - 1]); |
| 94 | const this_sep = sepPredicate(this_path[0]); |
| 95 | sum += @intFromBool(!prev_sep and !this_sep); |
| 96 | sum += if (prev_sep and this_sep) this_path.len - 1 else this_path.len; |
| 97 | prev_path = this_path; |
| 98 | } |
| 99 | |
| 100 | if (zero) sum += 1; |
| 101 | break :blk sum; |
| 102 | }; |
| 103 | |
| 104 | const buf = try allocator.alloc(u8, total_len); |
| 105 | errdefer allocator.free(buf); |
| 106 | |
| 107 | @memcpy(buf[0..paths[first_path_index].len], paths[first_path_index]); |
| 108 | var buf_index: usize = paths[first_path_index].len; |
| 109 | var prev_path = paths[first_path_index]; |
| 110 | assert(prev_path.len > 0); |
| 111 | var i: usize = first_path_index + 1; |
| 112 | while (i < paths.len) : (i += 1) { |
| 113 | const this_path = paths[i]; |
| 114 | if (this_path.len == 0) continue; |
| 115 | const prev_sep = sepPredicate(prev_path[prev_path.len - 1]); |
| 116 | const this_sep = sepPredicate(this_path[0]); |
| 117 | if (!prev_sep and !this_sep) { |
| 118 | buf[buf_index] = separator; |
| 119 | buf_index += 1; |
| 120 | } |
| 121 | const adjusted_path = if (prev_sep and this_sep) this_path[1..] else this_path; |
| 122 | @memcpy(buf[buf_index..][0..adjusted_path.len], adjusted_path); |
| 123 | buf_index += adjusted_path.len; |
| 124 | prev_path = this_path; |
| 125 | } |
| 126 | |
| 127 | if (zero) buf[buf.len - 1] = 0; |
| 128 | |
| 129 | // No need for shrink since buf is exactly the correct size. |
| 130 | return buf; |
| 131 | } |
| 132 | |
| 133 | /// Naively combines a series of paths with the native path separator. |
| 134 | /// Allocates memory for the result, which must be freed by the caller. |
| 135 | pub fn join(allocator: Allocator, paths: []const []const u8) ![]u8 { |
| 136 | return joinSepMaybeZ(allocator, sep, isSep, paths, false); |
| 137 | } |
| 138 | |
| 139 | /// Naively combines a series of paths with the native path separator and null terminator. |
| 140 | /// Allocates memory for the result, which must be freed by the caller. |
| 141 | pub fn joinZ(allocator: Allocator, paths: []const []const u8) ![:0]u8 { |
| 142 | const out = try joinSepMaybeZ(allocator, sep, isSep, paths, true); |
| 143 | return out[0 .. out.len - 1 :0]; |
| 144 | } |
| 145 | |
| 146 | pub fn fmtJoin(paths: []const []const u8) std.fmt.Alt([]const []const u8, formatJoin) { |
| 147 | return .{ .data = paths }; |
| 148 | } |
| 149 | |
| 150 | fn formatJoin(paths: []const []const u8, w: *std.Io.Writer) std.Io.Writer.Error!void { |
| 151 | const first_path_idx = for (paths, 0..) |p, idx| { |
| 152 | if (p.len != 0) break idx; |
| 153 | } else return; |
| 154 | |
| 155 | try w.writeAll(paths[first_path_idx]); // first component |
| 156 | var prev_path = paths[first_path_idx]; |
| 157 | for (paths[first_path_idx + 1 ..]) |this_path| { |
| 158 | if (this_path.len == 0) continue; // skip empty components |
| 159 | const prev_sep = isSep(prev_path[prev_path.len - 1]); |
| 160 | const this_sep = isSep(this_path[0]); |
| 161 | if (!prev_sep and !this_sep) { |
| 162 | try w.writeByte(sep); |
| 163 | } |
| 164 | if (prev_sep and this_sep) { |
| 165 | try w.writeAll(this_path[1..]); // skip redundant separator |
| 166 | } else { |
| 167 | try w.writeAll(this_path); |
| 168 | } |
| 169 | prev_path = this_path; |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | fn testJoinMaybeZUefi(paths: []const []const u8, expected: []const u8, zero: bool) !void { |
| 174 | const uefiIsSep = struct { |
| 175 | fn isSep(byte: u8) bool { |
| 176 | return byte == '\\'; |
| 177 | } |
| 178 | }.isSep; |
| 179 | const actual = try joinSepMaybeZ(testing.allocator, sep_windows, uefiIsSep, paths, zero); |
| 180 | defer testing.allocator.free(actual); |
| 181 | try testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual); |
| 182 | } |
| 183 | |
| 184 | fn testJoinMaybeZWindows(paths: []const []const u8, expected: []const u8, zero: bool) !void { |
| 185 | const windowsIsSep = struct { |
| 186 | fn isSep(byte: u8) bool { |
| 187 | return byte == '/' or byte == '\\'; |
| 188 | } |
| 189 | }.isSep; |
| 190 | const actual = try joinSepMaybeZ(testing.allocator, sep_windows, windowsIsSep, paths, zero); |
| 191 | defer testing.allocator.free(actual); |
| 192 | try testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual); |
| 193 | } |
| 194 | |
| 195 | fn testJoinMaybeZPosix(paths: []const []const u8, expected: []const u8, zero: bool) !void { |
| 196 | const posixIsSep = struct { |
| 197 | fn isSep(byte: u8) bool { |
| 198 | return byte == '/'; |
| 199 | } |
| 200 | }.isSep; |
| 201 | const actual = try joinSepMaybeZ(testing.allocator, sep_posix, posixIsSep, paths, zero); |
| 202 | defer testing.allocator.free(actual); |
| 203 | try testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual); |
| 204 | } |
| 205 | |
| 206 | test join { |
| 207 | { |
| 208 | const actual: []u8 = try join(testing.allocator, &[_][]const u8{}); |
| 209 | defer testing.allocator.free(actual); |
| 210 | try testing.expectEqualSlices(u8, "", actual); |
| 211 | } |
| 212 | { |
| 213 | const actual: [:0]u8 = try joinZ(testing.allocator, &[_][]const u8{}); |
| 214 | defer testing.allocator.free(actual); |
| 215 | try testing.expectEqualSlices(u8, "", actual); |
| 216 | } |
| 217 | for (&[_]bool{ false, true }) |zero| { |
| 218 | try testJoinMaybeZWindows(&[_][]const u8{}, "", zero); |
| 219 | try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero); |
| 220 | try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero); |
| 221 | try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b\\", "\\c" }, "c:\\a\\b\\c", zero); |
| 222 | |
| 223 | try testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b\\", "c" }, "c:\\a\\b\\c", zero); |
| 224 | try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\", "b\\", "c" }, "c:\\a\\b\\c", zero); |
| 225 | |
| 226 | try testJoinMaybeZWindows( |
| 227 | &[_][]const u8{ "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std", "ab.zig" }, |
| 228 | "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std\\ab.zig", |
| 229 | zero, |
| 230 | ); |
| 231 | |
| 232 | try testJoinMaybeZUefi(&[_][]const u8{ "EFI", "Boot", "bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero); |
| 233 | try testJoinMaybeZUefi(&[_][]const u8{ "EFI\\Boot", "bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero); |
| 234 | try testJoinMaybeZUefi(&[_][]const u8{ "EFI\\", "\\Boot", "bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero); |
| 235 | try testJoinMaybeZUefi(&[_][]const u8{ "EFI\\", "\\Boot\\", "\\bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero); |
| 236 | |
| 237 | try testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b/", "c" }, "c:\\a\\b/c", zero); |
| 238 | try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a/", "b\\", "/c" }, "c:\\a/b\\c", zero); |
| 239 | |
| 240 | try testJoinMaybeZWindows(&[_][]const u8{ "", "c:\\", "", "", "a", "b\\", "c", "" }, "c:\\a\\b\\c", zero); |
| 241 | try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a/", "", "b\\", "", "/c" }, "c:\\a/b\\c", zero); |
| 242 | try testJoinMaybeZWindows(&[_][]const u8{ "", "" }, "", zero); |
| 243 | |
| 244 | try testJoinMaybeZPosix(&[_][]const u8{}, "", zero); |
| 245 | try testJoinMaybeZPosix(&[_][]const u8{ "/a/b", "c" }, "/a/b/c", zero); |
| 246 | try testJoinMaybeZPosix(&[_][]const u8{ "/a/b/", "c" }, "/a/b/c", zero); |
| 247 | |
| 248 | try testJoinMaybeZPosix(&[_][]const u8{ "/", "a", "b/", "c" }, "/a/b/c", zero); |
| 249 | try testJoinMaybeZPosix(&[_][]const u8{ "/a/", "b/", "c" }, "/a/b/c", zero); |
| 250 | |
| 251 | try testJoinMaybeZPosix( |
| 252 | &[_][]const u8{ "/home/andy/dev/zig/build/lib/zig/std", "ab.zig" }, |
| 253 | "/home/andy/dev/zig/build/lib/zig/std/ab.zig", |
| 254 | zero, |
| 255 | ); |
| 256 | |
| 257 | try testJoinMaybeZPosix(&[_][]const u8{ "a", "/c" }, "a/c", zero); |
| 258 | try testJoinMaybeZPosix(&[_][]const u8{ "a/", "/c" }, "a/c", zero); |
| 259 | |
| 260 | try testJoinMaybeZPosix(&[_][]const u8{ "", "/", "a", "", "b/", "c", "" }, "/a/b/c", zero); |
| 261 | try testJoinMaybeZPosix(&[_][]const u8{ "/a/", "", "", "b/", "c" }, "/a/b/c", zero); |
| 262 | try testJoinMaybeZPosix(&[_][]const u8{ "", "" }, "", zero); |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | pub fn isAbsoluteZ(path_c: [*:0]const u8) bool { |
| 267 | if (native_os == .windows) { |
| 268 | return isAbsoluteWindowsZ(path_c); |
| 269 | } else { |
| 270 | return isAbsolutePosixZ(path_c); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | pub fn isAbsolute(path: []const u8) bool { |
| 275 | if (native_os == .windows) { |
| 276 | return isAbsoluteWindows(path); |
| 277 | } else { |
| 278 | return isAbsolutePosix(path); |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | fn isAbsoluteWindowsImpl(comptime T: type, path: []const T) bool { |
| 283 | return switch (getWin32PathType(T, path)) { |
| 284 | // Unambiguously absolute |
| 285 | .drive_absolute, .unc_absolute, .local_device, .root_local_device => true, |
| 286 | // Unambiguously relative |
| 287 | .relative => false, |
| 288 | // Ambiguous, more absolute than relative |
| 289 | .rooted => true, |
| 290 | // Ambiguous, more relative than absolute |
| 291 | .drive_relative => false, |
| 292 | }; |
| 293 | } |
| 294 | |
| 295 | pub fn isAbsoluteWindows(path: []const u8) bool { |
| 296 | return isAbsoluteWindowsImpl(u8, path); |
| 297 | } |
| 298 | |
| 299 | pub fn isAbsoluteWindowsW(path_w: [*:0]const u16) bool { |
| 300 | return isAbsoluteWindowsImpl(u16, mem.sliceTo(path_w, 0)); |
| 301 | } |
| 302 | |
| 303 | pub fn isAbsoluteWindowsWtf16(path: []const u16) bool { |
| 304 | return isAbsoluteWindowsImpl(u16, path); |
| 305 | } |
| 306 | |
| 307 | pub fn isAbsoluteWindowsZ(path_c: [*:0]const u8) bool { |
| 308 | return isAbsoluteWindowsImpl(u8, mem.sliceTo(path_c, 0)); |
| 309 | } |
| 310 | |
| 311 | pub fn isAbsolutePosix(path: []const u8) bool { |
| 312 | return path.len > 0 and path[0] == sep_posix; |
| 313 | } |
| 314 | |
| 315 | pub fn isAbsolutePosixZ(path_c: [*:0]const u8) bool { |
| 316 | return isAbsolutePosix(mem.sliceTo(path_c, 0)); |
| 317 | } |
| 318 | |
| 319 | test isAbsoluteWindows { |
| 320 | try testIsAbsoluteWindows("", false); |
| 321 | try testIsAbsoluteWindows("/", true); |
| 322 | try testIsAbsoluteWindows("//", true); |
| 323 | try testIsAbsoluteWindows("//server", true); |
| 324 | try testIsAbsoluteWindows("//server/file", true); |
| 325 | try testIsAbsoluteWindows("\\\\server\\file", true); |
| 326 | try testIsAbsoluteWindows("\\\\server", true); |
| 327 | try testIsAbsoluteWindows("\\\\", true); |
| 328 | try testIsAbsoluteWindows("c", false); |
| 329 | try testIsAbsoluteWindows("c:", false); |
| 330 | try testIsAbsoluteWindows("c:\\", true); |
| 331 | try testIsAbsoluteWindows("c:/", true); |
| 332 | try testIsAbsoluteWindows("c://", true); |
| 333 | try testIsAbsoluteWindows("C:/Users/", true); |
| 334 | try testIsAbsoluteWindows("C:\\Users\\", true); |
| 335 | try testIsAbsoluteWindows("C:cwd/another", false); |
| 336 | try testIsAbsoluteWindows("C:cwd\\another", false); |
| 337 | try testIsAbsoluteWindows("λ:\\", true); |
| 338 | try testIsAbsoluteWindows("λ:", false); |
| 339 | try testIsAbsoluteWindows("\u{10000}:\\", false); |
| 340 | try testIsAbsoluteWindows("directory/directory", false); |
| 341 | try testIsAbsoluteWindows("directory\\directory", false); |
| 342 | try testIsAbsoluteWindows("/usr/local", true); |
| 343 | } |
| 344 | |
| 345 | test isAbsolutePosix { |
| 346 | try testIsAbsolutePosix("", false); |
| 347 | try testIsAbsolutePosix("/home/foo", true); |
| 348 | try testIsAbsolutePosix("/home/foo/..", true); |
| 349 | try testIsAbsolutePosix("bar/", false); |
| 350 | try testIsAbsolutePosix("./baz", false); |
| 351 | } |
| 352 | |
| 353 | fn testIsAbsoluteWindows(path: []const u8, expected_result: bool) !void { |
| 354 | try testing.expectEqual(expected_result, isAbsoluteWindows(path)); |
| 355 | const path_w = try std.unicode.wtf8ToWtf16LeAllocZ(std.testing.allocator, path); |
| 356 | defer std.testing.allocator.free(path_w); |
| 357 | try testing.expectEqual(expected_result, isAbsoluteWindowsW(path_w)); |
| 358 | try testing.expectEqual(expected_result, isAbsoluteWindowsWtf16(path_w)); |
| 359 | } |
| 360 | |
| 361 | fn testIsAbsolutePosix(path: []const u8, expected_result: bool) !void { |
| 362 | try testing.expectEqual(expected_result, isAbsolutePosix(path)); |
| 363 | } |
| 364 | |
| 365 | /// Deprecated; see `WindowsPath2` |
| 366 | pub const WindowsPath = struct { |
| 367 | is_abs: bool, |
| 368 | kind: Kind, |
| 369 | disk_designator: []const u8, |
| 370 | |
| 371 | pub const Kind = enum { |
| 372 | None, |
| 373 | Drive, |
| 374 | NetworkShare, |
| 375 | }; |
| 376 | }; |
| 377 | |
| 378 | /// Deprecated; see `parsePathWindows` |
| 379 | pub fn windowsParsePath(path: []const u8) WindowsPath { |
| 380 | if (path.len >= 2 and path[1] == ':') { |
| 381 | return WindowsPath{ |
| 382 | .is_abs = isAbsoluteWindows(path), |
| 383 | .kind = WindowsPath.Kind.Drive, |
| 384 | .disk_designator = path[0..2], |
| 385 | }; |
| 386 | } |
| 387 | if (path.len >= 1 and (path[0] == '/' or path[0] == '\\') and |
| 388 | (path.len == 1 or (path[1] != '/' and path[1] != '\\'))) |
| 389 | { |
| 390 | return WindowsPath{ |
| 391 | .is_abs = true, |
| 392 | .kind = WindowsPath.Kind.None, |
| 393 | .disk_designator = path[0..0], |
| 394 | }; |
| 395 | } |
| 396 | const relative_path = WindowsPath{ |
| 397 | .kind = WindowsPath.Kind.None, |
| 398 | .disk_designator = &[_]u8{}, |
| 399 | .is_abs = false, |
| 400 | }; |
| 401 | |
| 402 | if (path.len >= 2 and PathType.windows.isSep(u8, path[0]) and PathType.windows.isSep(u8, path[1])) { |
| 403 | const root_end = root_end: { |
| 404 | var server_end = mem.findAnyPos(u8, path, 2, "/\\") orelse break :root_end path.len; |
| 405 | while (server_end < path.len and PathType.windows.isSep(u8, path[server_end])) server_end += 1; |
| 406 | break :root_end mem.findAnyPos(u8, path, server_end, "/\\") orelse path.len; |
| 407 | }; |
| 408 | return WindowsPath{ |
| 409 | .is_abs = true, |
| 410 | .kind = WindowsPath.Kind.NetworkShare, |
| 411 | .disk_designator = path[0..root_end], |
| 412 | }; |
| 413 | } |
| 414 | return relative_path; |
| 415 | } |
| 416 | |
| 417 | test windowsParsePath { |
| 418 | { |
| 419 | const parsed = windowsParsePath("//a/b"); |
| 420 | try testing.expect(parsed.is_abs); |
| 421 | try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare); |
| 422 | try testing.expect(mem.eql(u8, parsed.disk_designator, "//a/b")); |
| 423 | } |
| 424 | { |
| 425 | const parsed = windowsParsePath("\\\\a\\b"); |
| 426 | try testing.expect(parsed.is_abs); |
| 427 | try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare); |
| 428 | try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\b")); |
| 429 | } |
| 430 | { |
| 431 | const parsed = windowsParsePath("\\\\a/b"); |
| 432 | try testing.expect(parsed.is_abs); |
| 433 | try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare); |
| 434 | try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a/b")); |
| 435 | } |
| 436 | { |
| 437 | const parsed = windowsParsePath("\\/a\\"); |
| 438 | try testing.expect(parsed.is_abs); |
| 439 | try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare); |
| 440 | try testing.expect(mem.eql(u8, parsed.disk_designator, "\\/a\\")); |
| 441 | } |
| 442 | { |
| 443 | const parsed = windowsParsePath("\\\\a\\\\b"); |
| 444 | try testing.expect(parsed.is_abs); |
| 445 | try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare); |
| 446 | try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\\\b")); |
| 447 | } |
| 448 | { |
| 449 | const parsed = windowsParsePath("\\\\a\\\\b\\c"); |
| 450 | try testing.expect(parsed.is_abs); |
| 451 | try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare); |
| 452 | try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\\\b")); |
| 453 | } |
| 454 | { |
| 455 | const parsed = windowsParsePath("/usr/local"); |
| 456 | try testing.expect(parsed.is_abs); |
| 457 | try testing.expect(parsed.kind == WindowsPath.Kind.None); |
| 458 | try testing.expect(mem.eql(u8, parsed.disk_designator, "")); |
| 459 | } |
| 460 | { |
| 461 | const parsed = windowsParsePath("c:../"); |
| 462 | try testing.expect(!parsed.is_abs); |
| 463 | try testing.expect(parsed.kind == WindowsPath.Kind.Drive); |
| 464 | try testing.expect(mem.eql(u8, parsed.disk_designator, "c:")); |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | /// On Windows, this calls `parsePathWindows` and on POSIX it calls `parsePathPosix`. |
| 469 | /// |
| 470 | /// Returns a platform-specific struct with two fields: `root` and `kind`. |
| 471 | /// The `root` will be a slice of `path` (`/` for POSIX absolute paths, and things |
| 472 | /// like `C:\`, `\\server\share\`, etc for Windows paths). |
| 473 | /// If the path is of kind `.relative`, then `root` will be zero-length. |
| 474 | pub fn parsePath(path: []const u8) switch (native_os) { |
| 475 | .windows => WindowsPath2(u8), |
| 476 | else => PosixPath, |
| 477 | } { |
| 478 | switch (native_os) { |
| 479 | .windows => return parsePathWindows(u8, path), |
| 480 | else => return parsePathPosix(path), |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | const PosixPath = struct { |
| 485 | kind: enum { relative, absolute }, |
| 486 | root: []const u8, |
| 487 | }; |
| 488 | |
| 489 | pub fn parsePathPosix(path: []const u8) PosixPath { |
| 490 | const abs = isAbsolutePosix(path); |
| 491 | return .{ |
| 492 | .kind = if (abs) .absolute else .relative, |
| 493 | .root = if (abs) path[0..1] else path[0..0], |
| 494 | }; |
| 495 | } |
| 496 | |
| 497 | test parsePathPosix { |
| 498 | { |
| 499 | const parsed = parsePathPosix("a/b"); |
| 500 | try testing.expectEqual(.relative, parsed.kind); |
| 501 | try testing.expectEqualStrings("", parsed.root); |
| 502 | } |
| 503 | { |
| 504 | const parsed = parsePathPosix("/a/b"); |
| 505 | try testing.expectEqual(.absolute, parsed.kind); |
| 506 | try testing.expectEqualStrings("/", parsed.root); |
| 507 | } |
| 508 | { |
| 509 | const parsed = parsePathPosix("///a/b"); |
| 510 | try testing.expectEqual(.absolute, parsed.kind); |
| 511 | try testing.expectEqualStrings("/", parsed.root); |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | pub fn WindowsPath2(comptime T: type) type { |
| 516 | return struct { |
| 517 | kind: Win32PathType, |
| 518 | root: []const T, |
| 519 | }; |
| 520 | } |
| 521 | |
| 522 | pub fn parsePathWindows(comptime T: type, path: []const T) WindowsPath2(T) { |
| 523 | const kind = getWin32PathType(T, path); |
| 524 | const root = root: switch (kind) { |
| 525 | .drive_absolute, .drive_relative => { |
| 526 | const drive_letter_len = getDriveLetter(T, path).len; |
| 527 | break :root path[0 .. drive_letter_len + @as(usize, if (kind == .drive_absolute) 2 else 1)]; |
| 528 | }, |
| 529 | .relative => path[0..0], |
| 530 | .local_device => path[0..4], |
| 531 | .root_local_device => path, |
| 532 | .rooted => path[0..1], |
| 533 | .unc_absolute => { |
| 534 | const unc = parseUNC(T, path); |
| 535 | // There may be any number of path separators between the server and the share, |
| 536 | // so take that into account by using pointer math to get the difference. |
| 537 | var root_len = 2 + (unc.share.ptr - unc.server.ptr) + unc.share.len; |
| 538 | if (unc.sep_after_share) root_len += 1; |
| 539 | break :root path[0..root_len]; |
| 540 | }, |
| 541 | }; |
| 542 | return .{ |
| 543 | .kind = kind, |
| 544 | .root = root, |
| 545 | }; |
| 546 | } |
| 547 | |
| 548 | test parsePathWindows { |
| 549 | { |
| 550 | const path = "//a/b"; |
| 551 | const parsed = parsePathWindows(u8, path); |
| 552 | try testing.expectEqual(.unc_absolute, parsed.kind); |
| 553 | try testing.expectEqualStrings("//a/b", parsed.root); |
| 554 | try testWindowsParsePathHarmony(path); |
| 555 | } |
| 556 | { |
| 557 | const path = "\\\\a\\b"; |
| 558 | const parsed = parsePathWindows(u8, path); |
| 559 | try testing.expectEqual(.unc_absolute, parsed.kind); |
| 560 | try testing.expectEqualStrings("\\\\a\\b", parsed.root); |
| 561 | try testWindowsParsePathHarmony(path); |
| 562 | } |
| 563 | { |
| 564 | const path = "\\/a/b/c"; |
| 565 | const parsed = parsePathWindows(u8, path); |
| 566 | try testing.expectEqual(.unc_absolute, parsed.kind); |
| 567 | try testing.expectEqualStrings("\\/a/b/", parsed.root); |
| 568 | try testWindowsParsePathHarmony(path); |
| 569 | } |
| 570 | { |
| 571 | const path = "\\\\a\\"; |
| 572 | const parsed = parsePathWindows(u8, path); |
| 573 | try testing.expectEqual(.unc_absolute, parsed.kind); |
| 574 | try testing.expectEqualStrings("\\\\a\\", parsed.root); |
| 575 | try testWindowsParsePathHarmony(path); |
| 576 | } |
| 577 | { |
| 578 | const path = "\\\\a\\b\\"; |
| 579 | const parsed = parsePathWindows(u8, path); |
| 580 | try testing.expectEqual(.unc_absolute, parsed.kind); |
| 581 | try testing.expectEqualStrings("\\\\a\\b\\", parsed.root); |
| 582 | try testWindowsParsePathHarmony(path); |
| 583 | } |
| 584 | { |
| 585 | const path = "\\\\a\\/b\\/"; |
| 586 | const parsed = parsePathWindows(u8, path); |
| 587 | try testing.expectEqual(.unc_absolute, parsed.kind); |
| 588 | try testing.expectEqualStrings("\\\\a\\/b\\", parsed.root); |
| 589 | try testWindowsParsePathHarmony(path); |
| 590 | } |
| 591 | { |
| 592 | const path = "\\\\кириллица\\ελληνικά\\português"; |
| 593 | const parsed = parsePathWindows(u8, path); |
| 594 | try testing.expectEqual(.unc_absolute, parsed.kind); |
| 595 | try testing.expectEqualStrings("\\\\кириллица\\ελληνικά\\", parsed.root); |
| 596 | try testWindowsParsePathHarmony(path); |
| 597 | } |
| 598 | { |
| 599 | const path = "/usr/local"; |
| 600 | const parsed = parsePathWindows(u8, path); |
| 601 | try testing.expectEqual(.rooted, parsed.kind); |
| 602 | try testing.expectEqualStrings("/", parsed.root); |
| 603 | try testWindowsParsePathHarmony(path); |
| 604 | } |
| 605 | { |
| 606 | const path = "\\\\."; |
| 607 | const parsed = parsePathWindows(u8, path); |
| 608 | try testing.expectEqual(.root_local_device, parsed.kind); |
| 609 | try testing.expectEqualStrings("\\\\.", parsed.root); |
| 610 | try testWindowsParsePathHarmony(path); |
| 611 | } |
| 612 | { |
| 613 | const path = "\\\\.\\a"; |
| 614 | const parsed = parsePathWindows(u8, path); |
| 615 | try testing.expectEqual(.local_device, parsed.kind); |
| 616 | try testing.expectEqualStrings("\\\\.\\", parsed.root); |
| 617 | try testWindowsParsePathHarmony(path); |
| 618 | } |
| 619 | { |
| 620 | const path = "c:../"; |
| 621 | const parsed = parsePathWindows(u8, path); |
| 622 | try testing.expectEqual(.drive_relative, parsed.kind); |
| 623 | try testing.expectEqualStrings("c:", parsed.root); |
| 624 | try testWindowsParsePathHarmony(path); |
| 625 | } |
| 626 | { |
| 627 | const path = "C:\\../"; |
| 628 | const parsed = parsePathWindows(u8, path); |
| 629 | try testing.expectEqual(.drive_absolute, parsed.kind); |
| 630 | try testing.expectEqualStrings("C:\\", parsed.root); |
| 631 | try testWindowsParsePathHarmony(path); |
| 632 | } |
| 633 | { |
| 634 | // Non-ASCII code point that is encoded as one WTF-16 code unit is considered a valid drive letter |
| 635 | const path = "€:\\"; |
| 636 | const parsed = parsePathWindows(u8, path); |
| 637 | try testing.expectEqual(.drive_absolute, parsed.kind); |
| 638 | try testing.expectEqualStrings("€:\\", parsed.root); |
| 639 | try testWindowsParsePathHarmony(path); |
| 640 | } |
| 641 | { |
| 642 | const path = "€:"; |
| 643 | const parsed = parsePathWindows(u8, path); |
| 644 | try testing.expectEqual(.drive_relative, parsed.kind); |
| 645 | try testing.expectEqualStrings("€:", parsed.root); |
| 646 | try testWindowsParsePathHarmony(path); |
| 647 | } |
| 648 | { |
| 649 | // But code points that are encoded as two WTF-16 code units are not |
| 650 | const path = "\u{10000}:\\"; |
| 651 | const parsed = parsePathWindows(u8, path); |
| 652 | try testing.expectEqual(.relative, parsed.kind); |
| 653 | try testing.expectEqualStrings("", parsed.root); |
| 654 | try testWindowsParsePathHarmony(path); |
| 655 | } |
| 656 | { |
| 657 | const path = "\u{10000}:"; |
| 658 | const parsed = parsePathWindows(u8, path); |
| 659 | try testing.expectEqual(.relative, parsed.kind); |
| 660 | try testing.expectEqualStrings("", parsed.root); |
| 661 | try testWindowsParsePathHarmony(path); |
| 662 | } |
| 663 | { |
| 664 | // Paths are assumed to be in the Win32 namespace, so while this is |
| 665 | // likely a NT namespace path, it's treated as a rooted path. |
| 666 | const path = "\\??\\foo"; |
| 667 | const parsed = parsePathWindows(u8, path); |
| 668 | try testing.expectEqual(.rooted, parsed.kind); |
| 669 | try testing.expectEqualStrings("\\", parsed.root); |
| 670 | try testWindowsParsePathHarmony(path); |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | fn testWindowsParsePathHarmony(wtf8: []const u8) !void { |
| 675 | var wtf16_buf: [256]u16 = undefined; |
| 676 | const wtf16_len = try std.unicode.wtf8ToWtf16Le(&wtf16_buf, wtf8); |
| 677 | const wtf16 = wtf16_buf[0..wtf16_len]; |
| 678 | |
| 679 | const wtf8_parsed = parsePathWindows(u8, wtf8); |
| 680 | const wtf16_parsed = parsePathWindows(u16, wtf16); |
| 681 | |
| 682 | var wtf8_buf: [256]u8 = undefined; |
| 683 | const wtf16_root_as_wtf8_len = std.unicode.wtf16LeToWtf8(&wtf8_buf, wtf16_parsed.root); |
| 684 | const wtf16_root_as_wtf8 = wtf8_buf[0..wtf16_root_as_wtf8_len]; |
| 685 | |
| 686 | try std.testing.expectEqual(wtf8_parsed.kind, wtf16_parsed.kind); |
| 687 | try std.testing.expectEqualStrings(wtf8_parsed.root, wtf16_root_as_wtf8); |
| 688 | } |
| 689 | |
| 690 | /// Deprecated; use `parsePath` |
| 691 | pub fn diskDesignator(path: []const u8) []const u8 { |
| 692 | if (native_os == .windows) { |
| 693 | return diskDesignatorWindows(path); |
| 694 | } else { |
| 695 | return ""; |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | /// Deprecated; use `parsePathWindows` |
| 700 | pub fn diskDesignatorWindows(path: []const u8) []const u8 { |
| 701 | return windowsParsePath(path).disk_designator; |
| 702 | } |
| 703 | |
| 704 | fn WindowsUNC(comptime T: type) type { |
| 705 | return struct { |
| 706 | server: []const T, |
| 707 | sep_after_server: bool, |
| 708 | share: []const T, |
| 709 | sep_after_share: bool, |
| 710 | }; |
| 711 | } |
| 712 | |
| 713 | /// Asserts that `path` starts with two path separators |
| 714 | fn parseUNC(comptime T: type, path: []const T) WindowsUNC(T) { |
| 715 | assert(path.len >= 2 and PathType.windows.isSep(T, path[0]) and PathType.windows.isSep(T, path[1])); |
| 716 | const any_sep = switch (T) { |
| 717 | u8 => "/\\", |
| 718 | u16 => std.unicode.wtf8ToWtf16LeStringLiteral("/\\"), |
| 719 | else => @compileError("only u8 (WTF-8) and u16 (WTF-16LE) are supported"), |
| 720 | }; |
| 721 | // For the server, the first path separator after the initial two is always |
| 722 | // the terminator of the server name, even if that means the server name is |
| 723 | // zero-length. |
| 724 | const server_end = mem.findAnyPos(T, path, 2, any_sep) orelse return .{ |
| 725 | .server = path[2..path.len], |
| 726 | .sep_after_server = false, |
| 727 | .share = path[path.len..path.len], |
| 728 | .sep_after_share = false, |
| 729 | }; |
| 730 | // For the share, there can be any number of path separators between the server |
| 731 | // and the share, so we want to skip over all of them instead of just looking for |
| 732 | // the first one. |
| 733 | var it = mem.tokenizeAny(T, path[server_end + 1 ..], any_sep); |
| 734 | const share = it.next() orelse return .{ |
| 735 | .server = path[2..server_end], |
| 736 | .sep_after_server = true, |
| 737 | .share = path[server_end + 1 .. server_end + 1], |
| 738 | .sep_after_share = false, |
| 739 | }; |
| 740 | return .{ |
| 741 | .server = path[2..server_end], |
| 742 | .sep_after_server = true, |
| 743 | .share = share, |
| 744 | .sep_after_share = it.index != it.buffer.len, |
| 745 | }; |
| 746 | } |
| 747 | |
| 748 | test parseUNC { |
| 749 | { |
| 750 | const unc = parseUNC(u8, "//"); |
| 751 | try std.testing.expectEqualStrings("", unc.server); |
| 752 | try std.testing.expect(!unc.sep_after_server); |
| 753 | try std.testing.expectEqualStrings("", unc.share); |
| 754 | try std.testing.expect(!unc.sep_after_share); |
| 755 | } |
| 756 | { |
| 757 | const unc = parseUNC(u8, "\\\\s"); |
| 758 | try std.testing.expectEqualStrings("s", unc.server); |
| 759 | try std.testing.expect(!unc.sep_after_server); |
| 760 | try std.testing.expectEqualStrings("", unc.share); |
| 761 | try std.testing.expect(!unc.sep_after_share); |
| 762 | } |
| 763 | { |
| 764 | const unc = parseUNC(u8, "\\\\s/"); |
| 765 | try std.testing.expectEqualStrings("s", unc.server); |
| 766 | try std.testing.expect(unc.sep_after_server); |
| 767 | try std.testing.expectEqualStrings("", unc.share); |
| 768 | try std.testing.expect(!unc.sep_after_share); |
| 769 | } |
| 770 | { |
| 771 | const unc = parseUNC(u8, "\\/server\\share"); |
| 772 | try std.testing.expectEqualStrings("server", unc.server); |
| 773 | try std.testing.expect(unc.sep_after_server); |
| 774 | try std.testing.expectEqualStrings("share", unc.share); |
| 775 | try std.testing.expect(!unc.sep_after_share); |
| 776 | } |
| 777 | { |
| 778 | const unc = parseUNC(u8, "/\\server\\share/"); |
| 779 | try std.testing.expectEqualStrings("server", unc.server); |
| 780 | try std.testing.expect(unc.sep_after_server); |
| 781 | try std.testing.expectEqualStrings("share", unc.share); |
| 782 | try std.testing.expect(unc.sep_after_share); |
| 783 | } |
| 784 | { |
| 785 | const unc = parseUNC(u8, "\\\\server/\\share\\/"); |
| 786 | try std.testing.expectEqualStrings("server", unc.server); |
| 787 | try std.testing.expect(unc.sep_after_server); |
| 788 | try std.testing.expectEqualStrings("share", unc.share); |
| 789 | try std.testing.expect(unc.sep_after_share); |
| 790 | } |
| 791 | { |
| 792 | const unc = parseUNC(u8, "\\\\server\\/\\\\"); |
| 793 | try std.testing.expectEqualStrings("server", unc.server); |
| 794 | try std.testing.expect(unc.sep_after_server); |
| 795 | try std.testing.expectEqualStrings("", unc.share); |
| 796 | try std.testing.expect(!unc.sep_after_share); |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | const DiskDesignatorKind = enum { drive, unc }; |
| 801 | |
| 802 | /// `p1` and `p2` are both assumed to be the `kind` provided. |
| 803 | fn compareDiskDesignators(comptime T: type, kind: DiskDesignatorKind, p1: []const T, p2: []const T) bool { |
| 804 | const eql = switch (T) { |
| 805 | u8 => eqlIgnoreCaseWtf8, |
| 806 | u16 => eqlIgnoreCaseWtf16, |
| 807 | else => @compileError("only u8 (WTF-8) and u16 (WTF-16LE) is supported"), |
| 808 | }; |
| 809 | switch (kind) { |
| 810 | .drive => { |
| 811 | const drive_letter1 = getDriveLetter(T, p1); |
| 812 | const drive_letter2 = getDriveLetter(T, p2); |
| 813 | |
| 814 | return eql(drive_letter1, drive_letter2); |
| 815 | }, |
| 816 | .unc => { |
| 817 | const unc1 = parseUNC(T, p1); |
| 818 | const unc2 = parseUNC(T, p2); |
| 819 | |
| 820 | return eql(unc1.server, unc2.server) and |
| 821 | eql(unc1.share, unc2.share); |
| 822 | }, |
| 823 | } |
| 824 | } |
| 825 | |
| 826 | /// `path` is assumed to be drive-relative or drive-absolute. |
| 827 | fn getDriveLetter(comptime T: type, path: []const T) []const T { |
| 828 | const len: usize = switch (T) { |
| 829 | // getWin32PathType will only return .drive_absolute/.drive_relative when there is |
| 830 | // (1) a valid code point, and (2) a code point < U+10000, so we only need to |
| 831 | // get the length determined by the first byte. |
| 832 | u8 => std.unicode.utf8ByteSequenceLength(path[0]) catch unreachable, |
| 833 | u16 => 1, |
| 834 | else => @compileError("unsupported type: " ++ @typeName(T)), |
| 835 | }; |
| 836 | return path[0..len]; |
| 837 | } |
| 838 | |
| 839 | test compareDiskDesignators { |
| 840 | try testCompareDiskDesignators(true, .drive, "c:", "C:\\"); |
| 841 | try testCompareDiskDesignators(true, .drive, "C:\\", "C:"); |
| 842 | try testCompareDiskDesignators(false, .drive, "C:\\", "D:\\"); |
| 843 | // Case-insensitivity technically applies to non-ASCII drive letters |
| 844 | try testCompareDiskDesignators(true, .drive, "λ:\\", "Λ:"); |
| 845 | |
| 846 | try testCompareDiskDesignators(true, .unc, "\\\\server", "//server//"); |
| 847 | try testCompareDiskDesignators(true, .unc, "\\\\server\\\\share", "/\\server/share"); |
| 848 | try testCompareDiskDesignators(true, .unc, "\\\\server\\\\share", "/\\server/share\\\\foo"); |
| 849 | try testCompareDiskDesignators(false, .unc, "\\\\server\\sharefoo", "/\\server/share\\foo"); |
| 850 | try testCompareDiskDesignators(false, .unc, "\\\\serverfoo\\\\share", "//server/share"); |
| 851 | try testCompareDiskDesignators(false, .unc, "\\\\server\\", "//server/share"); |
| 852 | } |
| 853 | |
| 854 | fn testCompareDiskDesignators(expected_result: bool, kind: DiskDesignatorKind, p1: []const u8, p2: []const u8) !void { |
| 855 | var wtf16_buf1: [256]u16 = undefined; |
| 856 | const w1_len = try std.unicode.wtf8ToWtf16Le(&wtf16_buf1, p1); |
| 857 | var wtf16_buf2: [256]u16 = undefined; |
| 858 | const w2_len = try std.unicode.wtf8ToWtf16Le(&wtf16_buf2, p2); |
| 859 | try std.testing.expectEqual(expected_result, compareDiskDesignators(u8, kind, p1, p2)); |
| 860 | try std.testing.expectEqual(expected_result, compareDiskDesignators(u16, kind, wtf16_buf1[0..w1_len], wtf16_buf2[0..w2_len])); |
| 861 | } |
| 862 | |
| 863 | /// On Windows, this calls `resolveWindows` and on POSIX it calls `resolvePosix`. |
| 864 | pub fn resolve(allocator: Allocator, paths: []const []const u8) Allocator.Error![]u8 { |
| 865 | if (native_os == .windows) { |
| 866 | return resolveWindows(allocator, paths); |
| 867 | } else { |
| 868 | return resolvePosix(allocator, paths); |
| 869 | } |
| 870 | } |
| 871 | |
| 872 | /// This function is like a series of `cd` statements executed one after another. |
| 873 | /// It resolves "." and ".." to the best of its ability, but will not convert relative paths to |
| 874 | /// an absolute path, use Io.Dir.realpath instead. |
| 875 | /// ".." components may persist in the resolved path if the resolved path is relative or drive-relative. |
| 876 | /// Path separators are canonicalized to '\\' and drives are canonicalized to capital letters. |
| 877 | /// |
| 878 | /// The result will not have a trailing path separator, except for the following scenarios: |
| 879 | /// - The resolved path is drive-absolute with no components (e.g. `C:\`). |
| 880 | /// - The resolved path is a UNC path with only a server name, and the input path contained a trailing separator |
| 881 | /// (e.g. `\\server\`). |
| 882 | /// - The resolved path is a UNC path with no components after the share name, and the input path contained a |
| 883 | /// trailing separator (e.g. `\\server\share\`). |
| 884 | /// |
| 885 | /// Each drive has its own current working directory, which is only resolved via the paths provided. |
| 886 | /// In the scenario that the resolved path contains a drive-relative path that can't be resolved using the paths alone, |
| 887 | /// the result will be a drive-relative path. |
| 888 | /// Similarly, in the scenario that the resolved path contains a rooted path that can't be resolved using the paths alone, |
| 889 | /// the result will be a rooted path. |
| 890 | /// |
| 891 | /// Note: all usage of this function should be audited due to the existence of symlinks. |
| 892 | /// Without performing actual syscalls, resolving `..` could be incorrect. |
| 893 | /// This API may break in the future: https://github.com/ziglang/zig/issues/13613 |
| 894 | pub fn resolveWindows(allocator: Allocator, paths: []const []const u8) Allocator.Error![]u8 { |
| 895 | // Avoid heap allocation when paths.len is <= @bitSizeOf(usize) * 2 |
| 896 | // (we use `* 3` because stackFallback uses 1 usize as a length) |
| 897 | var buf: [3]usize = undefined; |
| 898 | var bit_set_allocator_state: std.heap.BufferFirstAllocator = .init(@ptrCast(&buf), allocator); |
| 899 | const bit_set_allocator = bit_set_allocator_state.allocator(); |
| 900 | var relevant_paths: std.bit_set.Dynamic = try .initEmpty(bit_set_allocator, paths.len); |
| 901 | defer relevant_paths.deinit(bit_set_allocator); |
| 902 | |
| 903 | // Iterate the paths backwards, marking the relevant paths along the way. |
| 904 | // This also allows us to break from the loop whenever any earlier paths are known to be irrelevant. |
| 905 | var first_path_i: usize = paths.len; |
| 906 | const effective_root_path: WindowsPath2(u8) = root: { |
| 907 | var last_effective_root_path: WindowsPath2(u8) = .{ .kind = .relative, .root = "" }; |
| 908 | var last_rooted_path_i: ?usize = null; |
| 909 | var last_drive_relative_path_i: usize = undefined; |
| 910 | while (first_path_i > 0) { |
| 911 | first_path_i -= 1; |
| 912 | const parsed = parsePathWindows(u8, paths[first_path_i]); |
| 913 | switch (parsed.kind) { |
| 914 | .unc_absolute, .root_local_device, .local_device => { |
| 915 | switch (last_effective_root_path.kind) { |
| 916 | .rooted => {}, |
| 917 | .drive_relative => continue, |
| 918 | else => { |
| 919 | relevant_paths.set(first_path_i); |
| 920 | }, |
| 921 | } |
| 922 | break :root parsed; |
| 923 | }, |
| 924 | .drive_relative, .drive_absolute => { |
| 925 | switch (last_effective_root_path.kind) { |
| 926 | .drive_relative => if (!compareDiskDesignators(u8, .drive, parsed.root, last_effective_root_path.root)) { |
| 927 | continue; |
| 928 | } else if (last_rooted_path_i != null) { |
| 929 | break :root .{ .kind = .drive_absolute, .root = parsed.root }; |
| 930 | }, |
| 931 | .relative => last_effective_root_path = parsed, |
| 932 | .rooted => { |
| 933 | // This is the end of the line, since the rooted path will always be relative |
| 934 | // to this drive letter, and even if the current path is drive-relative, the |
| 935 | // rooted-ness makes that irrelevant. |
| 936 | // |
| 937 | // Therefore, force the kind of the effective root to be drive-absolute in order to |
| 938 | // properly resolve a rooted path against a drive-relative one, as the result should |
| 939 | // always be drive-absolute. |
| 940 | break :root .{ .kind = .drive_absolute, .root = parsed.root }; |
| 941 | }, |
| 942 | .drive_absolute, .unc_absolute, .root_local_device, .local_device => unreachable, |
| 943 | } |
| 944 | relevant_paths.set(first_path_i); |
| 945 | last_drive_relative_path_i = first_path_i; |
| 946 | if (parsed.kind == .drive_absolute) { |
| 947 | break :root parsed; |
| 948 | } |
| 949 | }, |
| 950 | .relative => { |
| 951 | switch (last_effective_root_path.kind) { |
| 952 | .rooted => continue, |
| 953 | .relative => last_effective_root_path = parsed, |
| 954 | else => {}, |
| 955 | } |
| 956 | relevant_paths.set(first_path_i); |
| 957 | }, |
| 958 | .rooted => { |
| 959 | switch (last_effective_root_path.kind) { |
| 960 | .drive_relative => {}, |
| 961 | .relative => last_effective_root_path = parsed, |
| 962 | .rooted => continue, |
| 963 | .drive_absolute, .unc_absolute, .root_local_device, .local_device => unreachable, |
| 964 | } |
| 965 | if (last_rooted_path_i == null) { |
| 966 | last_rooted_path_i = first_path_i; |
| 967 | relevant_paths.set(first_path_i); |
| 968 | } |
| 969 | }, |
| 970 | } |
| 971 | } |
| 972 | // After iterating, if the pending effective root is drive-relative then that means |
| 973 | // nothing has led to forcing a drive-absolute root (a path that allows resolving the |
| 974 | // drive-specific CWD would cause an early break), so we now need to ignore all paths |
| 975 | // before the most recent drive-relative one. For example, if we're resolving |
| 976 | // { "\\rooted", "relative", "C:drive-relative" } |
| 977 | // then the `\rooted` and `relative` needs to be ignored since we can't |
| 978 | // know what the rooted path is rooted against as that'd require knowing the CWD. |
| 979 | if (last_effective_root_path.kind == .drive_relative) { |
| 980 | for (0..last_drive_relative_path_i) |i| { |
| 981 | relevant_paths.unset(i); |
| 982 | } |
| 983 | } |
| 984 | break :root last_effective_root_path; |
| 985 | }; |
| 986 | |
| 987 | var result: std.ArrayList(u8) = .empty; |
| 988 | defer result.deinit(allocator); |
| 989 | |
| 990 | var want_path_sep_between_root_and_component = false; |
| 991 | switch (effective_root_path.kind) { |
| 992 | .root_local_device, .local_device => { |
| 993 | try result.ensureUnusedCapacity(allocator, 3); |
| 994 | result.appendSliceAssumeCapacity("\\\\"); |
| 995 | result.appendAssumeCapacity(effective_root_path.root[2]); // . or ? |
| 996 | want_path_sep_between_root_and_component = true; |
| 997 | }, |
| 998 | .drive_absolute, .drive_relative => { |
| 999 | try result.ensureUnusedCapacity(allocator, effective_root_path.root.len); |
| 1000 | result.appendAssumeCapacity(std.ascii.toUpper(effective_root_path.root[0])); |
| 1001 | result.appendAssumeCapacity(':'); |
| 1002 | if (effective_root_path.kind == .drive_absolute) { |
| 1003 | result.appendAssumeCapacity('\\'); |
| 1004 | } |
| 1005 | }, |
| 1006 | .unc_absolute => { |
| 1007 | const unc = parseUNC(u8, effective_root_path.root); |
| 1008 | |
| 1009 | const root_len = len: { |
| 1010 | var len: usize = 2 + unc.server.len + unc.share.len; |
| 1011 | if (unc.sep_after_server) len += 1; |
| 1012 | if (unc.sep_after_share) len += 1; |
| 1013 | break :len len; |
| 1014 | }; |
| 1015 | try result.ensureUnusedCapacity(allocator, root_len); |
| 1016 | result.appendSliceAssumeCapacity("\\\\"); |
| 1017 | if (unc.server.len > 0 or unc.sep_after_server) { |
| 1018 | result.appendSliceAssumeCapacity(unc.server); |
| 1019 | if (unc.sep_after_server) |
| 1020 | result.appendAssumeCapacity('\\') |
| 1021 | else |
| 1022 | want_path_sep_between_root_and_component = true; |
| 1023 | } |
| 1024 | if (unc.share.len > 0) { |
| 1025 | result.appendSliceAssumeCapacity(unc.share); |
| 1026 | if (unc.sep_after_share) |
| 1027 | result.appendAssumeCapacity('\\') |
| 1028 | else |
| 1029 | want_path_sep_between_root_and_component = true; |
| 1030 | } |
| 1031 | }, |
| 1032 | .rooted => { |
| 1033 | try result.append(allocator, '\\'); |
| 1034 | }, |
| 1035 | .relative => {}, |
| 1036 | } |
| 1037 | |
| 1038 | const root_len = result.items.len; |
| 1039 | var negative_count: usize = 0; |
| 1040 | for (paths[first_path_i..], first_path_i..) |path, i| { |
| 1041 | if (!relevant_paths.isSet(i)) continue; |
| 1042 | |
| 1043 | const parsed = parsePathWindows(u8, path); |
| 1044 | const skip_len = parsed.root.len; |
| 1045 | var it = mem.tokenizeAny(u8, path[skip_len..], "/\\"); |
| 1046 | while (it.next()) |component| { |
| 1047 | if (mem.eql(u8, component, ".")) { |
| 1048 | continue; |
| 1049 | } else if (mem.eql(u8, component, "..")) { |
| 1050 | if (result.items.len == 0 or (result.items.len == root_len and effective_root_path.kind == .drive_relative)) { |
| 1051 | negative_count += 1; |
| 1052 | continue; |
| 1053 | } |
| 1054 | while (true) { |
| 1055 | if (result.items.len == root_len) { |
| 1056 | break; |
| 1057 | } |
| 1058 | const end_with_sep = PathType.windows.isSep(u8, result.items[result.items.len - 1]); |
| 1059 | result.items.len -= 1; |
| 1060 | if (end_with_sep) break; |
| 1061 | } |
| 1062 | } else if (result.items.len == root_len and !want_path_sep_between_root_and_component) { |
| 1063 | try result.appendSlice(allocator, component); |
| 1064 | } else { |
| 1065 | try result.ensureUnusedCapacity(allocator, 1 + component.len); |
| 1066 | result.appendAssumeCapacity('\\'); |
| 1067 | result.appendSliceAssumeCapacity(component); |
| 1068 | } |
| 1069 | } |
| 1070 | } |
| 1071 | |
| 1072 | if (root_len != 0 and result.items.len == root_len and negative_count == 0) { |
| 1073 | return result.toOwnedSlice(allocator); |
| 1074 | } |
| 1075 | |
| 1076 | if (result.items.len == root_len) { |
| 1077 | if (negative_count == 0) { |
| 1078 | return allocator.dupe(u8, "."); |
| 1079 | } |
| 1080 | |
| 1081 | try result.ensureTotalCapacityPrecise(allocator, 3 * negative_count - 1); |
| 1082 | for (0..negative_count - 1) |_| { |
| 1083 | result.appendSliceAssumeCapacity("..\\"); |
| 1084 | } |
| 1085 | result.appendSliceAssumeCapacity(".."); |
| 1086 | } else { |
| 1087 | const dest = try result.addManyAt(allocator, root_len, 3 * negative_count); |
| 1088 | for (0..negative_count) |i| { |
| 1089 | dest[i * 3 ..][0..3].* = "..\\".*; |
| 1090 | } |
| 1091 | } |
| 1092 | |
| 1093 | return result.toOwnedSlice(allocator); |
| 1094 | } |
| 1095 | |
| 1096 | /// Simulates a series of relative directory changes on a virtual filesystem |
| 1097 | /// that has no symlinks. |
| 1098 | /// |
| 1099 | /// "." and ".." are resolved but will not make relative paths absolute. ".." |
| 1100 | /// components remain in the resolved path when the resolved path is relative |
| 1101 | /// and there are not previous components to cancel out. |
| 1102 | /// |
| 1103 | /// The result does not have a trailing path separator. |
| 1104 | /// |
| 1105 | /// This function does not perform any syscalls. Executing this series of path |
| 1106 | /// lookups on an actual filesystem may produce different results due to |
| 1107 | /// symlinks. |
| 1108 | pub fn resolvePosix(gpa: Allocator, paths: []const []const u8) Allocator.Error![]u8 { |
| 1109 | assert(paths.len > 0); |
| 1110 | |
| 1111 | var result: std.ArrayList(u8) = .empty; |
| 1112 | defer result.deinit(gpa); |
| 1113 | |
| 1114 | var negative_count: usize = 0; |
| 1115 | var is_abs = false; |
| 1116 | |
| 1117 | for (paths) |p| { |
| 1118 | if (isAbsolutePosix(p)) { |
| 1119 | is_abs = true; |
| 1120 | negative_count = 0; |
| 1121 | result.clearRetainingCapacity(); |
| 1122 | } |
| 1123 | var it = mem.tokenizeScalar(u8, p, '/'); |
| 1124 | while (it.next()) |component| { |
| 1125 | if (mem.eql(u8, component, ".")) { |
| 1126 | continue; |
| 1127 | } else if (mem.eql(u8, component, "..")) { |
| 1128 | if (result.items.len == 0) { |
| 1129 | negative_count += @intFromBool(!is_abs); |
| 1130 | continue; |
| 1131 | } |
| 1132 | while (true) { |
| 1133 | const ends_with_slash = result.items[result.items.len - 1] == '/'; |
| 1134 | result.items.len -= 1; |
| 1135 | if (ends_with_slash or result.items.len == 0) break; |
| 1136 | } |
| 1137 | } else if (result.items.len > 0 or is_abs) { |
| 1138 | try result.ensureUnusedCapacity(gpa, 1 + component.len); |
| 1139 | result.appendAssumeCapacity('/'); |
| 1140 | result.appendSliceAssumeCapacity(component); |
| 1141 | } else { |
| 1142 | try result.appendSlice(gpa, component); |
| 1143 | } |
| 1144 | } |
| 1145 | } |
| 1146 | |
| 1147 | if (result.items.len == 0) { |
| 1148 | if (is_abs) { |
| 1149 | return gpa.dupe(u8, "/"); |
| 1150 | } |
| 1151 | if (negative_count == 0) { |
| 1152 | return gpa.dupe(u8, "."); |
| 1153 | } else { |
| 1154 | const real_result = try gpa.alloc(u8, 3 * negative_count - 1); |
| 1155 | var count = negative_count - 1; |
| 1156 | var i: usize = 0; |
| 1157 | while (count > 0) : (count -= 1) { |
| 1158 | real_result[i..][0..3].* = "../".*; |
| 1159 | i += 3; |
| 1160 | } |
| 1161 | real_result[i..][0..2].* = "..".*; |
| 1162 | return real_result; |
| 1163 | } |
| 1164 | } |
| 1165 | |
| 1166 | if (negative_count == 0) { |
| 1167 | return result.toOwnedSlice(gpa); |
| 1168 | } else { |
| 1169 | const real_result = try gpa.alloc(u8, 3 * negative_count + result.items.len); |
| 1170 | var count = negative_count; |
| 1171 | var i: usize = 0; |
| 1172 | while (count > 0) : (count -= 1) { |
| 1173 | real_result[i..][0..3].* = "../".*; |
| 1174 | i += 3; |
| 1175 | } |
| 1176 | @memcpy(real_result[i..][0..result.items.len], result.items); |
| 1177 | return real_result; |
| 1178 | } |
| 1179 | } |
| 1180 | |
| 1181 | test resolve { |
| 1182 | try testResolveWindows(&[_][]const u8{ "a", "..\\..\\.." }, "..\\.."); |
| 1183 | try testResolveWindows(&[_][]const u8{ "..", "", "..\\..\\foo" }, "..\\..\\..\\foo"); |
| 1184 | try testResolveWindows(&[_][]const u8{ "a\\b\\c\\", "..\\..\\.." }, "."); |
| 1185 | try testResolveWindows(&[_][]const u8{"."}, "."); |
| 1186 | try testResolveWindows(&[_][]const u8{""}, "."); |
| 1187 | |
| 1188 | try testResolvePosix(&[_][]const u8{ "a", "../../.." }, "../.."); |
| 1189 | try testResolvePosix(&[_][]const u8{ "..", "", "../../foo" }, "../../../foo"); |
| 1190 | try testResolvePosix(&[_][]const u8{ "a/b/c/", "../../.." }, "."); |
| 1191 | try testResolvePosix(&[_][]const u8{"."}, "."); |
| 1192 | try testResolvePosix(&[_][]const u8{""}, "."); |
| 1193 | } |
| 1194 | |
| 1195 | test resolveWindows { |
| 1196 | try testResolveWindows( |
| 1197 | &[_][]const u8{ "Z:\\", "/usr/local", "lib\\zig\\std\\array_list.zig" }, |
| 1198 | "Z:\\usr\\local\\lib\\zig\\std\\array_list.zig", |
| 1199 | ); |
| 1200 | try testResolveWindows( |
| 1201 | &[_][]const u8{ "z:\\", "usr/local", "lib\\zig" }, |
| 1202 | "Z:\\usr\\local\\lib\\zig", |
| 1203 | ); |
| 1204 | |
| 1205 | try testResolveWindows(&[_][]const u8{ "c:\\a\\b\\c", "/hi", "ok" }, "C:\\hi\\ok"); |
| 1206 | try testResolveWindows(&[_][]const u8{ "c:\\a\\b\\c\\", ".\\..\\foo" }, "C:\\a\\b\\foo"); |
| 1207 | try testResolveWindows(&[_][]const u8{ "c:/blah\\blah", "d:/games", "c:../a" }, "C:\\blah\\a"); |
| 1208 | try testResolveWindows(&[_][]const u8{ "c:/blah\\blah", "d:/games", "C:../a" }, "C:\\blah\\a"); |
| 1209 | try testResolveWindows(&[_][]const u8{ "c:/ignore", "d:\\a/b\\c/d", "\\e.exe" }, "D:\\e.exe"); |
| 1210 | try testResolveWindows(&[_][]const u8{ "c:/ignore", "c:/some/file" }, "C:\\some\\file"); |
| 1211 | // The first path "sets" the CWD, so the drive-relative path is then relative to that. |
| 1212 | try testResolveWindows(&[_][]const u8{ "d:/foo", "d:some/dir//", "D:another" }, "D:\\foo\\some\\dir\\another"); |
| 1213 | try testResolveWindows(&[_][]const u8{ "//server/share", "..", "relative\\" }, "\\\\server\\share\\relative"); |
| 1214 | try testResolveWindows(&[_][]const u8{ "\\\\server/share", "..", "relative\\" }, "\\\\server\\share\\relative"); |
| 1215 | try testResolveWindows(&[_][]const u8{ "\\\\server/share/ignore", "//server/share/bar" }, "\\\\server\\share\\bar"); |
| 1216 | try testResolveWindows(&[_][]const u8{ "\\/server\\share/", "..", "relative" }, "\\\\server\\share\\relative"); |
| 1217 | try testResolveWindows(&[_][]const u8{ "\\\\server\\share", "C:drive-relative" }, "C:drive-relative"); |
| 1218 | try testResolveWindows(&[_][]const u8{ "c:/", "//" }, "\\\\"); |
| 1219 | try testResolveWindows(&[_][]const u8{ "c:/", "//server" }, "\\\\server"); |
| 1220 | try testResolveWindows(&[_][]const u8{ "c:/", "//server/share" }, "\\\\server\\share"); |
| 1221 | try testResolveWindows(&[_][]const u8{ "c:/", "//server//share////" }, "\\\\server\\share\\"); |
| 1222 | try testResolveWindows(&[_][]const u8{ "c:/", "///some//dir" }, "\\\\\\some\\dir"); |
| 1223 | try testResolveWindows(&[_][]const u8{ "c:foo", "bar" }, "C:foo\\bar"); |
| 1224 | try testResolveWindows(&[_][]const u8{ "C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js" }, "C:\\foo\\tmp.3\\cycles\\root.js"); |
| 1225 | // Drive-relative stays drive-relative if there's nothing to provide the drive-specific CWD |
| 1226 | try testResolveWindows(&[_][]const u8{ "relative", "d:foo" }, "D:foo"); |
| 1227 | try testResolveWindows(&[_][]const u8{ "../..\\..", "d:foo" }, "D:foo"); |
| 1228 | try testResolveWindows(&[_][]const u8{ "../..\\..", "\\rooted", "d:foo" }, "D:foo"); |
| 1229 | try testResolveWindows(&[_][]const u8{ "C:\\foo", "../..\\..", "\\rooted", "d:foo" }, "D:foo"); |
| 1230 | try testResolveWindows(&[_][]const u8{ "D:relevant", "../..\\..", "d:foo" }, "D:..\\..\\foo"); |
| 1231 | try testResolveWindows(&[_][]const u8{ "D:relevant", "../..\\..", "\\\\.\\ignored", "C:\\ignored", "C:ignored", "\\\\ignored", "d:foo" }, "D:..\\..\\foo"); |
| 1232 | try testResolveWindows(&[_][]const u8{ "ignored", "\\\\.\\ignored", "C:\\ignored", "C:ignored", "\\\\ignored", "d:foo" }, "D:foo"); |
| 1233 | // Rooted paths remain rooted if there's no absolute path available to resolve the "root" |
| 1234 | try testResolveWindows(&[_][]const u8{ "/foo", "bar" }, "\\foo\\bar"); |
| 1235 | // Rooted against a UNC path |
| 1236 | try testResolveWindows(&[_][]const u8{ "//server/share/ignore", "/foo", "bar" }, "\\\\server\\share\\foo\\bar"); |
| 1237 | try testResolveWindows(&[_][]const u8{ "//server/share/", "/foo" }, "\\\\server\\share\\foo"); |
| 1238 | try testResolveWindows(&[_][]const u8{ "//server/share", "/foo" }, "\\\\server\\share\\foo"); |
| 1239 | try testResolveWindows(&[_][]const u8{ "//server/", "/foo" }, "\\\\server\\foo"); |
| 1240 | try testResolveWindows(&[_][]const u8{ "//server", "/foo" }, "\\\\server\\foo"); |
| 1241 | try testResolveWindows(&[_][]const u8{ "//", "/foo" }, "\\\\foo"); |
| 1242 | // Rooted against a drive-relative path |
| 1243 | try testResolveWindows(&[_][]const u8{ "C:", "/foo", "bar" }, "C:\\foo\\bar"); |
| 1244 | try testResolveWindows(&[_][]const u8{ "C:\\ignore", "C:", "/foo", "bar" }, "C:\\foo\\bar"); |
| 1245 | try testResolveWindows(&[_][]const u8{ "C:\\ignore", "\\foo", "C:bar" }, "C:\\foo\\bar"); |
| 1246 | // Only the last rooted path is relevant |
| 1247 | try testResolveWindows(&[_][]const u8{ "\\ignore", "\\foo" }, "\\foo"); |
| 1248 | try testResolveWindows(&[_][]const u8{ "c:ignore", "ignore", "\\ignore", "\\foo" }, "C:\\foo"); |
| 1249 | // Rooted is only relevant to a drive-relative if there's a previous drive-* path |
| 1250 | try testResolveWindows(&[_][]const u8{ "\\ignore", "C:foo" }, "C:foo"); |
| 1251 | try testResolveWindows(&[_][]const u8{ "\\ignore", "\\ignore2", "C:foo" }, "C:foo"); |
| 1252 | try testResolveWindows(&[_][]const u8{ "c:ignore", "\\ignore", "\\rooted", "C:foo" }, "C:\\rooted\\foo"); |
| 1253 | try testResolveWindows(&[_][]const u8{ "c:\\ignore", "\\ignore", "\\rooted", "C:foo" }, "C:\\rooted\\foo"); |
| 1254 | try testResolveWindows(&[_][]const u8{ "d:\\ignore", "\\ignore", "\\ignore2", "C:foo" }, "C:foo"); |
| 1255 | // Root local device paths |
| 1256 | try testResolveWindows(&[_][]const u8{"\\/."}, "\\\\."); |
| 1257 | try testResolveWindows(&[_][]const u8{ "\\/.", "C:drive-relative" }, "C:drive-relative"); |
| 1258 | try testResolveWindows(&[_][]const u8{"/\\?"}, "\\\\?"); |
| 1259 | try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "\\\\.", "foo" }, "\\\\.\\foo"); |
| 1260 | try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "\\\\?", "foo" }, "\\\\?\\foo"); |
| 1261 | try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "//.", "ignore", "\\foo" }, "\\\\.\\foo"); |
| 1262 | try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "\\\\?", "ignore", "\\foo" }, "\\\\?\\foo"); |
| 1263 | |
| 1264 | // Keep relative paths relative. |
| 1265 | try testResolveWindows(&[_][]const u8{"a/b"}, "a\\b"); |
| 1266 | try testResolveWindows(&[_][]const u8{".."}, ".."); |
| 1267 | try testResolveWindows(&[_][]const u8{"../.."}, "..\\.."); |
| 1268 | try testResolveWindows(&[_][]const u8{ "C:foo", "../.." }, "C:.."); |
| 1269 | try testResolveWindows(&[_][]const u8{ "d:foo", "../..\\.." }, "D:..\\.."); |
| 1270 | |
| 1271 | // Local device paths treat the \\.\ or \\?\ as the "root", everything afterwards is treated as a regular component. |
| 1272 | try testResolveWindows(&[_][]const u8{ "\\\\?\\C:\\foo", "../bar", "baz" }, "\\\\?\\C:\\bar\\baz"); |
| 1273 | try testResolveWindows(&[_][]const u8{ "\\\\.\\C:/foo", "../../../../bar", "baz" }, "\\\\.\\bar\\baz"); |
| 1274 | try testResolveWindows(&[_][]const u8{ "//./C:/foo", "../../../../bar", "baz" }, "\\\\.\\bar\\baz"); |
| 1275 | try testResolveWindows(&[_][]const u8{ "\\\\.\\foo", ".." }, "\\\\."); |
| 1276 | try testResolveWindows(&[_][]const u8{ "\\\\.\\foo", "..\\.." }, "\\\\."); |
| 1277 | |
| 1278 | // Paths are assumed to be Win32, so paths that are likely NT paths are treated as a rooted path. |
| 1279 | try testResolveWindows(&[_][]const u8{ "\\??\\C:\\foo", "/bar", "baz" }, "\\bar\\baz"); |
| 1280 | try testResolveWindows(&[_][]const u8{ "C:\\", "\\??\\C:\\foo", "bar" }, "C:\\??\\C:\\foo\\bar"); |
| 1281 | } |
| 1282 | |
| 1283 | test resolvePosix { |
| 1284 | try testResolvePosix(&.{ "/a/b", "c" }, "/a/b/c"); |
| 1285 | try testResolvePosix(&.{ "/a/b", "c", "//d", "e///" }, "/d/e"); |
| 1286 | try testResolvePosix(&.{ "/a/b/c", "..", "../" }, "/a"); |
| 1287 | try testResolvePosix(&.{ "/", "..", ".." }, "/"); |
| 1288 | try testResolvePosix(&.{"/a/b/c/"}, "/a/b/c"); |
| 1289 | |
| 1290 | try testResolvePosix(&.{ "/var/lib", "../", "file/" }, "/var/file"); |
| 1291 | try testResolvePosix(&.{ "/var/lib", "/../", "file/" }, "/file"); |
| 1292 | try testResolvePosix(&.{ "/some/dir", ".", "/absolute/" }, "/absolute"); |
| 1293 | try testResolvePosix(&.{ "/foo/tmp.3/", "../tmp.3/cycles/root.js" }, "/foo/tmp.3/cycles/root.js"); |
| 1294 | |
| 1295 | // Keep relative paths relative. |
| 1296 | try testResolvePosix(&.{"a/b"}, "a/b"); |
| 1297 | try testResolvePosix(&.{"."}, "."); |
| 1298 | try testResolvePosix(&.{ ".", "src/test.zig", "..", "../test/cases.zig" }, "test/cases.zig"); |
| 1299 | } |
| 1300 | |
| 1301 | fn testResolveWindows(paths: []const []const u8, expected: []const u8) !void { |
| 1302 | const actual = try resolveWindows(testing.allocator, paths); |
| 1303 | defer testing.allocator.free(actual); |
| 1304 | try testing.expectEqualStrings(expected, actual); |
| 1305 | } |
| 1306 | |
| 1307 | fn testResolvePosix(paths: []const []const u8, expected: []const u8) !void { |
| 1308 | const actual = try resolvePosix(testing.allocator, paths); |
| 1309 | defer testing.allocator.free(actual); |
| 1310 | try testing.expectEqualStrings(expected, actual); |
| 1311 | } |
| 1312 | |
| 1313 | /// Strip the last component from a file path. |
| 1314 | /// |
| 1315 | /// If the path is a file in the current directory (no directory component) |
| 1316 | /// then returns null. |
| 1317 | /// |
| 1318 | /// If the path is the root directory, returns null. |
| 1319 | pub fn dirname(path: []const u8) ?[]const u8 { |
| 1320 | if (native_os == .windows) { |
| 1321 | return dirnameWindows(path); |
| 1322 | } else { |
| 1323 | return dirnamePosix(path); |
| 1324 | } |
| 1325 | } |
| 1326 | |
| 1327 | pub fn dirnameWindows(path: []const u8) ?[]const u8 { |
| 1328 | return dirnameInner(.windows, path); |
| 1329 | } |
| 1330 | |
| 1331 | pub fn dirnamePosix(path: []const u8) ?[]const u8 { |
| 1332 | return dirnameInner(.posix, path); |
| 1333 | } |
| 1334 | |
| 1335 | fn dirnameInner(comptime path_type: PathType, path: []const u8) ?[]const u8 { |
| 1336 | var it = ComponentIterator(path_type, u8).init(path); |
| 1337 | _ = it.last() orelse return null; |
| 1338 | const up = it.previous() orelse return it.root(); |
| 1339 | return up.path; |
| 1340 | } |
| 1341 | |
| 1342 | test dirnamePosix { |
| 1343 | try testDirnamePosix("/a/b/c", "/a/b"); |
| 1344 | try testDirnamePosix("/a/b/c///", "/a/b"); |
| 1345 | try testDirnamePosix("/a", "/"); |
| 1346 | try testDirnamePosix("/", null); |
| 1347 | try testDirnamePosix("//", null); |
| 1348 | try testDirnamePosix("///", null); |
| 1349 | try testDirnamePosix("////", null); |
| 1350 | try testDirnamePosix("", null); |
| 1351 | try testDirnamePosix("a", null); |
| 1352 | try testDirnamePosix("a/", null); |
| 1353 | try testDirnamePosix("a//", null); |
| 1354 | } |
| 1355 | |
| 1356 | test dirnameWindows { |
| 1357 | try testDirnameWindows("c:\\", null); |
| 1358 | try testDirnameWindows("c:\\\\", null); |
| 1359 | try testDirnameWindows("c:\\foo", "c:\\"); |
| 1360 | try testDirnameWindows("c:\\\\foo\\", "c:\\"); |
| 1361 | try testDirnameWindows("c:\\foo\\bar", "c:\\foo"); |
| 1362 | try testDirnameWindows("c:\\foo\\bar\\", "c:\\foo"); |
| 1363 | try testDirnameWindows("c:\\\\foo\\bar\\baz", "c:\\\\foo\\bar"); |
| 1364 | try testDirnameWindows("\\", null); |
| 1365 | try testDirnameWindows("\\foo", "\\"); |
| 1366 | try testDirnameWindows("\\foo\\", "\\"); |
| 1367 | try testDirnameWindows("\\foo\\bar", "\\foo"); |
| 1368 | try testDirnameWindows("\\foo\\bar\\", "\\foo"); |
| 1369 | try testDirnameWindows("\\foo\\bar\\baz", "\\foo\\bar"); |
| 1370 | try testDirnameWindows("c:", null); |
| 1371 | try testDirnameWindows("c:foo", "c:"); |
| 1372 | try testDirnameWindows("c:foo\\", "c:"); |
| 1373 | try testDirnameWindows("c:foo\\bar", "c:foo"); |
| 1374 | try testDirnameWindows("c:foo\\bar\\", "c:foo"); |
| 1375 | try testDirnameWindows("c:foo\\bar\\baz", "c:foo\\bar"); |
| 1376 | try testDirnameWindows("file:stream", null); |
| 1377 | try testDirnameWindows("dir\\file:stream", "dir"); |
| 1378 | try testDirnameWindows("\\\\unc\\share", null); |
| 1379 | try testDirnameWindows("\\\\unc\\share\\\\", null); |
| 1380 | try testDirnameWindows("\\\\unc\\share\\foo", "\\\\unc\\share\\"); |
| 1381 | try testDirnameWindows("\\\\unc\\share\\foo\\", "\\\\unc\\share\\"); |
| 1382 | try testDirnameWindows("\\\\unc\\share\\foo\\bar", "\\\\unc\\share\\foo"); |
| 1383 | try testDirnameWindows("\\\\unc\\share\\foo\\bar\\", "\\\\unc\\share\\foo"); |
| 1384 | try testDirnameWindows("\\\\unc\\share\\foo\\bar\\baz", "\\\\unc\\share\\foo\\bar"); |
| 1385 | try testDirnameWindows("\\\\.", null); |
| 1386 | try testDirnameWindows("\\\\.\\", null); |
| 1387 | try testDirnameWindows("\\\\.\\device", "\\\\.\\"); |
| 1388 | try testDirnameWindows("\\\\.\\device\\", "\\\\.\\"); |
| 1389 | try testDirnameWindows("\\\\.\\device\\foo", "\\\\.\\device"); |
| 1390 | try testDirnameWindows("\\\\?", null); |
| 1391 | try testDirnameWindows("\\\\?\\", null); |
| 1392 | try testDirnameWindows("\\\\?\\device", "\\\\?\\"); |
| 1393 | try testDirnameWindows("\\\\?\\device\\", "\\\\?\\"); |
| 1394 | try testDirnameWindows("\\\\?\\device\\foo", "\\\\?\\device"); |
| 1395 | try testDirnameWindows("/a/b/", "/a"); |
| 1396 | try testDirnameWindows("/a/b", "/a"); |
| 1397 | try testDirnameWindows("/a", "/"); |
| 1398 | try testDirnameWindows("", null); |
| 1399 | try testDirnameWindows("/", null); |
| 1400 | try testDirnameWindows("////", null); |
| 1401 | try testDirnameWindows("foo", null); |
| 1402 | } |
| 1403 | |
| 1404 | fn testDirnamePosix(input: []const u8, expected_output: ?[]const u8) !void { |
| 1405 | if (dirnamePosix(input)) |output| { |
| 1406 | try testing.expect(mem.eql(u8, output, expected_output.?)); |
| 1407 | } else { |
| 1408 | try testing.expect(expected_output == null); |
| 1409 | } |
| 1410 | } |
| 1411 | |
| 1412 | fn testDirnameWindows(input: []const u8, expected_output: ?[]const u8) !void { |
| 1413 | if (dirnameWindows(input)) |output| { |
| 1414 | try testing.expectEqualStrings(expected_output.?, output); |
| 1415 | } else { |
| 1416 | try testing.expect(expected_output == null); |
| 1417 | } |
| 1418 | } |
| 1419 | |
| 1420 | pub fn basename(path: []const u8) []const u8 { |
| 1421 | if (native_os == .windows) { |
| 1422 | return basenameWindows(path); |
| 1423 | } else { |
| 1424 | return basenamePosix(path); |
| 1425 | } |
| 1426 | } |
| 1427 | |
| 1428 | pub fn basenamePosix(path: []const u8) []const u8 { |
| 1429 | return basenameInner(.posix, path); |
| 1430 | } |
| 1431 | |
| 1432 | pub fn basenameWindows(path: []const u8) []const u8 { |
| 1433 | return basenameInner(.windows, path); |
| 1434 | } |
| 1435 | |
| 1436 | fn basenameInner(comptime path_type: PathType, path: []const u8) []const u8 { |
| 1437 | var it = ComponentIterator(path_type, u8).init(path); |
| 1438 | const last = it.last() orelse return &[_]u8{}; |
| 1439 | return last.name; |
| 1440 | } |
| 1441 | |
| 1442 | test basename { |
| 1443 | try testBasename("", ""); |
| 1444 | try testBasename("/", ""); |
| 1445 | try testBasename("/dir/basename.ext", "basename.ext"); |
| 1446 | try testBasename("/basename.ext", "basename.ext"); |
| 1447 | try testBasename("basename.ext", "basename.ext"); |
| 1448 | try testBasename("basename.ext/", "basename.ext"); |
| 1449 | try testBasename("basename.ext//", "basename.ext"); |
| 1450 | try testBasename("/aaa/bbb", "bbb"); |
| 1451 | try testBasename("/aaa/", "aaa"); |
| 1452 | try testBasename("/aaa/b", "b"); |
| 1453 | try testBasename("/a/b", "b"); |
| 1454 | |
| 1455 | // For Windows, this is a UNC path that only has a server name component. |
| 1456 | try testBasename("//a", if (native_os == .windows) "" else "a"); |
| 1457 | |
| 1458 | try testBasenamePosix("\\dir\\basename.ext", "\\dir\\basename.ext"); |
| 1459 | try testBasenamePosix("\\basename.ext", "\\basename.ext"); |
| 1460 | try testBasenamePosix("basename.ext", "basename.ext"); |
| 1461 | try testBasenamePosix("basename.ext\\", "basename.ext\\"); |
| 1462 | try testBasenamePosix("basename.ext\\\\", "basename.ext\\\\"); |
| 1463 | try testBasenamePosix("foo", "foo"); |
| 1464 | |
| 1465 | try testBasenameWindows("\\dir\\basename.ext", "basename.ext"); |
| 1466 | try testBasenameWindows("\\basename.ext", "basename.ext"); |
| 1467 | try testBasenameWindows("basename.ext", "basename.ext"); |
| 1468 | try testBasenameWindows("basename.ext\\", "basename.ext"); |
| 1469 | try testBasenameWindows("basename.ext\\\\", "basename.ext"); |
| 1470 | try testBasenameWindows("foo", "foo"); |
| 1471 | try testBasenameWindows("C:", ""); |
| 1472 | try testBasenameWindows("C:.", "."); |
| 1473 | try testBasenameWindows("C:\\", ""); |
| 1474 | try testBasenameWindows("C:\\dir\\base.ext", "base.ext"); |
| 1475 | try testBasenameWindows("C:\\basename.ext", "basename.ext"); |
| 1476 | try testBasenameWindows("C:basename.ext", "basename.ext"); |
| 1477 | try testBasenameWindows("C:basename.ext\\", "basename.ext"); |
| 1478 | try testBasenameWindows("C:basename.ext\\\\", "basename.ext"); |
| 1479 | try testBasenameWindows("\\\\.", ""); |
| 1480 | try testBasenameWindows("\\\\.\\", ""); |
| 1481 | try testBasenameWindows("\\\\.\\basename.ext", "basename.ext"); |
| 1482 | try testBasenameWindows("\\\\?", ""); |
| 1483 | try testBasenameWindows("\\\\?\\", ""); |
| 1484 | try testBasenameWindows("\\\\?\\basename.ext", "basename.ext"); |
| 1485 | try testBasenameWindows("C:foo", "foo"); |
| 1486 | try testBasenameWindows("file:stream", "file:stream"); |
| 1487 | } |
| 1488 | |
| 1489 | fn testBasename(input: []const u8, expected_output: []const u8) !void { |
| 1490 | try testing.expectEqualSlices(u8, expected_output, basename(input)); |
| 1491 | } |
| 1492 | |
| 1493 | fn testBasenamePosix(input: []const u8, expected_output: []const u8) !void { |
| 1494 | try testing.expectEqualSlices(u8, expected_output, basenamePosix(input)); |
| 1495 | } |
| 1496 | |
| 1497 | fn testBasenameWindows(input: []const u8, expected_output: []const u8) !void { |
| 1498 | try testing.expectEqualSlices(u8, expected_output, basenameWindows(input)); |
| 1499 | } |
| 1500 | |
| 1501 | /// Returns the non-absolute path from `from` to `to`. |
| 1502 | /// |
| 1503 | /// Other than memory allocation, this is a pure function; the result solely |
| 1504 | /// depends on the input parameters. |
| 1505 | /// |
| 1506 | /// If `from` and `to` each resolve to the same path (after calling `resolve` |
| 1507 | /// on each), a zero-length string is returned. |
| 1508 | /// |
| 1509 | /// See `relativePosix` and `relativeWindows` for operating system specific |
| 1510 | /// details and for how `environ_map` is used. |
| 1511 | pub fn relative( |
| 1512 | gpa: Allocator, |
| 1513 | cwd: []const u8, |
| 1514 | environ_map: ?*const std.process.Environ.Map, |
| 1515 | from: []const u8, |
| 1516 | to: []const u8, |
| 1517 | ) Allocator.Error![]u8 { |
| 1518 | if (native_os == .windows) { |
| 1519 | return relativeWindows(gpa, cwd, environ_map, from, to); |
| 1520 | } else { |
| 1521 | return relativePosix(gpa, cwd, from, to); |
| 1522 | } |
| 1523 | } |
| 1524 | |
| 1525 | /// Returns the non-absolute path from `from` to `to` according to Windows rules. |
| 1526 | /// |
| 1527 | /// Other than memory allocation, this is a pure function; the result solely |
| 1528 | /// depends on the input parameters. |
| 1529 | /// |
| 1530 | /// If `from` and `to` each resolve to the same path (after calling `resolve` |
| 1531 | /// on each), a zero-length string is returned. |
| 1532 | /// |
| 1533 | /// The result is not guaranteed to be relative, as the paths may be on |
| 1534 | /// different volumes. In that case, the result will be the canonicalized |
| 1535 | /// absolute path of `to`. |
| 1536 | /// |
| 1537 | /// Per-drive CWDs are stored in special semi-hidden environment variables of |
| 1538 | /// the format `=<drive-letter>:`, e.g. `=C:`. This type of CWD is purely a |
| 1539 | /// shell concept, so there's no guarantee that it'll be set or that it'll even |
| 1540 | /// be accurate. This is the only reason for the `environ_map` parameter. `null` is |
| 1541 | /// treated equivalent to the environment variable missing. |
| 1542 | pub fn relativeWindows( |
| 1543 | gpa: Allocator, |
| 1544 | cwd: []const u8, |
| 1545 | environ_map: ?*const std.process.Environ.Map, |
| 1546 | from: []const u8, |
| 1547 | to: []const u8, |
| 1548 | ) Allocator.Error![]u8 { |
| 1549 | const parsed_from = parsePathWindows(u8, from); |
| 1550 | const parsed_to = parsePathWindows(u8, to); |
| 1551 | |
| 1552 | const result_is_always_to = x: { |
| 1553 | if (parsed_from.kind != parsed_to.kind) { |
| 1554 | break :x false; |
| 1555 | } |
| 1556 | switch (parsed_from.kind) { |
| 1557 | .drive_relative, .drive_absolute => { |
| 1558 | break :x !compareDiskDesignators(u8, .drive, parsed_from.root, parsed_to.root); |
| 1559 | }, |
| 1560 | .unc_absolute => { |
| 1561 | break :x !compareDiskDesignators(u8, .unc, parsed_from.root, parsed_to.root); |
| 1562 | }, |
| 1563 | .relative, .rooted, .local_device => break :x false, |
| 1564 | .root_local_device => break :x true, |
| 1565 | } |
| 1566 | }; |
| 1567 | |
| 1568 | if (result_is_always_to) { |
| 1569 | return windowsResolveAgainstCwd(gpa, cwd, environ_map, to, parsed_to); |
| 1570 | } |
| 1571 | |
| 1572 | const resolved_from = try windowsResolveAgainstCwd(gpa, cwd, environ_map, from, parsed_from); |
| 1573 | defer gpa.free(resolved_from); |
| 1574 | var clean_up_resolved_to = true; |
| 1575 | const resolved_to = try windowsResolveAgainstCwd(gpa, cwd, environ_map, to, parsed_to); |
| 1576 | defer if (clean_up_resolved_to) gpa.free(resolved_to); |
| 1577 | |
| 1578 | const parsed_resolved_from = parsePathWindows(u8, resolved_from); |
| 1579 | const parsed_resolved_to = parsePathWindows(u8, resolved_to); |
| 1580 | |
| 1581 | const result_is_to = x: { |
| 1582 | if (parsed_resolved_from.kind != parsed_resolved_to.kind) { |
| 1583 | break :x true; |
| 1584 | } |
| 1585 | switch (parsed_resolved_from.kind) { |
| 1586 | .drive_absolute, .drive_relative => { |
| 1587 | break :x !compareDiskDesignators(u8, .drive, parsed_resolved_from.root, parsed_resolved_to.root); |
| 1588 | }, |
| 1589 | .unc_absolute => { |
| 1590 | break :x !compareDiskDesignators(u8, .unc, parsed_resolved_from.root, parsed_resolved_to.root); |
| 1591 | }, |
| 1592 | .relative, .rooted, .local_device => break :x false, |
| 1593 | .root_local_device => break :x true, |
| 1594 | } |
| 1595 | }; |
| 1596 | |
| 1597 | if (result_is_to) { |
| 1598 | clean_up_resolved_to = false; |
| 1599 | return resolved_to; |
| 1600 | } |
| 1601 | |
| 1602 | var from_it = mem.tokenizeAny(u8, resolved_from[parsed_resolved_from.root.len..], "/\\"); |
| 1603 | var to_it = mem.tokenizeAny(u8, resolved_to[parsed_resolved_to.root.len..], "/\\"); |
| 1604 | while (true) { |
| 1605 | const from_component = from_it.next() orelse return gpa.dupe(u8, to_it.rest()); |
| 1606 | const to_rest = to_it.rest(); |
| 1607 | if (to_it.next()) |to_component| { |
| 1608 | if (eqlIgnoreCaseWtf8(from_component, to_component)) |
| 1609 | continue; |
| 1610 | } |
| 1611 | var up_index_end = "..".len; |
| 1612 | while (from_it.next()) |_| { |
| 1613 | up_index_end += "\\..".len; |
| 1614 | } |
| 1615 | const result = try gpa.alloc(u8, up_index_end + @intFromBool(to_rest.len > 0) + to_rest.len); |
| 1616 | errdefer gpa.free(result); |
| 1617 | |
| 1618 | result[0..2].* = "..".*; |
| 1619 | var result_index: usize = 2; |
| 1620 | while (result_index < up_index_end) { |
| 1621 | result[result_index..][0..3].* = "\\..".*; |
| 1622 | result_index += 3; |
| 1623 | } |
| 1624 | |
| 1625 | var rest_it = mem.tokenizeAny(u8, to_rest, "/\\"); |
| 1626 | while (rest_it.next()) |to_component| { |
| 1627 | result[result_index] = '\\'; |
| 1628 | result_index += 1; |
| 1629 | @memcpy(result[result_index..][0..to_component.len], to_component); |
| 1630 | result_index += to_component.len; |
| 1631 | } |
| 1632 | |
| 1633 | return gpa.realloc(result, result_index); |
| 1634 | } |
| 1635 | return [_]u8{}; |
| 1636 | } |
| 1637 | |
| 1638 | fn windowsResolveAgainstCwd( |
| 1639 | gpa: Allocator, |
| 1640 | cwd: []const u8, |
| 1641 | environ_map: ?*const std.process.Environ.Map, |
| 1642 | path: []const u8, |
| 1643 | parsed: WindowsPath2(u8), |
| 1644 | ) ![]u8 { |
| 1645 | // Space for 256 WTF-16 code units; potentially 3 WTF-8 bytes per WTF-16 code unit |
| 1646 | var buf: [256 * 3]u8 = undefined; |
| 1647 | var temp_allocator_state: std.heap.BufferFirstAllocator = .init(&buf, gpa); |
| 1648 | return switch (parsed.kind) { |
| 1649 | .drive_absolute, |
| 1650 | .unc_absolute, |
| 1651 | .root_local_device, |
| 1652 | .local_device, |
| 1653 | => try resolveWindows(gpa, &.{path}), |
| 1654 | |
| 1655 | .relative => try resolveWindows(gpa, &.{ cwd, path }), |
| 1656 | |
| 1657 | .rooted => blk: { |
| 1658 | const parsed_cwd = parsePathWindows(u8, cwd); |
| 1659 | switch (parsed_cwd.kind) { |
| 1660 | .drive_absolute => { |
| 1661 | var drive_buf = "_:\\".*; |
| 1662 | drive_buf[0] = cwd[0]; |
| 1663 | break :blk try resolveWindows(gpa, &.{ &drive_buf, path }); |
| 1664 | }, |
| 1665 | .unc_absolute => { |
| 1666 | break :blk try resolveWindows(gpa, &.{ parsed_cwd.root, path }); |
| 1667 | }, |
| 1668 | // Effectively a malformed CWD, give up and just return a normalized path |
| 1669 | else => break :blk try resolveWindows(gpa, &.{path}), |
| 1670 | } |
| 1671 | }, |
| 1672 | .drive_relative => blk: { |
| 1673 | const temp_allocator = temp_allocator_state.allocator(); |
| 1674 | const drive_cwd = drive_cwd: { |
| 1675 | const parsed_cwd = parsePathWindows(u8, cwd); |
| 1676 | |
| 1677 | if (parsed_cwd.kind == .drive_absolute) { |
| 1678 | const drive_letter_w = parsed_cwd.root[0]; |
| 1679 | const drive_letters_match = drive_letter_w <= 0x7F and |
| 1680 | std.ascii.toUpper(@intCast(drive_letter_w)) == std.ascii.toUpper(parsed.root[0]); |
| 1681 | if (drive_letters_match) |
| 1682 | break :drive_cwd cwd; |
| 1683 | |
| 1684 | if (environ_map) |m| { |
| 1685 | if (m.get(&.{ '=', parsed.root[0], ':' })) |v| { |
| 1686 | break :drive_cwd try temp_allocator.dupe(u8, v); |
| 1687 | } |
| 1688 | } |
| 1689 | } |
| 1690 | |
| 1691 | const drive_buf = try temp_allocator.alloc(u8, 3); |
| 1692 | drive_buf[0] = parsed.root[0]; |
| 1693 | drive_buf[1] = ':'; |
| 1694 | drive_buf[2] = '\\'; |
| 1695 | break :drive_cwd drive_buf; |
| 1696 | }; |
| 1697 | defer temp_allocator.free(drive_cwd); |
| 1698 | break :blk try resolveWindows(gpa, &.{ drive_cwd, path }); |
| 1699 | }, |
| 1700 | }; |
| 1701 | } |
| 1702 | |
| 1703 | /// Returns the non-absolute path from `from` to `to` according to Windows rules. |
| 1704 | /// |
| 1705 | /// Other than memory allocation, this is a pure function; the result solely |
| 1706 | /// depends on the input parameters. |
| 1707 | /// |
| 1708 | /// If `from` and `to` each resolve to the same path (after calling `resolve` |
| 1709 | /// on each), a zero-length string is returned. |
| 1710 | /// |
| 1711 | pub fn relativePosix(allocator: Allocator, cwd: []const u8, from: []const u8, to: []const u8) Allocator.Error![]u8 { |
| 1712 | const resolved_from = try resolvePosix(allocator, &[_][]const u8{ cwd, from }); |
| 1713 | defer allocator.free(resolved_from); |
| 1714 | const resolved_to = try resolvePosix(allocator, &[_][]const u8{ cwd, to }); |
| 1715 | defer allocator.free(resolved_to); |
| 1716 | |
| 1717 | var from_it = mem.tokenizeScalar(u8, resolved_from, '/'); |
| 1718 | var to_it = mem.tokenizeScalar(u8, resolved_to, '/'); |
| 1719 | while (true) { |
| 1720 | const from_component = from_it.next() orelse return allocator.dupe(u8, to_it.rest()); |
| 1721 | const to_rest = to_it.rest(); |
| 1722 | if (to_it.next()) |to_component| { |
| 1723 | if (mem.eql(u8, from_component, to_component)) |
| 1724 | continue; |
| 1725 | } |
| 1726 | var up_count: usize = 1; |
| 1727 | while (from_it.next()) |_| { |
| 1728 | up_count += 1; |
| 1729 | } |
| 1730 | const up_index_end = up_count * "../".len; |
| 1731 | const result = try allocator.alloc(u8, up_index_end + to_rest.len); |
| 1732 | errdefer allocator.free(result); |
| 1733 | |
| 1734 | var result_index: usize = 0; |
| 1735 | while (result_index < up_index_end) { |
| 1736 | result[result_index..][0..3].* = "../".*; |
| 1737 | result_index += 3; |
| 1738 | } |
| 1739 | if (to_rest.len == 0) { |
| 1740 | // shave off the trailing slash |
| 1741 | return allocator.realloc(result, result_index - 1); |
| 1742 | } |
| 1743 | |
| 1744 | @memcpy(result[result_index..][0..to_rest.len], to_rest); |
| 1745 | return result; |
| 1746 | } |
| 1747 | |
| 1748 | return [_]u8{}; |
| 1749 | } |
| 1750 | |
| 1751 | test relative { |
| 1752 | try testRelativeWindows("c:/blah\\blah", "d:/games", "D:\\games"); |
| 1753 | try testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa", ".."); |
| 1754 | try testRelativeWindows("c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc"); |
| 1755 | try testRelativeWindows("c:/aaaa/bbbb", "C:/aaaa/bbbb", ""); |
| 1756 | try testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa/cccc", "..\\cccc"); |
| 1757 | try testRelativeWindows("c:/aaaa/", "c:/aaaa/cccc", "cccc"); |
| 1758 | try testRelativeWindows("c:/", "c:\\aaaa\\bbbb", "aaaa\\bbbb"); |
| 1759 | try testRelativeWindows("c:/aaaa/bbbb", "d:\\", "D:\\"); |
| 1760 | try testRelativeWindows("c:/AaAa/bbbb", "c:/aaaa/bbbb", ""); |
| 1761 | try testRelativeWindows("c:/aaaaa/", "c:/aaaa/cccc", "..\\aaaa\\cccc"); |
| 1762 | try testRelativeWindows("C:\\foo\\bar\\baz\\quux", "C:\\", "..\\..\\..\\.."); |
| 1763 | try testRelativeWindows("C:\\foo\\test", "C:\\foo\\test\\bar\\package.json", "bar\\package.json"); |
| 1764 | try testRelativeWindows("C:\\foo\\bar\\baz-quux", "C:\\foo\\bar\\baz", "..\\baz"); |
| 1765 | try testRelativeWindows("C:\\foo\\bar\\baz", "C:\\foo\\bar\\baz-quux", "..\\baz-quux"); |
| 1766 | try testRelativeWindows("\\\\foo\\bar", "\\\\foo\\bar\\baz", "baz"); |
| 1767 | try testRelativeWindows("\\\\foo\\bar\\baz", "\\\\foo\\bar", ".."); |
| 1768 | try testRelativeWindows("\\\\foo\\bar\\baz-quux", "\\\\foo\\bar\\baz", "..\\baz"); |
| 1769 | try testRelativeWindows("\\\\foo/bar\\baz-quux", "//foo\\bar/baz", "..\\baz"); |
| 1770 | try testRelativeWindows("\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz-quux", "..\\baz-quux"); |
| 1771 | try testRelativeWindows("C:\\baz-quux", "C:\\baz", "..\\baz"); |
| 1772 | try testRelativeWindows("C:\\baz", "C:\\baz-quux", "..\\baz-quux"); |
| 1773 | try testRelativeWindows("\\\\foo\\baz-quux", "\\\\foo\\baz", "\\\\foo\\baz"); |
| 1774 | try testRelativeWindows("\\\\foo\\baz", "\\\\foo\\baz-quux", "\\\\foo\\baz-quux"); |
| 1775 | try testRelativeWindows("C:\\baz", "\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz"); |
| 1776 | try testRelativeWindows("\\\\foo\\bar\\baz", "C:\\baz", "C:\\baz"); |
| 1777 | |
| 1778 | try testRelativeWindows("c:blah\\blah", "c:foo", "..\\..\\foo"); |
| 1779 | try testRelativeWindows("c:foo", "c:foo\\bar", "bar"); |
| 1780 | try testRelativeWindows("\\blah\\blah", "\\foo", "..\\..\\foo"); |
| 1781 | try testRelativeWindows("\\foo", "\\foo\\bar", "bar"); |
| 1782 | |
| 1783 | try testRelativeWindows("a/b/c", "a\\b", ".."); |
| 1784 | try testRelativeWindows("a/b/c", "a", "..\\.."); |
| 1785 | try testRelativeWindows("a/b/c", "a\\b\\c\\d", "d"); |
| 1786 | |
| 1787 | try testRelativeWindows("\\\\FOO\\bar\\baz", "\\\\foo\\BAR\\BAZ", ""); |
| 1788 | // Unicode-aware case-insensitive path comparison |
| 1789 | try testRelativeWindows("\\\\кириллица\\ελληνικά\\português", "\\\\КИРИЛЛИЦА\\ΕΛΛΗΝΙΚΆ\\PORTUGUÊS", ""); |
| 1790 | |
| 1791 | try testRelativePosix("/var/lib", "/var", ".."); |
| 1792 | try testRelativePosix("/var/lib", "/bin", "../../bin"); |
| 1793 | try testRelativePosix("/var/lib", "/var/lib", ""); |
| 1794 | try testRelativePosix("/var/lib", "/var/apache", "../apache"); |
| 1795 | try testRelativePosix("/var/", "/var/lib", "lib"); |
| 1796 | try testRelativePosix("/", "/var/lib", "var/lib"); |
| 1797 | try testRelativePosix("/foo/test", "/foo/test/bar/package.json", "bar/package.json"); |
| 1798 | try testRelativePosix("/Users/a/web/b/test/mails", "/Users/a/web/b", "../.."); |
| 1799 | try testRelativePosix("/foo/bar/baz-quux", "/foo/bar/baz", "../baz"); |
| 1800 | try testRelativePosix("/foo/bar/baz", "/foo/bar/baz-quux", "../baz-quux"); |
| 1801 | try testRelativePosix("/baz-quux", "/baz", "../baz"); |
| 1802 | try testRelativePosix("/baz", "/baz-quux", "../baz-quux"); |
| 1803 | } |
| 1804 | |
| 1805 | fn testRelativePosix(from: []const u8, to: []const u8, expected_output: []const u8) !void { |
| 1806 | const result = try relativePosix(testing.allocator, ".", from, to); |
| 1807 | defer testing.allocator.free(result); |
| 1808 | try testing.expectEqualStrings(expected_output, result); |
| 1809 | } |
| 1810 | |
| 1811 | fn testRelativeWindows(from: []const u8, to: []const u8, expected_output: []const u8) !void { |
| 1812 | const result = try relativeWindows(testing.allocator, ".", null, from, to); |
| 1813 | defer testing.allocator.free(result); |
| 1814 | try testing.expectEqualStrings(expected_output, result); |
| 1815 | } |
| 1816 | |
| 1817 | /// Searches for a file extension separated by a `.` and returns the string after that `.`. |
| 1818 | /// Files that end or start with `.` and have no other `.` in their name |
| 1819 | /// are considered to have no extension, in which case this returns "". |
| 1820 | /// Examples: |
| 1821 | /// - `"main.zig"` ⇒ `".zig"` |
| 1822 | /// - `"src/main.zig"` ⇒ `".zig"` |
| 1823 | /// - `".gitignore"` ⇒ `""` |
| 1824 | /// - `".image.png"` ⇒ `".png"` |
| 1825 | /// - `"keep."` ⇒ `"."` |
| 1826 | /// - `"src.keep.me"` ⇒ `".me"` |
| 1827 | /// - `"/src/keep.me"` ⇒ `".me"` |
| 1828 | /// - `"/src/keep.me/"` ⇒ `".me"` |
| 1829 | /// The returned slice is guaranteed to have its pointer within the start and end |
| 1830 | /// pointer address range of `path`, even if it is length zero. |
| 1831 | pub fn extension(path: []const u8) []const u8 { |
| 1832 | const filename = basename(path); |
| 1833 | const index = mem.findScalarLast(u8, filename, '.') orelse return path[path.len..]; |
| 1834 | if (index == 0) return path[path.len..]; |
| 1835 | return filename[index..]; |
| 1836 | } |
| 1837 | |
| 1838 | fn testExtension(path: []const u8, expected: []const u8) !void { |
| 1839 | try testing.expectEqualStrings(expected, extension(path)); |
| 1840 | } |
| 1841 | |
| 1842 | test extension { |
| 1843 | try testExtension("", ""); |
| 1844 | try testExtension(".", ""); |
| 1845 | try testExtension("a.", "."); |
| 1846 | try testExtension("abc.", "."); |
| 1847 | try testExtension(".a", ""); |
| 1848 | try testExtension(".file", ""); |
| 1849 | try testExtension(".gitignore", ""); |
| 1850 | try testExtension(".image.png", ".png"); |
| 1851 | try testExtension("file.ext", ".ext"); |
| 1852 | try testExtension("file.ext.", "."); |
| 1853 | try testExtension("very-long-file.bruh", ".bruh"); |
| 1854 | try testExtension("a.b.c", ".c"); |
| 1855 | try testExtension("a.b.c/", ".c"); |
| 1856 | |
| 1857 | try testExtension("/", ""); |
| 1858 | try testExtension("/.", ""); |
| 1859 | try testExtension("/a.", "."); |
| 1860 | try testExtension("/abc.", "."); |
| 1861 | try testExtension("/.a", ""); |
| 1862 | try testExtension("/.file", ""); |
| 1863 | try testExtension("/.gitignore", ""); |
| 1864 | try testExtension("/file.ext", ".ext"); |
| 1865 | try testExtension("/file.ext.", "."); |
| 1866 | try testExtension("/very-long-file.bruh", ".bruh"); |
| 1867 | try testExtension("/a.b.c", ".c"); |
| 1868 | try testExtension("/a.b.c/", ".c"); |
| 1869 | |
| 1870 | try testExtension("/foo/bar/bam/", ""); |
| 1871 | try testExtension("/foo/bar/bam/.", ""); |
| 1872 | try testExtension("/foo/bar/bam/a.", "."); |
| 1873 | try testExtension("/foo/bar/bam/abc.", "."); |
| 1874 | try testExtension("/foo/bar/bam/.a", ""); |
| 1875 | try testExtension("/foo/bar/bam/.file", ""); |
| 1876 | try testExtension("/foo/bar/bam/.gitignore", ""); |
| 1877 | try testExtension("/foo/bar/bam/file.ext", ".ext"); |
| 1878 | try testExtension("/foo/bar/bam/file.ext.", "."); |
| 1879 | try testExtension("/foo/bar/bam/very-long-file.bruh", ".bruh"); |
| 1880 | try testExtension("/foo/bar/bam/a.b.c", ".c"); |
| 1881 | try testExtension("/foo/bar/bam/a.b.c/", ".c"); |
| 1882 | } |
| 1883 | |
| 1884 | /// Returns the last component of this path without its extension (if any): |
| 1885 | /// - "hello/world/lib.tar.gz" ⇒ "lib.tar" |
| 1886 | /// - "hello/world/lib.tar" ⇒ "lib" |
| 1887 | /// - "hello/world/lib" ⇒ "lib" |
| 1888 | pub fn stem(path: []const u8) []const u8 { |
| 1889 | const filename = basename(path); |
| 1890 | const index = mem.findScalarLast(u8, filename, '.') orelse return filename; |
| 1891 | if (index == 0) return filename; |
| 1892 | return filename[0..index]; |
| 1893 | } |
| 1894 | |
| 1895 | fn testStem(path: []const u8, expected: []const u8) !void { |
| 1896 | try testing.expectEqualStrings(expected, stem(path)); |
| 1897 | } |
| 1898 | |
| 1899 | test stem { |
| 1900 | try testStem("hello/world/lib.tar.gz", "lib.tar"); |
| 1901 | try testStem("hello/world/lib.tar", "lib"); |
| 1902 | try testStem("hello/world/lib", "lib"); |
| 1903 | try testStem("hello/lib/", "lib"); |
| 1904 | try testStem("hello...", "hello.."); |
| 1905 | try testStem("hello.", "hello"); |
| 1906 | try testStem("/hello.", "hello"); |
| 1907 | try testStem("hello/world/.gitignore", ".gitignore"); |
| 1908 | try testStem("/.gitignore", ".gitignore"); |
| 1909 | try testStem(".gitignore", ".gitignore"); |
| 1910 | try testStem(".gitignore/", ".gitignore"); |
| 1911 | try testStem("hello/world/.image.png", ".image"); |
| 1912 | try testStem("/.image.png", ".image"); |
| 1913 | try testStem(".image.png", ".image"); |
| 1914 | try testStem(".image.png/", ".image"); |
| 1915 | try testStem("file.ext", "file"); |
| 1916 | try testStem("file.ext.", "file.ext"); |
| 1917 | try testStem("a.b.c", "a.b"); |
| 1918 | try testStem("a.b.c/", "a.b"); |
| 1919 | try testStem(".a", ".a"); |
| 1920 | try testStem("///", ""); |
| 1921 | try testStem("..", "."); |
| 1922 | try testStem(".", "."); |
| 1923 | try testStem(" ", " "); |
| 1924 | try testStem("", ""); |
| 1925 | } |
| 1926 | |
| 1927 | /// A path component iterator that can move forwards and backwards. |
| 1928 | /// The 'root' of the path (`/` for POSIX, things like `C:\`, `\\server\share\`, etc |
| 1929 | /// for Windows) is treated specially and will never be returned by any of the |
| 1930 | /// `first`, `last`, `next`, or `previous` functions. |
| 1931 | /// Multiple consecutive path separators are skipped (treated as a single separator) |
| 1932 | /// when iterating. |
| 1933 | /// All returned component names/paths are slices of the original path. |
| 1934 | /// There is no normalization of paths performed while iterating. |
| 1935 | pub fn ComponentIterator(comptime path_type: PathType, comptime T: type) type { |
| 1936 | return struct { |
| 1937 | path: []const T, |
| 1938 | /// Length of the root with at most one trailing path separator included (e.g. `C:/`). |
| 1939 | root_len: usize, |
| 1940 | /// Length of the root with all trailing path separators included (e.g. `C://///`). |
| 1941 | root_end_index: usize, |
| 1942 | start_index: usize = 0, |
| 1943 | end_index: usize = 0, |
| 1944 | |
| 1945 | const Self = @This(); |
| 1946 | |
| 1947 | pub const Component = struct { |
| 1948 | /// The current component's path name, e.g. 'b'. |
| 1949 | /// This will never contain path separators. |
| 1950 | name: []const T, |
| 1951 | /// The full path up to and including the current component, e.g. '/a/b' |
| 1952 | /// This will never contain trailing path separators. |
| 1953 | path: []const T, |
| 1954 | }; |
| 1955 | |
| 1956 | /// After `init`, `next` will return the first component after the root |
| 1957 | /// (there is no need to call `first` after `init`). |
| 1958 | /// To iterate backwards (from the end of the path to the beginning), call `last` |
| 1959 | /// after `init` and then iterate via `previous` calls. |
| 1960 | /// For Windows paths, paths are assumed to be in the Win32 namespace. |
| 1961 | pub fn init(path: []const T) Self { |
| 1962 | const root_len: usize = switch (path_type) { |
| 1963 | .posix, .uefi => posix: { |
| 1964 | // Root on UEFI and POSIX only differs by the path separator |
| 1965 | break :posix if (path.len > 0 and path_type.isSep(T, path[0])) 1 else 0; |
| 1966 | }, |
| 1967 | .windows => windows: { |
| 1968 | break :windows parsePathWindows(T, path).root.len; |
| 1969 | }, |
| 1970 | }; |
| 1971 | // If there are repeated path separators directly after the root, |
| 1972 | // keep track of that info so that they don't have to be dealt with when |
| 1973 | // iterating components. |
| 1974 | var root_end_index = root_len; |
| 1975 | for (path[root_len..]) |c| { |
| 1976 | if (!path_type.isSep(T, c)) break; |
| 1977 | root_end_index += 1; |
| 1978 | } |
| 1979 | return .{ |
| 1980 | .path = path, |
| 1981 | .root_len = root_len, |
| 1982 | .root_end_index = root_end_index, |
| 1983 | .start_index = root_end_index, |
| 1984 | .end_index = root_end_index, |
| 1985 | }; |
| 1986 | } |
| 1987 | |
| 1988 | /// Returns the root of the path if it is not a relative path, or null otherwise. |
| 1989 | /// For POSIX paths, this will be `/`. |
| 1990 | /// For Windows paths, this will be something like `C:\`, `\\server\share\`, etc. |
| 1991 | /// For UEFI paths, this will be `\`. |
| 1992 | pub fn root(self: Self) ?[]const T { |
| 1993 | if (self.root_end_index == 0) return null; |
| 1994 | return self.path[0..self.root_len]; |
| 1995 | } |
| 1996 | |
| 1997 | /// Returns the first component (from the beginning of the path). |
| 1998 | /// For example, if the path is `/a/b/c` then this will return the `a` component. |
| 1999 | /// After calling `first`, `previous` will always return `null`, and `next` will return |
| 2000 | /// the component to the right of the one returned by `first`, if any exist. |
| 2001 | pub fn first(self: *Self) ?Component { |
| 2002 | self.start_index = self.root_end_index; |
| 2003 | self.end_index = self.start_index; |
| 2004 | while (self.end_index < self.path.len and !path_type.isSep(T, self.path[self.end_index])) { |
| 2005 | self.end_index += 1; |
| 2006 | } |
| 2007 | if (self.end_index == self.start_index) return null; |
| 2008 | return .{ |
| 2009 | .name = self.path[self.start_index..self.end_index], |
| 2010 | .path = self.path[0..self.end_index], |
| 2011 | }; |
| 2012 | } |
| 2013 | |
| 2014 | /// Returns the last component (from the end of the path). |
| 2015 | /// For example, if the path is `/a/b/c` then this will return the `c` component. |
| 2016 | /// After calling `last`, `next` will always return `null`, and `previous` will return |
| 2017 | /// the component to the left of the one returned by `last`, if any exist. |
| 2018 | pub fn last(self: *Self) ?Component { |
| 2019 | self.end_index = self.path.len; |
| 2020 | while (true) { |
| 2021 | if (self.end_index == self.root_end_index) { |
| 2022 | self.start_index = self.end_index; |
| 2023 | return null; |
| 2024 | } |
| 2025 | if (!path_type.isSep(T, self.path[self.end_index - 1])) break; |
| 2026 | self.end_index -= 1; |
| 2027 | } |
| 2028 | self.start_index = self.end_index; |
| 2029 | while (true) { |
| 2030 | if (self.start_index == self.root_end_index) break; |
| 2031 | if (path_type.isSep(T, self.path[self.start_index - 1])) break; |
| 2032 | self.start_index -= 1; |
| 2033 | } |
| 2034 | if (self.start_index == self.end_index) return null; |
| 2035 | return .{ |
| 2036 | .name = self.path[self.start_index..self.end_index], |
| 2037 | .path = self.path[0..self.end_index], |
| 2038 | }; |
| 2039 | } |
| 2040 | |
| 2041 | /// Returns the next component (the component to the right of the most recently |
| 2042 | /// returned component), or null if no such component exists. |
| 2043 | /// For example, if the path is `/a/b/c` and the most recently returned component |
| 2044 | /// is `b`, then this will return the `c` component. |
| 2045 | pub fn next(self: *Self) ?Component { |
| 2046 | const peek_result = self.peekNext() orelse return null; |
| 2047 | self.start_index = peek_result.path.len - peek_result.name.len; |
| 2048 | self.end_index = peek_result.path.len; |
| 2049 | return peek_result; |
| 2050 | } |
| 2051 | |
| 2052 | /// Like `next`, but does not modify the iterator state. |
| 2053 | pub fn peekNext(self: Self) ?Component { |
| 2054 | var start_index = self.end_index; |
| 2055 | while (start_index < self.path.len and path_type.isSep(T, self.path[start_index])) { |
| 2056 | start_index += 1; |
| 2057 | } |
| 2058 | var end_index = start_index; |
| 2059 | while (end_index < self.path.len and !path_type.isSep(T, self.path[end_index])) { |
| 2060 | end_index += 1; |
| 2061 | } |
| 2062 | if (start_index == end_index) return null; |
| 2063 | return .{ |
| 2064 | .name = self.path[start_index..end_index], |
| 2065 | .path = self.path[0..end_index], |
| 2066 | }; |
| 2067 | } |
| 2068 | |
| 2069 | /// Returns the previous component (the component to the left of the most recently |
| 2070 | /// returned component), or null if no such component exists. |
| 2071 | /// For example, if the path is `/a/b/c` and the most recently returned component |
| 2072 | /// is `b`, then this will return the `a` component. |
| 2073 | pub fn previous(self: *Self) ?Component { |
| 2074 | const peek_result = self.peekPrevious() orelse return null; |
| 2075 | self.start_index = peek_result.path.len - peek_result.name.len; |
| 2076 | self.end_index = peek_result.path.len; |
| 2077 | return peek_result; |
| 2078 | } |
| 2079 | |
| 2080 | /// Like `previous`, but does not modify the iterator state. |
| 2081 | pub fn peekPrevious(self: Self) ?Component { |
| 2082 | var end_index = self.start_index; |
| 2083 | while (true) { |
| 2084 | if (end_index == self.root_end_index) return null; |
| 2085 | if (!path_type.isSep(T, self.path[end_index - 1])) break; |
| 2086 | end_index -= 1; |
| 2087 | } |
| 2088 | var start_index = end_index; |
| 2089 | while (true) { |
| 2090 | if (start_index == self.root_end_index) break; |
| 2091 | if (path_type.isSep(T, self.path[start_index - 1])) break; |
| 2092 | start_index -= 1; |
| 2093 | } |
| 2094 | if (start_index == end_index) return null; |
| 2095 | return .{ |
| 2096 | .name = self.path[start_index..end_index], |
| 2097 | .path = self.path[0..end_index], |
| 2098 | }; |
| 2099 | } |
| 2100 | }; |
| 2101 | } |
| 2102 | |
| 2103 | pub const NativeComponentIterator = ComponentIterator(switch (native_os) { |
| 2104 | .windows => .windows, |
| 2105 | .uefi => .uefi, |
| 2106 | else => .posix, |
| 2107 | }, u8); |
| 2108 | |
| 2109 | pub fn componentIterator(path: []const u8) NativeComponentIterator { |
| 2110 | return NativeComponentIterator.init(path); |
| 2111 | } |
| 2112 | |
| 2113 | test "ComponentIterator posix" { |
| 2114 | const PosixComponentIterator = ComponentIterator(.posix, u8); |
| 2115 | { |
| 2116 | const path = "a/b/c/"; |
| 2117 | var it = PosixComponentIterator.init(path); |
| 2118 | try std.testing.expectEqual(0, it.root_len); |
| 2119 | try std.testing.expectEqual(0, it.root_end_index); |
| 2120 | try std.testing.expect(null == it.root()); |
| 2121 | { |
| 2122 | try std.testing.expect(null == it.previous()); |
| 2123 | |
| 2124 | const first_via_next = it.next().?; |
| 2125 | try std.testing.expectEqualStrings("a", first_via_next.name); |
| 2126 | try std.testing.expectEqualStrings("a", first_via_next.path); |
| 2127 | |
| 2128 | const first = it.first().?; |
| 2129 | try std.testing.expectEqualStrings("a", first.name); |
| 2130 | try std.testing.expectEqualStrings("a", first.path); |
| 2131 | |
| 2132 | try std.testing.expect(null == it.previous()); |
| 2133 | |
| 2134 | const second = it.next().?; |
| 2135 | try std.testing.expectEqualStrings("b", second.name); |
| 2136 | try std.testing.expectEqualStrings("a/b", second.path); |
| 2137 | |
| 2138 | const third = it.next().?; |
| 2139 | try std.testing.expectEqualStrings("c", third.name); |
| 2140 | try std.testing.expectEqualStrings("a/b/c", third.path); |
| 2141 | |
| 2142 | try std.testing.expect(null == it.next()); |
| 2143 | } |
| 2144 | { |
| 2145 | const last = it.last().?; |
| 2146 | try std.testing.expectEqualStrings("c", last.name); |
| 2147 | try std.testing.expectEqualStrings("a/b/c", last.path); |
| 2148 | |
| 2149 | try std.testing.expect(null == it.next()); |
| 2150 | |
| 2151 | const second_to_last = it.previous().?; |
| 2152 | try std.testing.expectEqualStrings("b", second_to_last.name); |
| 2153 | try std.testing.expectEqualStrings("a/b", second_to_last.path); |
| 2154 | |
| 2155 | const third_to_last = it.previous().?; |
| 2156 | try std.testing.expectEqualStrings("a", third_to_last.name); |
| 2157 | try std.testing.expectEqualStrings("a", third_to_last.path); |
| 2158 | |
| 2159 | try std.testing.expect(null == it.previous()); |
| 2160 | } |
| 2161 | } |
| 2162 | |
| 2163 | { |
| 2164 | const path = "/a/b/c/"; |
| 2165 | var it = PosixComponentIterator.init(path); |
| 2166 | try std.testing.expectEqual(1, it.root_len); |
| 2167 | try std.testing.expectEqual(1, it.root_end_index); |
| 2168 | try std.testing.expectEqualStrings("/", it.root().?); |
| 2169 | { |
| 2170 | try std.testing.expect(null == it.previous()); |
| 2171 | |
| 2172 | const first_via_next = it.next().?; |
| 2173 | try std.testing.expectEqualStrings("a", first_via_next.name); |
| 2174 | try std.testing.expectEqualStrings("/a", first_via_next.path); |
| 2175 | |
| 2176 | const first = it.first().?; |
| 2177 | try std.testing.expectEqualStrings("a", first.name); |
| 2178 | try std.testing.expectEqualStrings("/a", first.path); |
| 2179 | |
| 2180 | try std.testing.expect(null == it.previous()); |
| 2181 | |
| 2182 | const second = it.next().?; |
| 2183 | try std.testing.expectEqualStrings("b", second.name); |
| 2184 | try std.testing.expectEqualStrings("/a/b", second.path); |
| 2185 | |
| 2186 | const third = it.next().?; |
| 2187 | try std.testing.expectEqualStrings("c", third.name); |
| 2188 | try std.testing.expectEqualStrings("/a/b/c", third.path); |
| 2189 | |
| 2190 | try std.testing.expect(null == it.next()); |
| 2191 | } |
| 2192 | { |
| 2193 | const last = it.last().?; |
| 2194 | try std.testing.expectEqualStrings("c", last.name); |
| 2195 | try std.testing.expectEqualStrings("/a/b/c", last.path); |
| 2196 | |
| 2197 | try std.testing.expect(null == it.next()); |
| 2198 | |
| 2199 | const second_to_last = it.previous().?; |
| 2200 | try std.testing.expectEqualStrings("b", second_to_last.name); |
| 2201 | try std.testing.expectEqualStrings("/a/b", second_to_last.path); |
| 2202 | |
| 2203 | const third_to_last = it.previous().?; |
| 2204 | try std.testing.expectEqualStrings("a", third_to_last.name); |
| 2205 | try std.testing.expectEqualStrings("/a", third_to_last.path); |
| 2206 | |
| 2207 | try std.testing.expect(null == it.previous()); |
| 2208 | } |
| 2209 | } |
| 2210 | |
| 2211 | { |
| 2212 | const path = "////a///b///c////"; |
| 2213 | var it = PosixComponentIterator.init(path); |
| 2214 | try std.testing.expectEqual(1, it.root_len); |
| 2215 | try std.testing.expectEqual(4, it.root_end_index); |
| 2216 | try std.testing.expectEqualStrings("/", it.root().?); |
| 2217 | { |
| 2218 | try std.testing.expect(null == it.previous()); |
| 2219 | |
| 2220 | const first_via_next = it.next().?; |
| 2221 | try std.testing.expectEqualStrings("a", first_via_next.name); |
| 2222 | try std.testing.expectEqualStrings("////a", first_via_next.path); |
| 2223 | |
| 2224 | const first = it.first().?; |
| 2225 | try std.testing.expectEqualStrings("a", first.name); |
| 2226 | try std.testing.expectEqualStrings("////a", first.path); |
| 2227 | |
| 2228 | try std.testing.expect(null == it.previous()); |
| 2229 | |
| 2230 | const second = it.next().?; |
| 2231 | try std.testing.expectEqualStrings("b", second.name); |
| 2232 | try std.testing.expectEqualStrings("////a///b", second.path); |
| 2233 | |
| 2234 | const third = it.next().?; |
| 2235 | try std.testing.expectEqualStrings("c", third.name); |
| 2236 | try std.testing.expectEqualStrings("////a///b///c", third.path); |
| 2237 | |
| 2238 | try std.testing.expect(null == it.next()); |
| 2239 | } |
| 2240 | { |
| 2241 | const last = it.last().?; |
| 2242 | try std.testing.expectEqualStrings("c", last.name); |
| 2243 | try std.testing.expectEqualStrings("////a///b///c", last.path); |
| 2244 | |
| 2245 | try std.testing.expect(null == it.next()); |
| 2246 | |
| 2247 | const second_to_last = it.previous().?; |
| 2248 | try std.testing.expectEqualStrings("b", second_to_last.name); |
| 2249 | try std.testing.expectEqualStrings("////a///b", second_to_last.path); |
| 2250 | |
| 2251 | const third_to_last = it.previous().?; |
| 2252 | try std.testing.expectEqualStrings("a", third_to_last.name); |
| 2253 | try std.testing.expectEqualStrings("////a", third_to_last.path); |
| 2254 | |
| 2255 | try std.testing.expect(null == it.previous()); |
| 2256 | } |
| 2257 | } |
| 2258 | |
| 2259 | { |
| 2260 | const path = "/"; |
| 2261 | var it = PosixComponentIterator.init(path); |
| 2262 | try std.testing.expectEqual(1, it.root_len); |
| 2263 | try std.testing.expectEqual(1, it.root_end_index); |
| 2264 | try std.testing.expectEqualStrings("/", it.root().?); |
| 2265 | |
| 2266 | try std.testing.expect(null == it.first()); |
| 2267 | try std.testing.expect(null == it.previous()); |
| 2268 | try std.testing.expect(null == it.first()); |
| 2269 | try std.testing.expect(null == it.next()); |
| 2270 | |
| 2271 | try std.testing.expect(null == it.last()); |
| 2272 | try std.testing.expect(null == it.previous()); |
| 2273 | try std.testing.expect(null == it.last()); |
| 2274 | try std.testing.expect(null == it.next()); |
| 2275 | } |
| 2276 | |
| 2277 | { |
| 2278 | const path = ""; |
| 2279 | var it = PosixComponentIterator.init(path); |
| 2280 | try std.testing.expectEqual(0, it.root_len); |
| 2281 | try std.testing.expectEqual(0, it.root_end_index); |
| 2282 | try std.testing.expect(null == it.root()); |
| 2283 | |
| 2284 | try std.testing.expect(null == it.first()); |
| 2285 | try std.testing.expect(null == it.previous()); |
| 2286 | try std.testing.expect(null == it.first()); |
| 2287 | try std.testing.expect(null == it.next()); |
| 2288 | |
| 2289 | try std.testing.expect(null == it.last()); |
| 2290 | try std.testing.expect(null == it.previous()); |
| 2291 | try std.testing.expect(null == it.last()); |
| 2292 | try std.testing.expect(null == it.next()); |
| 2293 | } |
| 2294 | } |
| 2295 | |
| 2296 | test "ComponentIterator windows" { |
| 2297 | const WindowsComponentIterator = ComponentIterator(.windows, u8); |
| 2298 | { |
| 2299 | const path = "a/b\\c//"; |
| 2300 | var it = WindowsComponentIterator.init(path); |
| 2301 | try std.testing.expectEqual(0, it.root_len); |
| 2302 | try std.testing.expectEqual(0, it.root_end_index); |
| 2303 | try std.testing.expect(null == it.root()); |
| 2304 | { |
| 2305 | try std.testing.expect(null == it.previous()); |
| 2306 | |
| 2307 | const first_via_next = it.next().?; |
| 2308 | try std.testing.expectEqualStrings("a", first_via_next.name); |
| 2309 | try std.testing.expectEqualStrings("a", first_via_next.path); |
| 2310 | |
| 2311 | const first = it.first().?; |
| 2312 | try std.testing.expectEqualStrings("a", first.name); |
| 2313 | try std.testing.expectEqualStrings("a", first.path); |
| 2314 | |
| 2315 | try std.testing.expect(null == it.previous()); |
| 2316 | |
| 2317 | const second = it.next().?; |
| 2318 | try std.testing.expectEqualStrings("b", second.name); |
| 2319 | try std.testing.expectEqualStrings("a/b", second.path); |
| 2320 | |
| 2321 | const third = it.next().?; |
| 2322 | try std.testing.expectEqualStrings("c", third.name); |
| 2323 | try std.testing.expectEqualStrings("a/b\\c", third.path); |
| 2324 | |
| 2325 | try std.testing.expect(null == it.next()); |
| 2326 | } |
| 2327 | { |
| 2328 | const last = it.last().?; |
| 2329 | try std.testing.expectEqualStrings("c", last.name); |
| 2330 | try std.testing.expectEqualStrings("a/b\\c", last.path); |
| 2331 | |
| 2332 | try std.testing.expect(null == it.next()); |
| 2333 | |
| 2334 | const second_to_last = it.previous().?; |
| 2335 | try std.testing.expectEqualStrings("b", second_to_last.name); |
| 2336 | try std.testing.expectEqualStrings("a/b", second_to_last.path); |
| 2337 | |
| 2338 | const third_to_last = it.previous().?; |
| 2339 | try std.testing.expectEqualStrings("a", third_to_last.name); |
| 2340 | try std.testing.expectEqualStrings("a", third_to_last.path); |
| 2341 | |
| 2342 | try std.testing.expect(null == it.previous()); |
| 2343 | } |
| 2344 | } |
| 2345 | |
| 2346 | { |
| 2347 | const path = "C:\\a/b/c/"; |
| 2348 | var it = WindowsComponentIterator.init(path); |
| 2349 | try std.testing.expectEqual(3, it.root_len); |
| 2350 | try std.testing.expectEqual(3, it.root_end_index); |
| 2351 | try std.testing.expectEqualStrings("C:\\", it.root().?); |
| 2352 | { |
| 2353 | const first = it.first().?; |
| 2354 | try std.testing.expectEqualStrings("a", first.name); |
| 2355 | try std.testing.expectEqualStrings("C:\\a", first.path); |
| 2356 | |
| 2357 | const second = it.next().?; |
| 2358 | try std.testing.expectEqualStrings("b", second.name); |
| 2359 | try std.testing.expectEqualStrings("C:\\a/b", second.path); |
| 2360 | |
| 2361 | const third = it.next().?; |
| 2362 | try std.testing.expectEqualStrings("c", third.name); |
| 2363 | try std.testing.expectEqualStrings("C:\\a/b/c", third.path); |
| 2364 | |
| 2365 | try std.testing.expect(null == it.next()); |
| 2366 | } |
| 2367 | { |
| 2368 | const last = it.last().?; |
| 2369 | try std.testing.expectEqualStrings("c", last.name); |
| 2370 | try std.testing.expectEqualStrings("C:\\a/b/c", last.path); |
| 2371 | |
| 2372 | const second_to_last = it.previous().?; |
| 2373 | try std.testing.expectEqualStrings("b", second_to_last.name); |
| 2374 | try std.testing.expectEqualStrings("C:\\a/b", second_to_last.path); |
| 2375 | |
| 2376 | const third_to_last = it.previous().?; |
| 2377 | try std.testing.expectEqualStrings("a", third_to_last.name); |
| 2378 | try std.testing.expectEqualStrings("C:\\a", third_to_last.path); |
| 2379 | |
| 2380 | try std.testing.expect(null == it.previous()); |
| 2381 | } |
| 2382 | } |
| 2383 | |
| 2384 | { |
| 2385 | const path = "C:\\\\//a/\\/\\b///c////"; |
| 2386 | var it = WindowsComponentIterator.init(path); |
| 2387 | try std.testing.expectEqual(3, it.root_len); |
| 2388 | try std.testing.expectEqual(6, it.root_end_index); |
| 2389 | try std.testing.expectEqualStrings("C:\\", it.root().?); |
| 2390 | { |
| 2391 | const first = it.first().?; |
| 2392 | try std.testing.expectEqualStrings("a", first.name); |
| 2393 | try std.testing.expectEqualStrings("C:\\\\//a", first.path); |
| 2394 | |
| 2395 | const second = it.next().?; |
| 2396 | try std.testing.expectEqualStrings("b", second.name); |
| 2397 | try std.testing.expectEqualStrings("C:\\\\//a/\\/\\b", second.path); |
| 2398 | |
| 2399 | const third = it.next().?; |
| 2400 | try std.testing.expectEqualStrings("c", third.name); |
| 2401 | try std.testing.expectEqualStrings("C:\\\\//a/\\/\\b///c", third.path); |
| 2402 | |
| 2403 | try std.testing.expect(null == it.next()); |
| 2404 | } |
| 2405 | { |
| 2406 | const last = it.last().?; |
| 2407 | try std.testing.expectEqualStrings("c", last.name); |
| 2408 | try std.testing.expectEqualStrings("C:\\\\//a/\\/\\b///c", last.path); |
| 2409 | |
| 2410 | const second_to_last = it.previous().?; |
| 2411 | try std.testing.expectEqualStrings("b", second_to_last.name); |
| 2412 | try std.testing.expectEqualStrings("C:\\\\//a/\\/\\b", second_to_last.path); |
| 2413 | |
| 2414 | const third_to_last = it.previous().?; |
| 2415 | try std.testing.expectEqualStrings("a", third_to_last.name); |
| 2416 | try std.testing.expectEqualStrings("C:\\\\//a", third_to_last.path); |
| 2417 | |
| 2418 | try std.testing.expect(null == it.previous()); |
| 2419 | } |
| 2420 | } |
| 2421 | |
| 2422 | { |
| 2423 | const path = "/"; |
| 2424 | var it = WindowsComponentIterator.init(path); |
| 2425 | try std.testing.expectEqual(1, it.root_len); |
| 2426 | try std.testing.expectEqual(1, it.root_end_index); |
| 2427 | try std.testing.expectEqualStrings("/", it.root().?); |
| 2428 | |
| 2429 | try std.testing.expect(null == it.first()); |
| 2430 | try std.testing.expect(null == it.previous()); |
| 2431 | try std.testing.expect(null == it.first()); |
| 2432 | try std.testing.expect(null == it.next()); |
| 2433 | |
| 2434 | try std.testing.expect(null == it.last()); |
| 2435 | try std.testing.expect(null == it.previous()); |
| 2436 | try std.testing.expect(null == it.last()); |
| 2437 | try std.testing.expect(null == it.next()); |
| 2438 | } |
| 2439 | |
| 2440 | { |
| 2441 | const path = ""; |
| 2442 | var it = WindowsComponentIterator.init(path); |
| 2443 | try std.testing.expectEqual(0, it.root_len); |
| 2444 | try std.testing.expectEqual(0, it.root_end_index); |
| 2445 | try std.testing.expect(null == it.root()); |
| 2446 | |
| 2447 | try std.testing.expect(null == it.first()); |
| 2448 | try std.testing.expect(null == it.previous()); |
| 2449 | try std.testing.expect(null == it.first()); |
| 2450 | try std.testing.expect(null == it.next()); |
| 2451 | |
| 2452 | try std.testing.expect(null == it.last()); |
| 2453 | try std.testing.expect(null == it.previous()); |
| 2454 | try std.testing.expect(null == it.last()); |
| 2455 | try std.testing.expect(null == it.next()); |
| 2456 | } |
| 2457 | } |
| 2458 | |
| 2459 | test "ComponentIterator windows WTF-16" { |
| 2460 | const WindowsComponentIterator = ComponentIterator(.windows, u16); |
| 2461 | const L = std.unicode.utf8ToUtf16LeStringLiteral; |
| 2462 | |
| 2463 | const path = L("C:\\a/b/c/"); |
| 2464 | var it = WindowsComponentIterator.init(path); |
| 2465 | try std.testing.expectEqual(3, it.root_len); |
| 2466 | try std.testing.expectEqual(3, it.root_end_index); |
| 2467 | try std.testing.expectEqualSlices(u16, L("C:\\"), it.root().?); |
| 2468 | { |
| 2469 | const first = it.first().?; |
| 2470 | try std.testing.expectEqualSlices(u16, L("a"), first.name); |
| 2471 | try std.testing.expectEqualSlices(u16, L("C:\\a"), first.path); |
| 2472 | |
| 2473 | const second = it.next().?; |
| 2474 | try std.testing.expectEqualSlices(u16, L("b"), second.name); |
| 2475 | try std.testing.expectEqualSlices(u16, L("C:\\a/b"), second.path); |
| 2476 | |
| 2477 | const third = it.next().?; |
| 2478 | try std.testing.expectEqualSlices(u16, L("c"), third.name); |
| 2479 | try std.testing.expectEqualSlices(u16, L("C:\\a/b/c"), third.path); |
| 2480 | |
| 2481 | try std.testing.expect(null == it.next()); |
| 2482 | } |
| 2483 | { |
| 2484 | const last = it.last().?; |
| 2485 | try std.testing.expectEqualSlices(u16, L("c"), last.name); |
| 2486 | try std.testing.expectEqualSlices(u16, L("C:\\a/b/c"), last.path); |
| 2487 | |
| 2488 | const second_to_last = it.previous().?; |
| 2489 | try std.testing.expectEqualSlices(u16, L("b"), second_to_last.name); |
| 2490 | try std.testing.expectEqualSlices(u16, L("C:\\a/b"), second_to_last.path); |
| 2491 | |
| 2492 | const third_to_last = it.previous().?; |
| 2493 | try std.testing.expectEqualSlices(u16, L("a"), third_to_last.name); |
| 2494 | try std.testing.expectEqualSlices(u16, L("C:\\a"), third_to_last.path); |
| 2495 | |
| 2496 | try std.testing.expect(null == it.previous()); |
| 2497 | } |
| 2498 | } |
| 2499 | |
| 2500 | test "ComponentIterator roots" { |
| 2501 | // UEFI |
| 2502 | { |
| 2503 | var it = ComponentIterator(.uefi, u8).init("\\\\a"); |
| 2504 | try std.testing.expectEqualStrings("\\", it.root().?); |
| 2505 | |
| 2506 | it = ComponentIterator(.uefi, u8).init("//a"); |
| 2507 | try std.testing.expect(null == it.root()); |
| 2508 | } |
| 2509 | // POSIX |
| 2510 | { |
| 2511 | var it = ComponentIterator(.posix, u8).init("//a"); |
| 2512 | try std.testing.expectEqualStrings("/", it.root().?); |
| 2513 | |
| 2514 | it = ComponentIterator(.posix, u8).init("\\\\a"); |
| 2515 | try std.testing.expect(null == it.root()); |
| 2516 | } |
| 2517 | // Windows |
| 2518 | { |
| 2519 | // Drive relative |
| 2520 | var it = ComponentIterator(.windows, u8).init("C:a"); |
| 2521 | try std.testing.expectEqualStrings("C:", it.root().?); |
| 2522 | |
| 2523 | // Drive absolute |
| 2524 | it = ComponentIterator(.windows, u8).init("C:/a"); |
| 2525 | try std.testing.expectEqualStrings("C:/", it.root().?); |
| 2526 | it = ComponentIterator(.windows, u8).init("C:\\a"); |
| 2527 | try std.testing.expectEqualStrings("C:\\", it.root().?); |
| 2528 | it = ComponentIterator(.windows, u8).init("C:///a"); |
| 2529 | try std.testing.expectEqualStrings("C:/", it.root().?); |
| 2530 | |
| 2531 | // Rooted |
| 2532 | it = ComponentIterator(.windows, u8).init("\\a"); |
| 2533 | try std.testing.expectEqualStrings("\\", it.root().?); |
| 2534 | it = ComponentIterator(.windows, u8).init("/a"); |
| 2535 | try std.testing.expectEqualStrings("/", it.root().?); |
| 2536 | |
| 2537 | // Root local device |
| 2538 | it = ComponentIterator(.windows, u8).init("\\\\."); |
| 2539 | try std.testing.expectEqualStrings("\\\\.", it.root().?); |
| 2540 | it = ComponentIterator(.windows, u8).init("//?"); |
| 2541 | try std.testing.expectEqualStrings("//?", it.root().?); |
| 2542 | |
| 2543 | // UNC absolute |
| 2544 | it = ComponentIterator(.windows, u8).init("//"); |
| 2545 | try std.testing.expectEqualStrings("//", it.root().?); |
| 2546 | it = ComponentIterator(.windows, u8).init("\\\\a"); |
| 2547 | try std.testing.expectEqualStrings("\\\\a", it.root().?); |
| 2548 | it = ComponentIterator(.windows, u8).init("\\\\a\\b\\\\c"); |
| 2549 | try std.testing.expectEqualStrings("\\\\a\\b\\", it.root().?); |
| 2550 | it = ComponentIterator(.windows, u8).init("//a"); |
| 2551 | try std.testing.expectEqualStrings("//a", it.root().?); |
| 2552 | it = ComponentIterator(.windows, u8).init("//a/b//c"); |
| 2553 | try std.testing.expectEqualStrings("//a/b/", it.root().?); |
| 2554 | // Malformed UNC path with empty server name |
| 2555 | it = ComponentIterator(.windows, u8).init("\\\\\\a\\b\\c"); |
| 2556 | try std.testing.expectEqualStrings("\\\\\\a\\", it.root().?); |
| 2557 | } |
| 2558 | } |
| 2559 | |
| 2560 | /// Format a path encoded as bytes for display as UTF-8. |
| 2561 | /// Returns a Formatter for the given path. The path will be converted to valid UTF-8 |
| 2562 | /// during formatting. This is a lossy conversion if the path contains any ill-formed UTF-8. |
| 2563 | /// Ill-formed UTF-8 byte sequences are replaced by the replacement character (U+FFFD) |
| 2564 | /// according to "U+FFFD Substitution of Maximal Subparts" from Chapter 3 of |
| 2565 | /// the Unicode standard, and as specified by https://encoding.spec.whatwg.org/#utf-8-decoder |
| 2566 | pub const fmtAsUtf8Lossy = std.unicode.fmtUtf8; |
| 2567 | |
| 2568 | /// Format a path encoded as WTF-16 LE for display as UTF-8. |
| 2569 | /// Return a Formatter for a (potentially ill-formed) UTF-16 LE path. |
| 2570 | /// The path will be converted to valid UTF-8 during formatting. This is |
| 2571 | /// a lossy conversion if the path contains any unpaired surrogates. |
| 2572 | /// Unpaired surrogates are replaced by the replacement character (U+FFFD). |
| 2573 | pub const fmtWtf16LeAsUtf8Lossy = std.unicode.fmtUtf16Le; |
| 2574 | |
| 2575 | /// Similar to `RTL_PATH_TYPE`, but without the `UNKNOWN` path type. |
| 2576 | pub const Win32PathType = enum { |
| 2577 | /// `\\server\share\foo` |
| 2578 | unc_absolute, |
| 2579 | /// `C:\foo` |
| 2580 | drive_absolute, |
| 2581 | /// `C:foo` |
| 2582 | drive_relative, |
| 2583 | /// `\foo` |
| 2584 | rooted, |
| 2585 | /// `foo` |
| 2586 | relative, |
| 2587 | /// `\\.\foo`, `\\?\foo` |
| 2588 | local_device, |
| 2589 | /// `\\.`, `\\?` |
| 2590 | root_local_device, |
| 2591 | }; |
| 2592 | |
| 2593 | /// Get the path type of a Win32 namespace path. |
| 2594 | /// Similar to `RtlDetermineDosPathNameType_U`. |
| 2595 | /// If `T` is `u16`, then `path` should be encoded as WTF-16LE. |
| 2596 | pub fn getWin32PathType(comptime T: type, path: []const T) Win32PathType { |
| 2597 | if (path.len < 1) return .relative; |
| 2598 | |
| 2599 | const windows_path = std.fs.path.PathType.windows; |
| 2600 | if (windows_path.isSep(T, path[0])) { |
| 2601 | // \x |
| 2602 | if (path.len < 2 or !windows_path.isSep(T, path[1])) return .rooted; |
| 2603 | // \\. or \\? |
| 2604 | if (path.len > 2 and (path[2] == mem.nativeToLittle(T, '.') or path[2] == mem.nativeToLittle(T, '?'))) { |
| 2605 | // exactly \\. or \\? with nothing trailing |
| 2606 | if (path.len == 3) return .root_local_device; |
| 2607 | // \\.\x or \\?\x |
| 2608 | if (windows_path.isSep(T, path[3])) return .local_device; |
| 2609 | } |
| 2610 | // \\x |
| 2611 | return .unc_absolute; |
| 2612 | } else { |
| 2613 | // Some choice has to be made about how non-ASCII code points as drive-letters are handled, since |
| 2614 | // path[0] is a different size for WTF-16 vs WTF-8, leading to a potential mismatch in classification |
| 2615 | // for a WTF-8 path and its WTF-16 equivalent. For example, `€:\` encoded in WTF-16 is three code |
| 2616 | // units `<0x20AC>:\` whereas `€:\` encoded as WTF-8 is 6 code units `<0xE2><0x82><0xAC>:\` so |
| 2617 | // checking path[0], path[1] and path[2] would not behave the same between WTF-8/WTF-16. |
| 2618 | // |
| 2619 | // `RtlDetermineDosPathNameType_U` exclusively deals with WTF-16 and considers |
| 2620 | // `€:\` a drive-absolute path, but code points that take two WTF-16 code units to encode get |
| 2621 | // classified as a relative path (e.g. with U+20000 as the drive-letter that'd be encoded |
| 2622 | // in WTF-16 as `<0xD840><0xDC00>:\` and be considered a relative path). |
| 2623 | // |
| 2624 | // The choice made here is to emulate the behavior of `RtlDetermineDosPathNameType_U` for both |
| 2625 | // WTF-16 and WTF-8. This is because, while unlikely and not supported by the Disk Manager GUI, |
| 2626 | // drive letters are not actually restricted to A-Z. Using `SetVolumeMountPointW` will allow you |
| 2627 | // to set any byte value as a drive letter, and going through `IOCTL_MOUNTMGR_CREATE_POINT` will |
| 2628 | // allow you to set any WTF-16 code unit as a drive letter. |
| 2629 | // |
| 2630 | // Non-A-Z drive letters don't interact well with most of Windows, but certain things do work, e.g. |
| 2631 | // `cd /D €:\` will work, filesystem functions still work, etc. |
| 2632 | // |
| 2633 | // The unfortunate part of this is that this makes handling WTF-8 more complicated as we can't |
| 2634 | // just check path[0], path[1], path[2]. |
| 2635 | const colon_i: usize = switch (T) { |
| 2636 | u8 => i: { |
| 2637 | const code_point_len = std.unicode.utf8ByteSequenceLength(path[0]) catch return .relative; |
| 2638 | // Conveniently, 4-byte sequences in WTF-8 have the same starting code point |
| 2639 | // as 2-code-unit sequences in WTF-16. |
| 2640 | if (code_point_len > 3) return .relative; |
| 2641 | break :i code_point_len; |
| 2642 | }, |
| 2643 | u16 => 1, |
| 2644 | else => @compileError("unsupported type: " ++ @typeName(T)), |
| 2645 | }; |
| 2646 | // x |
| 2647 | if (path.len < colon_i + 1 or path[colon_i] != mem.nativeToLittle(T, ':')) return .relative; |
| 2648 | // x:\ |
| 2649 | if (path.len > colon_i + 1 and windows_path.isSep(T, path[colon_i + 1])) return .drive_absolute; |
| 2650 | // x: |
| 2651 | return .drive_relative; |
| 2652 | } |
| 2653 | } |
| 2654 | |
| 2655 | test getWin32PathType { |
| 2656 | try std.testing.expectEqual(.relative, getWin32PathType(u8, "")); |
| 2657 | try std.testing.expectEqual(.relative, getWin32PathType(u8, "x")); |
| 2658 | try std.testing.expectEqual(.relative, getWin32PathType(u8, "x\\")); |
| 2659 | |
| 2660 | try std.testing.expectEqual(.root_local_device, getWin32PathType(u8, "//.")); |
| 2661 | try std.testing.expectEqual(.root_local_device, getWin32PathType(u8, "/\\?")); |
| 2662 | try std.testing.expectEqual(.root_local_device, getWin32PathType(u8, "\\\\?")); |
| 2663 | |
| 2664 | try std.testing.expectEqual(.local_device, getWin32PathType(u8, "//./x")); |
| 2665 | try std.testing.expectEqual(.local_device, getWin32PathType(u8, "/\\?\\x")); |
| 2666 | try std.testing.expectEqual(.local_device, getWin32PathType(u8, "\\\\?\\x")); |
| 2667 | // local device paths require a path separator after the root, otherwise it is considered a UNC path |
| 2668 | try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "\\\\?x")); |
| 2669 | try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "//.x")); |
| 2670 | |
| 2671 | try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "//")); |
| 2672 | try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "\\\\x")); |
| 2673 | try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "//x")); |
| 2674 | |
| 2675 | try std.testing.expectEqual(.rooted, getWin32PathType(u8, "\\x")); |
| 2676 | try std.testing.expectEqual(.rooted, getWin32PathType(u8, "/")); |
| 2677 | |
| 2678 | try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "x:")); |
| 2679 | try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "x:abc")); |
| 2680 | try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "x:a/b/c")); |
| 2681 | |
| 2682 | try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "x:\\")); |
| 2683 | try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "x:\\abc")); |
| 2684 | try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "x:/a/b/c")); |
| 2685 | |
| 2686 | // Non-ASCII code point that is encoded as one WTF-16 code unit is considered a valid drive letter |
| 2687 | try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "€:\\")); |
| 2688 | try std.testing.expectEqual(.drive_absolute, getWin32PathType(u16, std.unicode.wtf8ToWtf16LeStringLiteral("€:\\"))); |
| 2689 | try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "€:")); |
| 2690 | try std.testing.expectEqual(.drive_relative, getWin32PathType(u16, std.unicode.wtf8ToWtf16LeStringLiteral("€:"))); |
| 2691 | // But code points that are encoded as two WTF-16 code units are not |
| 2692 | try std.testing.expectEqual(.relative, getWin32PathType(u8, "\u{10000}:\\")); |
| 2693 | try std.testing.expectEqual(.relative, getWin32PathType(u16, std.unicode.wtf8ToWtf16LeStringLiteral("\u{10000}:\\"))); |
| 2694 | } |