2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2022-08-20 11:31:33 -04:00
|
|
|
|
2024-07-23 17:34:46 -04:00
|
|
|
use deno_package_json::PackageJson;
|
|
|
|
use deno_package_json::PackageJsonRc;
|
2023-02-06 10:20:20 -05:00
|
|
|
use std::cell::RefCell;
|
|
|
|
use std::collections::HashMap;
|
2022-08-20 11:31:33 -04:00
|
|
|
use std::io::ErrorKind;
|
2024-06-26 17:24:10 -04:00
|
|
|
use std::path::Path;
|
2022-08-20 11:31:33 -04:00
|
|
|
use std::path::PathBuf;
|
|
|
|
|
2024-07-16 18:32:41 -04:00
|
|
|
use crate::errors::PackageJsonLoadError;
|
|
|
|
|
2024-06-26 17:24:10 -04:00
|
|
|
// use a thread local cache so that workers have their own distinct cache
|
2023-02-06 10:20:20 -05:00
|
|
|
thread_local! {
|
2024-06-26 17:24:10 -04:00
|
|
|
static CACHE: RefCell<HashMap<PathBuf, PackageJsonRc>> = RefCell::new(HashMap::new());
|
2023-02-06 10:20:20 -05:00
|
|
|
}
|
|
|
|
|
2024-06-26 17:24:10 -04:00
|
|
|
pub struct PackageJsonThreadLocalCache;
|
2023-02-23 10:58:10 -05:00
|
|
|
|
2024-06-26 17:24:10 -04:00
|
|
|
impl PackageJsonThreadLocalCache {
|
|
|
|
pub fn clear() {
|
|
|
|
CACHE.with(|cache| cache.borrow_mut().clear());
|
2023-02-23 10:58:10 -05:00
|
|
|
}
|
2022-08-20 11:31:33 -04:00
|
|
|
}
|
|
|
|
|
2024-07-23 17:34:46 -04:00
|
|
|
impl deno_package_json::PackageJsonCache for PackageJsonThreadLocalCache {
|
2024-06-26 17:24:10 -04:00
|
|
|
fn get(&self, path: &Path) -> Option<PackageJsonRc> {
|
|
|
|
CACHE.with(|cache| cache.borrow().get(path).cloned())
|
2022-08-20 11:31:33 -04:00
|
|
|
}
|
|
|
|
|
2024-06-26 17:24:10 -04:00
|
|
|
fn set(&self, path: PathBuf, package_json: PackageJsonRc) {
|
|
|
|
CACHE.with(|cache| cache.borrow_mut().insert(path, package_json));
|
2022-08-20 11:31:33 -04:00
|
|
|
}
|
|
|
|
}
|
2023-09-22 05:21:38 -04:00
|
|
|
|
2024-06-26 17:24:10 -04:00
|
|
|
/// Helper to load a package.json file using the thread local cache
|
2024-07-25 19:08:14 -04:00
|
|
|
/// in node_resolver.
|
2024-06-26 17:24:10 -04:00
|
|
|
pub fn load_pkg_json(
|
2024-07-25 19:08:14 -04:00
|
|
|
fs: &dyn deno_package_json::fs::DenoPkgJsonFs,
|
2024-06-26 17:24:10 -04:00
|
|
|
path: &Path,
|
|
|
|
) -> Result<Option<PackageJsonRc>, PackageJsonLoadError> {
|
2024-07-25 19:08:14 -04:00
|
|
|
let result =
|
|
|
|
PackageJson::load_from_path(path, fs, Some(&PackageJsonThreadLocalCache));
|
2024-06-26 17:24:10 -04:00
|
|
|
match result {
|
|
|
|
Ok(pkg_json) => Ok(Some(pkg_json)),
|
2024-07-23 17:34:46 -04:00
|
|
|
Err(deno_package_json::PackageJsonLoadError::Io { source, .. })
|
|
|
|
if source.kind() == ErrorKind::NotFound =>
|
|
|
|
{
|
|
|
|
Ok(None)
|
|
|
|
}
|
2024-07-16 18:32:41 -04:00
|
|
|
Err(err) => Err(PackageJsonLoadError(err)),
|
2023-09-22 05:21:38 -04:00
|
|
|
}
|
|
|
|
}
|