authorgravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2023-12-24 04:45:53-08:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2024-01-04 17:34:34+02:00
log0527cab71bac6067ceae6a1fb0a0f401a5027607
tree025db0799e40c1489ce51f68fc28b60d14c45718
parent9a1608509300fcdf118d82063bbf1481a10ca551

Use `std.fs.path.relative` for `@import` and `@embedFile` sub paths

Fixes edge cases where the `startsWith` that was used previously would return a false positive on a resolved path like `foo.zig` when the resolved root was `foo`. Before this commit, such a path would be treated as a sub path of 'foo' with a resolved sub file path of 'zig' (and the `.` would be assumed to be a path separator). After this commit, `foo.zig` will be correctly treated as outside of the root of `foo`. Closes #18355

1 files changed, 10 insertions(+), 18 deletions(-)

src/Module.zig+10-18
......@@ -3939,15 +3939,11 @@ pub fn importFile(
39393939 defer gpa.free(resolved_root_path);
39403940
39413941 const sub_file_path = p: {
3942 if (mem.startsWith(u8, resolved_path, resolved_root_path)) {
3943 // +1 for the directory separator here.
3944 break :p try gpa.dupe(u8, resolved_path[resolved_root_path.len + 1 ..]);
3945 }
3946 if (mem.eql(u8, resolved_root_path, ".") and
3947 !isUpDir(resolved_path) and
3948 !std.fs.path.isAbsolute(resolved_path))
3949 {
3950 break :p try gpa.dupe(u8, resolved_path);
3942 const relative = try std.fs.path.relative(gpa, resolved_root_path, resolved_path);
3943 errdefer gpa.free(relative);
3944
3945 if (!isUpDir(relative) and !std.fs.path.isAbsolute(relative)) {
3946 break :p relative;
39513947 }
39523948 return error.ImportOutsideModulePath;
39533949 };
......@@ -4038,15 +4034,11 @@ pub fn embedFile(
40384034 defer gpa.free(resolved_root_path);
40394035
40404036 const sub_file_path = p: {
4041 if (mem.startsWith(u8, resolved_path, resolved_root_path)) {
4042 // +1 for the directory separator here.
4043 break :p try gpa.dupe(u8, resolved_path[resolved_root_path.len + 1 ..]);
4044 }
4045 if (mem.eql(u8, resolved_root_path, ".") and
4046 !isUpDir(resolved_path) and
4047 !std.fs.path.isAbsolute(resolved_path))
4048 {
4049 break :p try gpa.dupe(u8, resolved_path);
4037 const relative = try std.fs.path.relative(gpa, resolved_root_path, resolved_path);
4038 errdefer gpa.free(relative);
4039
4040 if (!isUpDir(relative) and !std.fs.path.isAbsolute(relative)) {
4041 break :p relative;
40504042 }
40514043 return error.ImportOutsideModulePath;
40524044 };