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-06-26 17:24:10 -04:00
|
|
|
use deno_config::package_json::PackageJson;
|
|
|
|
use deno_config::package_json::PackageJsonRc;
|
|
|
|
use deno_fs::DenoConfigFsAdapter;
|
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-06-26 17:24:10 -04:00
|
|
|
impl deno_config::package_json::PackageJsonCache
|
|
|
|
for PackageJsonThreadLocalCache
|
|
|
|
{
|
|
|
|
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
|
|
|
|
/// in deno_node.
|
|
|
|
pub fn load_pkg_json(
|
|
|
|
fs: &dyn deno_fs::FileSystem,
|
|
|
|
path: &Path,
|
|
|
|
) -> Result<Option<PackageJsonRc>, PackageJsonLoadError> {
|
|
|
|
let result = PackageJson::load_from_path(
|
|
|
|
path,
|
|
|
|
&DenoConfigFsAdapter::new(fs),
|
|
|
|
Some(&PackageJsonThreadLocalCache),
|
|
|
|
);
|
|
|
|
match result {
|
|
|
|
Ok(pkg_json) => Ok(Some(pkg_json)),
|
2024-07-16 18:32:41 -04:00
|
|
|
Err(deno_config::package_json::PackageJsonLoadError::Io {
|
|
|
|
source, ..
|
|
|
|
}) if source.kind() == ErrorKind::NotFound => Ok(None),
|
|
|
|
Err(err) => Err(PackageJsonLoadError(err)),
|
2023-09-22 05:21:38 -04:00
|
|
|
}
|
|
|
|
}
|