diff options
Diffstat (limited to 'src/install')
-rw-r--r-- | src/install/bin.zig | 24 | ||||
-rw-r--r-- | src/install/bit_set.zig | 28 | ||||
-rw-r--r-- | src/install/dependency.zig | 28 | ||||
-rw-r--r-- | src/install/extract_tarball.zig | 12 | ||||
-rw-r--r-- | src/install/install.zig | 326 | ||||
-rw-r--r-- | src/install/integrity.zig | 8 | ||||
-rw-r--r-- | src/install/lockfile.zig | 30 | ||||
-rw-r--r-- | src/install/npm.zig | 57 | ||||
-rw-r--r-- | src/install/resolution.zig | 6 | ||||
-rw-r--r-- | src/install/resolvers/folder_resolver.zig | 2 | ||||
-rw-r--r-- | src/install/semver.zig | 8 | ||||
-rw-r--r-- | src/install/versioned_url.zig | 46 |
12 files changed, 293 insertions, 282 deletions
diff --git a/src/install/bin.zig b/src/install/bin.zig index fd2220abc..c7c3b3799 100644 --- a/src/install/bin.zig +++ b/src/install/bin.zig @@ -18,7 +18,7 @@ const bun = @import("bun"); /// - map where keys are names of the binaries and values are file paths to the binaries pub const Bin = extern struct { tag: Tag = Tag.none, - value: Value = Value{ .none = .{} }, + value: Value = Value{ .none = {} }, pub fn count(this: Bin, buf: []const u8, extern_strings: []const ExternalString, comptime StringBuilder: type, builder: StringBuilder) u32 { switch (this.tag) { @@ -42,7 +42,7 @@ pub const Bin = extern struct { pub fn clone(this: Bin, buf: []const u8, prev_external_strings: []const ExternalString, all_extern_strings: []ExternalString, extern_strings_slice: []ExternalString, comptime StringBuilder: type, builder: StringBuilder) Bin { return switch (this.tag) { - .none => Bin{ .tag = .none, .value = .{ .none = .{} } }, + .none => Bin{ .tag = .none, .value = .{ .none = {} } }, .file => Bin{ .tag = .file, .value = .{ .file = builder.append(String, this.value.file.slice(buf)) }, @@ -146,7 +146,7 @@ pub const Bin = extern struct { bin: Bin, i: usize = 0, done: bool = false, - dir_iterator: ?std.fs.Dir.Iterator = null, + dir_iterator: ?std.fs.IterableDir.Iterator = null, package_name: String, package_installed_node_modules: std.fs.Dir = std.fs.Dir{ .fd = std.math.maxInt(std.os.fd_t) }, buf: [bun.MAX_PATH_BYTES]u8 = undefined, @@ -167,7 +167,7 @@ pub const Bin = extern struct { var joined = Path.joinStringBuf(&this.buf, &parts, .auto); this.buf[joined.len] = 0; var joined_: [:0]u8 = this.buf[0..joined.len :0]; - var child_dir = try dir.openDirZ(joined_, .{ .iterate = true }); + var child_dir = try bun.openDir(dir, joined_); this.dir_iterator = child_dir.iterate(); } @@ -419,7 +419,7 @@ pub const Bin = extern struct { var joined = Path.joinStringBuf(&target_buf, &parts, .auto); @intToPtr([*]u8, @ptrToInt(joined.ptr))[joined.len] = 0; var joined_: [:0]const u8 = joined.ptr[0..joined.len :0]; - var child_dir = dir.openDirZ(joined_, .{ .iterate = true }) catch |err| { + var child_dir = bun.openDir(dir, joined_) catch |err| { this.err = err; return; }; @@ -427,7 +427,7 @@ pub const Bin = extern struct { var iter = child_dir.iterate(); - var basedir_path = std.os.getFdPath(child_dir.fd, &target_buf) catch |err| { + var basedir_path = std.os.getFdPath(child_dir.dir.fd, &target_buf) catch |err| { this.err = err; return; }; @@ -436,9 +436,9 @@ pub const Bin = extern struct { var prev_target_buf_remain = target_buf_remain; while (iter.next() catch null) |entry_| { - const entry: std.fs.Dir.Entry = entry_; + const entry: std.fs.IterableDir.Entry = entry_; switch (entry.kind) { - std.fs.Dir.Entry.Kind.SymLink, std.fs.Dir.Entry.Kind.File => { + std.fs.IterableDir.Entry.Kind.SymLink, std.fs.IterableDir.Entry.Kind.File => { target_buf_remain = prev_target_buf_remain; std.mem.copy(u8, target_buf_remain, entry.name); target_buf_remain = target_buf_remain[entry.name.len..]; @@ -571,7 +571,7 @@ pub const Bin = extern struct { var joined = Path.joinStringBuf(&target_buf, &parts, .auto); @intToPtr([*]u8, @ptrToInt(joined.ptr))[joined.len] = 0; var joined_: [:0]const u8 = joined.ptr[0..joined.len :0]; - var child_dir = dir.openDirZ(joined_, .{ .iterate = true }) catch |err| { + var child_dir = bun.openDir(dir, joined_) catch |err| { this.err = err; return; }; @@ -579,7 +579,7 @@ pub const Bin = extern struct { var iter = child_dir.iterate(); - var basedir_path = std.os.getFdPath(child_dir.fd, &target_buf) catch |err| { + var basedir_path = std.os.getFdPath(child_dir.dir.fd, &target_buf) catch |err| { this.err = err; return; }; @@ -588,9 +588,9 @@ pub const Bin = extern struct { var prev_target_buf_remain = target_buf_remain; while (iter.next() catch null) |entry_| { - const entry: std.fs.Dir.Entry = entry_; + const entry: std.fs.IterableDir.Entry = entry_; switch (entry.kind) { - std.fs.Dir.Entry.Kind.SymLink, std.fs.Dir.Entry.Kind.File => { + std.fs.IterableDir.Entry.Kind.SymLink, std.fs.IterableDir.Entry.Kind.File => { target_buf_remain = prev_target_buf_remain; std.mem.copy(u8, target_buf_remain, entry.name); target_buf_remain = target_buf_remain[entry.name.len..]; diff --git a/src/install/bit_set.zig b/src/install/bit_set.zig index 64903c9e9..b9f63e2ab 100644 --- a/src/install/bit_set.zig +++ b/src/install/bit_set.zig @@ -91,7 +91,7 @@ pub fn IntegerBitSet(comptime size: u16) type { /// Returns the total number of set bits in this bit set. pub fn count(self: Self) usize { - return @popCount(MaskInt, self.mask); + return @popCount(self.mask); } /// Changes the value of the specified bit of the bit @@ -154,7 +154,7 @@ pub fn IntegerBitSet(comptime size: u16) type { pub fn findFirstSet(self: Self) ?usize { const mask = self.mask; if (mask == 0) return null; - return @ctz(MaskInt, mask); + return @ctz(mask); } /// Finds the index of the first set bit, and unsets it. @@ -162,7 +162,7 @@ pub fn IntegerBitSet(comptime size: u16) type { pub fn toggleFirstSet(self: *Self) ?usize { const mask = self.mask; if (mask == 0) return null; - const index = @ctz(MaskInt, mask); + const index = @ctz(mask); self.mask = mask & (mask - 1); return index; } @@ -197,12 +197,12 @@ pub fn IntegerBitSet(comptime size: u16) type { switch (direction) { .forward => { - const next_index = @ctz(MaskInt, self.bits_remain); + const next_index = @ctz(self.bits_remain); self.bits_remain &= self.bits_remain - 1; return next_index; }, .reverse => { - const leading_zeroes = @clz(MaskInt, self.bits_remain); + const leading_zeroes = @clz(self.bits_remain); const top_bit = (@bitSizeOf(MaskInt) - 1) - leading_zeroes; self.bits_remain &= (@as(MaskInt, 1) << @intCast(ShiftInt, top_bit)) - 1; return top_bit; @@ -227,7 +227,7 @@ pub fn IntegerBitSet(comptime size: u16) type { /// This set is good for sets with a larger size, but may use /// more bytes than necessary if your set is small. pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type { - const mask_info: std.builtin.TypeInfo = @typeInfo(MaskIntType); + const mask_info: std.builtin.Type = @typeInfo(MaskIntType); // Make sure the mask int is indeed an int if (mask_info != .Int) @compileError("ArrayBitSet can only operate on integer masks, but was passed " ++ @typeName(MaskIntType)); @@ -322,7 +322,7 @@ pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type { pub fn count(self: Self) usize { var total: usize = 0; for (self.masks) |mask| { - total += @popCount(MaskInt, mask); + total += @popCount(mask); } return total; } @@ -405,7 +405,7 @@ pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type { if (mask != 0) break mask; offset += @bitSizeOf(MaskInt); } else return null; - return offset + @ctz(MaskInt, mask); + return offset + @ctz(mask); } /// Finds the index of the first set bit, and unsets it. @@ -416,7 +416,7 @@ pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type { if (mask.* != 0) break mask; offset += @bitSizeOf(MaskInt); } else return null; - const index = @ctz(MaskInt, mask.*); + const index = @ctz(mask.*); mask.* &= (mask.* - 1); return offset + index; } @@ -587,7 +587,7 @@ pub const DynamicBitSetUnmanaged = struct { var total: usize = 0; for (self.masks[0..num_masks]) |mask| { // Note: This is where we depend on padding bits being zero - total += @popCount(MaskInt, mask); + total += @popCount(mask); } return total; } @@ -712,7 +712,7 @@ pub const DynamicBitSetUnmanaged = struct { mask += 1; offset += @bitSizeOf(MaskInt); } else return null; - return offset + @ctz(MaskInt, mask[0]); + return offset + @ctz(mask[0]); } /// Finds the index of the first set bit, and unsets it. @@ -725,7 +725,7 @@ pub const DynamicBitSetUnmanaged = struct { mask += 1; offset += @bitSizeOf(MaskInt); } else return null; - const index = @ctz(MaskInt, mask[0]); + const index = @ctz(mask[0]); mask[0] &= (mask[0] - 1); return offset + index; } @@ -978,12 +978,12 @@ fn BitSetIterator(comptime MaskInt: type, comptime options: IteratorOptions) typ switch (direction) { .forward => { - const next_index = @ctz(MaskInt, self.bits_remain) + self.bit_offset; + const next_index = @ctz(self.bits_remain) + self.bit_offset; self.bits_remain &= self.bits_remain - 1; return next_index; }, .reverse => { - const leading_zeroes = @clz(MaskInt, self.bits_remain); + const leading_zeroes = @clz(self.bits_remain); const top_bit = (@bitSizeOf(MaskInt) - 1) - leading_zeroes; const no_top_bit_mask = (@as(MaskInt, 1) << @intCast(ShiftInt, top_bit)) - 1; self.bits_remain &= no_top_bit_mask; diff --git a/src/install/dependency.zig b/src/install/dependency.zig index 0c81edfad..f3dd663f8 100644 --- a/src/install/dependency.zig +++ b/src/install/dependency.zig @@ -189,7 +189,7 @@ pub const Version = struct { pub fn isLessThan(string_buf: []const u8, lhs: Dependency.Version, rhs: Dependency.Version) bool { std.debug.assert(lhs.tag == rhs.tag); - return strings.cmpStringsAsc(.{}, lhs.literal.slice(string_buf), rhs.literal.slice(string_buf)); + return strings.cmpStringsAsc({}, lhs.literal.slice(string_buf), rhs.literal.slice(string_buf)); } pub const External = [9]u8; @@ -332,29 +332,29 @@ pub const Version = struct { // git://, git@, git+ssh 'g' => { if (strings.eqlComptime( - dependency[0..@minimum("git://".len, dependency.len)], + dependency[0..@min("git://".len, dependency.len)], "git://", ) or strings.eqlComptime( - dependency[0..@minimum("git@".len, dependency.len)], + dependency[0..@min("git@".len, dependency.len)], "git@", ) or strings.eqlComptime( - dependency[0..@minimum("git+ssh".len, dependency.len)], + dependency[0..@min("git+ssh".len, dependency.len)], "git+ssh", ) or strings.eqlComptime( - dependency[0..@minimum("git+file".len, dependency.len)], + dependency[0..@min("git+file".len, dependency.len)], "git+file", ) or strings.eqlComptime( - dependency[0..@minimum("git+http".len, dependency.len)], + dependency[0..@min("git+http".len, dependency.len)], "git+http", ) or strings.eqlComptime( - dependency[0..@minimum("git+https".len, dependency.len)], + dependency[0..@min("git+https".len, dependency.len)], "git+https", )) { return .git; } if (strings.eqlComptime( - dependency[0..@minimum("github".len, dependency.len)], + dependency[0..@min("github".len, dependency.len)], "github", ) or isGitHubRepoPath(dependency)) { return .github; @@ -379,21 +379,21 @@ pub const Version = struct { var remainder = dependency; if (strings.eqlComptime( - remainder[0..@minimum("https://".len, remainder.len)], + remainder[0..@min("https://".len, remainder.len)], "https://", )) { remainder = remainder["https://".len..]; } if (strings.eqlComptime( - remainder[0..@minimum("http://".len, remainder.len)], + remainder[0..@min("http://".len, remainder.len)], "http://", )) { remainder = remainder["http://".len..]; } if (strings.eqlComptime( - remainder[0..@minimum("github".len, remainder.len)], + remainder[0..@min("github".len, remainder.len)], "github", ) or isGitHubRepoPath(remainder)) { return .github; @@ -423,7 +423,7 @@ pub const Version = struct { return .tarball; if (strings.eqlComptime( - dependency[0..@minimum("file:".len, dependency.len)], + dependency[0..@min("file:".len, dependency.len)], "file:", )) { return .folder; @@ -442,7 +442,7 @@ pub const Version = struct { return .tarball; if (strings.eqlComptime( - dependency[0..@minimum("link:".len, dependency.len)], + dependency[0..@min("link:".len, dependency.len)], "link:", )) { return .symlink; @@ -458,7 +458,7 @@ pub const Version = struct { // workspace:// 'w' => { if (strings.eqlComptime( - dependency[0..@minimum("workspace://".len, dependency.len)], + dependency[0..@min("workspace://".len, dependency.len)], "workspace://", )) { return .workspace; diff --git a/src/install/extract_tarball.zig b/src/install/extract_tarball.zig index 3b5271d48..219c89399 100644 --- a/src/install/extract_tarball.zig +++ b/src/install/extract_tarball.zig @@ -22,7 +22,7 @@ package_id: PackageID, skip_verify: bool = false, integrity: Integrity = Integrity{}, url: string = "", -package_manager: *PackageManager = &PackageManager.instance, +package_manager: *PackageManager, pub inline fn run(this: ExtractTarball, bytes: []const u8) !string { if (!this.skip_verify and this.integrity.tag.isSupported()) { @@ -156,9 +156,9 @@ fn extract(this: *const ExtractTarball, tgz_bytes: []const u8) !string { } } - var tmpname = try FileSystem.instance.tmpname(basename[0..@minimum(basename.len, 32)], &tmpname_buf, tgz_bytes.len); + var tmpname = try FileSystem.instance.tmpname(basename[0..@min(basename.len, 32)], &tmpname_buf, tgz_bytes.len); { - var extract_destination = tmpdir.makeOpenPath(std.mem.span(tmpname), .{ .iterate = true }) catch |err| { + var extract_destination = tmpdir.makeOpenPathIterable(std.mem.span(tmpname), .{}) catch |err| { Output.panic("err: {s} when create temporary directory named {s} (while extracting {s})", .{ @errorName(err), tmpname, name }); }; @@ -248,7 +248,7 @@ fn extract(this: *const ExtractTarball, tgz_bytes: []const u8) !string { // We return a resolved absolute absolute file path to the cache dir. // To get that directory, we open the directory again. - var final_dir = cache_dir.openDirZ(folder_name, .{ .iterate = false }) catch |err| { + var final_dir = cache_dir.openDirZ(folder_name, .{}, true) catch |err| { Output.prettyErrorln( "<r><red>Error {s}<r> failed to verify cache dir for {s}", .{ @@ -277,9 +277,9 @@ fn extract(this: *const ExtractTarball, tgz_bytes: []const u8) !string { // create an index storing each version of a package installed create_index: { - var index_dir = cache_dir.makeOpenPath(name, .{ .iterate = true }) catch break :create_index; + var index_dir = cache_dir.makeOpenPathIterable(name, .{}) catch break :create_index; defer index_dir.close(); - index_dir.symLink( + index_dir.dir.symLink( final_path, // trim "name@" from the prefix folder_name[name.len + 1 ..], diff --git a/src/install/install.zig b/src/install/install.zig index 2748a0af0..24512dff9 100644 --- a/src/install/install.zig +++ b/src/install/install.zig @@ -112,11 +112,11 @@ pub fn ExternalSliceAligned(comptime Type: type, comptime alignment_: ?u29) type pub inline fn get(this: Slice, in: []const Type) []const Type { // it should be impossible to address this out of bounds due to the minimum here - return in.ptr[this.off..@minimum(in.len, this.off + this.len)]; + return in.ptr[this.off..@min(in.len, this.off + this.len)]; } pub inline fn mut(this: Slice, in: []Type) []Type { - return in.ptr[this.off..@minimum(in.len, this.off + this.len)]; + return in.ptr[this.off..@min(in.len, this.off + this.len)]; } pub fn init(buf: []const Type, in: []const Type) Slice { @@ -157,7 +157,7 @@ pub const Aligner = struct { pub fn write(comptime Type: type, comptime Writer: type, writer: Writer, pos: usize) !usize { const to_write = skipAmount(Type, pos); - var remainder: string = alignment_bytes_to_repeat_buffer[0..@minimum(to_write, alignment_bytes_to_repeat_buffer.len)]; + var remainder: string = alignment_bytes_to_repeat_buffer[0..@min(to_write, alignment_bytes_to_repeat_buffer.len)]; try writer.writeAll(remainder); return to_write; @@ -175,7 +175,7 @@ const NetworkTask = struct { allocator: std.mem.Allocator, request_buffer: MutableString = undefined, response_buffer: MutableString = undefined, - package_manager: *PackageManager = &PackageManager.instance, + package_manager: *PackageManager, callback: union(Task.Tag) { package_manifest: struct { loaded_manifest: ?Npm.PackageManifest = null, @@ -490,11 +490,11 @@ const Task = struct { request: Request, data: Data, status: Status = Status.waiting, - threadpool_task: ThreadPool.Task = ThreadPool.Task{ .callback = callback }, + threadpool_task: ThreadPool.Task = ThreadPool.Task{ .callback = &callback }, log: logger.Log, id: u64, err: ?anyerror = null, - package_manager: *PackageManager = &PackageManager.instance, + package_manager: *PackageManager, /// An ID that lets us register a callback without keeping the same pointer around pub const Id = struct { @@ -631,8 +631,8 @@ const Task = struct { }; const PackageInstall = struct { - cache_dir: std.fs.Dir, - destination_dir: std.fs.Dir, + cache_dir: std.fs.IterableDir, + destination_dir: std.fs.IterableDir, cache_dir_subpath: stringZ = "", destination_dir_subpath: stringZ = "", destination_dir_subpath_buf: []u8, @@ -655,17 +655,17 @@ const PackageInstall = struct { channel: PackageInstall.Task.Channel = undefined, skip_verify: bool = false, progress: *Progress = undefined, - cache_dir: std.fs.Dir = undefined, + cache_dir: std.fs.IterableDir = undefined, allocator: std.mem.Allocator, }; pub const Task = struct { - task: ThreadPool.Task = .{ .callback = callback }, + task: ThreadPool.Task = .{ .callback = &callback }, result: Result = Result{ .pending = void{} }, package_install: PackageInstall = undefined, package_id: PackageID, ctx: *PackageInstall.Context, - destination_dir: std.fs.Dir, + destination_dir: std.fs.IterableDir, pub const Channel = sync.Channel(*PackageInstall.Task, .{ .Static = 1024 }); @@ -797,7 +797,7 @@ const PackageInstall = struct { var package_json_path: [:0]u8 = this.destination_dir_subpath_buf[0 .. this.destination_dir_subpath.len + std.fs.path.sep_str.len + "package.json".len :0]; defer this.destination_dir_subpath_buf[this.destination_dir_subpath.len] = 0; - var package_json_file = this.destination_dir.openFileZ(package_json_path, .{ .mode = .read_only }) catch return false; + var package_json_file = this.destination_dir.dir.openFileZ(package_json_path, .{ .mode = .read_only }) catch return false; defer package_json_file.close(); var body_pool = Npm.Registry.BodyPool.get(allocator); @@ -814,7 +814,7 @@ const PackageInstall = struct { // Heuristic: most package.jsons will be less than 2048 bytes. read = package_json_file.read(mutable.list.items[total..]) catch return false; - var remain = mutable.list.items[@minimum(total, read)..]; + var remain = mutable.list.items[@min(total, read)..]; if (read > 0 and remain.len < 1024) { mutable.growBy(4096) catch return false; mutable.list.expandToCapacity(); @@ -857,7 +857,7 @@ const PackageInstall = struct { skip: void, fail: struct { err: anyerror, - step: Step = Step.clone, + step: Step, pub inline fn isPackageMissingFromCache(this: @This()) bool { return this.err == error.FileNotFound and this.step == .opening_cache_dir; @@ -893,9 +893,7 @@ const PackageInstall = struct { fn installWithClonefileEachDir(this: *PackageInstall) !Result { const Walker = @import("../walker_skippable.zig"); - var cached_package_dir = this.cache_dir.openDirZ(this.cache_dir_subpath, .{ - .iterate = true, - }) catch |err| return Result{ + var cached_package_dir = bun.openDir(this.cache_dir.dir, this.cache_dir_subpath) catch |err| return Result{ .fail = .{ .err = err, .step = .opening_cache_dir }, }; defer cached_package_dir.close(); @@ -911,7 +909,7 @@ const PackageInstall = struct { const FileCopier = struct { pub fn copy( - destination_dir_: std.fs.Dir, + destination_dir_: std.fs.IterableDir, walker: *Walker, ) !u32 { var real_file_count: u32 = 0; @@ -919,7 +917,7 @@ const PackageInstall = struct { while (try walker.next()) |entry| { switch (entry.kind) { .Directory => { - std.os.mkdirat(destination_dir_.fd, entry.path, 0o755) catch {}; + std.os.mkdirat(destination_dir_.dir.fd, entry.path, 0o755) catch {}; }, .File => { std.mem.copy(u8, &stackpath, entry.path); @@ -927,9 +925,9 @@ const PackageInstall = struct { var path: [:0]u8 = stackpath[0..entry.path.len :0]; var basename: [:0]u8 = stackpath[entry.path.len - entry.basename.len .. entry.path.len :0]; switch (C.clonefileat( - entry.dir.fd, + entry.dir.dir.fd, basename, - destination_dir_.fd, + destination_dir_.dir.fd, path, 0, )) { @@ -953,7 +951,7 @@ const PackageInstall = struct { } }; - var subdir = this.destination_dir.makeOpenPath(std.mem.span(this.destination_dir_subpath), .{ .iterate = true }) catch |err| return Result{ + var subdir = this.destination_dir.dir.makeOpenPathIterable(std.mem.span(this.destination_dir_subpath), .{}) catch |err| return Result{ .fail = .{ .err = err, .step = .opening_cache_dir }, }; @@ -980,15 +978,15 @@ const PackageInstall = struct { if (strings.indexOfChar(current, std.fs.path.sep)) |slash| { this.destination_dir_subpath_buf[slash] = 0; var subdir = this.destination_dir_subpath_buf[0..slash :0]; - this.destination_dir.makeDirZ(subdir) catch {}; + this.destination_dir.dir.makeDirZ(subdir) catch {}; this.destination_dir_subpath_buf[slash] = std.fs.path.sep; } } return switch (C.clonefileat( - this.cache_dir.fd, + this.cache_dir.dir.fd, this.cache_dir_subpath, - this.destination_dir.fd, + this.destination_dir.dir.fd, this.destination_dir_subpath, 0, )) { @@ -1008,9 +1006,7 @@ const PackageInstall = struct { fn installWithCopyfile(this: *PackageInstall) Result { const Walker = @import("../walker_skippable.zig"); - var cached_package_dir = this.cache_dir.openDirZ(this.cache_dir_subpath, .{ - .iterate = true, - }) catch |err| return Result{ + var cached_package_dir = bun.openDir(this.cache_dir.dir, this.cache_dir_subpath) catch |err| return Result{ .fail = .{ .err = err, .step = .opening_cache_dir }, }; defer cached_package_dir.close(); @@ -1050,7 +1046,7 @@ const PackageInstall = struct { }; defer outfile.close(); - var infile = try entry.dir.openFile(entry.basename, .{ .mode = .read_only }); + var infile = try entry.dir.dir.openFile(entry.basename, .{ .mode = .read_only }); defer infile.close(); const stat = infile.stat() catch continue; @@ -1070,13 +1066,13 @@ const PackageInstall = struct { } }; - var subdir = this.destination_dir.makeOpenPath(std.mem.span(this.destination_dir_subpath), .{ .iterate = true }) catch |err| return Result{ + var subdir = this.destination_dir.dir.makeOpenPathIterable(std.mem.span(this.destination_dir_subpath), .{}) catch |err| return Result{ .fail = .{ .err = err, .step = .opening_cache_dir }, }; - defer subdir.close(); + defer subdir.dir.close(); - this.file_count = FileCopier.copy(subdir, &walker_, this.progress) catch |err| return Result{ + this.file_count = FileCopier.copy(subdir.dir, &walker_, this.progress) catch |err| return Result{ .fail = .{ .err = err, .step = .copying_files }, }; @@ -1088,9 +1084,7 @@ const PackageInstall = struct { fn installWithHardlink(this: *PackageInstall) !Result { const Walker = @import("../walker_skippable.zig"); - var cached_package_dir = this.cache_dir.openDirZ(this.cache_dir_subpath, .{ - .iterate = true, - }) catch |err| return Result{ + var cached_package_dir = bun.openDir(this.cache_dir.dir, this.cache_dir_subpath) catch |err| return Result{ .fail = .{ .err = err, .step = .opening_cache_dir }, }; defer cached_package_dir.close(); @@ -1106,17 +1100,17 @@ const PackageInstall = struct { const FileCopier = struct { pub fn copy( - destination_dir_: std.fs.Dir, + destination_dir_: std.fs.IterableDir, walker: *Walker, ) !u32 { var real_file_count: u32 = 0; while (try walker.next()) |entry| { switch (entry.kind) { .Directory => { - std.os.mkdirat(destination_dir_.fd, entry.path, 0o755) catch {}; + std.os.mkdirat(destination_dir_.dir.fd, entry.path, 0o755) catch {}; }, .File => { - try std.os.linkat(entry.dir.fd, entry.basename, destination_dir_.fd, entry.path, 0); + try std.os.linkat(entry.dir.dir.fd, entry.basename, destination_dir_.dir.fd, entry.path, 0); real_file_count += 1; }, else => {}, @@ -1127,7 +1121,7 @@ const PackageInstall = struct { } }; - var subdir = this.destination_dir.makeOpenPath(std.mem.span(this.destination_dir_subpath), .{ .iterate = true }) catch |err| return Result{ + var subdir = bun.openDir(this.destination_dir.dir, this.destination_dir_subpath) catch |err| return Result{ .fail = .{ .err = err, .step = .opening_cache_dir }, }; @@ -1151,9 +1145,7 @@ const PackageInstall = struct { fn installWithSymlink(this: *PackageInstall) !Result { const Walker = @import("../walker_skippable.zig"); - var cached_package_dir = this.cache_dir.openDirZ(this.cache_dir_subpath, .{ - .iterate = true, - }) catch |err| return Result{ + var cached_package_dir = bun.openDir(this.cache_dir.dir, this.cache_dir_subpath) catch |err| return Result{ .fail = .{ .err = err, .step = .opening_cache_dir }, }; defer cached_package_dir.close(); @@ -1222,15 +1214,15 @@ const PackageInstall = struct { } }; - var subdir = this.destination_dir.makeOpenPath(std.mem.span(this.destination_dir_subpath), .{ .iterate = true }) catch |err| return Result{ + var subdir = this.destination_dir.dir.makeOpenPathIterable(std.mem.span(this.destination_dir_subpath), .{}) catch |err| return Result{ .fail = .{ .err = err, .step = .opening_cache_dir }, }; defer subdir.close(); this.file_count = FileCopier.copy( - subdir.fd, - cached_package_dir.fd, + subdir.dir.fd, + cached_package_dir.dir.fd, &walker_, ) catch |err| return Result{ @@ -1246,12 +1238,12 @@ const PackageInstall = struct { } pub fn uninstall(this: *PackageInstall) !void { - try this.destination_dir.deleteTree(std.mem.span(this.destination_dir_subpath)); + try this.destination_dir.dir.deleteTree(std.mem.span(this.destination_dir_subpath)); } fn isDanglingSymlink(path: [:0]const u8) bool { if (comptime Environment.isLinux) { - const rc = Syscall.system.open(path, @as(u31, std.os.O.PATH | 0), @as(u31, 0)); + const rc = Syscall.system.open(path, @as(u32, std.os.O.PATH | 0), @as(u32, 0)); switch (Syscall.getErrno(rc)) { .SUCCESS => { const fd = @intCast(std.os.fd_t, rc); @@ -1261,7 +1253,7 @@ const PackageInstall = struct { else => return true, } } else { - const rc = Syscall.system.open(path, @as(u31, 0), @as(u31, 0)); + const rc = Syscall.system.open(path, @as(u32, 0), @as(u32, 0)); switch (Syscall.getErrno(rc)) { .SUCCESS => { _ = Syscall.system.close(rc); @@ -1281,7 +1273,7 @@ const PackageInstall = struct { // cache_dir_subpath in here is actually the full path to the symlink pointing to the linked package const symlinked_path = this.cache_dir_subpath; - std.os.symlinkatZ(symlinked_path, this.destination_dir.fd, this.destination_dir_subpath) catch |err| { + std.os.symlinkatZ(symlinked_path, this.destination_dir.dir.fd, this.destination_dir_subpath) catch |err| { return Result{ .fail = .{ .err = err, @@ -1443,8 +1435,8 @@ const Waker = AsyncIO.Waker; // 1. Download all packages, parsing their dependencies and enqueuing all dependencies for resolution // 2. pub const PackageManager = struct { - cache_directory_: ?std.fs.Dir = null, - temp_dir_: ?std.fs.Dir = null, + cache_directory_: ?std.fs.IterableDir = null, + temp_dir_: ?std.fs.IterableDir = null, root_dir: *Fs.FileSystem.DirEntry, env_loader: *DotEnv.Loader, allocator: std.mem.Allocator, @@ -1496,8 +1488,8 @@ pub const PackageManager = struct { options: Options = Options{}, preinstall_state: std.ArrayListUnmanaged(PreinstallState) = std.ArrayListUnmanaged(PreinstallState){}, - global_link_dir: ?std.fs.Dir = null, - global_dir: ?std.fs.Dir = null, + global_link_dir: ?std.fs.IterableDir = null, + global_dir: ?std.fs.IterableDir = null, global_link_dir_path: string = "", waiter: Waker = undefined, wait_count: std.atomic.Atomic(usize) = std.atomic.Atomic(usize).init(0), @@ -1517,16 +1509,26 @@ pub const PackageManager = struct { ); pub const WakeHandler = struct { - handler: fn (ctx: *anyopaque, pm: *PackageManager) void = undefined, - onDependencyError: fn (ctx: *anyopaque, Dependency, PackageID, anyerror) void = undefined, + // handler: fn (ctx: *anyopaque, pm: *PackageManager) void = undefined, + // onDependencyError: fn (ctx: *anyopaque, Dependency, PackageID, anyerror) void = undefined, + handler: *const anyopaque = undefined, + onDependencyError: *const anyopaque = undefined, context: ?*anyopaque = null, + + pub inline fn getHandler(t: @This()) *const fn (ctx: *anyopaque, pm: *PackageManager) void { + return bun.cast(*const fn (ctx: *anyopaque, pm: *PackageManager) void, t.handler); + } + + pub inline fn getonDependencyError(t: @This()) *const fn (ctx: *anyopaque, Dependency, PackageID, anyerror) void { + return bun.cast(*const fn (ctx: *anyopaque, Dependency, PackageID, anyerror) void, t.handler); + } }; pub fn failRootResolution(this: *PackageManager, dependency: Dependency, dependency_id: PackageID, err: anyerror) void { if (this.dynamic_root_dependencies) |*dynamic| { dynamic.items[dependency_id].failed = err; if (this.onWake.context) |ctx| { - this.onWake.onDependencyError( + this.onWake.getonDependencyError()( ctx, dependency, dependency_id, @@ -1541,7 +1543,7 @@ pub const PackageManager = struct { pub fn wake(this: *PackageManager) void { if (this.onWake.context != null) { - this.onWake.handler(this.onWake.context.?, this); + this.onWake.getHandler()(this.onWake.context.?, this); return; } @@ -1655,13 +1657,13 @@ pub const PackageManager = struct { return .{ .pending = index }; } - pub fn globalLinkDir(this: *PackageManager) !std.fs.Dir { + pub fn globalLinkDir(this: *PackageManager) !std.fs.IterableDir { return this.global_link_dir orelse brk: { var global_dir = try Options.openGlobalDir(this.options.explicit_global_directory); this.global_dir = global_dir; - this.global_link_dir = try global_dir.makeOpenPath("node_modules", .{ .iterate = true }); + this.global_link_dir = try global_dir.dir.makeOpenPathIterable("node_modules", .{}); var buf: [bun.MAX_PATH_BYTES]u8 = undefined; - const _path = try std.os.getFdPath(this.global_link_dir.?.fd, &buf); + const _path = try std.os.getFdPath(this.global_link_dir.?.dir.fd, &buf); this.global_link_dir_path = try Fs.FileSystem.DirnameStore.instance.append([]const u8, _path); break :brk this.global_link_dir.?; }; @@ -1751,31 +1753,31 @@ pub const PackageManager = struct { var cached_package_folder_name_buf: [bun.MAX_PATH_BYTES]u8 = undefined; - pub inline fn getCacheDirectory(this: *PackageManager) std.fs.Dir { + pub inline fn getCacheDirectory(this: *PackageManager) std.fs.IterableDir { return this.cache_directory_ orelse brk: { this.cache_directory_ = this.ensureCacheDirectory(); break :brk this.cache_directory_.?; }; } - pub inline fn getTemporaryDirectory(this: *PackageManager) std.fs.Dir { + pub inline fn getTemporaryDirectory(this: *PackageManager) std.fs.IterableDir { return this.temp_dir_ orelse brk: { this.temp_dir_ = this.ensureTemporaryDirectory(); break :brk this.temp_dir_.?; }; } - noinline fn ensureCacheDirectory(this: *PackageManager) std.fs.Dir { + noinline fn ensureCacheDirectory(this: *PackageManager) std.fs.IterableDir { loop: while (true) { if (this.options.enable.cache) { const cache_dir = fetchCacheDirectoryPath(this.env_loader); - return std.fs.cwd().makeOpenPath(cache_dir.path, .{ .iterate = true }) catch { + return std.fs.cwd().makeOpenPathIterable(cache_dir.path, .{}) catch { this.options.enable.cache = false; continue :loop; }; } - return std.fs.cwd().makeOpenPath("node_modules/.cache", .{ .iterate = true }) catch |err| { + return std.fs.cwd().makeOpenPathIterable("node_modules/.cache", .{}) catch |err| { Output.prettyErrorln("<r><red>error<r>: bun is unable to write files: {s}", .{@errorName(err)}); Global.crash(); }; @@ -1788,15 +1790,15 @@ pub const PackageManager = struct { // // However, we want it to be reused! Otherwise a cache is silly. // Error RenameAcrossMountPoints moving react-is to cache dir: - noinline fn ensureTemporaryDirectory(this: *PackageManager) std.fs.Dir { + noinline fn ensureTemporaryDirectory(this: *PackageManager) std.fs.IterableDir { var cache_directory = this.getCacheDirectory(); // The chosen tempdir must be on the same filesystem as the cache directory // This makes renameat() work const default_tempdir = Fs.FileSystem.RealFS.getDefaultTempDir(); var tried_dot_tmp = false; - var tempdir: std.fs.Dir = std.fs.cwd().makeOpenPath(default_tempdir, .{ .iterate = true }) catch brk: { + var tempdir: std.fs.IterableDir = std.fs.cwd().makeOpenPathIterable(default_tempdir, .{}) catch brk: { tried_dot_tmp = true; - break :brk cache_directory.makeOpenPath(".tmp", .{ .iterate = true }) catch |err| { + break :brk cache_directory.dir.makeOpenPathIterable(".tmp", .{}) catch |err| { Output.prettyErrorln("<r><red>error<r>: bun is unable to access tempdir: {s}", .{@errorName(err)}); Global.crash(); }; @@ -1805,11 +1807,11 @@ pub const PackageManager = struct { const tmpname = Fs.FileSystem.instance.tmpname("hm", &tmpbuf, 999) catch unreachable; var timer: std.time.Timer = if (this.options.log_level != .silent) std.time.Timer.start() catch unreachable else undefined; brk: while (true) { - _ = tempdir.createFileZ(tmpname, .{ .truncate = true }) catch |err2| { + _ = tempdir.dir.createFileZ(tmpname, .{ .truncate = true }) catch |err2| { if (!tried_dot_tmp) { tried_dot_tmp = true; - tempdir = cache_directory.makeOpenPath(".tmp", .{ .iterate = true }) catch |err| { + tempdir = cache_directory.dir.makeOpenPathIterable(".tmp", .{}) catch |err| { Output.prettyErrorln("<r><red>error<r>: bun is unable to access tempdir: {s}", .{@errorName(err)}); Global.crash(); }; @@ -1821,10 +1823,10 @@ pub const PackageManager = struct { Global.crash(); }; - std.os.renameatZ(tempdir.fd, tmpname, cache_directory.fd, tmpname) catch |err| { + std.os.renameatZ(tempdir.dir.fd, tmpname, cache_directory.dir.fd, tmpname) catch |err| { if (!tried_dot_tmp) { tried_dot_tmp = true; - tempdir = cache_directory.makeOpenPath(".tmp", .{ .iterate = true }) catch |err2| { + tempdir = cache_directory.dir.makeOpenPathIterable(".tmp", .{}) catch |err2| { Output.prettyErrorln("<r><red>error<r>: bun is unable to write files to tempdir: {s}", .{@errorName(err2)}); Global.crash(); }; @@ -1836,13 +1838,13 @@ pub const PackageManager = struct { }); Global.crash(); }; - cache_directory.deleteFileZ(tmpname) catch {}; + cache_directory.dir.deleteFileZ(tmpname) catch {}; break; } if (this.options.log_level != .silent) { const elapsed = timer.read(); if (elapsed > std.time.ns_per_ms * 100) { - var cache_dir_path = std.os.getFdPath(cache_directory.fd, &path_buf) catch "it's"; + var cache_dir_path = std.os.getFdPath(cache_directory.dir.fd, &path_buf) catch "it's"; Output.prettyErrorln( "<r><yellow>warn<r>: Slow filesystem detected. If {s} is a network drive, consider setting $BUN_INSTALL_CACHE_DIR to a local folder.", .{cache_dir_path}, @@ -1879,8 +1881,8 @@ pub const PackageManager = struct { var available = buf[spanned.len..]; var end: []u8 = undefined; if (scope.url.hostname.len > 32 or available.len < 64) { - const visible_hostname = scope.url.hostname[0..@minimum(scope.url.hostname.len, 12)]; - end = std.fmt.bufPrint(available, "@@{s}__{x}", .{ visible_hostname, String.Builder.stringHash(scope.url.href) }) catch unreachable; + const visible_hostname = scope.url.hostname[0..@min(scope.url.hostname.len, 12)]; + end = std.fmt.bufPrint(available, "@@{s}__{any}", .{ visible_hostname, bun.fmt.hexIntLower(String.Builder.stringHash(scope.url.href)) }) catch unreachable; } else { end = std.fmt.bufPrint(available, "@@{s}", .{scope.url.hostname}) catch unreachable; } @@ -1900,25 +1902,28 @@ pub const PackageManager = struct { // TODO: normalize to alphanumeric pub fn cachedNPMPackageFolderPrintBasename(buf: []u8, name: string, version: Semver.Version) stringZ { + const pre_hex_int = version.tag.pre.hash; + const build_hex_int = version.tag.build.hash; + if (!version.tag.hasPre() and !version.tag.hasBuild()) { return std.fmt.bufPrintZ(buf, "{s}@{d}.{d}.{d}", .{ name, version.major, version.minor, version.patch }) catch unreachable; } else if (version.tag.hasPre() and version.tag.hasBuild()) { return std.fmt.bufPrintZ( buf, - "{s}@{d}.{d}.{d}-{x}+{X}", - .{ name, version.major, version.minor, version.patch, version.tag.pre.hash, version.tag.build.hash }, + "{s}@{d}.{d}.{d}-{any}+{any}", + .{ name, version.major, version.minor, version.patch, bun.fmt.hexIntLower(pre_hex_int), bun.fmt.hexIntUpper(build_hex_int) }, ) catch unreachable; } else if (version.tag.hasPre()) { return std.fmt.bufPrintZ( buf, - "{s}@{d}.{d}.{d}-{x}", - .{ name, version.major, version.minor, version.patch, version.tag.pre.hash }, + "{s}@{d}.{d}.{d}-{any}", + .{ name, version.major, version.minor, version.patch, bun.fmt.hexIntLower(pre_hex_int) }, ) catch unreachable; } else if (version.tag.hasBuild()) { return std.fmt.bufPrintZ( buf, - "{s}@{d}.{d}.{d}+{X}", - .{ name, version.major, version.minor, version.patch, version.tag.build.hash }, + "{s}@{d}.{d}.{d}+{any}", + .{ name, version.major, version.minor, version.patch, bun.fmt.hexIntUpper(build_hex_int) }, ) catch unreachable; } else { unreachable; @@ -1929,7 +1934,7 @@ pub const PackageManager = struct { pub fn isFolderInCache(this: *PackageManager, folder_path: stringZ) bool { // TODO: is this slow? - var dir = this.getCacheDirectory().openDirZ(folder_path, .{ .iterate = false }) catch return false; + var dir = this.getCacheDirectory().dir.openDirZ(folder_path, .{}, true) catch return false; dir.close(); return true; } @@ -1950,13 +1955,13 @@ pub const PackageManager = struct { npm.fmt(this.lockfile.buffers.string_bytes.items), }, ) catch unreachable; - return this.getCacheDirectory().readLink( + return this.getCacheDirectory().dir.readLink( subpath, buf, ) catch |err| { // if we run into an error, delete the symlink // so that we don't repeatedly try to read it - std.os.unlinkat(this.getCacheDirectory().fd, subpath, 0) catch {}; + std.os.unlinkat(this.getCacheDirectory().dir.fd, subpath, 0) catch {}; return err; }; } @@ -1982,7 +1987,7 @@ pub const PackageManager = struct { pub fn getInstalledVersionsFromDiskCache(this: *PackageManager, tags_buf: *std.ArrayList(u8), package_name: []const u8, allocator: std.mem.Allocator) !std.ArrayList(Semver.Version) { var list = std.ArrayList(Semver.Version).init(allocator); - var dir = this.getCacheDirectory().openDir(package_name, .{ .iterate = true }) catch |err| { + var dir = this.getCacheDirectory().dir.openIterableDir(package_name, .{}) catch |err| { switch (err) { error.FileNotFound, error.NotDir, error.AccessDenied, error.DeviceBusy => { return list; @@ -2191,6 +2196,7 @@ pub const PackageManager = struct { try network_task.forTarball( this.allocator, ExtractTarball{ + .package_manager = &PackageManager.instance, // https://github.com/ziglang/zig/issues/14005 .name = if (package.name.len() >= strings.StringOrTinyString.Max) strings.StringOrTinyString.init( try FileSystem.FilenameStore.instance.append( @@ -2202,8 +2208,8 @@ pub const PackageManager = struct { strings.StringOrTinyString.init(this.lockfile.str(package.name)), .resolution = package.resolution, - .cache_dir = this.getCacheDirectory(), - .temp_dir = this.getTemporaryDirectory(), + .cache_dir = this.getCacheDirectory().dir, + .temp_dir = this.getTemporaryDirectory().dir, .registry = scope.url.href, .package_id = package.meta.id, .integrity = package.meta.integrity, @@ -2281,8 +2287,8 @@ pub const PackageManager = struct { this.network_task_fifo.writeItemAssumeCapacity(task); } - const SuccessFn = fn (*PackageManager, PackageID, PackageID) void; - const FailFn = fn (*PackageManager, Dependency, PackageID, anyerror) void; + const SuccessFn = *const fn (*PackageManager, PackageID, PackageID) void; + const FailFn = *const fn (*PackageManager, Dependency, PackageID, anyerror) void; fn assignResolution(this: *PackageManager, dependency_id: PackageID, package_id: PackageID) void { this.lockfile.buffers.resolutions.items[dependency_id] = package_id; } @@ -2387,6 +2393,7 @@ pub const PackageManager = struct { ) *ThreadPool.Task { var task = this.allocator.create(Task) catch unreachable; task.* = Task{ + .package_manager = &PackageManager.instance, // https://github.com/ziglang/zig/issues/14005 .log = logger.Log.init(this.allocator), .tag = Task.Tag.package_manifest, .request = .{ @@ -2408,6 +2415,7 @@ pub const PackageManager = struct { ) *ThreadPool.Task { var task = this.allocator.create(Task) catch unreachable; task.* = Task{ + .package_manager = &PackageManager.instance, // https://github.com/ziglang/zig/issues/14005 .log = logger.Log.init(this.allocator), .tag = Task.Tag.extract, .request = .{ @@ -2459,7 +2467,8 @@ pub const PackageManager = struct { var tmpfile = FileSystem.RealFS.Tmpfile{}; var secret: [32]u8 = undefined; std.mem.writeIntNative(u64, secret[0..8], @intCast(u64, std.time.milliTimestamp())); - var rng = std.rand.Xoodoo.init(secret).random(); + var state = std.rand.Xoodoo.init(secret); + const rng = state.random(); var base64_bytes: [64]u8 = undefined; rng.bytes(&base64_bytes); @@ -2484,7 +2493,7 @@ pub const PackageManager = struct { _ = C.fchmod( tmpfile.fd, // chmod 666, - 0000040 | 0000004 | 0000002 | 0000400 | 0000200 | 0000020, + 0o0000040 | 0o0000004 | 0o0000002 | 0o0000400 | 0o0000200 | 0o0000020, ); try tmpfile.promote(tmpname, std.fs.cwd().fd, "yarn.lock"); @@ -2696,6 +2705,7 @@ pub const PackageManager = struct { var network_task = this.getNetworkTask(); network_task.* = NetworkTask{ + .package_manager = &PackageManager.instance, // https://github.com/ziglang/zig/issues/14005 .callback = undefined, .task_id = task_id, .allocator = this.allocator, @@ -2735,7 +2745,7 @@ pub const PackageManager = struct { successFn, ) catch |err| brk: { if (err == error.MissingPackageJSON) { - break :brk null; + break :brk @as(?ResolvedPackageResult, null); } return err; @@ -3146,7 +3156,7 @@ pub const PackageManager = struct { if (comptime log_level.isVerbose()) { Output.prettyError(" ", .{}); - Output.printElapsed(@floatCast(f64, @intToFloat(f128, task.http.elapsed) / std.time.ns_per_ms)); + Output.printElapsed(@intToFloat(f64, task.http.elapsed) / std.time.ns_per_ms); Output.prettyError("\n <d>Downloaded <r><green>{s}<r> versions\n", .{name.slice()}); Output.flush(); } @@ -3158,7 +3168,7 @@ pub const PackageManager = struct { entry.value_ptr.* = manifest; if (timestamp_this_tick == null) { - timestamp_this_tick = @truncate(u32, @intCast(u64, @maximum(0, std.time.timestamp()))) +| 300; + timestamp_this_tick = @truncate(u32, @intCast(u64, @max(0, std.time.timestamp()))) +| 300; } entry.value_ptr.*.pkg.public_max_age = timestamp_this_tick.?; @@ -3268,7 +3278,7 @@ pub const PackageManager = struct { if (comptime log_level.isVerbose()) { Output.prettyError(" ", .{}); - Output.printElapsed(@floatCast(f64, @intToFloat(f128, task.http.elapsed) / std.time.ns_per_ms)); + Output.printElapsed(@floatCast(f64, @intToFloat(f64, task.http.elapsed) / std.time.ns_per_ms)); Output.prettyError(" <d>Downloaded <r><green>{s}<r> tarball\n", .{extract.name.slice()}); Output.flush(); } @@ -3444,7 +3454,7 @@ pub const PackageManager = struct { log_level: LogLevel = LogLevel.default, global: bool = false, - global_bin_dir: std.fs.Dir = std.fs.Dir{ .fd = std.math.maxInt(std.os.fd_t) }, + global_bin_dir: std.fs.IterableDir = std.fs.IterableDir{ .dir = .{ .fd = std.math.maxInt(std.os.fd_t) } }, explicit_global_directory: string = "", /// destination directory to link bins into // must be a variable due to global installs and bunx @@ -3523,41 +3533,41 @@ pub const PackageManager = struct { optional: bool = false, }; - pub fn openGlobalDir(explicit_global_dir: string) !std.fs.Dir { + pub fn openGlobalDir(explicit_global_dir: string) !std.fs.IterableDir { if (bun.getenvZ("BUN_INSTALL_GLOBAL_DIR")) |home_dir| { - return try std.fs.cwd().makeOpenPath(home_dir, .{ .iterate = true }); + return try std.fs.cwd().makeOpenPathIterable(home_dir, .{}); } if (explicit_global_dir.len > 0) { - return try std.fs.cwd().makeOpenPath(explicit_global_dir, .{ .iterate = true }); + return try std.fs.cwd().makeOpenPathIterable(explicit_global_dir, .{}); } if (bun.getenvZ("BUN_INSTALL")) |home_dir| { var buf: [bun.MAX_PATH_BYTES]u8 = undefined; var parts = [_]string{ "install", "global" }; var path = Path.joinAbsStringBuf(home_dir, &buf, &parts, .auto); - return try std.fs.cwd().makeOpenPath(path, .{ .iterate = true }); + return try std.fs.cwd().makeOpenPathIterable(path, .{}); } if (bun.getenvZ("XDG_CACHE_HOME") orelse bun.getenvZ("HOME")) |home_dir| { var buf: [bun.MAX_PATH_BYTES]u8 = undefined; var parts = [_]string{ ".bun", "install", "global" }; var path = Path.joinAbsStringBuf(home_dir, &buf, &parts, .auto); - return try std.fs.cwd().makeOpenPath(path, .{ .iterate = true }); + return try std.fs.cwd().makeOpenPathIterable(path, .{}); } return error.@"No global directory found"; } - pub fn openGlobalBinDir(opts_: ?*const Api.BunInstall) !std.fs.Dir { + pub fn openGlobalBinDir(opts_: ?*const Api.BunInstall) !std.fs.IterableDir { if (bun.getenvZ("BUN_INSTALL_BIN")) |home_dir| { - return try std.fs.cwd().makeOpenPath(home_dir, .{ .iterate = true }); + return try std.fs.cwd().makeOpenPathIterable(home_dir, .{}); } if (opts_) |opts| { if (opts.global_bin_dir) |home_dir| { if (home_dir.len > 0) { - return try std.fs.cwd().makeOpenPath(home_dir, .{ .iterate = true }); + return try std.fs.cwd().makeOpenPathIterable(home_dir, .{}); } } } @@ -3568,7 +3578,7 @@ pub const PackageManager = struct { "bin", }; var path = Path.joinAbsStringBuf(home_dir, &buf, &parts, .auto); - return try std.fs.cwd().makeOpenPath(path, .{ .iterate = true }); + return try std.fs.cwd().makeOpenPathIterable(path, .{}); } if (bun.getenvZ("XDG_CACHE_HOME") orelse bun.getenvZ("HOME")) |home_dir| { @@ -3578,7 +3588,7 @@ pub const PackageManager = struct { "bin", }; var path = Path.joinAbsStringBuf(home_dir, &buf, &parts, .auto); - return try std.fs.cwd().makeOpenPath(path, .{ .iterate = true }); + return try std.fs.cwd().makeOpenPathIterable(path, .{}); } return error.@"Missing global bin directory: try setting $BUN_INSTALL"; @@ -3778,7 +3788,7 @@ pub const PackageManager = struct { if (env_loader.map.get("BUN_CONFIG_HTTP_RETRY_COUNT")) |retry_count| { if (std.fmt.parseInt(i32, retry_count, 10)) |int| { - this.max_retry_count = @intCast(u16, @minimum(@maximum(int, 0), 65355)); + this.max_retry_count = @intCast(u16, @min(@max(int, 0), 65355)); } else |_| {} } @@ -4199,7 +4209,7 @@ pub const PackageManager = struct { explicit_global_dir = opts.global_dir orelse explicit_global_dir; } var global_dir = try Options.openGlobalDir(explicit_global_dir); - try global_dir.setAsCwd(); + try global_dir.dir.setAsCwd(); } var fs = try Fs.FileSystem.init1(ctx.allocator, null); @@ -4282,7 +4292,7 @@ pub const PackageManager = struct { if (env_loader.map.get("GOMAXPROCS")) |max_procs| { if (std.fmt.parseInt(u32, max_procs, 10)) |cpu_count_| { - cpu_count = @minimum(cpu_count, cpu_count_); + cpu_count = @min(cpu_count, cpu_count_); } else |_| {} } @@ -4335,7 +4345,7 @@ pub const PackageManager = struct { ctx.install, ); - manager.timestamp_for_manifest_cache_control = @truncate(u32, @intCast(u64, @maximum(std.time.timestamp(), 0))); + manager.timestamp_for_manifest_cache_control = @truncate(u32, @intCast(u64, @max(std.time.timestamp(), 0))); return manager; } @@ -4354,7 +4364,7 @@ pub const PackageManager = struct { if (env_loader.map.get("GOMAXPROCS")) |max_procs| { if (std.fmt.parseInt(u32, max_procs, 10)) |cpu_count_| { - cpu_count = @minimum(cpu_count, cpu_count_); + cpu_count = @min(cpu_count, cpu_count_); } else |_| {} } @@ -4421,7 +4431,7 @@ pub const PackageManager = struct { u32, @intCast( u64, - @maximum( + @max( std.time.timestamp(), 0, ), @@ -4540,7 +4550,7 @@ pub const PackageManager = struct { } // Step 2. Setup the global directory - var node_modules: std.fs.Dir = brk: { + var node_modules: std.fs.IterableDir = brk: { Bin.Linker.umask = C.umask(0); var explicit_global_dir: string = ""; if (ctx.install) |install_| { @@ -4550,7 +4560,7 @@ pub const PackageManager = struct { try manager.setupGlobalDir(&ctx); - break :brk manager.global_dir.?.makeOpenPath("node_modules", .{ .iterate = true }) catch |err| { + break :brk manager.global_dir.?.dir.makeOpenPathIterable("node_modules", .{}) catch |err| { if (manager.options.log_level != .silent) Output.prettyErrorln("<r><red>error:<r> failed to create node_modules in global dir due to error {s}", .{@errorName(err)}); Global.crash(); @@ -4560,10 +4570,10 @@ pub const PackageManager = struct { // Step 3a. symlink to the node_modules folder { // delete it if it exists - node_modules.deleteTree(name) catch {}; + node_modules.dir.deleteTree(name) catch {}; // create the symlink - node_modules.symLink(Fs.FileSystem.instance.topLevelDirWithoutTrailingSlash(), name, .{ .is_directory = true }) catch |err| { + node_modules.dir.symLink(Fs.FileSystem.instance.topLevelDirWithoutTrailingSlash(), name, .{ .is_directory = true }) catch |err| { if (manager.options.log_level != .silent) Output.prettyErrorln("<r><red>error:<r> failed to create symlink to node_modules in global dir due to error {s}", .{@errorName(err)}); Global.crash(); @@ -4574,12 +4584,12 @@ pub const PackageManager = struct { if (package.bin.tag != .none) { var bin_linker = Bin.Linker{ .bin = package.bin, - .package_installed_node_modules = node_modules.fd, + .package_installed_node_modules = node_modules.dir.fd, .global_bin_path = manager.options.bin_path, - .global_bin_dir = manager.options.global_bin_dir, + .global_bin_dir = manager.options.global_bin_dir.dir, // .destination_dir_subpath = destination_dir_subpath, - .root_node_modules_folder = node_modules.fd, + .root_node_modules_folder = node_modules.dir.fd, .package_name = strings.StringOrTinyString.init(name), .string_buf = lockfile.buffers.string_bytes.items, .extern_string_buf = lockfile.buffers.extern_strings.items, @@ -4703,7 +4713,7 @@ pub const PackageManager = struct { } // Step 2. Setup the global directory - var node_modules: std.fs.Dir = brk: { + var node_modules: std.fs.IterableDir = brk: { Bin.Linker.umask = C.umask(0); var explicit_global_dir: string = ""; if (ctx.install) |install_| { @@ -4713,7 +4723,7 @@ pub const PackageManager = struct { try manager.setupGlobalDir(&ctx); - break :brk manager.global_dir.?.makeOpenPath("node_modules", .{ .iterate = true }) catch |err| { + break :brk manager.global_dir.?.dir.makeOpenPathIterable("node_modules", .{}) catch |err| { if (manager.options.log_level != .silent) Output.prettyErrorln("<r><red>error:<r> failed to create node_modules in global dir due to error {s}", .{@errorName(err)}); Global.crash(); @@ -4724,12 +4734,12 @@ pub const PackageManager = struct { if (package.bin.tag != .none) { var bin_linker = Bin.Linker{ .bin = package.bin, - .package_installed_node_modules = node_modules.fd, + .package_installed_node_modules = node_modules.dir.fd, .global_bin_path = manager.options.bin_path, - .global_bin_dir = manager.options.global_bin_dir, + .global_bin_dir = manager.options.global_bin_dir.dir, // .destination_dir_subpath = destination_dir_subpath, - .root_node_modules_folder = node_modules.fd, + .root_node_modules_folder = node_modules.dir.fd, .package_name = strings.StringOrTinyString.init(name), .string_buf = lockfile.buffers.string_bytes.items, .extern_string_buf = lockfile.buffers.extern_strings.items, @@ -4738,7 +4748,7 @@ pub const PackageManager = struct { } // delete it if it exists - node_modules.deleteTree(name) catch |err| { + node_modules.dir.deleteTree(name) catch |err| { if (manager.options.log_level != .silent) Output.prettyErrorln("<r><red>error:<r> failed to unlink package in global dir due to error {s}", .{@errorName(err)}); Global.crash(); @@ -5475,14 +5485,12 @@ pub const PackageManager = struct { // This is where we clean dangling symlinks // This could be slow if there are a lot of symlinks - if (cwd.openDirZ(manager.options.bin_path, .{ - .iterate = true, - })) |node_modules_bin_| { - var node_modules_bin: std.fs.Dir = node_modules_bin_; - var iter: std.fs.Dir.Iterator = node_modules_bin.iterate(); + if (cwd.openIterableDir(manager.options.bin_path, .{})) |node_modules_bin_| { + var node_modules_bin: std.fs.IterableDir = node_modules_bin_; + var iter: std.fs.IterableDir.Iterator = node_modules_bin.iterate(); iterator: while (iter.next() catch null) |entry| { switch (entry.kind) { - std.fs.Dir.Entry.Kind.SymLink => { + std.fs.IterableDir.Entry.Kind.SymLink => { // any symlinks which we are unable to open are assumed to be dangling // note that using access won't work here, because access doesn't resolve symlinks @@ -5490,8 +5498,8 @@ pub const PackageManager = struct { node_modules_buf[entry.name.len] = 0; var buf: [:0]u8 = node_modules_buf[0..entry.name.len :0]; - var file = node_modules_bin.openFileZ(buf, .{ .mode = .read_only }) catch { - node_modules_bin.deleteFileZ(buf) catch {}; + var file = node_modules_bin.dir.openFileZ(buf, .{ .mode = .read_only }) catch { + node_modules_bin.dir.deleteFileZ(buf) catch {}; continue :iterator; }; @@ -5545,11 +5553,11 @@ pub const PackageManager = struct { manager: *PackageManager, lockfile: *Lockfile, progress: *std.Progress, - node_modules_folder: std.fs.Dir, + node_modules_folder: std.fs.IterableDir, skip_verify_installed_version_number: bool, skip_delete: bool, force_install: bool, - root_node_modules_folder: std.fs.Dir, + root_node_modules_folder: std.fs.IterableDir, summary: *PackageInstall.Summary, options: *const PackageManager.Options, metas: []const Lockfile.Package.Meta, @@ -5558,7 +5566,7 @@ pub const PackageManager = struct { resolutions: []Resolution, node: *Progress.Node, has_created_bin: bool = false, - global_bin_dir: std.fs.Dir, + global_bin_dir: std.fs.IterableDir, destination_dir_subpath_buf: [bun.MAX_PATH_BYTES]u8 = undefined, folder_path_buf: [bun.MAX_PATH_BYTES]u8 = undefined, install_count: usize = 0, @@ -5571,7 +5579,7 @@ pub const PackageManager = struct { pub const DeferredBinLink = struct { package_id: PackageID, - node_modules_folder: std.fs.Dir, + node_modules_folder: std.fs.IterableDir, }; /// Install versions of a package which are waiting on a network request @@ -5597,7 +5605,7 @@ pub const PackageManager = struct { defer this.node_modules_folder = prev_node_modules_folder; for (callbacks.items) |cb| { const node_modules_folder = cb.node_modules_folder; - this.node_modules_folder = std.fs.Dir{ .fd = @intCast(std.os.fd_t, node_modules_folder) }; + this.node_modules_folder = .{ .dir = .{ .fd = @intCast(bun.FileDescriptor, node_modules_folder) } }; this.installPackageWithNameAndResolution(package_id, log_level, name, resolution); } } @@ -5641,12 +5649,12 @@ pub const PackageManager = struct { // "mineflayer": "file:." if (folder.len == 0 or (folder.len == 1 and folder[0] == '.')) { installer.cache_dir_subpath = "."; - installer.cache_dir = std.fs.cwd(); + installer.cache_dir = .{ .dir = std.fs.cwd() }; } else { @memcpy(&this.folder_path_buf, folder.ptr, folder.len); this.folder_path_buf[folder.len] = 0; installer.cache_dir_subpath = std.meta.assumeSentinel(this.folder_path_buf[0..folder.len], 0); - installer.cache_dir = std.fs.cwd(); + installer.cache_dir = .{ .dir = std.fs.cwd() }; } }, .symlink => { @@ -5679,7 +5687,7 @@ pub const PackageManager = struct { if (folder.len == 0 or (folder.len == 1 and folder[0] == '.')) { installer.cache_dir_subpath = "."; - installer.cache_dir = std.fs.cwd(); + installer.cache_dir = .{ .dir = std.fs.cwd() }; } else { const global_link_dir = this.manager.globalLinkDirPath() catch unreachable; var ptr = &this.folder_path_buf; @@ -5727,7 +5735,7 @@ pub const PackageManager = struct { if (!this.has_created_bin) { Bin.Linker.umask = C.umask(0); if (!this.options.global) - this.node_modules_folder.makeDirZ(".bin") catch {}; + this.node_modules_folder.dir.makeDirZ(".bin") catch {}; this.has_created_bin = true; } @@ -5746,12 +5754,12 @@ pub const PackageManager = struct { var bin_linker = Bin.Linker{ .bin = bin, - .package_installed_node_modules = this.node_modules_folder.fd, + .package_installed_node_modules = this.node_modules_folder.dir.fd, .global_bin_path = this.options.bin_path, - .global_bin_dir = this.options.global_bin_dir, + .global_bin_dir = this.options.global_bin_dir.dir, // .destination_dir_subpath = destination_dir_subpath, - .root_node_modules_folder = this.root_node_modules_folder.fd, + .root_node_modules_folder = this.root_node_modules_folder.dir.fd, .package_name = strings.StringOrTinyString.init(name), .string_buf = buf, .extern_string_buf = extern_string_buf, @@ -5794,7 +5802,7 @@ pub const PackageManager = struct { resolution.value.npm.version, resolution.value.npm.url.slice(buf), .{ - .node_modules_folder = @intCast(u32, this.node_modules_folder.fd), + .node_modules_folder = @intCast(u32, this.node_modules_folder.dir.fd), }, ); }, @@ -5917,13 +5925,13 @@ pub const PackageManager = struct { // we want to check lazily though // no need to download packages you've already installed!! var skip_verify_installed_version_number = false; - var node_modules_folder = std.fs.cwd().openDirZ("node_modules", .{ .iterate = true }) catch brk: { + var node_modules_folder = std.fs.cwd().openIterableDir("node_modules", .{}) catch brk: { skip_verify_installed_version_number = true; std.fs.cwd().makeDirZ("node_modules") catch |err| { Output.prettyErrorln("<r><red>error<r>: <b><red>{s}<r> creating <b>node_modules<r> folder", .{@errorName(err)}); Global.crash(); }; - break :brk std.fs.cwd().openDirZ("node_modules", .{ .iterate = true }) catch |err| { + break :brk std.fs.cwd().openIterableDir("node_modules", .{}) catch |err| { Output.prettyErrorln("<r><red>error<r>: <b><red>{s}<r> opening <b>node_modules<r> folder", .{@errorName(err)}); Global.crash(); }; @@ -5982,9 +5990,7 @@ pub const PackageManager = struct { // We deliberately do not close this folder. // If the package hasn't been downloaded, we will need to install it later // We use this file descriptor to know where to put it. - var folder = try cwd.openDirZ(node_modules.relative_path, .{ - .iterate = true, - }); + var folder = try cwd.openIterableDir(node_modules.relative_path, .{}); installer.node_modules_folder = folder; @@ -6078,7 +6084,7 @@ pub const PackageManager = struct { if (!installer.has_created_bin) { if (!this.options.global) { - node_modules_folder.makeDirZ(".bin") catch {}; + node_modules_folder.dir.makeDirZ(".bin") catch {}; } Bin.Linker.umask = C.umask(0); installer.has_created_bin = true; @@ -6086,10 +6092,10 @@ pub const PackageManager = struct { var bin_linker = Bin.Linker{ .bin = original_bin, - .package_installed_node_modules = folder.fd, - .root_node_modules_folder = node_modules_folder.fd, + .package_installed_node_modules = folder.dir.fd, + .root_node_modules_folder = node_modules_folder.dir.fd, .global_bin_path = this.options.bin_path, - .global_bin_dir = this.options.global_bin_dir, + .global_bin_dir = this.options.global_bin_dir.dir, .package_name = strings.StringOrTinyString.init(name), .string_buf = lockfile.buffers.string_bytes.items, @@ -6145,7 +6151,7 @@ pub const PackageManager = struct { pub fn setupGlobalDir(manager: *PackageManager, ctx: *const Command.Context) !void { manager.options.global_bin_dir = try Options.openGlobalBinDir(ctx.install); var out_buffer: [bun.MAX_PATH_BYTES]u8 = undefined; - var result = try std.os.getFdPath(manager.options.global_bin_dir.fd, &out_buffer); + var result = try std.os.getFdPath(manager.options.global_bin_dir.dir.fd, &out_buffer); out_buffer[result.len] = 0; var result_: [:0]u8 = out_buffer[0..result.len :0]; manager.options.bin_path = std.meta.assumeSentinel(try FileSystem.instance.dirname_store.append([:0]u8, result_), 0); @@ -6191,7 +6197,7 @@ pub const PackageManager = struct { manager.options.lockfile_path, ) else - Lockfile.LoadFromDiskResult{ .not_found = .{} }; + Lockfile.LoadFromDiskResult{ .not_found = {} }; var root = Lockfile.Package{}; var maybe_root: Lockfile.Package = undefined; @@ -6632,7 +6638,7 @@ pub const PackageManager = struct { if (install_summary.success > 0) { // it's confusing when it shows 3 packages and says it installed 1 - Output.pretty("\n <green>{d}<r> packages<r> installed ", .{@maximum( + Output.pretty("\n <green>{d}<r> packages<r> installed ", .{@max( install_summary.success, @truncate( u32, @@ -6706,7 +6712,7 @@ pub const PackageManager = struct { // bun install may have installed new bins, so we need to update the PATH // this can happen if node_modules/.bin didn't previously exist // note: it is harmless to have the same directory in the PATH multiple times - const current_path = manager.env.map.get("PATH"); + const current_path = manager.env.map.get("PATH") orelse ""; // TODO: windows const cwd_without_trailing_slash = if (Fs.FileSystem.instance.top_level_dir.len > 1 and Fs.FileSystem.instance.top_level_dir[Fs.FileSystem.instance.top_level_dir.len - 1] == '/') diff --git a/src/install/integrity.zig b/src/install/integrity.zig index 3d3ab41c4..e54d9b7e1 100644 --- a/src/install/integrity.zig +++ b/src/install/integrity.zig @@ -20,7 +20,7 @@ pub const Integrity = extern struct { var value: usize = 0; for (values) |val| { - value = @maximum(val, value); + value = @max(val, value); } break :brk value; @@ -36,7 +36,7 @@ pub const Integrity = extern struct { // e.g. "3cd0599b099384b815c10f7fa7df0092b62d534f" var integrity = Integrity{ .tag = Tag.sha1 }; - const end: usize = @minimum("3cd0599b099384b815c10f7fa7df0092b62d534f".len, buf.len); + const end: usize = @min("3cd0599b099384b815c10f7fa7df0092b62d534f".len, buf.len); var out_i: usize = 0; var i: usize = 0; @@ -117,7 +117,7 @@ pub const Integrity = extern struct { pub fn parse(buf: []const u8) Tag { const Matcher = strings.ExactSizeMatcher(8); - const i = std.mem.indexOfScalar(u8, buf[0..@minimum(buf.len, 7)], '-') orelse return Tag.unknown; + const i = std.mem.indexOfScalar(u8, buf[0..@min(buf.len, 7)], '-') orelse return Tag.unknown; return switch (Matcher.match(buf[0..i])) { Matcher.case("sha1") => Tag.sha1, @@ -167,7 +167,7 @@ pub const Integrity = extern struct { } pub fn verify(this: *const Integrity, bytes: []const u8) bool { - return @call(.{ .modifier = .always_inline }, verifyByTag, .{ this.tag, bytes, &this.value }); + return @call(.always_inline, verifyByTag, .{ this.tag, bytes, &this.value }); } pub fn verifyByTag(tag: Tag, bytes: []const u8, sum: []const u8) bool { diff --git a/src/install/lockfile.zig b/src/install/lockfile.zig index 8e90eb58a..93d81e18e 100644 --- a/src/install/lockfile.zig +++ b/src/install/lockfile.zig @@ -171,7 +171,7 @@ pub fn loadFromDisk(this: *Lockfile, allocator: std.mem.Allocator, log: *logger. if (filename.len > 0) file = std.fs.cwd().openFileZ(filename, .{ .mode = .read_only }) catch |err| { return switch (err) { - error.FileNotFound, error.AccessDenied, error.BadPathName => LoadFromDiskResult{ .not_found = .{} }, + error.FileNotFound, error.AccessDenied, error.BadPathName => LoadFromDiskResult{ .not_found = {} }, else => LoadFromDiskResult{ .err = .{ .step = .open_file, .value = err } }, }; }; @@ -1438,7 +1438,7 @@ pub fn saveToDisk(this: *Lockfile, filename: stringZ) void { _ = C.fchmod( tmpfile.fd, // chmod 777 - 0000010 | 0000100 | 0000001 | 0001000 | 0000040 | 0000004 | 0000002 | 0000400 | 0000200 | 0000020, + 0o0000010 | 0o0000100 | 0o0000001 | 0o0001000 | 0o0000040 | 0o0000004 | 0o0000002 | 0o0000400 | 0o0000200 | 0o0000020, ); tmpfile.promote(tmpname, std.fs.cwd().fd, filename) catch |err| { @@ -1687,7 +1687,7 @@ pub const StringBuilder = struct { } pub fn append(this: *StringBuilder, comptime Type: type, slice: string) Type { - return @call(.{ .modifier = .always_inline }, appendWithHash, .{ this, Type, slice, stringHash(slice) }); + return @call(.always_inline, appendWithHash, .{ this, Type, slice, stringHash(slice) }); } // SlicedString is not supported due to inline strings. @@ -2566,7 +2566,7 @@ pub const Package = extern struct { } else { package.resolution = .{ .tag = .root, - .value = .{ .root = .{} }, + .value = .{ .root = {} }, }; } @@ -2617,12 +2617,12 @@ pub const Package = extern struct { break :bin; }, - .e_string => |str| { - if (str.data.len > 0) { + .e_string => |stri| { + if (stri.data.len > 0) { package.bin = Bin{ .tag = Bin.Tag.file, .value = .{ - .file = string_builder.append(String, str.data), + .file = string_builder.append(String, stri.data), }, }; break :bin; @@ -2829,10 +2829,10 @@ pub const Package = extern struct { var data: [fields.len]Data = undefined; for (fields) |field_info, i| { data[i] = .{ - .size = @sizeOf(field_info.field_type), + .size = @sizeOf(field_info.type), .size_index = i, - .Type = field_info.field_type, - .alignment = if (@sizeOf(field_info.field_type) == 0) 1 else field_info.alignment, + .Type = field_info.type, + .alignment = if (@sizeOf(field_info.type) == 0) 1 else field_info.alignment, }; } const Sort = struct { @@ -2977,16 +2977,16 @@ const Buffers = struct { const Data = struct { size: usize, name: []const u8, - field_type: type, + type: type, alignment: usize, }; var data: [fields.len]Data = undefined; for (fields) |field_info, i| { data[i] = .{ - .size = @sizeOf(field_info.field_type), + .size = @sizeOf(field_info.type), .name = field_info.name, - .alignment = if (@sizeOf(field_info.field_type) == 0) 1 else field_info.alignment, - .field_type = field_info.field_type.Slice, + .alignment = if (@sizeOf(field_info.type) == 0) 1 else field_info.alignment, + .type = field_info.type.Slice, }; } const Sort = struct { @@ -3003,7 +3003,7 @@ const Buffers = struct { for (data) |elem, i| { sizes_bytes[i] = elem.size; names[i] = elem.name; - types[i] = elem.field_type; + types[i] = elem.type; } break :blk .{ .bytes = sizes_bytes, diff --git a/src/install/npm.zig b/src/install/npm.zig index 60ffefdbb..ca1472039 100644 --- a/src/install/npm.zig +++ b/src/install/npm.zig @@ -1,4 +1,5 @@ const URL = @import("../url.zig").URL; +const bun = @import("bun"); const std = @import("std"); const MutableString = @import("../string_mutable.zig").MutableString; const Semver = @import("./semver.zig"); @@ -163,7 +164,7 @@ pub const Registry = struct { switch (response.status_code) { 400 => return error.BadRequest, 429 => return error.TooManyRequests, - 404 => return PackageVersionResponse{ .not_found = .{} }, + 404 => return PackageVersionResponse{ .not_found = {} }, 500...599 => return error.HTTPInternalServerError, 304 => return PackageVersionResponse{ .cached = loaded_manifest.?, @@ -203,7 +204,7 @@ pub const Registry = struct { package_name, newly_last_modified, new_etag, - @truncate(u32, @intCast(u64, @maximum(0, std.time.timestamp()))) + 300, + @truncate(u32, @intCast(u64, @max(0, std.time.timestamp()))) + 300, )) |package| { if (package_manager.options.enable.manifest_cache) { PackageManifest.Serializer.save(&package, package_manager.getTemporaryDirectory(), package_manager.getCacheDirectory()) catch {}; @@ -459,9 +460,9 @@ pub const PackageManifest = struct { var data: [fields.len]Data = undefined; for (fields) |field_info, i| { data[i] = .{ - .size = @sizeOf(field_info.field_type), + .size = @sizeOf(field_info.type), .name = field_info.name, - .alignment = if (@sizeOf(field_info.field_type) == 0) 1 else field_info.alignment, + .alignment = if (@sizeOf(field_info.type) == 0) 1 else field_info.alignment, }; } const Sort = struct { @@ -536,8 +537,8 @@ pub const PackageManifest = struct { } } - fn writeFile(this: *const PackageManifest, tmp_path: [:0]const u8, tmpdir: std.fs.Dir) !void { - var tmpfile = try tmpdir.createFileZ(tmp_path, .{ + fn writeFile(this: *const PackageManifest, tmp_path: [:0]const u8, tmpdir: std.fs.IterableDir) !void { + var tmpfile = try tmpdir.dir.createFileZ(tmp_path, .{ .truncate = true, }); defer tmpfile.close(); @@ -545,25 +546,29 @@ pub const PackageManifest = struct { try Serializer.write(this, @TypeOf(writer), writer); } - pub fn save(this: *const PackageManifest, tmpdir: std.fs.Dir, cache_dir: std.fs.Dir) !void { + pub fn save(this: *const PackageManifest, tmpdir: std.fs.IterableDir, cache_dir: std.fs.IterableDir) !void { const file_id = std.hash.Wyhash.hash(0, this.name()); var dest_path_buf: [512 + 64]u8 = undefined; var out_path_buf: ["-18446744073709551615".len + ".npm".len + 1]u8 = undefined; var dest_path_stream = std.io.fixedBufferStream(&dest_path_buf); var dest_path_stream_writer = dest_path_stream.writer(); - try dest_path_stream_writer.print("{x}.npm-{x}", .{ file_id, @maximum(std.time.milliTimestamp(), 0) }); + const hex_fmt = bun.fmt.hexIntLower(file_id); + const hex_timestamp = @intCast(usize, @max(std.time.milliTimestamp(), 0)); + const hex_timestamp_fmt = bun.fmt.hexIntLower(hex_timestamp); + try dest_path_stream_writer.print("{any}.npm-{any}", .{ hex_fmt, hex_timestamp_fmt }); try dest_path_stream_writer.writeByte(0); var tmp_path: [:0]u8 = dest_path_buf[0 .. dest_path_stream.pos - 1 :0]; try writeFile(this, tmp_path, tmpdir); - var out_path = std.fmt.bufPrintZ(&out_path_buf, "{x}.npm", .{file_id}) catch unreachable; - try std.os.renameatZ(tmpdir.fd, tmp_path, cache_dir.fd, out_path); + var out_path = std.fmt.bufPrintZ(&out_path_buf, "{any}.npm", .{hex_fmt}) catch unreachable; + try std.os.renameatZ(tmpdir.dir.fd, tmp_path, cache_dir.dir.fd, out_path); } - pub fn load(allocator: std.mem.Allocator, cache_dir: std.fs.Dir, package_name: string) !?PackageManifest { + pub fn load(allocator: std.mem.Allocator, cache_dir: std.fs.IterableDir, package_name: string) !?PackageManifest { const file_id = std.hash.Wyhash.hash(0, package_name); var file_path_buf: [512 + 64]u8 = undefined; - var file_path = try std.fmt.bufPrintZ(&file_path_buf, "{x}.npm", .{file_id}); - var cache_file = cache_dir.openFileZ( + const hex_fmt = bun.fmt.hexIntLower(file_id); + var file_path = try std.fmt.bufPrintZ(&file_path_buf, "{any}.npm", .{hex_fmt}); + var cache_file = cache_dir.dir.openFileZ( file_path, .{ .mode = .read_only }, ) catch return null; @@ -931,13 +936,13 @@ pub const PackageManifest = struct { string_builder.count(etag); } - var versioned_packages = try allocator.allocAdvanced(PackageVersion, null, release_versions_len + pre_versions_len, .exact); - var all_semver_versions = try allocator.allocAdvanced(Semver.Version, null, release_versions_len + pre_versions_len + dist_tags_count, .exact); - var all_extern_strings = try allocator.allocAdvanced(ExternalString, null, extern_string_count + tarball_urls_count, .exact); - var version_extern_strings = try allocator.allocAdvanced(ExternalString, null, dependency_sum, .exact); - var extern_strings_bin_entries = try allocator.allocAdvanced(ExternalString, null, extern_string_count_bin, .exact); + var versioned_packages = try allocator.alloc(PackageVersion, release_versions_len + pre_versions_len); + var all_semver_versions = try allocator.alloc(Semver.Version, release_versions_len + pre_versions_len + dist_tags_count); + var all_extern_strings = try allocator.alloc(ExternalString, extern_string_count + tarball_urls_count); + var version_extern_strings = try allocator.alloc(ExternalString, dependency_sum); + var extern_strings_bin_entries = try allocator.alloc(ExternalString, extern_string_count_bin); var all_extern_strings_bin_entries = extern_strings_bin_entries; - var all_tarball_url_strings = try allocator.allocAdvanced(ExternalString, null, tarball_urls_count, .exact); + var all_tarball_url_strings = try allocator.alloc(ExternalString, tarball_urls_count); var tarball_url_strings = all_tarball_url_strings; if (versioned_packages.len > 0) { @@ -1040,8 +1045,8 @@ pub const PackageManifest = struct { } } }, - .e_string => |str| { - package_version.cpu = Architecture.apply(Architecture.none, str.data); + .e_string => |stri| { + package_version.cpu = Architecture.apply(Architecture.none, stri.data); }, else => {}, } @@ -1062,8 +1067,8 @@ pub const PackageManifest = struct { } } }, - .e_string => |str| { - package_version.os = OperatingSystem.apply(OperatingSystem.none, str.data); + .e_string => |stri| { + package_version.os = OperatingSystem.apply(OperatingSystem.none, stri.data); }, else => {}, } @@ -1127,12 +1132,12 @@ pub const PackageManifest = struct { break :bin; }, - .e_string => |str| { - if (str.data.len > 0) { + .e_string => |stri| { + if (stri.data.len > 0) { package_version.bin = Bin{ .tag = Bin.Tag.file, .value = .{ - .file = string_builder.append(String, str.data), + .file = string_builder.append(String, stri.data), }, }; break :bin; diff --git a/src/install/resolution.zig b/src/install/resolution.zig index baf31b2ad..d21855d7c 100644 --- a/src/install/resolution.zig +++ b/src/install/resolution.zig @@ -7,11 +7,11 @@ const Repository = @import("./repository.zig").Repository; const string = @import("../string_types.zig").string; const ExtractTarball = @import("./extract_tarball.zig"); const strings = @import("../string_immutable.zig"); -const VersionedURL = @import("./versioned_url.zig"); +const VersionedURL = @import("./versioned_url.zig").VersionedURL; pub const Resolution = extern struct { tag: Tag = Tag.uninitialized, - value: Value = Value{ .uninitialized = .{} }, + value: Value = Value{ .uninitialized = {} }, pub fn order( lhs: *const Resolution, @@ -93,7 +93,7 @@ pub const Resolution = extern struct { .gitlab => Resolution.Value{ .gitlab = this.value.gitlab.clone(buf, Builder, builder), }, - .root => Resolution.Value{ .root = .{} }, + .root => Resolution.Value{ .root = {} }, else => unreachable, }, }; diff --git a/src/install/resolvers/folder_resolver.zig b/src/install/resolvers/folder_resolver.zig index a102e22db..b25623cfe 100644 --- a/src/install/resolvers/folder_resolver.zig +++ b/src/install/resolvers/folder_resolver.zig @@ -134,7 +134,7 @@ pub const FolderResolution = union(Tag) { const len = try package_json.getEndPos(); body.data.reset(); - body.data.inflate(@maximum(len, 2048)) catch unreachable; + body.data.inflate(@max(len, 2048)) catch unreachable; body.data.list.expandToCapacity(); const source_buf = try package_json.readAll(body.data.list.items); diff --git a/src/install/semver.zig b/src/install/semver.zig index f9699e214..5722b4d4b 100644 --- a/src/install/semver.zig +++ b/src/install/semver.zig @@ -292,7 +292,7 @@ pub const String = extern struct { } pub fn append(this: *Builder, comptime Type: type, slice_: string) Type { - return @call(.{ .modifier = .always_inline }, appendWithHash, .{ this, Type, slice_, stringHash(slice_) }); + return @call(.always_inline, appendWithHash, .{ this, Type, slice_, stringHash(slice_) }); } pub fn appendUTF8WithoutPool(this: *Builder, comptime Type: type, slice_: string, hash: u64) Type { @@ -1255,11 +1255,11 @@ pub const Query = struct { // OR next: ?*List = null, - pub inline fn satisfies(this: *const List, version: Version) bool { + pub fn satisfies(this: *const List, version: Version) bool { return this.head.satisfies(version) or (this.next orelse return false).satisfies(version); } - pub inline fn eql(lhs: *const List, rhs: *const List) bool { + pub fn eql(lhs: *const List, rhs: *const List) bool { if (!lhs.head.eql(&rhs.head)) return false; var lhs_next = lhs.next orelse return rhs.next == null; @@ -1395,7 +1395,7 @@ pub const Query = struct { return lhs_next.eql(rhs_next); } - pub inline fn satisfies(this: *const Query, version: Version) bool { + pub fn satisfies(this: *const Query, version: Version) bool { const left = this.range.satisfies(version); return left and (this.next orelse return true).satisfies(version); diff --git a/src/install/versioned_url.zig b/src/install/versioned_url.zig index c52a64d97..bf510b545 100644 --- a/src/install/versioned_url.zig +++ b/src/install/versioned_url.zig @@ -1,31 +1,31 @@ const Semver = @import("./semver.zig"); const String = @import("./semver.zig").String; -const VersionedURL = @This(); +pub const VersionedURL = extern struct { + url: String, + version: Semver.Version, -url: String, -version: Semver.Version, + pub fn eql(this: VersionedURL, other: VersionedURL) bool { + return this.version.eql(other.version); + } -pub fn eql(this: VersionedURL, other: VersionedURL) bool { - return this.version.eql(other.version); -} + pub fn order(this: VersionedURL, other: VersionedURL, lhs_buf: []const u8, rhs_buf: []const u8) @import("std").math.Order { + return this.version.order(other.version, lhs_buf, rhs_buf); + } -pub fn order(this: VersionedURL, other: VersionedURL, lhs_buf: []const u8, rhs_buf: []const u8) @import("std").math.Order { - return this.version.order(other.version, lhs_buf, rhs_buf); -} + pub fn fmt(this: VersionedURL, buf: []const u8) Semver.Version.Formatter { + return this.version.fmt(buf); + } -pub fn fmt(this: VersionedURL, buf: []const u8) Semver.Version.Formatter { - return this.version.fmt(buf); -} + pub fn count(this: VersionedURL, buf: []const u8, comptime Builder: type, builder: Builder) void { + this.version.count(buf, comptime Builder, builder); + builder.count(this.url.slice(buf)); + } -pub fn count(this: VersionedURL, buf: []const u8, comptime Builder: type, builder: Builder) void { - this.version.count(buf, comptime Builder, builder); - builder.count(this.url.slice(buf)); -} - -pub fn clone(this: VersionedURL, buf: []const u8, comptime Builder: type, builder: Builder) VersionedURL { - return VersionedURL{ - .version = this.version.clone(buf, Builder, builder), - .url = builder.append(String, this.url.slice(buf)), - }; -} + pub fn clone(this: VersionedURL, buf: []const u8, comptime Builder: type, builder: Builder) VersionedURL { + return VersionedURL{ + .version = this.version.clone(buf, Builder, builder), + .url = builder.append(String, this.url.slice(buf)), + }; + } +}; |