Commit 8cab0762d8

Jan Philipp Hafer <jan.hafer@rwth-aachen.de>
2022-05-28 05:06:32
place zig-cache directory next to build.zig
* search upwards, if no build.zig is found * if this fails or any error occurs, fallback to global zig-cache Closes #11672
1 parent 3250b20
Changed files (1)
src/main.zig
@@ -2825,13 +2825,28 @@ fn buildOutputType(
             break :l global_cache_directory;
         }
         if (main_pkg) |pkg| {
-            const cache_dir_path = try pkg.root_src_directory.join(arena, &[_][]const u8{"zig-cache"});
-            const dir = try pkg.root_src_directory.handle.makeOpenPath("zig-cache", .{});
-            cleanup_local_cache_dir = dir;
-            break :l .{
-                .handle = dir,
-                .path = cache_dir_path,
-            };
+            // search upwards from cwd until we find directory with build.zig
+            const cwd_path = try process.getCwdAlloc(arena);
+            const build_zig = "build.zig";
+            const zig_cache = "zig-cache";
+            var dirname: []const u8 = cwd_path;
+            while (true) {
+                const joined_path = try fs.path.join(arena, &[_][]const u8{ dirname, build_zig });
+                if (fs.cwd().access(joined_path, .{})) |_| {
+                    const cache_dir_path = try fs.path.join(arena, &[_][]const u8{ dirname, zig_cache });
+                    const dir = try pkg.root_src_directory.handle.makeOpenPath(cache_dir_path, .{});
+                    cleanup_local_cache_dir = dir;
+                    break :l .{ .handle = dir, .path = cache_dir_path };
+                } else |err| switch (err) {
+                    error.FileNotFound => {
+                        dirname = fs.path.dirname(dirname) orelse {
+                            break :l global_cache_directory;
+                        };
+                        continue;
+                    },
+                    else => break :l global_cache_directory,
+                }
+            }
         }
         // Otherwise we really don't have a reasonable place to put the local cache directory,
         // so we utilize the global one.