refactor(npm): use per-thread package.json cache (#17644)

This commit adds a per-thread cache for `package.json` files. It's
similar to what Node.js is doing.
This commit is contained in:
Bartek Iwańczuk 2023-02-06 16:20:20 +01:00 committed by GitHub
parent fd511d5755
commit 34bfa2cb2c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -11,9 +11,15 @@ use deno_core::serde_json;
use deno_core::serde_json::Map;
use deno_core::serde_json::Value;
use serde::Serialize;
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::ErrorKind;
use std::path::PathBuf;
thread_local! {
static CACHE: RefCell<HashMap<PathBuf, PackageJson>> = RefCell::new(HashMap::new());
}
#[derive(Clone, Debug, Serialize)]
pub struct PackageJson {
pub exists: bool,
@ -58,6 +64,12 @@ impl PackageJson {
pub fn load_skip_read_permission(
path: PathBuf,
) -> Result<PackageJson, AnyError> {
assert!(path.is_absolute());
if CACHE.with(|cache| cache.borrow().contains_key(&path)) {
return Ok(CACHE.with(|cache| cache.borrow()[&path].clone()));
}
let source = match std::fs::read_to_string(&path) {
Ok(source) => source,
Err(err) if err.kind() == ErrorKind::NotFound => {
@ -136,6 +148,12 @@ impl PackageJson {
imports,
bin,
};
CACHE.with(|cache| {
cache
.borrow_mut()
.insert(package_json.path.clone(), package_json.clone());
});
Ok(package_json)
}