-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathpackage_manager.rs
More file actions
1889 lines (1637 loc) · 78.5 KB
/
package_manager.rs
File metadata and controls
1889 lines (1637 loc) · 78.5 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
use std::{
collections::HashMap,
env, fmt,
fs::{self, File},
io::{BufReader, Seek, SeekFrom},
path::Path,
};
use semver::{Version, VersionReq};
use serde::{Deserialize, Serialize};
use tokio::fs::remove_dir_all;
use vite_error::Error;
use vite_path::{AbsolutePath, AbsolutePathBuf, RelativePathBuf};
use vite_str::Str;
use crate::{
config::{get_cache_dir, get_npm_package_tgz_url, get_npm_package_version_url},
request::{HttpClient, download_and_extract_tgz_with_hash},
shim,
};
#[derive(Serialize, Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
struct PackageJson {
#[serde(default)]
pub version: Str,
#[serde(default)]
pub package_manager: Str,
}
/// The package manager type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PackageManagerType {
Pnpm,
Yarn,
Npm,
}
impl fmt::Display for PackageManagerType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Pnpm => write!(f, "pnpm"),
Self::Yarn => write!(f, "yarn"),
Self::Npm => write!(f, "npm"),
}
}
}
// TODO(@fengmk2): should move ResolveCommandResult to vite-common crate
#[derive(Debug)]
pub struct ResolveCommandResult {
pub bin_path: String,
pub args: Vec<String>,
pub envs: HashMap<String, String>,
}
/// The package manager.
/// Use `PackageManager::builder()` to create a package manager.
/// Then use `PackageManager::resolve_command()` to resolve the command result.
#[derive(Debug)]
pub struct PackageManager {
pub client: PackageManagerType,
pub package_name: Str,
pub version: Str,
pub hash: Option<Str>,
pub bin_name: Str,
pub workspace_root: AbsolutePathBuf,
pub install_dir: AbsolutePathBuf,
}
#[derive(Debug)]
pub struct PackageManagerBuilder {
client_override: Option<PackageManagerType>,
cwd: AbsolutePathBuf,
}
impl PackageManagerBuilder {
pub fn new(cwd: impl AsRef<AbsolutePath>) -> Self {
Self { client_override: None, cwd: cwd.as_ref().to_absolute_path_buf() }
}
#[must_use]
pub const fn package_manager_type(mut self, package_manager_type: PackageManagerType) -> Self {
self.client_override = Some(package_manager_type);
self
}
/// Build the package manager.
/// Detect the package manager from the current working directory.
pub async fn build(self) -> Result<PackageManager, Error> {
let workspace_root = find_workspace_root(&self.cwd)?;
let (package_manager_type, mut version, mut hash) =
get_package_manager_type_and_version(&workspace_root, self.client_override)?;
let mut package_name = package_manager_type.to_string();
let mut should_update_package_manager_field = false;
if version == "latest" {
version = get_latest_version(package_manager_type).await?;
should_update_package_manager_field = true;
hash = None; // Reset hash when fetching latest since hash is version-specific
}
// handle yarn >= 2.0.0 to use `@yarnpkg/cli-dist` as package name
// @see https://github.com/nodejs/corepack/blob/main/config.json#L135
if matches!(package_manager_type, PackageManagerType::Yarn) {
let version_req = VersionReq::parse(">=2.0.0")?;
if version_req.matches(&Version::parse(&version)?) {
package_name = "@yarnpkg/cli-dist".to_string();
}
}
// only download the package manager if it's not already downloaded
let install_dir = download_package_manager(
package_manager_type,
&package_name,
&version,
hash.as_deref(),
)
.await?;
if should_update_package_manager_field {
// auto set `packageManager` field in package.json
let package_json_path = workspace_root.path.join("package.json");
set_package_manager_field(&package_json_path, package_manager_type, &version).await?;
}
Ok(PackageManager {
client: package_manager_type,
package_name: package_name.into(),
version,
hash,
bin_name: package_manager_type.to_string().into(),
workspace_root: workspace_root.path.to_absolute_path_buf(),
install_dir,
})
}
}
impl PackageManager {
pub fn builder(workspace_root: impl AsRef<AbsolutePath>) -> PackageManagerBuilder {
PackageManagerBuilder::new(workspace_root)
}
#[must_use]
pub fn get_bin_prefix(&self) -> AbsolutePathBuf {
self.install_dir.join("bin")
}
#[must_use]
pub fn get_fingerprint_ignores(&self) -> Vec<Str> {
let mut ignores: Vec<Str> = vec![
// ignore all files by default
"**/*".into(),
// keep all package.json files except under node_modules
"!**/package.json".into(),
"!**/.npmrc".into(),
];
match self.client {
PackageManagerType::Pnpm => {
ignores.push("!**/pnpm-workspace.yaml".into());
ignores.push("!**/pnpm-lock.yaml".into());
// https://pnpm.io/pnpmfile
ignores.push("!**/.pnpmfile.cjs".into());
ignores.push("!**/pnpmfile.cjs".into());
// pnpm support Plug'n'Play https://pnpm.io/blog/2020/10/17/node-modules-configuration-options-with-pnpm#plugnplay-the-strictest-configuration
ignores.push("!**/.pnp.cjs".into());
}
PackageManagerType::Yarn => {
ignores.push("!**/.yarnrc".into()); // yarn 1.x
ignores.push("!**/.yarnrc.yml".into()); // yarn 2.x
ignores.push("!**/yarn.config.cjs".into()); // yarn 2.x
ignores.push("!**/yarn.lock".into());
// .yarn/patches, .yarn/releases
ignores.push("!**/.yarn/**/*".into());
// .pnp.cjs https://yarnpkg.com/features/pnp
ignores.push("!**/.pnp.cjs".into());
}
PackageManagerType::Npm => {
ignores.push("!**/package-lock.json".into());
ignores.push("!**/npm-shrinkwrap.json".into());
}
}
// ignore all files under node_modules
// e.g. node_modules/mqtt/package.json
ignores.push("**/node_modules/**/*".into());
// keep the node_modules directory
ignores.push("!**/node_modules".into());
// keep the scoped directory
ignores.push("!**/node_modules/@*".into());
// ignore all patterns under nested node_modules
// e.g. node_modules/mqtt/node_modules/mqtt-packet/node_modules
ignores.push("**/node_modules/**/node_modules/**".into());
ignores
}
}
/// The package root directory and its package.json file.
#[derive(Debug)]
pub struct PackageRoot<'a> {
pub path: &'a AbsolutePath,
pub cwd: RelativePathBuf,
pub package_json: File,
}
/// Find the package root directory from the current working directory. `original_cwd` must be absolute.
///
/// If the package.json file is not found, will return `PackageJsonNotFound` error.
pub fn find_package_root(original_cwd: &AbsolutePath) -> Result<PackageRoot<'_>, Error> {
let mut cwd = original_cwd;
loop {
// Check for package.json
if let Some(file) = open_exists_file(cwd.join("package.json"))? {
return Ok(PackageRoot {
path: cwd,
cwd: original_cwd.strip_prefix(cwd)?.expect("cwd must be within the package root"),
package_json: file,
});
}
if let Some(parent) = cwd.parent() {
// Move up one directory
cwd = parent;
} else {
// We've reached the root, return PackageJsonNotFound error.
return Err(Error::PackageJsonNotFound(original_cwd.to_absolute_path_buf()));
}
}
}
/// The workspace file.
///
/// - `PnpmWorkspaceYaml` is the pnpm workspace file.
/// - `NpmWorkspaceJson` is the package.json file of a yarn/npm workspace.
/// - `NonWorkspacePackage` is the package.json file of a non-workspace package.
#[derive(Debug)]
pub enum WorkspaceFile {
/// The pnpm-workspace.yaml file of a pnpm workspace.
PnpmWorkspaceYaml(File),
/// The package.json file of a yarn/npm workspace.
NpmWorkspaceJson(File),
/// The package.json file of a non-workspace package.
NonWorkspacePackage(File),
}
/// The workspace root directory and its workspace file.
///
/// If the workspace file is not found, but a package is found, `workspace_file` will be `NonWorkspacePackage` with the `package.json` File.
#[derive(Debug)]
pub struct WorkspaceRoot<'a> {
pub path: &'a AbsolutePath,
pub cwd: RelativePathBuf,
pub workspace_file: WorkspaceFile,
}
/// Find the workspace root directory from the current working directory. `original_cwd` must be absolute.
///
/// If the workspace file is not found, but a package is found, `workspace_file` will be `NonWorkspacePackage` with the `package.json` File.
///
/// If neither workspace nor package is found, will return `PackageJsonNotFound` error.
pub fn find_workspace_root(original_cwd: &AbsolutePath) -> Result<WorkspaceRoot<'_>, Error> {
let mut cwd = original_cwd;
loop {
// Check for pnpm-workspace.yaml for pnpm workspace
if let Some(file) = open_exists_file(cwd.join("pnpm-workspace.yaml"))? {
return Ok(WorkspaceRoot {
path: cwd,
cwd: original_cwd
.strip_prefix(cwd)?
.expect("cwd must be within the pnpm workspace"),
workspace_file: WorkspaceFile::PnpmWorkspaceYaml(file),
});
}
// Check for package.json with workspaces field for npm/yarn workspace
let package_json_path = cwd.join("package.json");
if let Some(mut file) = open_exists_file(&package_json_path)? {
let package_json: serde_json::Value = serde_json::from_reader(BufReader::new(&file))?;
if package_json.get("workspaces").is_some() {
// Reset the file cursor since we consumed it reading
file.seek(SeekFrom::Start(0))?;
return Ok(WorkspaceRoot {
path: cwd,
cwd: original_cwd.strip_prefix(cwd)?.expect("cwd must be within the workspace"),
workspace_file: WorkspaceFile::NpmWorkspaceJson(file),
});
}
}
// TODO(@fengmk2): other package manager support
// Move up one directory
if let Some(parent) = cwd.parent() {
cwd = parent;
} else {
// We've reached the root, try to find the package root and return the non-workspace package.
let package_root = find_package_root(original_cwd)?;
let workspace_file = WorkspaceFile::NonWorkspacePackage(package_root.package_json);
return Ok(WorkspaceRoot {
path: package_root.path,
cwd: package_root.cwd,
workspace_file,
});
}
}
}
/// Get the package manager name, version and optional hash from the workspace root.
fn get_package_manager_type_and_version(
workspace_root: &WorkspaceRoot,
default: Option<PackageManagerType>,
) -> Result<(PackageManagerType, Str, Option<Str>), Error> {
// check packageManager field in package.json
let package_json_path = workspace_root.path.join("package.json");
if let Some(file) = open_exists_file(&package_json_path)? {
let package_json: PackageJson = serde_json::from_reader(BufReader::new(&file))?;
if !package_json.package_manager.is_empty()
&& let Some((name, version_with_hash)) = package_json.package_manager.split_once('@')
{
// Parse version and optional hash (format: version+sha512.hash)
let (version, hash) = if let Some((ver, hash_part)) = version_with_hash.split_once('+')
{
(ver, Some(hash_part.into()))
} else {
(version_with_hash, None)
};
// check if the version is a valid semver
semver::Version::parse(version).map_err(|_| Error::PackageManagerVersionInvalid {
name: name.into(),
version: version.into(),
package_json_path: package_json_path.to_absolute_path_buf(),
})?;
match name {
"pnpm" => return Ok((PackageManagerType::Pnpm, version.into(), hash)),
"yarn" => return Ok((PackageManagerType::Yarn, version.into(), hash)),
"npm" => return Ok((PackageManagerType::Npm, version.into(), hash)),
_ => return Err(Error::UnsupportedPackageManager(name.into())),
}
}
}
// TODO(@fengmk2): check devEngines.packageManager field in package.json
let version = Str::from("latest");
// if pnpm-workspace.yaml exists, use pnpm@latest
if matches!(workspace_root.workspace_file, WorkspaceFile::PnpmWorkspaceYaml(_)) {
return Ok((PackageManagerType::Pnpm, version, None));
}
// if pnpm-lock.yaml exists, use pnpm@latest
let pnpm_lock_yaml_path = workspace_root.path.join("pnpm-lock.yaml");
if is_exists_file(&pnpm_lock_yaml_path)? {
return Ok((PackageManagerType::Pnpm, version, None));
}
// if yarn.lock or .yarnrc.yml exists, use yarn@latest
let yarn_lock_path = workspace_root.path.join("yarn.lock");
let yarnrc_yml_path = workspace_root.path.join(".yarnrc.yml");
if is_exists_file(&yarn_lock_path)? || is_exists_file(&yarnrc_yml_path)? {
return Ok((PackageManagerType::Yarn, version, None));
}
// if package-lock.json exists, use npm@latest
let package_lock_json_path = workspace_root.path.join("package-lock.json");
if is_exists_file(&package_lock_json_path)? {
return Ok((PackageManagerType::Npm, version, None));
}
// if .pnpmfile.cjs exists, use pnpm@latest
let pnpmfile_cjs_path = workspace_root.path.join(".pnpmfile.cjs");
if is_exists_file(&pnpmfile_cjs_path)? {
return Ok((PackageManagerType::Pnpm, version, None));
}
// if legacy pnpmfile.cjs exists, use pnpm@latest
// https://newreleases.io/project/npm/pnpm/release/6.0.0
let legacy_pnpmfile_cjs_path = workspace_root.path.join("pnpmfile.cjs");
if is_exists_file(&legacy_pnpmfile_cjs_path)? {
return Ok((PackageManagerType::Pnpm, version, None));
}
// if yarn.config.cjs exists, use yarn@latest (yarn 2.0+)
let yarn_config_cjs_path = workspace_root.path.join("yarn.config.cjs");
if is_exists_file(&yarn_config_cjs_path)? {
return Ok((PackageManagerType::Yarn, version, None));
}
// if default is specified, use it
if let Some(default) = default {
return Ok((default, version, None));
}
// unrecognized package manager, let user specify the package manager
Err(Error::UnrecognizedPackageManager)
}
/// Open the file if it exists, otherwise return None.
fn open_exists_file(path: impl AsRef<Path>) -> Result<Option<File>, Error> {
match File::open(path) {
Ok(file) => Ok(Some(file)),
// if the file does not exist, return None
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
/// Check if the file exists.
fn is_exists_file(path: impl AsRef<Path>) -> Result<bool, Error> {
match fs::metadata(path) {
Ok(metadata) => Ok(metadata.is_file()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e.into()),
}
}
async fn get_latest_version(package_manager_type: PackageManagerType) -> Result<Str, Error> {
let package_name = if matches!(package_manager_type, PackageManagerType::Yarn) {
// yarn latest version should use `@yarnpkg/cli-dist` as package name
"@yarnpkg/cli-dist".to_string()
} else {
package_manager_type.to_string()
};
let url = get_npm_package_version_url(&package_name, "latest");
let package_json: PackageJson = HttpClient::new().get_json(&url).await?;
Ok(package_json.version)
}
/// Download the package manager and extract it to the cache directory.
/// Return the install directory, e.g. $`CACHE_DIR/vite/package_manager/pnpm/10.0.0/pnpm`
async fn download_package_manager(
package_manager_type: PackageManagerType,
package_name: &str,
version: &str,
expected_hash: Option<&str>,
) -> Result<AbsolutePathBuf, Error> {
let tgz_url = get_npm_package_tgz_url(package_name, version);
let cache_dir = get_cache_dir()?;
let bin_name = package_manager_type.to_string();
// $CACHE_DIR/vite/package_manager/pnpm/10.0.0
let target_dir = cache_dir.join(format!("package_manager/{bin_name}/{version}"));
let install_dir = target_dir.join(&bin_name);
// If all shims are already exists, return the target directory
// $CACHE_DIR/vite/package_manager/pnpm/10.0.0/pnpm/bin/(pnpm|pnpm.cmd|pnpm.ps1)
let bin_prefix = install_dir.join("bin");
let bin_file = bin_prefix.join(&bin_name);
if is_exists_file(&bin_file)?
&& is_exists_file(bin_file.with_extension("cmd"))?
&& is_exists_file(bin_file.with_extension("ps1"))?
{
return Ok(install_dir);
}
// $CACHE_DIR/vite/package_manager/pnpm/{tmp_name}
// Use tempfile::TempDir for robust temporary directory creation
let parent_dir = target_dir.parent().unwrap();
tokio::fs::create_dir_all(parent_dir).await?;
let target_dir_tmp = tempfile::tempdir_in(parent_dir)?.path().to_path_buf();
download_and_extract_tgz_with_hash(&tgz_url, &target_dir_tmp, expected_hash).await.map_err(
|err| {
// status 404 means the version is not found, convert to PackageManagerVersionNotFound error
if let Error::Reqwest(e) = &err
&& let Some(status) = e.status()
&& status == reqwest::StatusCode::NOT_FOUND
{
Error::PackageManagerVersionNotFound {
name: package_manager_type.to_string().into(),
version: version.into(),
url: tgz_url.into(),
}
} else {
err
}
},
)?;
// rename $target_dir_tmp/package to $target_dir_tmp/{bin_name}
tracing::debug!("Rename package dir to {}", bin_name);
tokio::fs::rename(&target_dir_tmp.join("package"), &target_dir_tmp.join(&bin_name)).await?;
// check bin_file again, for the concurrent download cases
if is_exists_file(&bin_file)? {
tracing::debug!("bin_file already exists, skip rename");
return Ok(install_dir);
}
// rename $target_dir_tmp to $target_dir
tracing::debug!("Rename {:?} to {:?}", target_dir_tmp, target_dir);
remove_dir_all_force(&target_dir).await?;
tokio::fs::rename(&target_dir_tmp, &target_dir).await?;
// create shim file
tracing::debug!("Create shim files for {}", bin_name);
create_shim_files(package_manager_type, &bin_prefix).await?;
Ok(install_dir)
}
/// Remove the directory and all its contents.
/// Ignore the error if the directory is not found.
async fn remove_dir_all_force(path: impl AsRef<Path>) -> Result<(), std::io::Error> {
match remove_dir_all(path).await {
Ok(()) => Ok(()),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Ok(())
} else {
Err(e)
}
}
}
}
/// Create shim files for the package manager.
///
/// Will automatically create `{cli_name}.cjs`, `{cli_name}.cmd`, `{cli_name}.ps1` files for the package manager.
/// Example:
/// - $`bin_prefix/pnpm` -> $`bin_prefix/pnpm.cjs`
/// - $`bin_prefix/pnpm.cmd` -> $`bin_prefix/pnpm.cjs`
/// - $`bin_prefix/pnpm.ps1` -> $`bin_prefix/pnpm.cjs`
/// - $`bin_prefix/pnpx` -> $`bin_prefix/pnpx.cjs`
/// - $`bin_prefix/pnpx.cmd` -> $`bin_prefix/pnpx.cjs`
/// - $`bin_prefix/pnpx.ps1` -> $`bin_prefix/pnpx.cjs`
async fn create_shim_files(
package_manager_type: PackageManagerType,
bin_prefix: impl AsRef<AbsolutePath>,
) -> Result<(), Error> {
let mut bin_names: Vec<(&str, &str)> = Vec::new();
match package_manager_type {
PackageManagerType::Pnpm => {
bin_names.push(("pnpm", "pnpm"));
bin_names.push(("pnpx", "pnpx"));
}
PackageManagerType::Yarn => {
// yarn don't have the `npx` like cli, so we don't need to create shim files for it
bin_names.push(("yarn", "yarn"));
// but it has alias `yarnpkg`
bin_names.push(("yarnpkg", "yarn"));
}
PackageManagerType::Npm => {
// npm has two cli: bin/npm-cli.js and bin/npx-cli.js
bin_names.push(("npm", "npm-cli"));
bin_names.push(("npx", "npx-cli"));
}
}
let bin_prefix = bin_prefix.as_ref();
for (bin_name, js_bin_basename) in bin_names {
// try .cjs first
let mut js_bin_name = format!("{js_bin_basename}.cjs");
if !is_exists_file(bin_prefix.join(&js_bin_name))? {
// fallback to .js
js_bin_name = format!("{js_bin_basename}.js");
if !is_exists_file(bin_prefix.join(&js_bin_name))? {
continue;
}
}
let source_file = bin_prefix.join(js_bin_name);
let to_bin = bin_prefix.join(bin_name);
shim::write_shims(&source_file, &to_bin).await?;
}
Ok(())
}
async fn set_package_manager_field(
package_json_path: impl AsRef<AbsolutePath>,
package_manager_type: PackageManagerType,
version: &str,
) -> Result<(), Error> {
let package_json_path = package_json_path.as_ref();
let package_manager_value = format!("{package_manager_type}@{version}");
let mut package_json = if is_exists_file(package_json_path)? {
let content = tokio::fs::read(&package_json_path).await?;
serde_json::from_slice(&content)?
} else {
serde_json::json!({})
};
// use IndexMap to preserve the order of the fields
if let Some(package_json) = package_json.as_object_mut() {
package_json.insert("packageManager".into(), serde_json::json!(package_manager_value));
}
let json_string = serde_json::to_string_pretty(&package_json)?;
tokio::fs::write(&package_json_path, json_string).await?;
tracing::debug!(
"set_package_manager_field: {:?} to {:?}",
package_json_path,
package_manager_value
);
Ok(())
}
pub(crate) fn format_path_env(bin_prefix: impl AsRef<Path>) -> String {
let mut paths = env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect::<Vec<_>>();
paths.insert(0, bin_prefix.as_ref().to_path_buf());
env::join_paths(paths).unwrap().to_string_lossy().to_string()
}
#[cfg(test)]
mod tests {
use std::fs;
use tempfile::{TempDir, tempdir};
use super::*;
fn create_temp_dir() -> TempDir {
tempdir().expect("Failed to create temp directory")
}
fn create_package_json(dir: &AbsolutePath, content: &str) {
fs::write(dir.join("package.json"), content).expect("Failed to write package.json");
}
fn create_pnpm_workspace_yaml(dir: &AbsolutePath, content: &str) {
fs::write(dir.join("pnpm-workspace.yaml"), content)
.expect("Failed to write pnpm-workspace.yaml");
}
#[test]
fn test_find_package_root() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let nested_dir = temp_dir_path.join("a").join("b").join("c");
fs::create_dir_all(&nested_dir).unwrap();
// Create package.json in a/b
let package_dir = temp_dir_path.join("a").join("b");
File::create(package_dir.join("package.json")).unwrap();
// Should find package.json in parent directory
let found = find_package_root(&nested_dir);
let package_root = found.unwrap();
assert_eq!(package_root.path, package_dir);
// Should return the same directory if package.json is there
let found = find_package_root(&package_dir);
let package_root = found.unwrap();
assert_eq!(package_root.path, package_dir);
// Should return PackageJsonNotFound error if no package.json found
let root_dir = temp_dir_path.join("x").join("y");
fs::create_dir_all(&root_dir).unwrap();
let found = find_package_root(&root_dir);
let err = found.unwrap_err();
assert!(matches!(err, Error::PackageJsonNotFound(_)));
}
#[test]
fn test_find_workspace_root_with_pnpm() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let nested_dir = temp_dir_path.join("packages").join("app");
fs::create_dir_all(&nested_dir).unwrap();
// Create pnpm-workspace.yaml at root
File::create(temp_dir_path.join("pnpm-workspace.yaml")).unwrap();
// Should find workspace root
let found = find_workspace_root(&nested_dir).unwrap();
assert_eq!(found.path, temp_dir_path);
assert!(matches!(found.workspace_file, WorkspaceFile::PnpmWorkspaceYaml(_)));
}
#[test]
fn test_find_workspace_root_with_npm_workspaces() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let nested_dir = temp_dir_path.join("packages").join("app");
fs::create_dir_all(&nested_dir).unwrap();
// Create package.json with workspaces field
let package_json = r#"{"workspaces": ["packages/*"]}"#;
fs::write(temp_dir_path.join("package.json"), package_json).unwrap();
// Should find workspace root
let found = find_workspace_root(&temp_dir_path).unwrap();
assert_eq!(found.path, temp_dir_path);
assert!(matches!(found.workspace_file, WorkspaceFile::NpmWorkspaceJson(_)));
}
#[test]
fn test_find_workspace_root_fallback_to_package_root() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let nested_dir = temp_dir_path.join("src");
fs::create_dir_all(&nested_dir).unwrap();
// Create package.json without workspaces field
let package_json = r#"{"name": "test"}"#;
fs::write(temp_dir_path.join("package.json"), package_json).unwrap();
// Should fallback to package root
let found = find_workspace_root(&nested_dir).unwrap();
assert_eq!(found.path, temp_dir_path);
assert!(matches!(found.workspace_file, WorkspaceFile::NonWorkspacePackage(_)));
let package_root = find_package_root(&temp_dir_path).unwrap();
// equal to workspace root
assert_eq!(package_root.path, found.path);
}
#[test]
fn test_find_workspace_root_with_package_json_not_found() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let nested_dir = temp_dir_path.join("src");
fs::create_dir_all(&nested_dir).unwrap();
// Should return PackageJsonNotFound error if no package.json found
let found = find_workspace_root(&nested_dir);
let err = found.unwrap_err();
assert!(matches!(err, Error::PackageJsonNotFound(_)));
}
#[test]
fn test_find_package_root_with_package_json_in_current_dir() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let package_content = r#"{"name": "test-package"}"#;
create_package_json(&temp_dir_path, package_content);
let result = find_package_root(&temp_dir_path).unwrap();
assert_eq!(result.path, temp_dir_path);
}
#[test]
fn test_find_package_root_with_package_json_in_parent_dir() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let package_content = r#"{"name": "test-package"}"#;
create_package_json(&temp_dir_path, package_content);
let sub_dir = temp_dir_path.join("subdir");
fs::create_dir(&sub_dir).expect("Failed to create subdirectory");
let result = find_package_root(&sub_dir).unwrap();
assert_eq!(result.path, temp_dir_path);
}
#[test]
fn test_find_package_root_with_package_json_in_grandparent_dir() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let package_content = r#"{"name": "test-package"}"#;
create_package_json(&temp_dir_path, package_content);
let sub_dir = temp_dir_path.join("subdir").join("nested");
fs::create_dir_all(&sub_dir).expect("Failed to create nested directories");
let result = find_package_root(&sub_dir).unwrap();
assert_eq!(result.path, temp_dir_path);
}
#[test]
fn test_find_workspace_root_with_pnpm_workspace_yaml() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let workspace_content = "packages:\n - 'packages/*'";
create_pnpm_workspace_yaml(&temp_dir_path, workspace_content);
let result = find_workspace_root(&temp_dir_path).expect("Should find workspace root");
assert_eq!(result.path, temp_dir_path);
}
#[test]
fn test_find_workspace_root_with_pnpm_workspace_yaml_in_parent_dir() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let workspace_content = "packages:\n - 'packages/*'";
create_pnpm_workspace_yaml(&temp_dir_path, workspace_content);
let sub_dir = temp_dir_path.join("subdir");
fs::create_dir(&sub_dir).expect("Failed to create subdirectory");
let result = find_workspace_root(&sub_dir).expect("Should find workspace root");
assert_eq!(result.path, temp_dir_path);
}
#[test]
fn test_find_workspace_root_with_package_json_workspaces() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let package_content = r#"{"name": "test-workspace", "workspaces": ["packages/*"]}"#;
create_package_json(&temp_dir_path, package_content);
let result = find_workspace_root(&temp_dir_path).unwrap();
assert_eq!(result.path, temp_dir_path);
assert!(matches!(result.workspace_file, WorkspaceFile::NpmWorkspaceJson(_)));
}
#[test]
fn test_find_workspace_root_with_package_json_workspaces_in_parent_dir() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let package_content = r#"{"name": "test-workspace", "workspaces": ["packages/*"]}"#;
create_package_json(&temp_dir_path, package_content);
let sub_dir = temp_dir_path.join("subdir");
fs::create_dir(&sub_dir).expect("Failed to create subdirectory");
let result = find_workspace_root(&sub_dir).unwrap();
assert_eq!(result.path, temp_dir_path);
assert!(matches!(result.workspace_file, WorkspaceFile::NpmWorkspaceJson(_)));
}
#[test]
fn test_find_workspace_root_prioritizes_pnpm_workspace_over_package_json() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
// Create package.json with workspaces first
let package_content = r#"{"name": "test-workspace", "workspaces": ["packages/*"]}"#;
create_package_json(&temp_dir_path, package_content);
// Then create pnpm-workspace.yaml (should take precedence)
let workspace_content = "packages:\n - 'packages/*'";
create_pnpm_workspace_yaml(&temp_dir_path, workspace_content);
let result = find_workspace_root(&temp_dir_path).expect("Should find workspace root");
assert_eq!(result.path, temp_dir_path);
}
#[test]
fn test_find_workspace_root_falls_back_to_package_root_when_no_workspace_found() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let package_content = r#"{"name": "test-package"}"#;
create_package_json(&temp_dir_path, package_content);
let sub_dir = temp_dir_path.join("subdir");
fs::create_dir(&sub_dir).expect("Failed to create subdirectory");
let result = find_workspace_root(&sub_dir).expect("Should fall back to package root");
assert_eq!(result.path, temp_dir_path);
}
#[test]
fn test_find_workspace_root_with_nested_structure() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let workspace_content = "packages:\n - 'packages/*'";
create_pnpm_workspace_yaml(&temp_dir_path, workspace_content);
let nested_dir = temp_dir_path.join("packages").join("app").join("src");
fs::create_dir_all(&nested_dir).expect("Failed to create nested directories");
let result = find_workspace_root(&nested_dir).expect("Should find workspace root");
assert_eq!(result.path, temp_dir_path);
}
#[test]
fn test_find_workspace_root_without_workspace_files_returns_package_root() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let package_content = r#"{"name": "test-package"}"#;
create_package_json(&temp_dir_path, package_content);
let result = find_workspace_root(&temp_dir_path).expect("Should return package root");
assert_eq!(result.path, temp_dir_path);
}
#[test]
fn test_find_workspace_root_with_invalid_package_json_handles_error() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let invalid_package_content = "{ invalid json content";
create_package_json(&temp_dir_path, invalid_package_content);
let result = find_workspace_root(&temp_dir_path);
assert!(result.is_err());
}
#[test]
fn test_find_workspace_root_with_mixed_structure() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
// Create a package.json without workspaces
let package_content = r#"{"name": "test-package"}"#;
create_package_json(&temp_dir_path, package_content);
// Create a subdirectory with its own package.json
let sub_dir = temp_dir_path.join("subdir");
fs::create_dir(&sub_dir).expect("Failed to create subdirectory");
let sub_package_content = r#"{"name": "sub-package"}"#;
create_package_json(&sub_dir, sub_package_content);
// Should find the subdirectory package.json since find_package_root searches upward from original_cwd
let workspace_root =
find_workspace_root(&sub_dir).expect("Should find subdirectory package");
assert_eq!(workspace_root.path, sub_dir);
assert!(matches!(workspace_root.workspace_file, WorkspaceFile::NonWorkspacePackage(_)));
}
#[tokio::test]
async fn test_detect_package_manager_with_pnpm_workspace_yaml() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let workspace_content = "packages:\n - 'packages/*'";
create_pnpm_workspace_yaml(&temp_dir_path, workspace_content);
let result =
PackageManager::builder(temp_dir_path).build().await.expect("Should detect pnpm");
assert_eq!(result.bin_name, "pnpm");
}
#[tokio::test]
async fn test_detect_package_manager_with_pnpm_lock_yaml() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let package_content = r#"{"name": "test-package", "version": "1.0.0"}"#;
create_package_json(&temp_dir_path, package_content);
// Create pnpm-lock.yaml
fs::write(temp_dir_path.join("pnpm-lock.yaml"), "lockfileVersion: '6.0'")
.expect("Failed to write pnpm-lock.yaml");
let result =
PackageManager::builder(temp_dir_path).build().await.expect("Should detect pnpm");
assert_eq!(result.bin_name, "pnpm");
// check if the package.json file has the `packageManager` field
let package_json_path = temp_dir.path().join("package.json");
let package_json: serde_json::Value =
serde_json::from_slice(&fs::read(&package_json_path).unwrap()).unwrap();
println!("package_json: {package_json:?}");
assert!(package_json["packageManager"].as_str().unwrap().starts_with("pnpm@"));
// keep other fields
assert_eq!(package_json["version"].as_str().unwrap(), "1.0.0");
assert_eq!(package_json["name"].as_str().unwrap(), "test-package");
}
#[tokio::test]
async fn test_detect_package_manager_with_yarn_lock() {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let package_content = r#"{"name": "test-package"}"#;
create_package_json(&temp_dir_path, package_content);
// Create yarn.lock
fs::write(temp_dir_path.join("yarn.lock"), "# yarn lockfile v1")
.expect("Failed to write yarn.lock");
let result = PackageManager::builder(temp_dir_path.to_absolute_path_buf())
.build()
.await
.expect("Should detect yarn");
assert_eq!(result.bin_name, "yarn");
assert_eq!(result.workspace_root, temp_dir_path);
assert!(
result.get_bin_prefix().ends_with("yarn/bin"),
"bin_prefix should end with yarn/bin, but got {:?}",
result.get_bin_prefix()
);
// package.json should have the `packageManager` field
let package_json_path = temp_dir_path.join("package.json");
let package_json: serde_json::Value =
serde_json::from_slice(&fs::read(&package_json_path).unwrap()).unwrap();
println!("package_json: {package_json:?}");
assert!(package_json["packageManager"].as_str().unwrap().starts_with("yarn@"));
// keep other fields
assert_eq!(package_json["name"].as_str().unwrap(), "test-package");
}
#[tokio::test]
#[cfg(not(windows))] // FIXME
async fn test_detect_package_manager_with_package_lock_json() {
use std::process::Command;
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let package_content = r#"{"name": "test-package"}"#;
create_package_json(&temp_dir_path, package_content);
// Create package-lock.json
fs::write(temp_dir_path.join("package-lock.json"), r#"{"lockfileVersion": 2}"#)
.expect("Failed to write package-lock.json");
let result =
PackageManager::builder(temp_dir_path).build().await.expect("Should detect npm");
assert_eq!(result.bin_name, "npm");
// check shim files
let bin_prefix = result.get_bin_prefix();
assert!(is_exists_file(bin_prefix.join("npm")).unwrap());
assert!(is_exists_file(bin_prefix.join("npm.cmd")).unwrap());
assert!(is_exists_file(bin_prefix.join("npm.ps1")).unwrap());
assert!(is_exists_file(bin_prefix.join("npx")).unwrap());
assert!(is_exists_file(bin_prefix.join("npx.cmd")).unwrap());
assert!(is_exists_file(bin_prefix.join("npx.ps1")).unwrap());
// run npm --version
let mut paths =
env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect::<Vec<_>>();
paths.insert(0, bin_prefix.into_path_buf());
let output = Command::new("npm")