-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathpackage_manager.rs
More file actions
2481 lines (2163 loc) · 103 KB
/
package_manager.rs
File metadata and controls
2481 lines (2163 loc) · 103 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::{self, BufReader, IsTerminal, Write},
path::Path,
};
use crossterm::{
cursor,
event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
execute,
style::{Color, Print, ResetColor, SetForegroundColor},
terminal,
};
use semver::{Version, VersionReq};
use serde::{Deserialize, Serialize};
use tokio::fs::remove_dir_all;
use vite_error::Error;
use vite_path::{AbsolutePath, AbsolutePathBuf};
use vite_str::Str;
#[cfg(test)]
use vite_workspace::find_package_root;
use vite_workspace::{WorkspaceFile, WorkspaceRoot, find_workspace_root, load_package_graph};
use crate::{
config::{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,
Bun,
}
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"),
Self::Bun => write!(f, "bun"),
}
}
}
// 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,
/// Whether the workspace is a monorepo.
pub is_monorepo: bool,
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, _cwd) = find_workspace_root(&self.cwd)?;
let (package_manager_type, version_or_latest, hash) =
get_package_manager_type_and_version(&workspace_root, self.client_override)?;
// only download the package manager if it's not already downloaded
let (install_dir, package_name, version) =
download_package_manager(package_manager_type, &version_or_latest, hash.as_deref())
.await?;
if version_or_latest != version {
// 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?;
}
let is_monorepo = matches!(
workspace_root.workspace_file,
WorkspaceFile::PnpmWorkspaceYaml(_) | WorkspaceFile::NpmWorkspaceJson(_)
);
Ok(PackageManager {
client: package_manager_type,
package_name,
version,
hash,
bin_name: package_manager_type.to_string().into(),
workspace_root: workspace_root.path.to_absolute_path_buf(),
is_monorepo,
install_dir,
})
}
/// Build the package manager with default package manager.
/// If the package manager is not specified, prompt the user to select a package manager.
pub async fn build_with_default(&self) -> Result<PackageManager, Error> {
let package_manager = match self.build().await {
Ok(pm) => pm,
Err(Error::UnrecognizedPackageManager) => {
// Prompt user to select a package manager
let selected_type = prompt_package_manager_selection()?;
PackageManagerBuilder::new(&self.cwd)
.package_manager_type(selected_type)
.build()
.await?
}
Err(e) => return Err(e),
};
Ok(package_manager)
}
}
impl PackageManager {
pub fn builder(cwd: impl AsRef<AbsolutePath>) -> PackageManagerBuilder {
PackageManagerBuilder::new(cwd)
}
#[must_use]
pub fn get_bin_prefix(&self) -> AbsolutePathBuf {
self.install_dir.join("bin")
}
#[must_use]
pub fn get_fingerprint_ignores(&self) -> Result<Vec<Str>, Error> {
let mut ignores: Vec<Str> = vec![
// ignore all files by default, the package manager will traverse all subdirectories
"**/*".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());
}
PackageManagerType::Bun => {
ignores.push("!**/bun.lock".into());
ignores.push("!**/bun.lockb".into());
ignores.push("!**/bunfig.toml".into());
}
}
// if the workspace is a monorepo, keep workspace packages' parent directories to watch for new packages being added
if self.is_monorepo {
// TODO(@fengmk2): should use a more efficient way to get the workspace packages parent directories
let (workspace_root_info, _) = find_workspace_root(&self.workspace_root)?;
let package_graph = load_package_graph(&workspace_root_info)?;
for node_index in package_graph.node_indices() {
let package_info = &package_graph[node_index];
if let Some(parent_path) = package_info.path.as_path().parent() {
let rule: Str = format!("!{}", parent_path.display()).into();
// check if the rule is already in the ignores
if ignores.contains(&rule) {
continue;
}
ignores.push(rule);
}
}
}
// 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());
Ok(ignores)
}
}
/// Get the package manager name, version and optional hash from the workspace root.
pub 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)),
"bun" => return Ok((PackageManagerType::Bun, 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 bun.lock (text format) or bun.lockb (binary format) exists, use bun@latest
let bun_lock_path = workspace_root.path.join("bun.lock");
if is_exists_file(&bun_lock_path)? {
return Ok((PackageManagerType::Bun, version, None));
}
let bun_lockb_path = workspace_root.path.join("bun.lockb");
if is_exists_file(&bun_lockb_path)? {
return Ok((PackageManagerType::Bun, 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 bunfig.toml exists, use bun@latest
let bunfig_toml_path = workspace_root.path.join("bunfig.toml");
if is_exists_file(&bunfig_toml_path)? {
return Ok((PackageManagerType::Bun, 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 vite-plus home directory.
/// Return the install directory, e.g. `$VP_HOME/package_manager/pnpm/10.0.0/pnpm`
pub async fn download_package_manager(
package_manager_type: PackageManagerType,
version_or_latest: &str,
expected_hash: Option<&str>,
) -> Result<(AbsolutePathBuf, Str, Str), Error> {
let version: Str = if version_or_latest == "latest" {
get_latest_version(package_manager_type).await?
} else {
version_or_latest.into()
};
let mut package_name: Str = package_manager_type.to_string().into();
// 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".into();
}
}
let home_dir = vite_shared::get_vp_home()?;
let bin_name = package_manager_type.to_string();
// For bun, use platform-specific download flow.
// The hash from `packageManager` field belongs to the main `bun` npm package,
// not the platform-specific binary, so we don't pass it through.
if matches!(package_manager_type, PackageManagerType::Bun) {
return download_bun_package_manager(&version, &home_dir).await;
}
let tgz_url = get_npm_package_tgz_url(&package_name, &version);
// $VP_HOME/package_manager/pnpm/10.0.0
let target_dir = home_dir.join("package_manager").join(&bin_name).join(&version);
let install_dir = target_dir.join(&bin_name);
// If all shims already exist, return the target directory
// $VP_HOME/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, package_name, version));
}
// $VP_HOME/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.clone(),
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?;
// Use a file-based lock to ensure atomicity of remove + rename operations
// This prevents DirectoryNotEmpty error when multiple processes/threads
// try to install the same package manager version concurrently.
// The lock is automatically skipped on NFS filesystems where locking is unreliable.
let lock_path = parent_dir.join(format!("{version}.lock"));
tracing::debug!("Acquire lock file: {:?}", lock_path);
let lock_file = File::create(lock_path.as_path())?;
// Acquire exclusive lock (blocks until available)
lock_file.lock()?;
tracing::debug!("Lock acquired: {:?}", lock_path);
// Check again after acquiring the lock, in case another thread completed
// the installation while we were downloading
if is_exists_file(&bin_file)? {
tracing::debug!("bin_file already exists after lock acquisition, skip rename");
return Ok((install_dir, package_name, version));
}
// 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, package_name, version))
}
/// Get the platform-specific npm package name for bun.
/// Returns the `@oven/bun-{os}-{arch}` package name for the current platform.
fn get_bun_platform_package_name() -> Result<&'static str, Error> {
let name = match (env::consts::OS, env::consts::ARCH) {
("macos", "aarch64") => "@oven/bun-darwin-aarch64",
("macos", "x86_64") => "@oven/bun-darwin-x64",
#[cfg(target_env = "musl")]
("linux", "aarch64") => "@oven/bun-linux-aarch64-musl",
#[cfg(not(target_env = "musl"))]
("linux", "aarch64") => "@oven/bun-linux-aarch64",
#[cfg(target_env = "musl")]
("linux", "x86_64") => "@oven/bun-linux-x64-musl",
#[cfg(not(target_env = "musl"))]
("linux", "x86_64") => "@oven/bun-linux-x64",
("windows", "x86_64") => "@oven/bun-windows-x64",
("windows", "aarch64") => "@oven/bun-windows-aarch64",
(os, arch) => {
return Err(Error::UnsupportedPackageManager(
format!("bun (unsupported platform: {os}-{arch})").into(),
));
}
};
Ok(name)
}
/// Download bun package manager (native binary) from npm.
///
/// Unlike JS-based package managers (pnpm/npm/yarn), bun is a native binary
/// distributed via platform-specific npm packages (`@oven/bun-{os}-{arch}`).
///
/// Layout: `$VP_HOME/package_manager/bun/{version}/bun/bin/bun.native`
async fn download_bun_package_manager(
version: &Str,
home_dir: &AbsolutePath,
) -> Result<(AbsolutePathBuf, Str, Str), Error> {
let package_name: Str = "bun".into();
let platform_package_name = get_bun_platform_package_name()?;
// $VP_HOME/package_manager/bun/{version}
let target_dir = home_dir.join("package_manager").join("bun").join(version.as_str());
let install_dir = target_dir.join("bun");
let bin_prefix = install_dir.join("bin");
let bin_file = bin_prefix.join("bun");
// If shims already exist, return early
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, package_name, version.clone()));
}
let parent_dir = target_dir.parent().unwrap();
tokio::fs::create_dir_all(parent_dir).await?;
// Download the platform-specific package directly
let platform_tgz_url = get_npm_package_tgz_url(platform_package_name, version);
let target_dir_tmp = tempfile::tempdir_in(parent_dir)?.path().to_path_buf();
download_and_extract_tgz_with_hash(&platform_tgz_url, &target_dir_tmp, None).await.map_err(
|err| {
if let Error::Reqwest(e) = &err
&& let Some(status) = e.status()
&& status == reqwest::StatusCode::NOT_FOUND
{
Error::PackageManagerVersionNotFound {
name: "bun".into(),
version: version.clone(),
url: platform_tgz_url.into(),
}
} else {
err
}
},
)?;
// Create the expected directory structure: bun/bin/
let tmp_bun_dir = target_dir_tmp.join("bun");
let tmp_bin_dir = tmp_bun_dir.join("bin");
tokio::fs::create_dir_all(&tmp_bin_dir).await?;
// The platform package extracts to `package/bin/` with the bun binary inside
// Find the native binary in the extracted package
let package_dir = target_dir_tmp.join("package");
let package_bin_dir = package_dir.join("bin");
let native_bin_src =
if cfg!(windows) { package_bin_dir.join("bun.exe") } else { package_bin_dir.join("bun") };
// Move native binary to bin/bun.native
let native_bin_dest = if cfg!(windows) {
tmp_bin_dir.join("bun.native.exe")
} else {
tmp_bin_dir.join("bun.native")
};
tokio::fs::rename(&native_bin_src, &native_bin_dest).await?;
// Set executable permission on the native binary
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
tokio::fs::set_permissions(&native_bin_dest, fs::Permissions::from_mode(0o755)).await?;
}
// Clean up the extracted package directory
remove_dir_all_force(&package_dir).await?;
// Acquire lock for atomic rename
let lock_path = parent_dir.join(format!("{version}.lock"));
tracing::debug!("Acquire lock file: {:?}", lock_path);
let lock_file = File::create(lock_path.as_path())?;
lock_file.lock()?;
tracing::debug!("Lock acquired: {:?}", lock_path);
if is_exists_file(&bin_file)? {
tracing::debug!("bun bin_file already exists after lock acquisition, skip rename");
return Ok((install_dir, package_name, version.clone()));
}
// Rename temp dir to final location
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 native binary shims
tracing::debug!("Create shim files for bun");
create_shim_files(PackageManagerType::Bun, &bin_prefix).await?;
Ok((install_dir, package_name, version.clone()))
}
/// 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> {
let path = path.as_ref();
remove_dir_all(path).await.or_else(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
Ok(())
} else {
tracing::error!("remove_dir_all_force path: {:?} error: {e:?}", path);
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"));
}
PackageManagerType::Bun => {
// bun is a native binary, not a JS package.
// Create native binary shims instead of Node.js-based shims.
let bin_prefix = bin_prefix.as_ref();
return create_bun_shim_files(bin_prefix).await;
}
}
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(())
}
/// Create shim files for bun's native binary.
///
/// Bun is a native binary distributed via platform-specific npm packages.
/// The native binary is placed at `bin_prefix/bun.native` (unix) or
/// `bin_prefix/bun.native.exe` (windows), and we create shim wrappers
/// that exec it directly (without Node.js).
async fn create_bun_shim_files(bin_prefix: &AbsolutePath) -> Result<(), Error> {
// The native binary should already be at bin_prefix/bun.native (unix) or
// bin_prefix/bun.native.exe (windows), placed there by download_bun_platform_binary.
let native_bin = if cfg!(windows) {
bin_prefix.join("bun.native.exe")
} else {
bin_prefix.join("bun.native")
};
if !is_exists_file(&native_bin)? {
return Err(Error::CannotFindBinaryPath(
"bun native binary not found. Expected bin/bun.native".into(),
));
}
// Create bun shim -> bun.native
let bun_shim = bin_prefix.join("bun");
shim::write_native_shims(&native_bin, &bun_shim).await?;
// Create bunx shim -> bun.native (bunx is just bun with different argv[0])
let bunx_shim = bin_prefix.join("bunx");
shim::write_native_shims(&native_bin, &bunx_shim).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) use vite_shared::format_path_prepended as format_path_env;
/// Common CI environment variables
const CI_ENV_VARS: &[&str] = &[
"CI",
"CONTINUOUS_INTEGRATION",
"GITHUB_ACTIONS",
"GITLAB_CI",
"CIRCLECI",
"TRAVIS",
"JENKINS_URL",
"BUILDKITE",
"DRONE",
"CODEBUILD_BUILD_ID", // AWS CodeBuild
"TF_BUILD", // Azure Pipelines
];
/// Check if running in a CI environment
fn is_ci_environment() -> bool {
CI_ENV_VARS.iter().any(|key| env::var(key).is_ok())
}
/// Interactive menu for selecting a package manager with keyboard navigation
fn interactive_package_manager_menu() -> Result<PackageManagerType, Error> {
let options = [
("pnpm (recommended)", PackageManagerType::Pnpm),
("npm", PackageManagerType::Npm),
("yarn", PackageManagerType::Yarn),
("bun", PackageManagerType::Bun),
];
let mut selected_index = 0;
// Print header and instructions with proper line breaks
println!("\nNo package manager detected. Please select one:");
println!(
" Use ↑↓ arrows to navigate, Enter to select, 1-{} for quick selection",
options.len()
);
println!(" Press Esc, q, or Ctrl+C to cancel installation\n");
// Enable raw mode for keyboard input
terminal::enable_raw_mode()?;
// Clear the selection area and hide cursor
execute!(io::stdout(), cursor::Hide)?;
let result = loop {
// Display menu with current selection
for (i, (name, _)) in options.iter().enumerate() {
execute!(io::stdout(), cursor::MoveToColumn(2))?;
if i == selected_index {
// Highlight selected item
execute!(
io::stdout(),
SetForegroundColor(Color::Blue),
Print("▶ "),
Print(format!("[{}] ", i + 1)),
Print(name),
ResetColor,
Print(" ← ")
)?;
} else {
execute!(
io::stdout(),
Print(" "),
SetForegroundColor(Color::DarkGrey),
Print(format!("[{}] ", i + 1)),
ResetColor,
Print(name),
Print(" ")
)?;
}
if i < options.len() - 1 {
execute!(io::stdout(), Print("\n"))?;
}
}
// Move cursor back up for next iteration
if options.len() > 1 {
execute!(io::stdout(), cursor::MoveUp((options.len() - 1) as u16))?;
}
// Read keyboard input, skipping non-Press events (e.g. Release on Windows)
let (code, modifiers) = loop {
if let Event::Key(KeyEvent { code, modifiers, kind, .. }) = event::read()? {
if kind == KeyEventKind::Press {
break (code, modifiers);
}
}
};
match code {
// Handle Ctrl+C for exit
KeyCode::Char('c') if modifiers.contains(event::KeyModifiers::CONTROL) => {
// Clean up terminal before exiting
terminal::disable_raw_mode()?;
execute!(
io::stdout(),
cursor::Show,
cursor::MoveDown(options.len() as u16),
Print("\n\n"),
SetForegroundColor(Color::Yellow),
Print("⚠ Installation cancelled by user\n"),
ResetColor
)?;
return Err(Error::UserCancelled);
}
KeyCode::Up => {
selected_index = selected_index.saturating_sub(1);
}
KeyCode::Down => {
if selected_index < options.len() - 1 {
selected_index += 1;
}
}
KeyCode::Enter | KeyCode::Char(' ') => {
break Ok(options[selected_index].1);
}
KeyCode::Char('1') => {
break Ok(options[0].1);
}
KeyCode::Char('2') if options.len() > 1 => {
break Ok(options[1].1);
}
KeyCode::Char('3') if options.len() > 2 => {
break Ok(options[2].1);
}
KeyCode::Char('4') if options.len() > 3 => {
break Ok(options[3].1);
}
KeyCode::Esc | KeyCode::Char('q') => {
// Exit on escape/quit
terminal::disable_raw_mode()?;
execute!(
io::stdout(),
cursor::Show,
cursor::MoveDown(options.len() as u16),
Print("\n\n"),
SetForegroundColor(Color::Yellow),
Print("⚠ Installation cancelled by user\n"),
ResetColor
)?;
return Err(Error::UserCancelled);
}
_ => {}
}
};
// Clean up: disable raw mode and show cursor
terminal::disable_raw_mode()?;
execute!(io::stdout(), cursor::Show, cursor::MoveDown(options.len() as u16), Print("\n"))?;
// Print selection confirmation
if let Ok(pm) = &result {
let name = match pm {
PackageManagerType::Pnpm => "pnpm",
PackageManagerType::Npm => "npm",
PackageManagerType::Yarn => "yarn",
PackageManagerType::Bun => "bun",
};
println!("\n✓ Selected package manager: {name}\n");
}
result
}
/// Prompt the user to select a package manager
fn prompt_package_manager_selection() -> Result<PackageManagerType, Error> {
// In CI environment, automatically use pnpm without prompting
if is_ci_environment() {
tracing::info!("CI environment detected. Using default package manager: pnpm");
return Ok(PackageManagerType::Pnpm);
}
// Check if stdin is a TTY (terminal) - if not, use default
if !io::stdin().is_terminal() {
tracing::info!("Non-interactive environment detected. Using default package manager: pnpm");
return Ok(PackageManagerType::Pnpm);
}
// Try interactive menu first, fall back to simple prompt on error
match interactive_package_manager_menu() {
Ok(pm) => Ok(pm),
Err(err) => {
match err {
Error::UserCancelled => Err(err),
// Fallback to simple text prompt if interactive menu fails
_ => simple_text_prompt(),
}
}
}
}
/// Simple text-based prompt as fallback
fn simple_text_prompt() -> Result<PackageManagerType, Error> {
let managers = [
("pnpm", PackageManagerType::Pnpm),
("npm", PackageManagerType::Npm),
("yarn", PackageManagerType::Yarn),
("bun", PackageManagerType::Bun),
];
println!("\nNo package manager detected. Please select one:");
println!("────────────────────────────────────────────────");
for (i, (name, _)) in managers.iter().enumerate() {
if i == 0 {
println!(" [{}] {} (recommended)", i + 1, name);
} else {
println!(" [{}] {}", i + 1, name);
}
}
print!("\nEnter your choice (1-{}) [default: 1]: ", managers.len());
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let choice = input.trim();
let index = if choice.is_empty() {
0 // Default to pnpm
} else {
choice
.parse::<usize>()
.ok()
.and_then(|n| if n > 0 && n <= managers.len() { Some(n - 1) } else { None })
.unwrap_or(0) // Default to pnpm if invalid input
};
let (name, selected_type) = &managers[index];
println!("✓ Selected package manager: {name}\n");
Ok(*selected_type)
}
#[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)