Skip to content

fmt: Fix relative paths with . and .. on Windows #4655

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions src-self-hosted/stage2.zig
Original file line number Diff line number Diff line change
Expand Up @@ -315,11 +315,18 @@ const FmtError = error{
} || fs.File.OpenError;

fn fmtPath(fmt: *Fmt, file_path: []const u8, check_mode: bool) FmtError!void {
if (fmt.seen.exists(file_path)) return;
try fmt.seen.put(file_path);
// get the real path here to avoid Windows failing on relative file paths with . or .. in them
var real_path = fs.realpathAlloc(fmt.allocator, file_path) catch |err| {
try stderr.print("unable to open '{}': {}\n", .{ file_path, err });
fmt.any_error = true;
return;
};
defer fmt.allocator.free(real_path);

if (fmt.seen.exists(real_path)) return;
try fmt.seen.put(real_path);

const max = std.math.maxInt(usize);
const source_code = fs.cwd().readFileAlloc(fmt.allocator, file_path, max) catch |err| switch (err) {
const source_code = fs.cwd().readFileAlloc(fmt.allocator, real_path, self_hosted_main.max_src_size) catch |err| switch (err) {
error.IsDir, error.AccessDenied => {
// TODO make event based (and dir.next())
var dir = try fs.cwd().openDir(file_path, .{ .iterate = true });
Expand All @@ -329,7 +336,7 @@ fn fmtPath(fmt: *Fmt, file_path: []const u8, check_mode: bool) FmtError!void {

while (try dir_it.next()) |entry| {
if (entry.kind == .Directory or mem.endsWith(u8, entry.name, ".zig")) {
const full_path = try fs.path.join(fmt.allocator, &[_][]const u8{ file_path, entry.name });
const full_path = try fs.path.join(fmt.allocator, &[_][]const u8{ real_path, entry.name });
try fmtPath(fmt, full_path, check_mode);
}
}
Expand Down Expand Up @@ -367,7 +374,7 @@ fn fmtPath(fmt: *Fmt, file_path: []const u8, check_mode: bool) FmtError!void {
fmt.any_error = true;
}
} else {
const baf = try io.BufferedAtomicFile.create(fmt.allocator, file_path);
const baf = try io.BufferedAtomicFile.create(fmt.allocator, real_path);
defer baf.destroy();

const anything_changed = try std.zig.render(fmt.allocator, baf.stream(), tree);
Expand Down