summaryrefslogtreecommitdiff
path: root/cli/tools
diff options
context:
space:
mode:
authorNathan Whitaker <17734409+nathanwhit@users.noreply.github.com>2024-11-01 19:10:35 -0700
committerGitHub <noreply@github.com>2024-11-01 19:10:35 -0700
commit2c8a0e791732ab00907ca11c3a4918ad26ead03f (patch)
treec63f2264f0cbb18c501b8d5fb9355ac0b5057025 /cli/tools
parent826e42a5b5880c974ae019a7a21aade6a718062c (diff)
fix(add): only add npm deps to package.json if it's at least as close as deno.json (#26683)
Fixes https://github.com/denoland/deno/issues/26653
Diffstat (limited to 'cli/tools')
-rw-r--r--cli/tools/registry/pm.rs26
1 files changed, 25 insertions, 1 deletions
diff --git a/cli/tools/registry/pm.rs b/cli/tools/registry/pm.rs
index d1be901d6..4e0387998 100644
--- a/cli/tools/registry/pm.rs
+++ b/cli/tools/registry/pm.rs
@@ -1,5 +1,6 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
+use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
@@ -333,6 +334,14 @@ fn load_configs(
Ok((cli_factory, npm_config, deno_config))
}
+fn path_distance(a: &Path, b: &Path) -> usize {
+ let diff = pathdiff::diff_paths(a, b);
+ let Some(diff) = diff else {
+ return usize::MAX;
+ };
+ diff.components().count()
+}
+
pub async fn add(
flags: Arc<Flags>,
add_flags: AddFlags,
@@ -357,6 +366,21 @@ pub async fn add(
}
}
+ let start_dir = cli_factory.cli_options()?.start_dir.dir_path();
+
+ // only prefer to add npm deps to `package.json` if there isn't a closer deno.json.
+ // example: if deno.json is in the CWD and package.json is in the parent, we should add
+ // npm deps to deno.json, since it's closer
+ let prefer_npm_config = match (npm_config.as_ref(), deno_config.as_ref()) {
+ (Some(npm), Some(deno)) => {
+ let npm_distance = path_distance(&npm.path, &start_dir);
+ let deno_distance = path_distance(&deno.path, &start_dir);
+ npm_distance <= deno_distance
+ }
+ (Some(_), None) => true,
+ (None, _) => false,
+ };
+
let http_client = cli_factory.http_client_provider();
let deps_http_cache = cli_factory.global_http_cache()?;
let mut deps_file_fetcher = FileFetcher::new(
@@ -455,7 +479,7 @@ pub async fn add(
selected_package.selected_version
);
- if selected_package.package_name.starts_with("npm:") {
+ if selected_package.package_name.starts_with("npm:") && prefer_npm_config {
if let Some(npm) = &mut npm_config {
npm.add(selected_package, dev);
} else {