summaryrefslogtreecommitdiff
path: root/resolvers/node/package_json.rs
diff options
context:
space:
mode:
authorDavid Sherret <dsherret@users.noreply.github.com>2024-09-28 19:17:48 -0400
committerGitHub <noreply@github.com>2024-09-28 19:17:48 -0400
commit5faf769ac61b627d14710cdf487de7cd4eb3f9d3 (patch)
tree2cc4ab975522b3c8845ab3040c010fd998a769a6 /resolvers/node/package_json.rs
parent3138478f66823348eb745c7f0c2d34eed378a3f0 (diff)
refactor: extract out sloppy imports resolution from CLI crate (#25920)
This is slow progress towards creating a `deno_resolver` crate. Waiting on: * https://github.com/denoland/deno/pull/25918 * https://github.com/denoland/deno/pull/25916
Diffstat (limited to 'resolvers/node/package_json.rs')
-rw-r--r--resolvers/node/package_json.rs53
1 files changed, 53 insertions, 0 deletions
diff --git a/resolvers/node/package_json.rs b/resolvers/node/package_json.rs
new file mode 100644
index 000000000..de750f1d7
--- /dev/null
+++ b/resolvers/node/package_json.rs
@@ -0,0 +1,53 @@
+// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
+
+use deno_package_json::PackageJson;
+use deno_package_json::PackageJsonRc;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::io::ErrorKind;
+use std::path::Path;
+use std::path::PathBuf;
+
+use crate::errors::PackageJsonLoadError;
+
+// use a thread local cache so that workers have their own distinct cache
+thread_local! {
+ static CACHE: RefCell<HashMap<PathBuf, PackageJsonRc>> = RefCell::new(HashMap::new());
+}
+
+pub struct PackageJsonThreadLocalCache;
+
+impl PackageJsonThreadLocalCache {
+ pub fn clear() {
+ CACHE.with(|cache| cache.borrow_mut().clear());
+ }
+}
+
+impl deno_package_json::PackageJsonCache for PackageJsonThreadLocalCache {
+ fn get(&self, path: &Path) -> Option<PackageJsonRc> {
+ CACHE.with(|cache| cache.borrow().get(path).cloned())
+ }
+
+ fn set(&self, path: PathBuf, package_json: PackageJsonRc) {
+ CACHE.with(|cache| cache.borrow_mut().insert(path, package_json));
+ }
+}
+
+/// Helper to load a package.json file using the thread local cache
+/// in node_resolver.
+pub fn load_pkg_json(
+ fs: &dyn deno_package_json::fs::DenoPkgJsonFs,
+ path: &Path,
+) -> Result<Option<PackageJsonRc>, PackageJsonLoadError> {
+ let result =
+ PackageJson::load_from_path(path, fs, Some(&PackageJsonThreadLocalCache));
+ match result {
+ Ok(pkg_json) => Ok(Some(pkg_json)),
+ Err(deno_package_json::PackageJsonLoadError::Io { source, .. })
+ if source.kind() == ErrorKind::NotFound =>
+ {
+ Ok(None)
+ }
+ Err(err) => Err(PackageJsonLoadError(err)),
+ }
+}