Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions docs/runtime/glob.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,18 @@ The `Glob` class implements the following interface:

```ts
class Glob {
scan(root: string | ScanOptions): AsyncIterable<string>;
scanSync(root: string | ScanOptions): Iterable<string>;
scan(root: string | URL | ScanOptions): AsyncIterable<string>;
scanSync(root: string | URL | ScanOptions): Iterable<string>;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

match(path: string): boolean;
}

interface ScanOptions {
/**
* The root directory to start matching from. Defaults to `process.cwd()`
* The root directory to start matching from, as a path or a `file:` URL.
* Defaults to `process.cwd()`
*/
cwd?: string;
cwd?: string | URL;

/**
* Allow patterns to match entries that begin with a period (`.`).
Expand Down
9 changes: 5 additions & 4 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8815,9 +8815,10 @@ declare module "bun" {

interface GlobScanOptions {
/**
* The root directory to start matching from. Defaults to `process.cwd()`
* The root directory to start matching from, as a path or a `file:` URL.
* Defaults to `process.cwd()`
*/
cwd?: string;
cwd?: string | URL;

/**
* Allow patterns to match entries that begin with a period (`.`).
Expand Down Expand Up @@ -8911,7 +8912,7 @@ declare module "bun" {
* }
* ```
*/
scan(optionsOrCwd?: string | GlobScanOptions): AsyncIterableIterator<string>;
scan(optionsOrCwd?: string | URL | GlobScanOptions): AsyncIterableIterator<string>;

/**
* Synchronously scan a root directory recursively for files that match this glob pattern. Returns an iterator.
Expand All @@ -8932,7 +8933,7 @@ declare module "bun" {
* }
* ```
*/
scanSync(optionsOrCwd?: string | GlobScanOptions): IterableIterator<string>;
scanSync(optionsOrCwd?: string | URL | GlobScanOptions): IterableIterator<string>;

/**
* Match the glob against a string
Expand Down
19 changes: 18 additions & 1 deletion src/jsc/DOMURL.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use core::ffi::c_int;

use crate::{JSValue, VM};
use crate::{ErrorCode, JSGlobalObject, JSValue, JsResult, VM};
use bun_core as bstr;

bun_opaque::opaque_ffi! {
Expand Down Expand Up @@ -57,4 +57,21 @@ impl DOMURL {
debug_assert!(path.tag() != bun_core::Tag::Dead);
Ok(path)
}

/// [`file_system_path`](Self::file_system_path) for a path argument: a URL
/// that is not a non-empty `file:` path throws `ERR_INVALID_URL_SCHEME` /
/// `ERR_INVALID_FILE_URL_PATH` / `ERR_INVALID_FILE_URL_HOST` /
/// `ERR_INVALID_ARG_VALUE`, like `fileURLToPath()`.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn file_system_path_for_js(&mut self, global: &JSGlobalObject) -> JsResult<bstr::String> {
let code = match self.file_system_path() {
Ok(path) if !path.is_empty() => return Ok(path),
Ok(_) => ErrorCode::INVALID_ARG_VALUE,
Err(ToFileSystemPathError::NotFileUrl) => ErrorCode::INVALID_URL_SCHEME,
Err(ToFileSystemPathError::InvalidPath) => ErrorCode::INVALID_FILE_URL_PATH,
Err(ToFileSystemPathError::InvalidHost) => ErrorCode::INVALID_FILE_URL_HOST,
};
Err(global
.err(code, format_args!("URL must be a non-empty \"file:\" path"))
.throw())
}
}
51 changes: 26 additions & 25 deletions src/runtime/api/glob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use bun_glob::BunGlobWalker as GlobWalker;
use bun_glob::walk;
use bun_jsc::bun_string_jsc;
use bun_jsc::{
ArgumentsSlice, CallFrame, JSGlobalObject, JSPromiseStrong, JSValue, Job, JobContext, JsPtr,
JsResult, JsThread, StringJsc as _, SysErrorJsc as _,
ArgumentsSlice, CallFrame, DOMURL, JSGlobalObject, JSPromiseStrong, JSValue, Job, JobContext,
JsPtr, JsResult, JsThread, StringJsc as _, SysErrorJsc as _,
};
use bun_paths::resolve_path::join_string_buf;
use bun_paths::{self as resolve_path, MAX_PATH_BYTES, platform};
Expand Down Expand Up @@ -38,7 +38,16 @@ impl ScanOpts {
absolute: bool,
fn_name: &'static str,
) -> JsResult<Box<[u8]>> {
let cwd_string = BunString::from_js(cwd_val, global_this)?;
let cwd_string = if let Some(url) = DOMURL::cast(cwd_val) {
url.file_system_path_for_js(global_this)?
} else if cwd_val.is_string() {
BunString::from_js(cwd_val, global_this)?
} else {
return Err(global_this.throw(format_args!(
"{}: invalid `cwd`, not a string or URL",
fn_name
)));
};
if cwd_string.is_empty() {
return Ok(Box::default());
}
Expand Down Expand Up @@ -114,19 +123,19 @@ impl ScanOpts {
if opts_obj.is_undefined_or_null() {
return Ok(Some(out));
}
if !opts_obj.is_object() {
if opts_obj.is_string() {
{
let result =
Self::parse_cwd(global_this, arena, opts_obj, out.absolute, fn_name)?;
if !result.is_empty() {
out.cwd = Some(result);
}
}
return Ok(Some(out));
// `scan(cwd)`: a string or a `file:` URL in the options slot is the cwd.
if opts_obj.is_string() || DOMURL::cast(opts_obj).is_some() {
let result = Self::parse_cwd(global_this, arena, opts_obj, out.absolute, fn_name)?;
if !result.is_empty() {
out.cwd = Some(result);
}
return Ok(Some(out));
}
// A Buffer or an array is an object too, but never an options bag. Taking
// it as one would silently scan `process.cwd()`.
if !opts_obj.is_object() || opts_obj.js_type().is_array_like() {
return Err(global_this.throw(format_args!(
"{}: expected first argument to be an object",
"{}: expected first argument to be a string, URL, or options object",
fn_name
)));
}
Expand Down Expand Up @@ -166,17 +175,9 @@ impl ScanOpts {
}

if let Some(cwd_val) = opts_obj.get_truthy(global_this, "cwd")? {
if !cwd_val.is_string() {
return Err(
global_this.throw(format_args!("{}: invalid `cwd`, not a string", fn_name))
);
}

{
let result = Self::parse_cwd(global_this, arena, cwd_val, out.absolute, fn_name)?;
if !result.is_empty() {
out.cwd = Some(result);
}
let result = Self::parse_cwd(global_this, arena, cwd_val, out.absolute, fn_name)?;
if !result.is_empty() {
out.cwd = Some(result);
}
}

Expand Down
37 changes: 1 addition & 36 deletions src/runtime/node/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1128,42 +1128,7 @@ impl PathLikeExt for PathLike<'_> {
}
_ => {
if let Some(domurl) = jsc::DOMURL::cast(arg) {
use jsc::dom_url::ToFileSystemPathError;
let str = match domurl.file_system_path() {
Ok(s) => s,
Err(ToFileSystemPathError::NotFileUrl) => {
return Err(ctx
.err(
jsc::ErrorCode::INVALID_URL_SCHEME,
format_args!("URL must be a non-empty \"file:\" path"),
)
.throw());
}
Err(ToFileSystemPathError::InvalidPath) => {
return Err(ctx
.err(
jsc::ErrorCode::INVALID_FILE_URL_PATH,
format_args!("URL must be a non-empty \"file:\" path"),
)
.throw());
}
Err(ToFileSystemPathError::InvalidHost) => {
return Err(ctx
.err(
jsc::ErrorCode::INVALID_FILE_URL_HOST,
format_args!("URL must be a non-empty \"file:\" path"),
)
.throw());
}
};
if str.is_empty() {
return Err(ctx
.err(
jsc::ErrorCode::INVALID_ARG_VALUE,
format_args!("URL must be a non-empty \"file:\" path"),
)
.throw());
}
let str = domurl.file_system_path_for_js(ctx)?;
arguments.eat();
path_like_from_string(ctx, str, arguments.will_be_async)?
} else {
Expand Down
67 changes: 67 additions & 0 deletions test/js/bun/glob/scan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,73 @@ describe("glob.match", async () => {
}
});

test("cwd accepts a file URL, and a non-options object in the cwd slot throws", async () => {
using dir = tempDir("glob-scan-url-cwd", {
"real/REAL.txt": "",
"real/sub/INNER.txt": "",
"other/OTHER.txt": "",
});
const real = path.join(String(dir), "real");

// Run from a sibling directory so that a silently ignored cwd shows up as
// ["OTHER.txt"]. Both URL spellings (with and without the trailing slash
// that `new URL("./real/", import.meta.url)` produces) must work.
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const real = process.argv[1];
const urls = [Bun.pathToFileURL(real), Bun.pathToFileURL(real + ${JSON.stringify(path.sep)})];
const results = {};
const attempt = async (label, fn) => {
try {
results[label] = (await fn()).sort();
} catch (e) {
results[label] = "throw: " + e.message;
}
};
for (const [i, u] of urls.entries()) {
await attempt("scanSync(URL" + i + ")", () => [...new Bun.Glob("**/*.txt").scanSync(u)]);
await attempt("scan(URL" + i + ")", () => Array.fromAsync(new Bun.Glob("**/*.txt").scan(u)));
await attempt("scanSync({cwd: URL" + i + "})", () => [...new Bun.Glob("**/*.txt").scanSync({ cwd: u })]);
await attempt("scan({cwd: URL" + i + "})", () => Array.fromAsync(new Bun.Glob("**/*.txt").scan({ cwd: u })));
}
await attempt("scanSync(string)", () => [...new Bun.Glob("**/*.txt").scanSync(real)]);
await attempt("scanSync(Buffer)", () => [...new Bun.Glob("*").scanSync(Buffer.from(real))]);
await attempt("scanSync([real])", () => [...new Bun.Glob("*").scanSync([real])]);
await attempt("scanSync({cwd: Buffer})", () => [...new Bun.Glob("*").scanSync({ cwd: Buffer.from(real) })]);
await attempt("scanSync(http URL)", () => [...new Bun.Glob("*").scanSync(new URL("http://example.com/real"))]);
await attempt("scanSync({cwd: http URL})", () => [...new Bun.Glob("*").scanSync({ cwd: new URL("http://example.com/real") })]);
console.log(JSON.stringify(results));
`,
real,
],
env: bunEnv,
cwd: path.join(String(dir), "other"),
stdout: "pipe",
stderr: "inherit",
});
const found = ["REAL.txt", path.join("sub", "INNER.txt")].sort();
expect(JSON.parse(await proc.stdout.text())).toEqual({
"scanSync(URL0)": found,
"scan(URL0)": found,
"scanSync({cwd: URL0})": found,
"scan({cwd: URL0})": found,
"scanSync(URL1)": found,
"scan(URL1)": found,
"scanSync({cwd: URL1})": found,
"scan({cwd: URL1})": found,
"scanSync(string)": found,
"scanSync(Buffer)": "throw: scanSync: expected first argument to be a string, URL, or options object",
"scanSync([real])": "throw: scanSync: expected first argument to be a string, URL, or options object",
"scanSync({cwd: Buffer})": "throw: scanSync: invalid `cwd`, not a string or URL",
"scanSync(http URL)": 'throw: URL must be a non-empty "file:" path',
"scanSync({cwd: http URL})": 'throw: URL must be a non-empty "file:" path',
});
expect(await proc.exited).toBe(0);
});

test("oversized cwd throws instead of crashing", async () => {
const glob = new Glob("*.ts");
const tooLong = Buffer.alloc(100_000, "x").toString();
Expand Down
Loading