Skip to content

Commit f7d6006

Browse files
committed
CLI: improved local cache directory logic
Previously, when choosing the local cache directory, if there was no root source file, an explicitly chosen path, or other clues, zig would choose cwd + zig-cache/ as the local cache directory. This can be problematic if Zig is invoked with the CWD set to a read-only directory, or a directory unrelated to the actual source files being compiled. In the real world, we see this when using `zig cc` with CGo, which for some reason changes the current working directory to the read-only go standard library path before running the C compiler. This commit conservatively chooses to use the global cache directory as the local cache directory when there is no other reasonable choice, and no longer will rely on the cwd path to choose a local cache directory. As a reminder, the --cache-dir CLI flag and ZIG_LOCAL_CACHE_DIR environment variable are available for overriding the decision. For the zig build system, it will always choose the directory that build.zig is + zig-cache/. Closes #7342
1 parent 26399b5 commit f7d6006

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed

src/main.zig

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1656,21 +1656,18 @@ fn buildOutputType(
16561656
if (arg_mode == .run) {
16571657
break :l global_cache_directory;
16581658
}
1659-
const cache_dir_path = blk: {
1660-
if (root_pkg) |pkg| {
1661-
if (pkg.root_src_directory.path) |p| {
1662-
break :blk try fs.path.join(arena, &[_][]const u8{ p, "zig-cache" });
1663-
}
1664-
}
1665-
break :blk "zig-cache";
1666-
};
1667-
const cache_parent_dir = if (root_pkg) |pkg| pkg.root_src_directory.handle else fs.cwd();
1668-
const dir = try cache_parent_dir.makeOpenPath("zig-cache", .{});
1669-
cleanup_local_cache_dir = dir;
1670-
break :l .{
1671-
.handle = dir,
1672-
.path = cache_dir_path,
1673-
};
1659+
if (root_pkg) |pkg| {
1660+
const cache_dir_path = try pkg.root_src_directory.join(arena, &[_][]const u8{"zig-cache"});
1661+
const dir = try pkg.root_src_directory.handle.makeOpenPath("zig-cache", .{});
1662+
cleanup_local_cache_dir = dir;
1663+
break :l .{
1664+
.handle = dir,
1665+
.path = cache_dir_path,
1666+
};
1667+
}
1668+
// Otherwise we really don't have a reasonable place to put the local cache directory,
1669+
// so we utilize the global one.
1670+
break :l global_cache_directory;
16741671
};
16751672

16761673
if (build_options.have_llvm and emit_asm != .no) {

0 commit comments

Comments
 (0)