forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal.rs
More file actions
1617 lines (1495 loc) · 51.3 KB
/
local.rs
File metadata and controls
1617 lines (1495 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018-2026 the Deno authors. MIT license.
//! Code for local node_modules resolution.
use std::borrow::Cow;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::hash_map::Entry;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::Error as AnyError;
use async_trait::async_trait;
use deno_error::JsErrorBox;
use deno_npm::NpmResolutionPackage;
use deno_npm::NpmSystemInfo;
use deno_npm::resolution::NpmResolutionSnapshot;
use deno_npm_cache::NpmCache;
use deno_npm_cache::NpmCacheHttpClient;
use deno_npm_cache::NpmCacheSys;
use deno_npm_cache::TarballCache;
use deno_npm_cache::hard_link_file;
use deno_path_util::fs::atomic_write_file_with_retries;
use deno_resolver::npm::get_package_folder_id_folder_name;
use deno_resolver::npm::managed::NpmResolutionCell;
use deno_semver::StackString;
use deno_semver::package::PackageNv;
use deno_terminal::colors;
use futures::FutureExt;
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use parking_lot::Mutex;
use serde::Deserialize;
use serde::Serialize;
use sys_traits::FsDirEntry;
use sys_traits::FsMetadata;
use sys_traits::FsOpen;
use sys_traits::FsWrite;
use sys_traits::PathsInErrorsExt;
use crate::BinEntries;
use crate::CachedNpmPackageExtraInfoProvider;
use crate::ExpectedExtraInfo;
use crate::LifecycleScriptsConfig;
use crate::NpmPackageExtraInfoProvider;
use crate::NpmPackageFsInstaller;
use crate::PackageCaching;
use crate::Reporter;
use crate::bin_entries::EntrySetupOutcome;
use crate::bin_entries::SetupBinEntrySys;
use crate::flag::LaxSingleProcessFsFlag;
use crate::flag::LaxSingleProcessFsFlagSys;
use crate::fs::CloneDirRecursiveSys;
use crate::fs::clone_dir_recursive;
use crate::fs::symlink_dir;
use crate::lifecycle_scripts::LifecycleScripts;
use crate::lifecycle_scripts::LifecycleScriptsExecutor;
use crate::lifecycle_scripts::LifecycleScriptsExecutorOptions;
use crate::lifecycle_scripts::LifecycleScriptsStrategy;
use crate::lifecycle_scripts::has_lifecycle_scripts;
use crate::lifecycle_scripts::is_running_lifecycle_script;
use crate::package_json::NpmInstallDepsProvider;
use crate::process_state::NpmProcessState;
#[sys_traits::auto_impl]
pub trait LocalNpmInstallSys:
NpmCacheSys
+ CloneDirRecursiveSys
+ SetupBinEntrySys
+ LaxSingleProcessFsFlagSys
+ sys_traits::EnvVar
+ sys_traits::FsSymlinkDir
+ sys_traits::FsCreateJunction
+ sys_traits::FsRemoveDir
{
}
#[derive(Debug)]
pub struct LocalNpmPackageInstallerOptions {
pub clean_on_install: bool,
pub lifecycle_scripts: Arc<LifecycleScriptsConfig>,
pub node_modules_folder: PathBuf,
pub reporter: Option<Arc<dyn crate::InstallReporter>>,
pub system_info: NpmSystemInfo,
}
/// Resolver that creates a local node_modules directory
/// and resolves packages from it.
pub struct LocalNpmPackageInstaller<
THttpClient: NpmCacheHttpClient,
TReporter: Reporter,
TSys: LocalNpmInstallSys,
> {
lifecycle_scripts_executor: Arc<dyn LifecycleScriptsExecutor>,
npm_cache: Arc<NpmCache<TSys>>,
npm_install_deps_provider: Arc<NpmInstallDepsProvider>,
npm_package_extra_info_provider: Arc<NpmPackageExtraInfoProvider>,
reporter: TReporter,
resolution: Arc<NpmResolutionCell>,
sys: TSys,
tarball_cache: Arc<TarballCache<THttpClient, TSys>>,
clean_on_install: bool,
lifecycle_scripts_config: Arc<LifecycleScriptsConfig>,
root_node_modules_path: PathBuf,
system_info: NpmSystemInfo,
install_reporter: Option<Arc<dyn crate::InstallReporter>>,
}
impl<
THttpClient: NpmCacheHttpClient,
TReporter: Reporter,
TSys: LocalNpmInstallSys,
> std::fmt::Debug for LocalNpmPackageInstaller<THttpClient, TReporter, TSys>
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LocalNpmPackageInstaller")
.field("npm_cache", &self.npm_cache)
.field("npm_install_deps_provider", &self.npm_install_deps_provider)
.field("reporter", &self.reporter)
.field("resolution", &self.resolution)
.field("sys", &self.sys)
.field("tarball_cache", &self.tarball_cache)
.field("clean_on_install", &self.clean_on_install)
.field("lifecycle_scripts_config", &self.lifecycle_scripts_config)
.field("root_node_modules_path", &self.root_node_modules_path)
.field("system_info", &self.system_info)
.finish()
}
}
struct InitializingGuard {
nv: PackageNv,
install_reporter: Arc<dyn crate::InstallReporter>,
}
impl Drop for InitializingGuard {
fn drop(&mut self) {
self.install_reporter.initialized(&self.nv);
}
}
impl<
THttpClient: NpmCacheHttpClient,
TReporter: Reporter,
TSys: LocalNpmInstallSys,
> LocalNpmPackageInstaller<THttpClient, TReporter, TSys>
{
#[allow(clippy::too_many_arguments)]
pub fn new(
lifecycle_scripts_executor: Arc<dyn LifecycleScriptsExecutor>,
npm_cache: Arc<NpmCache<TSys>>,
npm_package_extra_info_provider: Arc<NpmPackageExtraInfoProvider>,
npm_install_deps_provider: Arc<NpmInstallDepsProvider>,
reporter: TReporter,
resolution: Arc<NpmResolutionCell>,
sys: TSys,
tarball_cache: Arc<TarballCache<THttpClient, TSys>>,
options: LocalNpmPackageInstallerOptions,
) -> Self {
Self {
lifecycle_scripts_executor,
npm_cache,
npm_install_deps_provider,
npm_package_extra_info_provider,
reporter,
resolution,
tarball_cache,
sys,
clean_on_install: options.clean_on_install,
lifecycle_scripts_config: options.lifecycle_scripts,
root_node_modules_path: options.node_modules_folder,
install_reporter: options.reporter,
system_info: options.system_info,
}
}
async fn sync_resolution_with_fs(
&self,
snapshot: &NpmResolutionSnapshot,
) -> Result<(), SyncResolutionWithFsError> {
if snapshot.is_empty()
&& self.npm_install_deps_provider.local_pkgs().is_empty()
{
return Ok(()); // don't create the directory
}
// don't set up node_modules (and more importantly try to acquire the file lock)
// if we're running as part of a lifecycle script
if is_running_lifecycle_script(&self.sys) {
return Ok(());
}
let sys = self.sys.with_paths_in_errors();
let deno_local_registry_dir = self.root_node_modules_path.join(".deno");
let deno_node_modules_dir = deno_local_registry_dir.join("node_modules");
sys.fs_create_dir_all(&deno_node_modules_dir)?;
let bin_node_modules_dir_path = self.root_node_modules_path.join(".bin");
let single_process_lock = LaxSingleProcessFsFlag::lock(
sys.as_ref(),
deno_local_registry_dir.join(".deno.lock"),
&self.reporter,
// similar message used by cargo build
"waiting for file lock on node_modules directory",
)
.await;
let package_partitions =
snapshot.all_system_packages_partitioned(&self.system_info);
let pb_clear_guard = self.reporter.clear_guard(); // prevent flickering
// load this after we get the directory lock
let mut setup_cache = LocalSetupCache::load(
sys.as_ref().clone(),
deno_local_registry_dir.join(".setup-cache.bin"),
);
// 1. Check if packages changed and clean up if needed
if self.clean_on_install {
let packages_hash = calculate_packages_hash(&package_partitions);
if setup_cache.packages_changed(packages_hash) {
cleanup_unused_packages(
sys.as_ref(),
&self.root_node_modules_path,
&deno_local_registry_dir,
&package_partitions,
&mut setup_cache,
);
}
setup_cache.set_clean_packages_hash(packages_hash);
}
// 2. Write all the packages out the .deno directory.
//
// Copy (hardlink in future) <global_registry_cache>/<package_id>/ to
// node_modules/.deno/<package_folder_id_folder_name>/node_modules/<package_name>
let mut cache_futures = FuturesUnordered::new();
let mut newest_packages_by_name: HashMap<
&StackString,
&NpmResolutionPackage,
> = HashMap::with_capacity(package_partitions.packages.len());
let bin_entries = Rc::new(RefCell::new(BinEntries::new(sys)));
let lifecycle_scripts = Rc::new(RefCell::new(LifecycleScripts::new(
sys.as_ref(),
&self.lifecycle_scripts_config,
LocalLifecycleScripts {
sys: sys.as_ref(),
deno_local_registry_dir: &deno_local_registry_dir,
install_reporter: self.install_reporter.clone(),
},
)));
let packages_with_deprecation_warnings = Arc::new(Mutex::new(Vec::new()));
let mut package_tags: HashMap<&PackageNv, BTreeSet<&str>> = HashMap::new();
for (package_req, package_nv) in snapshot.package_reqs() {
if let Some(tag) = package_req.version_req.tag() {
package_tags.entry(package_nv).or_default().insert(tag);
}
}
let extra_info_provider = Arc::new(CachedNpmPackageExtraInfoProvider::new(
self.npm_package_extra_info_provider.clone(),
));
for package in &package_partitions.packages {
if let Some(current_pkg) =
newest_packages_by_name.get_mut(&package.id.nv.name)
{
if current_pkg.id.nv.cmp(&package.id.nv) == Ordering::Less {
*current_pkg = package;
}
} else {
newest_packages_by_name.insert(&package.id.nv.name, package);
};
let package_folder_name = get_package_folder_id_folder_name(
&package.get_package_cache_folder_id(),
);
let folder_path = deno_local_registry_dir.join(&package_folder_name);
let tags = package_tags
.get(&package.id.nv)
.map(|tags| {
capacity_builder::StringBuilder::<String>::build(|builder| {
for (i, tag) in tags.iter().enumerate() {
if i > 0 {
builder.append(',')
}
builder.append(*tag);
}
})
.unwrap()
})
.unwrap_or_default();
enum PackageFolderState {
UpToDate,
Uninitialized,
TagsOutdated,
}
let initialized_file = folder_path.join(".initialized");
let package_state = if tags.is_empty() {
if sys.fs_exists_no_err(&initialized_file) {
PackageFolderState::UpToDate
} else {
PackageFolderState::Uninitialized
}
} else {
self
.sys
.fs_read_to_string(&initialized_file)
.map(|s| {
if s != tags {
PackageFolderState::TagsOutdated
} else {
PackageFolderState::UpToDate
}
})
.unwrap_or(PackageFolderState::Uninitialized)
};
if !self
.npm_cache
.cache_setting()
.should_use_for_npm_package(&package.id.nv.name)
|| matches!(package_state, PackageFolderState::Uninitialized)
{
if let Some(dist) = &package.dist {
// cache bust the dep from the dep setup cache so the symlinks
// are forced to be recreated
setup_cache.remove_dep(&package_folder_name);
let folder_path = folder_path.clone();
let packages_with_deprecation_warnings =
packages_with_deprecation_warnings.clone();
let extra_info_provider = extra_info_provider.clone();
let lifecycle_scripts = lifecycle_scripts.clone();
let bin_entries_to_setup = bin_entries.clone();
let install_reporter = self.install_reporter.clone();
cache_futures.push(
async move {
self
.tarball_cache
.ensure_package(&package.id.nv, dist)
.await
.map_err(JsErrorBox::from_err)?;
let pb_guard =
self.reporter.on_initializing(&package.id.nv.to_string());
let _initialization_guard =
install_reporter.as_ref().map(|install_reporter| {
install_reporter.initializing(&package.id.nv);
InitializingGuard {
nv: package.id.nv.clone(),
install_reporter: install_reporter.clone(),
}
});
let sub_node_modules = folder_path.join("node_modules");
let package_path = join_package_name(
Cow::Owned(sub_node_modules),
&package.id.nv.name,
);
let cache_folder =
self.npm_cache.package_folder_for_nv(&package.id.nv);
let handle = crate::rt::spawn_blocking({
let package_path = package_path.clone();
let sys = self.sys.clone();
move || {
clone_dir_recursive(&sys, &cache_folder, &package_path)?;
// write out a file that indicates this folder has been initialized
write_initialized_file(&sys, &initialized_file, &tags)?;
Ok::<_, SyncResolutionWithFsError>(())
}
});
let needs_extra_from_disk = package.extra.is_none()
// When using abbreviated packument format, has_scripts may
// be true (from hasInstallScript) while extra.scripts is
// empty. In that case, read from disk to get real scripts.
|| (package.has_scripts
&& package
.extra
.as_ref()
.is_some_and(|e| e.scripts.is_empty()));
let extra = if (package.has_bin
|| package.has_scripts
|| package.is_deprecated)
&& needs_extra_from_disk
{
// Wait for extraction to complete first, since
// get_package_extra_info may read from the on-disk
// package.json which doesn't exist until extraction finishes.
handle
.await
.map_err(JsErrorBox::from_err)?
.map_err(JsErrorBox::from_err)?;
extra_info_provider
.get_package_extra_info(
&package.id.nv,
&package_path,
ExpectedExtraInfo::from_package(package),
)
.await
.map_err(JsErrorBox::from_err)?
} else {
let (result, extra) = futures::future::join(
handle,
std::future::ready(Ok::<_, JsErrorBox>(
package.extra.clone().unwrap_or_default(),
)),
)
.await;
result
.map_err(JsErrorBox::from_err)?
.map_err(JsErrorBox::from_err)?;
extra?
};
if package.has_bin {
bin_entries_to_setup.borrow_mut().add(
package,
&extra,
package_path.to_path_buf(),
);
}
if package.has_scripts {
lifecycle_scripts.borrow_mut().add(
package,
&extra,
package_path.into(),
);
}
if package.is_deprecated
&& let Some(deprecated) = &extra.deprecated
{
packages_with_deprecation_warnings
.lock()
.push((package.id.nv.clone(), deprecated.clone()));
}
// finally stop showing the progress bar
drop(pb_guard); // explicit for clarity
Ok::<_, JsErrorBox>(())
}
.boxed_local(),
);
}
} else {
if matches!(package_state, PackageFolderState::TagsOutdated) {
write_initialized_file(sys.as_ref(), &initialized_file, &tags)?;
}
if package.has_bin || package.has_scripts {
let bin_entries_to_setup = bin_entries.clone();
let lifecycle_scripts = lifecycle_scripts.clone();
let extra_info_provider = extra_info_provider.clone();
let sub_node_modules = folder_path.join("node_modules");
let package_path = join_package_name(
Cow::Owned(sub_node_modules),
&package.id.nv.name,
);
cache_futures.push(
async move {
let extra = extra_info_provider
.get_package_extra_info(
&package.id.nv,
&package_path,
ExpectedExtraInfo::from_package(package),
)
.await
.map_err(JsErrorBox::from_err)?;
if package.has_bin {
bin_entries_to_setup.borrow_mut().add(
package,
&extra,
package_path.to_path_buf(),
);
}
if package.has_scripts {
lifecycle_scripts.borrow_mut().add(
package,
&extra,
package_path.into(),
);
}
Ok(())
}
.boxed_local(),
);
}
}
}
// Wait for all npm package installations to complete before applying patches
// This prevents race conditions where npm packages could overwrite patch files
while let Some(result) = cache_futures.next().await {
result?; // surface the first error
}
// 3. Setup the patch packages
for patch_pkg in self.npm_install_deps_provider.patch_pkgs() {
// there might be multiple ids per package due to peer dep copy packages
for id in snapshot.package_ids_for_nv(&patch_pkg.nv) {
let package = snapshot.package_from_id(id).unwrap();
let package_folder_name = get_package_folder_id_folder_name(
&package.get_package_cache_folder_id(),
);
// node_modules/.deno/<package_folder_id_folder_name>/node_modules/<package_name> -> local package folder
let target = join_package_name(
Cow::Owned(
deno_local_registry_dir
.join(&package_folder_name)
.join("node_modules"),
),
&patch_pkg.nv.name,
);
cache_futures.push(
async move {
let from_path = patch_pkg.target_dir.clone();
let sys = self.sys.clone();
crate::rt::spawn_blocking({
move || {
clone_dir_recursive_except_node_modules_child(
&sys, &from_path, &target,
)
}
})
.await
.map_err(JsErrorBox::from_err)?
.map_err(JsErrorBox::from_err)?;
Ok::<_, JsErrorBox>(())
}
.boxed_local(),
);
}
}
// copy packages copy from the main packages, so wait
// until these are all done
while let Some(result) = cache_futures.next().await {
result?; // surface the first error
}
// 4. Create any "copy" packages, which are used for peer dependencies
for package in &package_partitions.copy_packages {
let package_cache_folder_id = package.get_package_cache_folder_id();
let destination_path = deno_local_registry_dir
.join(get_package_folder_id_folder_name(&package_cache_folder_id));
let initialized_file = destination_path.join(".initialized");
if !sys.fs_exists_no_err(&initialized_file) {
let sub_node_modules = destination_path.join("node_modules");
let package_path =
join_package_name(Cow::Owned(sub_node_modules), &package.id.nv.name);
let source_path = join_package_name(
Cow::Owned(
deno_local_registry_dir
.join(get_package_folder_id_folder_name(
&package_cache_folder_id.with_no_count(),
))
.join("node_modules"),
),
&package.id.nv.name,
);
cache_futures.push(
async move {
let sys = self.sys.clone();
crate::rt::spawn_blocking(move || {
clone_dir_recursive(&sys, &source_path, &package_path)
.map_err(JsErrorBox::from_err)?;
// write out a file that indicates this folder has been initialized
create_initialized_file(&sys, &initialized_file)
.map_err(JsErrorBox::from_err)?;
Ok::<_, JsErrorBox>(())
})
.await
.map_err(JsErrorBox::from_err)?
.map_err(JsErrorBox::from_err)?;
Ok::<_, JsErrorBox>(())
}
.boxed_local(),
);
}
}
while let Some(result) = cache_futures.next().await {
result?; // surface the first error
}
// 5. Symlink all the dependencies into the .deno directory.
//
// Symlink node_modules/.deno/<package_id>/node_modules/<dep_name> to
// node_modules/.deno/<dep_id>/node_modules/<dep_package_name>
for package in package_partitions.iter_all() {
let package_folder_name = get_package_folder_id_folder_name(
&package.get_package_cache_folder_id(),
);
let sub_node_modules = deno_local_registry_dir
.join(&package_folder_name)
.join("node_modules");
let mut dep_setup_cache = setup_cache.with_dep(&package_folder_name);
for (name, dep_id) in &package.dependencies {
let dep = snapshot.package_from_id(dep_id).unwrap();
if package.optional_dependencies.contains(name)
&& !dep.system.matches_system(&self.system_info)
{
continue; // this isn't a dependency for the current system
}
let dep_cache_folder_id = dep.get_package_cache_folder_id();
let dep_folder_name =
get_package_folder_id_folder_name(&dep_cache_folder_id);
if package.dist.is_none()
|| dep_setup_cache.insert(name, &dep_folder_name)
{
let dep_folder_path = join_package_name(
Cow::Owned(
deno_local_registry_dir
.join(dep_folder_name)
.join("node_modules"),
),
&dep_id.nv.name,
);
symlink_package_dir(
sys.as_ref(),
&dep_folder_path,
&join_package_name(Cow::Borrowed(&sub_node_modules), name),
)?;
}
}
}
let mut found_names: HashMap<&StackString, &PackageNv> = HashMap::new();
// set of node_modules in workspace packages that we've already ensured exist
let mut existing_child_node_modules_dirs: HashSet<PathBuf> = HashSet::new();
// 6. Create symlinks for package json dependencies
{
for remote in self.npm_install_deps_provider.remote_pkgs() {
let remote_pkg = match snapshot.resolve_pkg_from_pkg_req(&remote.req) {
Ok(remote_pkg) => remote_pkg,
_ => {
if remote.req.version_req.tag().is_some() {
// couldn't find a match, and `resolve_best_package_id`
// panics if you give it a tag
continue;
} else {
match snapshot.resolve_best_package_id(
&remote.req.name,
&remote.req.version_req,
) {
Some(remote_id) => {
snapshot.package_from_id(&remote_id).unwrap()
}
_ => {
continue; // skip, package not found
}
}
}
}
};
let Some(remote_alias) = &remote.alias else {
continue;
};
let alias_clashes = remote.req.name != *remote_alias
&& newest_packages_by_name.contains_key(remote_alias);
let install_in_child = {
// we'll install in the child if the alias is taken by another package, or
// if there's already a package with the same name but different version
// linked into the root
match found_names.entry(remote_alias) {
Entry::Occupied(nv) => {
// alias to a different package (in case of duplicate aliases)
// or the version doesn't match the version in the root node_modules
alias_clashes || &remote_pkg.id.nv != *nv.get()
}
Entry::Vacant(entry) => {
entry.insert(&remote_pkg.id.nv);
alias_clashes
}
}
};
let target_folder_name = get_package_folder_id_folder_name(
&remote_pkg.get_package_cache_folder_id(),
);
let local_registry_package_path = join_package_name(
Cow::Owned(
deno_local_registry_dir
.join(&target_folder_name)
.join("node_modules"),
),
&remote_pkg.id.nv.name,
);
if install_in_child {
// symlink the dep into the package's child node_modules folder
let dest_node_modules = remote.base_dir.join("node_modules");
if !existing_child_node_modules_dirs.contains(&dest_node_modules) {
sys.fs_create_dir_all(&dest_node_modules)?;
existing_child_node_modules_dirs.insert(dest_node_modules.clone());
}
let mut dest_path = dest_node_modules;
dest_path.push(remote_alias);
symlink_package_dir(
sys.as_ref(),
&local_registry_package_path,
&dest_path,
)?;
} else {
// symlink the package into `node_modules/<alias>`
if setup_cache
.insert_root_symlink(&remote_pkg.id.nv.name, &target_folder_name)
{
symlink_package_dir(
sys.as_ref(),
&local_registry_package_path,
&join_package_name(
Cow::Borrowed(&self.root_node_modules_path),
remote_alias,
),
)?;
}
}
}
}
// 7. Create symlinks for the remaining top level packages in the node_modules folder.
// (These may be present if they are not in the package.json dependencies)
// Symlink node_modules/.deno/<package_id>/node_modules/<package_name> to
// node_modules/<package_name>
let mut ids = snapshot
.top_level_packages()
.filter(|f| !found_names.contains_key(&f.nv.name))
.collect::<Vec<_>>();
ids.sort_by(|a, b| b.cmp(a)); // create determinism and only include the latest version
for id in ids {
match found_names.entry(&id.nv.name) {
Entry::Occupied(_) => {
continue; // skip, already handled
}
Entry::Vacant(entry) => {
entry.insert(&id.nv);
}
}
let package = snapshot.package_from_id(id).unwrap();
let target_folder_name = get_package_folder_id_folder_name(
&package.get_package_cache_folder_id(),
);
if setup_cache.insert_root_symlink(&id.nv.name, &target_folder_name) {
let local_registry_package_path = join_package_name(
Cow::Owned(
deno_local_registry_dir
.join(target_folder_name)
.join("node_modules"),
),
&id.nv.name,
);
symlink_package_dir(
sys.as_ref(),
&local_registry_package_path,
&join_package_name(
Cow::Borrowed(&self.root_node_modules_path),
&id.nv.name,
),
)?;
}
}
// 8. Create a node_modules/.deno/node_modules/<package-name> directory with
// the remaining packages
for package in newest_packages_by_name.values() {
match found_names.entry(&package.id.nv.name) {
Entry::Occupied(_) => {
continue; // skip, already handled
}
Entry::Vacant(entry) => {
entry.insert(&package.id.nv);
}
}
let target_folder_name = get_package_folder_id_folder_name(
&package.get_package_cache_folder_id(),
);
if setup_cache
.insert_deno_symlink(&package.id.nv.name, &target_folder_name)
{
let local_registry_package_path = join_package_name(
Cow::Owned(
deno_local_registry_dir
.join(target_folder_name)
.join("node_modules"),
),
&package.id.nv.name,
);
symlink_package_dir(
sys.as_ref(),
&local_registry_package_path,
&join_package_name(
Cow::Borrowed(&deno_node_modules_dir),
&package.id.nv.name,
),
)?;
}
}
// 9. Set up `node_modules/.bin` entries for packages that need it.
{
let bin_entries = match Rc::try_unwrap(bin_entries) {
Ok(bin_entries) => bin_entries.into_inner(),
Err(_) => panic!("Should have sole ref to rc."),
};
bin_entries.finish(
snapshot,
&bin_node_modules_dir_path,
|setup_outcome| {
let lifecycle_scripts = lifecycle_scripts.borrow();
match setup_outcome {
EntrySetupOutcome::MissingEntrypoint {
package,
package_path,
extra,
..
} if has_lifecycle_scripts(sys.as_ref(), extra, package_path)
&& lifecycle_scripts.can_run_scripts(&package.id.nv)
&& !lifecycle_scripts.has_run_scripts(package) =>
{
// ignore, it might get fixed when the lifecycle scripts run.
// if not, we'll warn then
}
outcome => outcome.warn_if_failed(),
}
},
)?;
}
// 10. Create symlinks for the workspace packages
{
// todo(dsherret): this is not exactly correct because it should
// install correctly for a workspace (potentially in sub directories),
// but this is good enough for a first pass
for pkg in self.npm_install_deps_provider.local_pkgs() {
let Some(pkg_alias) = &pkg.alias else {
continue;
};
symlink_package_dir(
sys.as_ref(),
&pkg.target_dir,
&self.root_node_modules_path.join(pkg_alias),
)?;
}
}
{
let packages_with_deprecation_warnings =
packages_with_deprecation_warnings.lock();
if !packages_with_deprecation_warnings.is_empty() {
use std::fmt::Write;
let mut output = String::new();
let _ = writeln!(
&mut output,
"{} The following packages are deprecated:",
colors::yellow("Warning")
);
let len = packages_with_deprecation_warnings.len();
for (idx, (package_nv, msg)) in
packages_with_deprecation_warnings.iter().enumerate()
{
if idx != len - 1 {
let _ = writeln!(
&mut output,
"┠─ {}",
colors::gray(format!("npm:{:?} ({})", package_nv, msg))
);
} else {
let _ = write!(
&mut output,
"┖─ {}",
colors::gray(format!("npm:{:?} ({})", package_nv, msg))
);
}
}
if let Some(install_reporter) = &self.install_reporter {
install_reporter.deprecated_message(output);
} else {
log::warn!("{}", output);
}
}
}
let lifecycle_scripts = std::mem::replace(
&mut *lifecycle_scripts.borrow_mut(),
LifecycleScripts::new(
sys.as_ref(),
&self.lifecycle_scripts_config,
LocalLifecycleScripts {
sys: sys.as_ref(),
deno_local_registry_dir: &deno_local_registry_dir,
install_reporter: self.install_reporter.clone(),
},
),
);
lifecycle_scripts.warn_not_run_scripts()?;
let packages_with_scripts = lifecycle_scripts.packages_with_scripts();
if !packages_with_scripts.is_empty() {
let process_state = NpmProcessState::new_local(
snapshot.as_valid_serialized(),
&self.root_node_modules_path,
)
.as_serialized();
self
.lifecycle_scripts_executor
.execute(LifecycleScriptsExecutorOptions {
init_cwd: &self.lifecycle_scripts_config.initial_cwd,
process_state: process_state.as_str(),
root_node_modules_dir_path: &self.root_node_modules_path,
on_ran_pkg_scripts: &|pkg| {
create_initialized_file(
sys.as_ref(),
&ran_scripts_file(&deno_local_registry_dir, pkg),
)
.map_err(JsErrorBox::from_err)
},
snapshot,
system_packages: &package_partitions.packages,
packages_with_scripts,
extra_info_provider: &extra_info_provider,
})
.await
.map_err(SyncResolutionWithFsError::LifecycleScripts)?
}
setup_cache.save();
drop(single_process_lock);
drop(pb_clear_guard);
Ok(())
}
}
#[async_trait(?Send)]
impl<
THttpClient: NpmCacheHttpClient,
TReporter: Reporter,
TSys: LocalNpmInstallSys,
> NpmPackageFsInstaller
for LocalNpmPackageInstaller<THttpClient, TReporter, TSys>
{
async fn cache_packages<'a>(
&self,
caching: PackageCaching<'a>,
) -> Result<(), JsErrorBox> {
let snapshot = match caching {
PackageCaching::All => self.resolution.snapshot(),
PackageCaching::Only(reqs) => self.resolution.subset(&reqs),
};
self
.sync_resolution_with_fs(&snapshot)
.await
.map_err(JsErrorBox::from_err)
}
}
#[derive(Debug, thiserror::Error, deno_error::JsError)]
pub enum SyncResolutionWithFsError {
#[class(generic)]
#[error(transparent)]
LifecycleScripts(AnyError),
#[class(inherit)]
#[error(transparent)]
Io(#[from] std::io::Error),
#[class(inherit)]
#[error(transparent)]
Other(#[from] JsErrorBox),
}
fn clone_dir_recursive_except_node_modules_child(
sys: &impl CloneDirRecursiveSys,
from: &Path,
to: &Path,
) -> Result<(), std::io::Error> {
let sys = sys.with_paths_in_errors();
_ = sys.fs_remove_dir_all(to);
sys.fs_create_dir_all(to)?;
for entry in sys.fs_read_dir(from)? {
let entry = entry?;
if entry.file_name().to_str() == Some("node_modules") {
continue; // ignore