Compare commits

...

1 Commits

Author SHA1 Message Date
John-David Dalton
cc045719bd Reduce dirname/basename/unc methods and rely more on zig standard lib 2024-01-24 10:38:15 -08:00
13 changed files with 399 additions and 596 deletions

View File

@@ -234,7 +234,8 @@ pub fn build_(b: *Build) !void {
const outfile_maybe = b.option([]const u8, "output-file", "target to install to");
if (outfile_maybe) |outfile| {
output_dir = try pathRel(b.allocator, b.install_prefix, std.fs.path.dirname(outfile) orelse "");
const to_path = std.fs.path.dirname(outfile) orelse &([_]u8{});
output_dir = try pathRel(b.allocator, b.install_prefix, to_path);
} else {
const output_dir_base = try std.fmt.bufPrint(&output_dir_buf, "{s}{s}", .{ bin_label, triplet });
output_dir = try pathRel(b.allocator, b.install_prefix, output_dir_base);

View File

@@ -1,14 +1,14 @@
const Bun = @This();
const root = @import("root");
const default_allocator = bun.default_allocator;
const bun = @import("root").bun;
const bun = root.bun;
const Environment = bun.Environment;
const Global = bun.Global;
const strings = bun.strings;
const string = bun.string;
const Output = @import("root").bun.Output;
const MutableString = @import("root").bun.MutableString;
const Output = bun.Output;
const MutableString = bun.MutableString;
const std = @import("std");
const Allocator = std.mem.Allocator;
const IdentityContext = @import("../../identity_context.zig").IdentityContext;
@@ -17,7 +17,7 @@ const Resolver = @import("../../resolver/resolver.zig");
const ast = @import("../../import_record.zig");
const MacroEntryPoint = bun.bundler.MacroEntryPoint;
const logger = @import("root").bun.logger;
const logger = bun.logger;
const Api = @import("../../api/schema.zig").Api;
const options = @import("../../options.zig");
const Bundler = bun.Bundler;
@@ -26,47 +26,48 @@ const js_printer = bun.js_printer;
const js_parser = bun.js_parser;
const js_ast = bun.JSAst;
const NodeFallbackModules = @import("../../node_fallbacks.zig");
const path_handler = bun.path;
const ImportKind = ast.ImportKind;
const Analytics = @import("../../analytics/analytics_thread.zig");
const ZigString = @import("root").bun.JSC.ZigString;
const ZigString = bun.JSC.ZigString;
const Runtime = @import("../../runtime.zig");
const ImportRecord = ast.ImportRecord;
const DotEnv = @import("../../env_loader.zig");
const ParseResult = bun.bundler.ParseResult;
const PackageJSON = @import("../../resolver/package_json.zig").PackageJSON;
const MacroRemap = @import("../../resolver/package_json.zig").MacroMap;
const WebCore = @import("root").bun.JSC.WebCore;
const WebCore = bun.JSC.WebCore;
const Request = WebCore.Request;
const Response = WebCore.Response;
const Headers = WebCore.Headers;
const Fetch = WebCore.Fetch;
const FetchEvent = WebCore.FetchEvent;
const js = @import("root").bun.JSC.C;
const JSC = @import("root").bun.JSC;
const js = bun.JSC.C;
const JSC = bun.JSC;
const JSError = @import("../base.zig").JSError;
const MarkedArrayBuffer = @import("../base.zig").MarkedArrayBuffer;
const getAllocator = @import("../base.zig").getAllocator;
const JSValue = @import("root").bun.JSC.JSValue;
const JSValue = bun.JSC.JSValue;
const JSGlobalObject = @import("root").bun.JSC.JSGlobalObject;
const ExceptionValueRef = @import("root").bun.JSC.ExceptionValueRef;
const JSPrivateDataPtr = @import("root").bun.JSC.JSPrivateDataPtr;
const ConsoleObject = @import("root").bun.JSC.ConsoleObject;
const Node = @import("root").bun.JSC.Node;
const ZigException = @import("root").bun.JSC.ZigException;
const ZigStackTrace = @import("root").bun.JSC.ZigStackTrace;
const ErrorableResolvedSource = @import("root").bun.JSC.ErrorableResolvedSource;
const ResolvedSource = @import("root").bun.JSC.ResolvedSource;
const JSPromise = @import("root").bun.JSC.JSPromise;
const JSInternalPromise = @import("root").bun.JSC.JSInternalPromise;
const JSModuleLoader = @import("root").bun.JSC.JSModuleLoader;
const JSPromiseRejectionOperation = @import("root").bun.JSC.JSPromiseRejectionOperation;
const Exception = @import("root").bun.JSC.Exception;
const ErrorableZigString = @import("root").bun.JSC.ErrorableZigString;
const ZigGlobalObject = @import("root").bun.JSC.ZigGlobalObject;
const VM = @import("root").bun.JSC.VM;
const JSFunction = @import("root").bun.JSC.JSFunction;
const JSGlobalObject = bun.JSC.JSGlobalObject;
const ExceptionValueRef = bun.JSC.ExceptionValueRef;
const JSPrivateDataPtr = bun.JSC.JSPrivateDataPtr;
const ConsoleObject = bun.JSC.ConsoleObject;
const Node = bun.JSC.Node;
const ZigException = bun.JSC.ZigException;
const ZigStackTrace = bun.JSC.ZigStackTrace;
const ErrorableResolvedSource = bun.JSC.ErrorableResolvedSource;
const ResolvedSource = bun.JSC.ResolvedSource;
const JSPromise = bun.JSC.JSPromise;
const JSInternalPromise = bun.JSC.JSInternalPromise;
const JSModuleLoader = bun.JSC.JSModuleLoader;
const JSPromiseRejectionOperation = bun.JSC.JSPromiseRejectionOperation;
const Exception = bun.JSC.Exception;
const ErrorableZigString = bun.JSC.ErrorableZigString;
const ZigGlobalObject = bun.JSC.ZigGlobalObject;
const VM = bun.JSC.VM;
const JSFunction = bun.JSC.JSFunction;
const Config = @import("../config.zig");
const URL = @import("../../url.zig").URL;
const VirtualMachine = JSC.VirtualMachine;
@@ -711,7 +712,7 @@ pub const FFI = struct {
const FFI_HEADER: string = @embedFile("./FFI.h");
pub inline fn ffiHeader() string {
if (comptime Environment.isDebug) {
const dirpath = comptime bun.Environment.base_path ++ (bun.Dirname.dirname(u8, @src().file) orelse "");
const dirpath = comptime bun.Environment.base_path ++ (std.fs.path.dirname(@src().file).?);
var buf: bun.PathBuffer = undefined;
const user = bun.getUserName(&buf) orelse "";
const dir = std.mem.replaceOwned(

View File

@@ -1,11 +1,12 @@
const std = @import("std");
const bun = @import("root").bun;
const Api = @import("../../api/schema.zig").Api;
const JavaScript = @import("../javascript.zig");
const QueryStringMap = @import("../../url.zig").QueryStringMap;
const CombinedScanner = @import("../../url.zig").CombinedScanner;
const bun = @import("root").bun;
const path_handler = bun.path;
const string = bun.string;
const JSC = @import("root").bun.JSC;
const JSC = bun.JSC;
const js = JSC.C;
const WebCore = JSC.WebCore;
const Bundler = bun.bundler;
@@ -19,14 +20,14 @@ const JSObject = JSC.JSObject;
const JSError = Base.JSError;
const JSValue = JSC.JSValue;
const JSGlobalObject = JSC.JSGlobalObject;
const strings = @import("root").bun.strings;
const strings = bun.strings;
const To = Base.To;
const Request = WebCore.Request;
const URLPath = @import("../../http/url_path.zig");
const URL = @import("../../url.zig").URL;
const Log = @import("root").bun.logger;
const Log = bun.logger;
const Resolver = @import("../../resolver/resolver.zig").Resolver;
const Router = @import("../../router.zig");
@@ -88,11 +89,11 @@ pub const FileSystemRouter = struct {
if (!(root_dir_path_.len == 0 or strings.eqlComptime(root_dir_path_.slice(), "."))) {
// resolve relative path if needed
const path = root_dir_path_.slice();
if (bun.path.Platform.isAbsolute(.auto, path)) {
if (path_handler.Platform.auto.isAbsolute(path)) {
root_dir_path = root_dir_path_;
} else {
var parts = [_][]const u8{path};
root_dir_path = JSC.ZigString.Slice.fromUTF8NeverFree(bun.path.joinAbsStringBuf(Fs.FileSystem.instance.top_level_dir, &out_buf, &parts, .auto));
root_dir_path = JSC.ZigString.Slice.fromUTF8NeverFree(path_handler.joinAbsStringBuf(Fs.FileSystem.instance.top_level_dir, &out_buf, &parts, .auto));
}
}
} else {

View File

@@ -1,7 +1,7 @@
const std = @import("std");
const bun = @import("root").bun;
const uv = bun.windows.libuv;
const Path = @import("../../resolver/resolve_path.zig");
const path_handler = bun.path;
const Fs = @import("../../fs.zig");
const Mutex = @import("../../lock.zig").Lock;
const string = bun.string;
@@ -57,7 +57,7 @@ pub const PathWatcherManager = struct {
.is_file = true,
.path = cloned_path,
// if is really a file we need to get the dirname
.dirname = Path.dirname(cloned_path, .windows),
.dirname = std.fs.path.dirname(cloned_path),
.hash = Watcher.getHash(cloned_path),
.refs = 1,
};
@@ -276,12 +276,12 @@ pub const PathWatcher = struct {
// we need the absolute path to get the file info
var buf: [bun.MAX_PATH_BYTES + 1]u8 = undefined;
var parts = [_]string{path};
const cwd = Path.dirname(this.path.path, .windows);
const cwd = std.fs.path.dirname(this.path.path);
@memcpy(buf[0..cwd.len], cwd);
buf[cwd.len] = std.fs.path.sep;
var joined_buf: [bun.MAX_PATH_BYTES + 1]u8 = undefined;
const file_path = Path.joinAbsStringBuf(
const file_path = path_handler.joinAbsStringBuf(
buf[0 .. cwd.len + 1],
&joined_buf,
&parts,

View File

@@ -21,7 +21,7 @@ const linker = @import("../linker.zig");
const allocators = @import("../allocators.zig");
const sync = @import("../sync.zig");
const Api = @import("../api/schema.zig").Api;
const resolve_path = @import("../resolver/resolve_path.zig");
const path_handler = bun.path;
const configureTransformOptionsForBun = @import("../bun.js/config.zig").configureTransformOptionsForBun;
const Command = @import("../cli.zig").Command;
const bundler = bun.bundler;
@@ -263,7 +263,7 @@ pub const CreateCommand = struct {
break :brk positionals[1];
};
const destination = try filesystem.dirname_store.append([]const u8, resolve_path.joinAbs(filesystem.top_level_dir, .auto, dirname));
const destination = try filesystem.dirname_store.append([]const u8, path_handler.joinAbs(filesystem.top_level_dir, .auto, dirname));
var progress = std.Progress{};
var node = progress.start(try ProgressBuf.print("Loading {s}", .{template}), 0);
@@ -485,7 +485,7 @@ pub const CreateCommand = struct {
const createFile = if (comptime Environment.isWindows) std.fs.Dir.createFileW else std.fs.Dir.createFile;
var outfile = createFile(destination_dir_, entry.path, .{}) catch brk: {
if (bun.Dirname.dirname(bun.OSPathChar, entry.path)) |entry_dirname| {
if (std.fs.path.dirname(entry.path)) |entry_dirname| {
bun.MakePath.makePath(bun.OSPathChar, destination_dir_, entry_dirname) catch {};
}
break :brk createFile(destination_dir_, entry.path, .{}) catch |err| {

View File

@@ -16,7 +16,7 @@ const sync = @import("sync.zig");
const Mutex = @import("./lock.zig").Lock;
const Semaphore = sync.Semaphore;
const Fs = @This();
const path_handler = @import("./resolver/resolve_path.zig");
const path_handler = bun.path;
const PathString = bun.PathString;
const allocators = @import("./allocators.zig");
@@ -124,7 +124,7 @@ pub const FileSystem = struct {
// Ensure there's a trailing separator in the top level directory
// This makes path resolution more reliable
if (!bun.path.isSepAny(top_level_dir[top_level_dir.len - 1])) {
if (!std.fs.path.isSep(top_level_dir[top_level_dir.len - 1])) {
const tld = try allocator.alloc(u8, top_level_dir.len + 1);
bun.copy(u8, tld, top_level_dir);
tld[tld.len - 1] = std.fs.path.sep;
@@ -546,7 +546,7 @@ pub const FileSystem = struct {
if (bun.getenvZ("USERPROFILE")) |profile| {
var buf: [bun.MAX_PATH_BYTES]u8 = undefined;
var parts = [_]string{"AppData\\Local\\Temp"};
const out = bun.path.joinAbsStringBuf(profile, &buf, &parts, .loose);
const out = path_handler.joinAbsStringBuf(profile, &buf, &parts, .loose);
break :brk bun.default_allocator.dupe(u8, out) catch unreachable;
}
@@ -1352,63 +1352,15 @@ pub const NodeJSPathName = struct {
pub fn init(_path: string, comptime isWindows: bool) NodeJSPathName {
const platform: path_handler.Platform = if (isWindows) .windows else .posix;
const getLastSep = comptime platform.getLastSeparatorFunc();
var path = _path;
var base = path;
// ext must be empty if not detected
var ext: string = "";
var dir = path;
var is_absolute = true;
var _i = getLastSep(path);
var first = true;
while (_i) |i| {
// Stop if we found a non-trailing slash
if (i + 1 != path.len and path.len >= i + 1) {
base = path[i + 1 ..];
dir = path[0..i];
is_absolute = false;
break;
}
// If the path starts with a slash and it's the only slash, it's absolute
if (i == 0 and first) {
base = path[1..];
dir = &([_]u8{});
break;
}
first = false;
// Ignore trailing slashes
path = path[0..i];
_i = getLastSep(path);
}
// clean trailing slashs
if (base.len > 1 and platform.isSeparator(base[base.len - 1])) {
base = base[0 .. base.len - 1];
}
const isAbsolute = platform.isAbsolute(_path);
const dir = if (isAbsolute) &([_]u8{}) else platform.dirname(_path) orelse &([_]u8{});
const base = platform.basename(_path);
const ext = std.fs.path.extension(base);
// filename is base without extension
var filename = base;
// if only one character ext = "" even if filename it's "."
if (filename.len > 1) {
// Strip off the extension
if (strings.lastIndexOfChar(filename, '.')) |dot| {
if (dot > 0) {
filename = filename[0..dot];
ext = base[dot..];
}
}
if (filename.len > 1 and ext.len > 0) {
filename = filename[0 .. filename.len - ext.len];
}
if (is_absolute) {
dir = &([_]u8{});
}
return NodeJSPathName{
.dir = dir,
.base = base,
@@ -1476,7 +1428,7 @@ pub const PathName = struct {
return if (this.dir.len == 0) "./" else this.dir.ptr[0 .. this.dir.len + @as(
usize,
@intCast(@intFromBool(
!bun.path.isSepAny(this.dir[this.dir.len - 1]) and (@intFromPtr(this.dir.ptr) + this.dir.len + 1) == @intFromPtr(this.base.ptr),
!std.fs.path.isSep(this.dir[this.dir.len - 1]) and (@intFromPtr(this.dir.ptr) + this.dir.len + 1) == @intFromPtr(this.base.ptr),
)),
)];
}
@@ -1488,61 +1440,15 @@ pub const PathName = struct {
std.debug.assert(!strings.startsWith(_path, "/:/"));
std.debug.assert(!strings.startsWith(_path, "\\:\\"));
}
var path = _path;
var base = path;
var ext: []const u8 = undefined;
var dir = path;
var is_absolute = true;
const has_disk_designator = path.len > 2 and path[1] == ':' and switch (path[0]) {
'a'...'z', 'A'...'Z' => true,
else => false,
} and bun.path.isSepAny(path[2]);
if (has_disk_designator) {
path = path[2..];
}
var _i = bun.path.lastIndexOfSep(path);
while (_i) |i| {
// Stop if we found a non-trailing slash
if (i + 1 != path.len and path.len > i + 1) {
base = path[i + 1 ..];
dir = path[0..i];
is_absolute = false;
break;
}
// Ignore trailing slashes
path = path[0..i];
_i = bun.path.lastIndexOfSep(path);
}
// Strip off the extension
if (strings.lastIndexOfChar(base, '.')) |dot| {
ext = base[dot..];
base = base[0..dot];
} else {
ext = "";
}
if (is_absolute) {
dir = &([_]u8{});
}
if (base.len > 1 and bun.path.isSepAny(base[base.len - 1])) {
base = base[0 .. base.len - 1];
}
if (!is_absolute and has_disk_designator) {
dir = _path[0 .. dir.len + 2];
}
const isAbsolute = std.fs.path.isAbsolute(_path);
const dir = if (isAbsolute) &([_]u8{}) else std.fs.path.dirname(_path) orelse &([_]u8{});
const base = std.fs.path.basename(_path);
const filename = if (dir.len > 0) _path[dir.len + 1 ..] else _path;
return PathName{
.dir = dir,
.base = base,
.ext = ext,
.filename = if (dir.len > 0) _path[dir.len + 1 ..] else _path,
.ext = std.fs.path.extension(base),
.filename = filename,
};
}
};

View File

@@ -24,7 +24,7 @@ const linker = @import("../linker.zig");
const sync = @import("../sync.zig");
const Api = @import("../api/schema.zig").Api;
const Path = bun.path;
const path_handler = bun.path;
const configureTransformOptionsForBun = @import("../bun.js/config.zig").configureTransformOptionsForBun;
const Command = @import("../cli.zig").Command;
const BunArguments = @import("../cli.zig").Arguments;
@@ -1251,7 +1251,7 @@ pub const PackageInstall = struct {
const createFile = if (comptime Environment.isWindows) std.fs.Dir.createFileW else std.fs.Dir.createFile;
var outfile = createFile(destination_dir_, entry.path, .{}) catch brk: {
if (bun.Dirname.dirname(bun.OSPathChar, entry.path)) |entry_dirname| {
if (std.fs.path.dirname(entry.path)) |entry_dirname| {
bun.MakePath.makePath(bun.OSPathChar, destination_dir_, entry_dirname) catch {};
}
break :brk createFile(destination_dir_, entry.path, .{}) catch |err| {
@@ -1666,7 +1666,7 @@ pub const PackageInstall = struct {
const dest = std.fs.path.basename(dest_path);
if (comptime Environment.isWindows) {
var dest_buf2: bun.PathBuffer = undefined;
const dest_z = bun.path.joinAbsStringBufZ(
const dest_z = path_handler.joinAbsStringBufZ(
dest_dir_path,
&dest_buf2,
&.{
@@ -1692,7 +1692,7 @@ pub const PackageInstall = struct {
.result => {},
}
} else {
const target = Path.relative(dest_dir_path, to_path);
const target = path_handler.relative(dest_dir_path, to_path);
std.os.symlinkat(target, dest_dir.fd, dest) catch |err| return Result{
.fail = .{
.err = err,
@@ -2482,7 +2482,7 @@ pub const PackageManager = struct {
};
}
this.cache_directory_path = this.allocator.dupe(u8, Path.joinAbsString(
this.cache_directory_path = this.allocator.dupe(u8, path_handler.joinAbsString(
Fs.FileSystem.instance.top_level_dir,
&.{
"node_modules",
@@ -5366,7 +5366,7 @@ pub const PackageManager = struct {
if (bun.getenvZ("BUN_INSTALL")) |home_dir| {
var buf: [bun.MAX_PATH_BYTES]u8 = undefined;
var parts = [_]string{ "install", "global" };
const path = Path.joinAbsStringBuf(home_dir, &buf, &parts, .auto);
const path = path_handler.joinAbsStringBuf(home_dir, &buf, &parts, .auto);
return try std.fs.cwd().makeOpenPath(path, .{});
}
@@ -5374,14 +5374,14 @@ pub const PackageManager = struct {
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" };
const path = Path.joinAbsStringBuf(home_dir, &buf, &parts, .auto);
const path = path_handler.joinAbsStringBuf(home_dir, &buf, &parts, .auto);
return try std.fs.cwd().makeOpenPath(path, .{});
}
} else {
if (bun.getenvZ("USERPROFILE")) |home_dir| {
var buf: [bun.MAX_PATH_BYTES]u8 = undefined;
var parts = [_]string{ ".bun", "install", "global" };
const path = Path.joinAbsStringBuf(home_dir, &buf, &parts, .auto);
const path = path_handler.joinAbsStringBuf(home_dir, &buf, &parts, .auto);
return try std.fs.cwd().makeOpenPath(path, .{});
}
}
@@ -5407,7 +5407,7 @@ pub const PackageManager = struct {
var parts = [_]string{
"bin",
};
const path = Path.joinAbsStringBuf(home_dir, &buf, &parts, .auto);
const path = path_handler.joinAbsStringBuf(home_dir, &buf, &parts, .auto);
return try std.fs.cwd().makeOpenPath(path, .{});
}
@@ -5417,7 +5417,7 @@ pub const PackageManager = struct {
".bun",
"bin",
};
const path = Path.joinAbsStringBuf(home_dir, &buf, &parts, .auto);
const path = path_handler.joinAbsStringBuf(home_dir, &buf, &parts, .auto);
return try std.fs.cwd().makeOpenPath(path, .{});
}
@@ -6481,7 +6481,7 @@ pub const PackageManager = struct {
var parts = [_]string{
"./bun.lockb",
};
const lockfile_path = Path.joinAbsStringBuf(
const lockfile_path = path_handler.joinAbsStringBuf(
Fs.FileSystem.instance.top_level_dir,
&buf,
&parts,
@@ -6748,7 +6748,7 @@ pub const PackageManager = struct {
}
}
switch (Syscall.lstat(Path.joinAbsStringZ(try manager.globalLinkDirPath(), &.{name}, .auto))) {
switch (Syscall.lstat(path_handler.joinAbsStringZ(try manager.globalLinkDirPath(), &.{name}, .auto))) {
.result => |stat| {
if (!std.os.S.ISLNK(stat.mode)) {
Output.prettyErrorln("<r><green>success:<r> package \"{s}\" is not globally linked, so there's nothing to do.", .{name});
@@ -7173,7 +7173,7 @@ pub const PackageManager = struct {
if (cwd_.len > 0 and cwd_[0] == '.') {
const cwd = try bun.getcwd(&buf);
var parts = [_]string{cwd_};
const path_ = Path.joinAbsStringBuf(cwd, &buf2, &parts, .auto);
const path_ = path_handler.joinAbsStringBuf(cwd, &buf2, &parts, .auto);
buf2[path_.len] = 0;
final_path = buf2[0..path_.len :0];
} else {
@@ -8323,7 +8323,7 @@ pub const PackageManager = struct {
scripts.install.isEmpty() and
scripts.postinstall.isEmpty())
brk: {
const binding_dot_gyp_path = Path.joinAbsStringZ(
const binding_dot_gyp_path = path_handler.joinAbsStringZ(
this.node_modules_folder_path.items,
&[_]string{ folder_name, "binding.gyp" },
.auto,
@@ -8332,7 +8332,7 @@ pub const PackageManager = struct {
break :brk Syscall.exists(binding_dot_gyp_path);
} else false;
const cwd = Path.joinAbsStringBufZTrailingSlash(
const cwd = path_handler.joinAbsStringBufZTrailingSlash(
this.node_modules_folder_path.items,
&path_buf_to_use,
&[_]string{destination_dir_subpath},
@@ -9401,7 +9401,7 @@ pub const PackageManager = struct {
}
}
const binding_dot_gyp_path = Path.joinAbsStringZ(
const binding_dot_gyp_path = path_handler.joinAbsStringZ(
Fs.FileSystem.instance.top_level_dir,
&[_]string{"binding.gyp"},
.auto,

View File

@@ -1,6 +1,7 @@
const std = @import("std");
const logger = @import("root").bun.logger;
const bun = @import("root").bun;
const logger = bun.logger;
const path_handler = bun.path;
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
@@ -13,7 +14,7 @@ const C = bun.C;
const CLI = @import("./cli.zig").Cli;
const Features = @import("./analytics/analytics_thread.zig").Features;
const Platform = @import("./analytics/analytics_thread.zig").GenerateHeader.GeneratePlatform;
const HTTP = @import("root").bun.http.AsyncHTTP;
const HTTP = bun.http.AsyncHTTP;
const CrashReporter = @import("./crash_reporter.zig");
const Report = @This();
@@ -72,7 +73,7 @@ pub const CrashReportWriter = struct {
.{ base_dir, Global.package_json_version, @as(u64, @intCast(@max(std.time.milliTimestamp(), 0))) },
) catch return;
if (bun.path.nextDirname(file_path)) |dirname| {
if (std.fs.path.dirname(file_path)) |dirname| {
_ = bun.sys.mkdirA(dirname, 0);
}
@@ -238,7 +239,7 @@ pub fn fatal(err_: ?anyerror, msg_: ?string) void {
// because zig's panic handler will also trigger right after
if (!Environment.isWindows) {
// It only is a real crash report if it's not coming from Zig
if (comptime !@import("root").bun.JSC.is_bindgen) {
if (comptime !bun.JSC.is_bindgen) {
std.mem.doNotOptimizeAway(&Bun__crashReportWrite);
Bun__crashReportDumpStackTrace(&crash_report_writer);
}
@@ -306,7 +307,7 @@ pub noinline fn handleCrash(signal: i32, addr: usize) void {
}
if (!Environment.isWindows) {
if (comptime !@import("root").bun.JSC.is_bindgen) {
if (comptime !bun.JSC.is_bindgen) {
std.mem.doNotOptimizeAway(&Bun__crashReportWrite);
Bun__crashReportDumpStackTrace(&crash_report_writer);
}

File diff suppressed because it is too large Load Diff

View File

@@ -26,7 +26,7 @@ const BrowserMap = @import("./package_json.zig").BrowserMap;
const CacheSet = cache.Set;
const DataURL = @import("./data_url.zig").DataURL;
pub const DirInfo = @import("./dir_info.zig");
const ResolvePath = @import("./resolve_path.zig");
const path_handler = bun.path;
const NodeFallbackModules = @import("../node_fallbacks.zig");
const Mutex = @import("../lock.zig").Lock;
const StringBoolMap = bun.StringHashMap(bool);
@@ -1188,7 +1188,7 @@ pub const Resolver = struct {
}
// Run node's resolution rules (e.g. adding ".js")
var normalizer = ResolvePath.PosixToWinNormalizer{};
var normalizer = path_handler.PosixToWinNormalizer{};
if (r.loadAsFileOrDirectory(normalizer.resolve(source_dir, import_path), kind)) |entry| {
return .{
.success = Result{
@@ -2293,7 +2293,7 @@ pub const Resolver = struct {
if (entries.get(file_name) != null) {
if (r.debug_logs) |*debug| {
const parts = [_]string{ package_json.name, package_subpath };
debug.addNoteFmt("The import {s} is missing the extension {s}", .{ ResolvePath.join(parts, .auto), ext });
debug.addNoteFmt("The import {s} is missing the extension {s}", .{ path_handler.join(parts, .auto), ext });
}
esm_resolution.status = .ModuleNotFoundMissingExtension;
missing_suffix = ext;
@@ -2323,7 +2323,7 @@ pub const Resolver = struct {
missing_suffix = std.fmt.allocPrint(r.allocator, "/{s}", .{file_name}) catch unreachable;
defer r.allocator.free(missing_suffix);
const parts = [_]string{ package_json.name, package_subpath };
debug.addNoteFmt("The import {s} is missing the suffix {s}", .{ ResolvePath.join(parts, .auto), missing_suffix });
debug.addNoteFmt("The import {s} is missing the suffix {s}", .{ path_handler.join(parts, .auto), missing_suffix });
}
break;
}
@@ -2542,25 +2542,20 @@ pub const Resolver = struct {
var path = dir_info_uncached_path_buf[0.._path.len];
bufs(.dir_entry_paths_to_resolve)[0] = (DirEntryResolveQueueItem{ .result = top_result, .unsafe_path = path, .safe_path = "" });
var top = Dirname.dirname(path);
var top = std.fs.path.dirname(path) orelse &([_]u8{});
var top_parent: allocators.Result = allocators.Result{
.index = allocators.NotFound,
.hash = 0,
.status = .not_found,
};
const root_path = if (comptime Environment.isWindows)
ResolvePath.windowsFilesystemRoot(path)
else
// we cannot just use "/"
// we will write to the buffer past the ptr len so it must be a non-const buffer
path[0..1];
const root_path = path_handler.getRoot(path);
var rfs: *Fs.FileSystem.RealFS = &r.fs.fs;
rfs.entries_mutex.lock();
defer rfs.entries_mutex.unlock();
while (!strings.eql(top, root_path)) : (top = Dirname.dirname(top)) {
while (!strings.eql(top, root_path)) : (top = std.fs.path.dirname(top) orelse &([_]u8{})) {
const result = try r.dir_cache.getOrPut(top);
if (result.status != .unknown) {
@@ -3054,7 +3049,7 @@ pub const Resolver = struct {
var index_path: string = "";
{
var parts = [_]string{ std.mem.trimRight(u8, path_to_check, std.fs.path.sep_str), std.fs.path.sep_str ++ "index" };
index_path = ResolvePath.joinStringBuf(bufs(.tsconfig_base_url), &parts, .auto);
index_path = path_handler.joinStringBuf(bufs(.tsconfig_base_url), &parts, .auto);
}
if (map.get(index_path)) |_remapped| {
@@ -3618,7 +3613,7 @@ pub const Resolver = struct {
}
}
const dir_path = Dirname.dirname(path);
const dir_path = std.fs.path.dirname(path) orelse &([_]u8{});
const dir_entry: *Fs.FileSystem.RealFS.EntriesOption = rfs.readDirectory(
dir_path,
@@ -4011,8 +4006,8 @@ pub const Resolver = struct {
try parent_configs.append(tsconfig_json);
var current = tsconfig_json;
while (current.extends.len > 0) {
const ts_dir_name = Dirname.dirname(current.abs_path);
const abs_path = ResolvePath.joinAbsStringBuf(ts_dir_name, bufs(.tsconfig_path_abs), &[_]string{ ts_dir_name, current.extends }, .auto);
const ts_dir_name = std.fs.path.dirname(current.abs_path) orelse &([_]u8{});
const abs_path = path_handler.joinAbsStringBuf(ts_dir_name, bufs(.tsconfig_path_abs), &[_]string{ ts_dir_name, current.extends }, .auto);
const parent_config_maybe = r.parseTSConfig(abs_path, bun.invalid_fd) catch |err| {
r.log.addDebugFmt(null, logger.Loc.Empty, r.allocator, "{s} loading tsconfig.json extends {}", .{
@errorName(err),
@@ -4060,43 +4055,6 @@ pub const Resolver = struct {
}
};
pub const Dirname = struct {
pub fn dirname(path: string) string {
if (path.len == 0)
return std.fs.path.sep_str;
const root = brk: {
if (Environment.isWindows) {
const root = ResolvePath.windowsFilesystemRoot(path);
std.debug.assert(root.len > 0);
break :brk root;
}
break :brk "/";
};
var end_index: usize = path.len - 1;
while (bun.path.isSepAny(path[end_index])) {
if (end_index == 0)
return root;
end_index -= 1;
}
while (!bun.path.isSepAny(path[end_index])) {
if (end_index == 0)
return root;
end_index -= 1;
}
if (end_index == 0 and bun.path.isSepAny(path[0]))
return path[0..1];
if (end_index == 0)
return root;
return path[0 .. end_index + 1];
}
};
pub const RootPathPair = struct {
base_path: string,
package_json: *const PackageJSON,

View File

@@ -10,7 +10,7 @@ const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const std = @import("std");
const resolve_path = @import("./resolver/resolve_path.zig");
const path_handler = bun.path;
const Fs = @import("./fs.zig");
const Schema = @import("./api/schema.zig");
const Ref = @import("ast/base.zig").Ref;
@@ -38,7 +38,7 @@ pub const ErrorCSS = struct {
const dirname = std.fs.selfExeDirPath(&out_buffer) catch unreachable;
var paths = [_]string{ dirname, BUN_ROOT, content.error_css_path };
const file = std.fs.cwd().openFile(
resolve_path.joinAbsString(dirname, &paths, .auto),
path_handler.joinAbsString(dirname, &paths, .auto),
.{ .mode = .read_only },
) catch return embedDebugFallback(
"Missing packages/bun-error/bun-error.css. Please run \"make bun_error\"",
@@ -61,7 +61,7 @@ pub const ErrorJS = struct {
const dirname = std.fs.selfExeDirPath(&out_buffer) catch unreachable;
var paths = [_]string{ dirname, BUN_ROOT, content.error_js_path };
const file = std.fs.cwd().openFile(
resolve_path.joinAbsString(dirname, &paths, .auto),
path_handler.joinAbsString(dirname, &paths, .auto),
.{ .mode = .read_only },
) catch return embedDebugFallback(
"Missing " ++ content.error_js_path ++ ". Please run \"make bun_error\"",
@@ -117,7 +117,7 @@ pub const Fallback = struct {
pub inline fn scriptContent() string {
if (comptime Environment.isDebug) {
const dirpath = comptime bun.Environment.base_path ++ (bun.Dirname.dirname(u8, @src().file) orelse "");
const dirpath = comptime bun.Environment.base_path ++ (std.fs.path.dirname(@src().file).?);
var buf: bun.PathBuffer = undefined;
const user = bun.getUserName(&buf) orelse "";
const dir = std.mem.replaceOwned(

View File

@@ -16,10 +16,11 @@
//! `defer` some code, then try to yield execution to some state machine struct,
//! and it immediately finishes, it will deinit itself and the defer code might
//! use undefined memory.
const bun = @import("root").bun;
//!
const std = @import("std");
const os = std.os;
const builtin = @import("builtin");
const bun = @import("root").bun;
const os = std.os;
const Arena = std.heap.ArenaAllocator;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
@@ -27,11 +28,11 @@ const JSC = bun.JSC;
const JSValue = bun.JSC.JSValue;
const JSPromise = bun.JSC.JSPromise;
const JSGlobalObject = bun.JSC.JSGlobalObject;
const path_handler = bun.path;
const which = @import("../which.zig").which;
const Braces = @import("./braces.zig");
const Syscall = @import("../sys.zig");
const Glob = @import("../glob.zig");
const ResolvePath = @import("../resolver/resolve_path.zig");
const DirIterator = @import("../bun.js/node/dir_iterator.zig");
const CodepointIterator = @import("../string_immutable.zig").PackedCodepointIterator;
const isAllAscii = @import("../string_immutable.zig").isAllASCII;
@@ -662,27 +663,27 @@ pub fn NewInterpreter(comptime EventLoopKind: JSC.EventLoopKind) type {
const is_sentinel = @TypeOf(new_cwd_) == [:0]const u8;
const new_cwd: [:0]const u8 = brk: {
if (ResolvePath.Platform.auto.isAbsolute(new_cwd_)) {
if (path_handler.Platform.auto.isAbsolute(new_cwd_)) {
if (is_sentinel) {
@memcpy(ResolvePath.join_buf[0..new_cwd_.len], new_cwd_[0..new_cwd_.len]);
ResolvePath.join_buf[new_cwd_.len] = 0;
break :brk ResolvePath.join_buf[0..new_cwd_.len :0];
@memcpy(path_handler.join_buf[0..new_cwd_.len], new_cwd_[0..new_cwd_.len]);
path_handler.join_buf[new_cwd_.len] = 0;
break :brk path_handler.join_buf[0..new_cwd_.len :0];
}
std.mem.copyForwards(u8, &ResolvePath.join_buf, new_cwd_);
ResolvePath.join_buf[new_cwd_.len] = 0;
break :brk ResolvePath.join_buf[0..new_cwd_.len :0];
std.mem.copyForwards(u8, &path_handler.join_buf, new_cwd_);
path_handler.join_buf[new_cwd_.len] = 0;
break :brk path_handler.join_buf[0..new_cwd_.len :0];
}
const existing_cwd = this.cwd();
const cwd_str = ResolvePath.joinZ(&[_][]const u8{
const cwd_str = path_handler.joinZ(&[_][]const u8{
existing_cwd,
new_cwd_,
}, .auto);
// remove trailing separator
if (cwd_str.len > 1 and cwd_str[cwd_str.len - 1] == '/') {
ResolvePath.join_buf[cwd_str.len - 1] = 0;
break :brk ResolvePath.join_buf[0 .. cwd_str.len - 1 :0];
path_handler.join_buf[cwd_str.len - 1] = 0;
break :brk path_handler.join_buf[0 .. cwd_str.len - 1 :0];
}
break :brk cwd_str;
@@ -5009,11 +5010,11 @@ pub fn NewInterpreter(comptime EventLoopKind: JSC.EventLoopKind) type {
_ = this; // autofix
if (!is_absolute) {
// If relative paths enabled, stdlib join is preferred over
// ResolvePath.joinBuf because it doesn't try to normalize the path
// path_handler.joinBuf because it doesn't try to normalize the path
return std.fs.path.joinZ(alloc, subdir_parts) catch bun.outOfMemory();
}
const out = alloc.dupeZ(u8, bun.path.join(subdir_parts, .auto)) catch bun.outOfMemory();
const out = alloc.dupeZ(u8, path_handler.join(subdir_parts, .auto)) catch bun.outOfMemory();
return out;
}
@@ -5665,7 +5666,7 @@ pub fn NewInterpreter(comptime EventLoopKind: JSC.EventLoopKind) type {
const path_in_dir = std.fs.path.joinZ(fixed_alloc.allocator(), &[_][]const u8{
"./",
ResolvePath.basename(src),
std.fs.path.basename(src),
}) catch {
this.err = Syscall.Error.fromCode(bun.C.E.NAMETOOLONG, .rename);
return false;
@@ -5673,9 +5674,9 @@ pub fn NewInterpreter(comptime EventLoopKind: JSC.EventLoopKind) type {
switch (Syscall.renameat(this.cwd, src, this.target_fd.?, path_in_dir)) {
.err => |e| {
const target_path = ResolvePath.joinZ(&[_][]const u8{
const target_path = path_handler.joinZ(&[_][]const u8{
this.target,
ResolvePath.basename(src),
std.fs.path.basename(src),
}, .auto);
this.err = e.withPath(bun.default_allocator.dupeZ(u8, target_path[0..]) catch bun.outOfMemory());
@@ -6285,10 +6286,10 @@ pub fn NewInterpreter(comptime EventLoopKind: JSC.EventLoopKind) type {
for (filepath_args) |filepath| {
const path = filepath[0..bun.len(filepath)];
const resolved_path = if (ResolvePath.Platform.auto.isAbsolute(path)) path else bun.path.join(&[_][]const u8{ cwd, path }, .auto);
const resolved_path = if (path_handler.Platform.auto.isAbsolute(path)) path else path_handler.join(&[_][]const u8{ cwd, path }, .auto);
const is_root = brk: {
const normalized = bun.path.normalizeString(resolved_path, false, .auto);
const dirname = ResolvePath.dirname(normalized, .auto);
const normalized = path_handler.normalizeString(resolved_path, false, .auto);
const dirname = path_handler.Platform.auto.dirname(normalized) orelse &([_]u8{});
const is_root = std.mem.eql(u8, dirname, "");
break :brk is_root;
};
@@ -6405,7 +6406,7 @@ pub fn NewInterpreter(comptime EventLoopKind: JSC.EventLoopKind) type {
for (this.state.exec.filepath_args) |root_raw| {
const root = root_raw[0..std.mem.len(root_raw)];
const root_path_string = bun.PathString.init(root[0..root.len]);
const is_absolute = ResolvePath.Platform.auto.isAbsolute(root);
const is_absolute = path_handler.Platform.auto.isAbsolute(root);
var task = ShellRmTask.create(root_path_string, this, cwd, &this.state.exec.error_signal, is_absolute);
task.schedule();
// task.
@@ -6730,7 +6731,7 @@ pub fn NewInterpreter(comptime EventLoopKind: JSC.EventLoopKind) type {
defer this.postRun();
print("DirTask: {s}", .{this.path});
switch (this.task_manager.removeEntry(this, ResolvePath.Platform.auto.isAbsolute(this.path[0..this.path.len]))) {
switch (this.task_manager.removeEntry(this, path_handler.Platform.auto.isAbsolute(this.path[0..this.path.len]))) {
.err => |err| {
print("DirTask({x}) failed: {s}: {s}", .{ @intFromPtr(this), @tagName(err.getErrno()), err.path });
this.task_manager.err_mutex.lock();
@@ -7206,11 +7207,11 @@ pub fn NewInterpreter(comptime EventLoopKind: JSC.EventLoopKind) type {
_ = this;
if (!is_absolute) {
// If relative paths enabled, stdlib join is preferred over
// ResolvePath.joinBuf because it doesn't try to normalize the path
// path_handler.joinBuf because it doesn't try to normalize the path
return std.fs.path.joinZ(alloc, subdir_parts) catch bun.outOfMemory();
}
const out = alloc.dupeZ(u8, bun.path.join(subdir_parts, .auto)) catch bun.outOfMemory();
const out = alloc.dupeZ(u8, path_handler.join(subdir_parts, .auto)) catch bun.outOfMemory();
return out;
}

View File

@@ -1,10 +1,11 @@
const std = @import("std");
const bun = @import("root").bun;
const expect = std.testing.expect;
const Environment = @import("./env.zig");
const string = bun.string;
const stringZ = bun.stringZ;
const CodePoint = bun.CodePoint;
const bun = @import("root").bun;
const path_handler = bun.path;
pub const joiner = @import("./string_joiner.zig");
const log = bun.Output.scoped(.STR, true);
const js_lexer = @import("./js_lexer.zig");
@@ -16,6 +17,9 @@ pub const Encoding = enum {
utf16,
};
const sep_posix = std.fs.path.sep_posix;
const sep_windows = std.fs.path.sep_windows;
pub inline fn containsChar(self: string, char: u8) bool {
return indexOfChar(self, char) != null;
}
@@ -1651,18 +1655,18 @@ pub fn toWPathNormalized(wbuf: []u16, utf8: []const u8) [:0]const u16 {
var renormalized: [bun.MAX_PATH_BYTES]u8 = undefined;
var path_to_use = utf8;
if (bun.strings.containsChar(utf8, '/')) {
if (bun.strings.containsChar(utf8, sep_posix)) {
@memcpy(renormalized[0..utf8.len], utf8);
for (renormalized[0..utf8.len]) |*c| {
if (c.* == '/') {
c.* = '\\';
if (c.* == sep_posix) {
c.* = sep_windows;
}
}
path_to_use = renormalized[0..utf8.len];
}
// is there a trailing slash? Let's remove it before converting to UTF-16
if (path_to_use.len > 3 and bun.path.isSepAny(path_to_use[path_to_use.len - 1])) {
if (path_to_use.len > 3 and std.fs.path.isSep(path_to_use[path_to_use.len - 1])) {
path_to_use = path_to_use[0 .. path_to_use.len - 1];
}
@@ -1673,11 +1677,11 @@ pub fn toWDirNormalized(wbuf: []u16, utf8: []const u8) [:0]const u16 {
var renormalized: [bun.MAX_PATH_BYTES]u8 = undefined;
var path_to_use = utf8;
if (bun.strings.containsChar(utf8, '/')) {
if (bun.strings.containsChar(utf8, sep_posix)) {
@memcpy(renormalized[0..utf8.len], utf8);
for (renormalized[0..utf8.len]) |*c| {
if (c.* == '/') {
c.* = '\\';
if (c.* == sep_posix) {
c.* = sep_windows;
}
}
path_to_use = renormalized[0..utf8.len];
@@ -2287,7 +2291,7 @@ pub fn elementLengthLatin1IntoUTF8(comptime Type: type, latin1_: Type) usize {
return input_len + total_non_ascii_count;
}
const JSC = @import("root").bun.JSC;
const JSC = bun.JSC;
pub fn copyLatin1IntoUTF16(comptime Buffer: type, buf_: Buffer, comptime Type: type, latin1_: Type) EncodeIntoResult {
var buf = buf_;