mirror of
https://github.com/denoland/deno.git
synced 2024-11-21 15:04:11 -05:00
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:
parent
4e08dd540b
commit
9529138c36
1 changed files with 18 additions and 0 deletions
|
@ -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)
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue