From 87dc7f0e18d0f766b6c06a2e88d0bf4df97be7a9 Mon Sep 17 00:00:00 2001 From: Gengkun Date: Wed, 24 Apr 2024 14:30:08 +0800 Subject: [PATCH] fix: RootsPlugin should fall through if it fails to resolve the roots (#144) --------- Co-authored-by: Boshen --- .../test/fixtures/roots_fall_through/index.js | 0 src/lib.rs | 30 ++++++++----------- src/tests/roots.rs | 9 ++++++ 3 files changed, 21 insertions(+), 18 deletions(-) create mode 100644 fixtures/enhanced_resolve/test/fixtures/roots_fall_through/index.js diff --git a/fixtures/enhanced_resolve/test/fixtures/roots_fall_through/index.js b/fixtures/enhanced_resolve/test/fixtures/roots_fall_through/index.js new file mode 100644 index 00000000..e69de29b diff --git a/src/lib.rs b/src/lib.rs index 57cc9678..b45caeb6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -333,27 +333,21 @@ impl ResolverGeneric { return Ok(path); } } - if self.options.roots.is_empty() { - // 2. If X begins with '/' - // a. set Y to be the file system root - let path = self.cache.value(Path::new(specifier)); - if let Some(path) = self.load_as_file_or_directory(&path, specifier, ctx)? { + // enhanced-resolve: RootsPlugin + for root in &self.options.roots { + let cached_path = self.cache.value(root); + let specifier = specifier.trim_start_matches(SLASH_START); + if let Ok(path) = self.require_relative(&cached_path, specifier, ctx) { return Ok(path); } - Err(ResolveError::NotFound(specifier.to_string())) - } else { - for root in &self.options.roots { - let cached_path = self.cache.value(root); - if let Ok(path) = self.require_relative( - &cached_path, - specifier.trim_start_matches(SLASH_START), - ctx, - ) { - return Ok(path); - } - } - Err(ResolveError::NotFound(specifier.to_string())) } + // 2. If X begins with '/' + // a. set Y to be the file system root + let path = self.cache.value(Path::new(specifier)); + if let Some(path) = self.load_as_file_or_directory(&path, specifier, ctx)? { + return Ok(path); + } + Err(ResolveError::NotFound(specifier.to_string())) } // 3. If X begins with './' or '/' or '../' diff --git a/src/tests/roots.rs b/src/tests/roots.rs index 72f122fb..cc3b4895 100644 --- a/src/tests/roots.rs +++ b/src/tests/roots.rs @@ -78,3 +78,12 @@ fn prefer_absolute() { assert_eq!(resolved_path, Ok(expected), "{comment} {request}"); } } + +#[test] +fn roots_fall_through() { + let f = super::fixture(); + let absolute_path = f.join("roots_fall_through/index.js"); + let specifier = absolute_path.to_string_lossy(); + let resolution = Resolver::new(ResolveOptions::default().with_root(&f)).resolve(&f, &specifier); + assert_eq!(resolution.map(|r| r.into_path_buf()), Ok(absolute_path)); +}