forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 1
/
installer.rs
1416 lines (1278 loc) · 38.6 KB
/
installer.rs
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-2024 the Deno authors. All rights reserved. MIT license.
use crate::args::resolve_no_prompt;
use crate::args::AddFlags;
use crate::args::CaData;
use crate::args::Flags;
use crate::args::InstallFlags;
use crate::args::InstallFlagsGlobal;
use crate::args::InstallKind;
use crate::args::TypeCheckMode;
use crate::args::UninstallFlags;
use crate::args::UninstallKind;
use crate::factory::CliFactory;
use crate::http_util::HttpClient;
use crate::util::fs::canonicalize_path_maybe_not_exists;
use deno_config::ConfigFlag;
use deno_core::anyhow::Context;
use deno_core::error::generic_error;
use deno_core::error::AnyError;
use deno_core::resolve_url_or_path;
use deno_core::url::Url;
use deno_semver::npm::NpmPackageReqReference;
use log::Level;
use once_cell::sync::Lazy;
use regex::Regex;
use regex::RegexBuilder;
use std::env;
use std::fs;
use std::fs::File;
use std::io;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
#[cfg(not(windows))]
use std::os::unix::fs::PermissionsExt;
static EXEC_NAME_RE: Lazy<Regex> = Lazy::new(|| {
RegexBuilder::new(r"^[a-z0-9][\w-]*$")
.case_insensitive(true)
.build()
.expect("invalid regex")
});
fn validate_name(exec_name: &str) -> Result<(), AnyError> {
if EXEC_NAME_RE.is_match(exec_name) {
Ok(())
} else {
Err(generic_error(format!(
"Invalid executable name: {exec_name}"
)))
}
}
#[cfg(windows)]
/// On Windows, 2 files are generated.
/// One compatible with cmd & powershell with a .cmd extension
/// A second compatible with git bash / MINGW64
/// Generate batch script to satisfy that.
fn generate_executable_file(shim_data: &ShimData) -> Result<(), AnyError> {
let args: Vec<String> =
shim_data.args.iter().map(|c| format!("\"{c}\"")).collect();
let template = format!(
"% generated by deno install %\n@deno {} %*\n",
args
.iter()
.map(|arg| arg.replace('%', "%%"))
.collect::<Vec<_>>()
.join(" ")
);
let mut file = File::create(&shim_data.file_path)?;
file.write_all(template.as_bytes())?;
// write file for bash
// create filepath without extensions
let template = format!(
r#"#!/bin/sh
# generated by deno install
deno {} "$@"
"#,
args.join(" "),
);
let mut file = File::create(shim_data.file_path.with_extension(""))?;
file.write_all(template.as_bytes())?;
Ok(())
}
#[cfg(not(windows))]
fn generate_executable_file(shim_data: &ShimData) -> Result<(), AnyError> {
use shell_escape::escape;
let args: Vec<String> = shim_data
.args
.iter()
.map(|c| escape(c.into()).into_owned())
.collect();
let template = format!(
r#"#!/bin/sh
# generated by deno install
exec deno {} "$@"
"#,
args.join(" "),
);
let mut file = File::create(&shim_data.file_path)?;
file.write_all(template.as_bytes())?;
let _metadata = fs::metadata(&shim_data.file_path)?;
let mut permissions = _metadata.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&shim_data.file_path, permissions)?;
Ok(())
}
fn get_installer_root() -> Result<PathBuf, io::Error> {
if let Ok(env_dir) = env::var("DENO_INSTALL_ROOT") {
if !env_dir.is_empty() {
return canonicalize_path_maybe_not_exists(&PathBuf::from(env_dir));
}
}
// Note: on Windows, the $HOME environment variable may be set by users or by
// third party software, but it is non-standard and should not be relied upon.
let home_env_var = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
let mut home_path =
env::var_os(home_env_var)
.map(PathBuf::from)
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("${home_env_var} is not defined"),
)
})?;
home_path.push(".deno");
Ok(home_path)
}
pub async fn infer_name_from_url(url: &Url) -> Option<String> {
// If there's an absolute url with no path, eg. https://my-cli.com
// perform a request, and see if it redirects another file instead.
let mut url = url.clone();
if url.path() == "/" {
let client = HttpClient::new(None, None);
if let Ok(res) = client.get_redirected_response(url.clone()).await {
url = res.url().clone();
}
}
if let Ok(npm_ref) = NpmPackageReqReference::from_specifier(&url) {
let npm_ref = npm_ref.into_inner();
if let Some(sub_path) = npm_ref.sub_path {
if !sub_path.contains('/') {
return Some(sub_path);
}
}
if !npm_ref.req.name.contains('/') {
return Some(npm_ref.req.name);
}
return None;
}
let percent_decode = percent_encoding::percent_decode(url.path().as_bytes());
#[cfg(unix)]
let path = {
use std::os::unix::prelude::OsStringExt;
PathBuf::from(std::ffi::OsString::from_vec(
percent_decode.collect::<Vec<u8>>(),
))
};
#[cfg(windows)]
let path = PathBuf::from(percent_decode.decode_utf8_lossy().as_ref());
let mut stem = path.file_stem()?.to_string_lossy();
if matches!(stem.as_ref(), "main" | "mod" | "index" | "cli") {
if let Some(parent_name) = path.parent().and_then(|p| p.file_name()) {
stem = parent_name.to_string_lossy();
}
}
// if atmark symbol appears in the index other than 0 (e.g. `foo@bar`) we use
// the former part as the inferred name because the latter part is most likely
// a version number.
match stem.find('@') {
Some(at_index) if at_index > 0 => {
stem = stem.split_at(at_index).0.to_string().into();
}
_ => {}
}
Some(stem.to_string())
}
pub fn uninstall(uninstall_flags: UninstallFlags) -> Result<(), AnyError> {
if !uninstall_flags.global {
log::warn!("⚠️ `deno install` behavior will change in Deno 2. To preserve the current behavior use the `-g` or `--global` flag.");
}
let uninstall_flags = match uninstall_flags.kind {
UninstallKind::Global(flags) => flags,
UninstallKind::Local => unreachable!(),
};
let cwd = std::env::current_dir().context("Unable to get CWD")?;
let root = if let Some(root) = uninstall_flags.root {
canonicalize_path_maybe_not_exists(&cwd.join(root))?
} else {
get_installer_root()?
};
let installation_dir = root.join("bin");
// ensure directory exists
if let Ok(metadata) = fs::metadata(&installation_dir) {
if !metadata.is_dir() {
return Err(generic_error("Installation path is not a directory"));
}
}
let file_path = installation_dir.join(&uninstall_flags.name);
let mut removed = false;
if file_path.exists() {
fs::remove_file(&file_path)?;
log::info!("deleted {}", file_path.to_string_lossy());
removed = true
};
if cfg!(windows) {
let file_path = file_path.with_extension("cmd");
if file_path.exists() {
fs::remove_file(&file_path)?;
log::info!("deleted {}", file_path.to_string_lossy());
removed = true
}
}
if !removed {
return Err(generic_error(format!(
"No installation found for {}",
uninstall_flags.name
)));
}
// There might be some extra files to delete
// Note: tsconfig.json is legacy. We renamed it to deno.json.
// Remove cleaning it up after January 2024
for ext in ["tsconfig.json", "deno.json", "lock.json"] {
let file_path = file_path.with_extension(ext);
if file_path.exists() {
fs::remove_file(&file_path)?;
log::info!("deleted {}", file_path.to_string_lossy());
}
}
log::info!("✅ Successfully uninstalled {}", uninstall_flags.name);
Ok(())
}
async fn install_local(
flags: Flags,
maybe_add_flags: Option<AddFlags>,
) -> Result<(), AnyError> {
if let Some(add_flags) = maybe_add_flags {
return super::registry::add(flags, add_flags).await;
}
let factory = CliFactory::from_flags(flags)?;
crate::module_loader::load_top_level_deps(&factory).await?;
if let Some(lockfile) = factory.cli_options().maybe_lockfile() {
lockfile.lock().write()?;
}
Ok(())
}
pub async fn install_command(
flags: Flags,
install_flags: InstallFlags,
) -> Result<(), AnyError> {
if !install_flags.global {
log::warn!("⚠️ `deno install` behavior will change in Deno 2. To preserve the current behavior use the `-g` or `--global` flag.");
}
let install_flags_global = match install_flags.kind {
InstallKind::Global(flags) => flags,
InstallKind::Local(maybe_add_flags) => {
return install_local(flags, maybe_add_flags).await
}
};
// ensure the module is cached
let factory = CliFactory::from_flags(flags.clone())?;
factory
.main_module_graph_container()
.await?
.load_and_type_check_files(&[install_flags_global.module_url.clone()])
.await?;
// create the install shim
create_install_shim(flags, install_flags_global).await
}
async fn create_install_shim(
flags: Flags,
install_flags_global: InstallFlagsGlobal,
) -> Result<(), AnyError> {
let shim_data = resolve_shim_data(&flags, &install_flags_global).await?;
// ensure directory exists
if let Ok(metadata) = fs::metadata(&shim_data.installation_dir) {
if !metadata.is_dir() {
return Err(generic_error("Installation path is not a directory"));
}
} else {
fs::create_dir_all(&shim_data.installation_dir)?;
};
if shim_data.file_path.exists() && !install_flags_global.force {
return Err(generic_error(
"Existing installation found. Aborting (Use -f to overwrite).",
));
};
generate_executable_file(&shim_data)?;
for (path, contents) in shim_data.extra_files {
fs::write(path, contents)?;
}
log::info!("✅ Successfully installed {}", shim_data.name);
log::info!("{}", shim_data.file_path.display());
if cfg!(windows) {
let display_path = shim_data.file_path.with_extension("");
log::info!("{} (shell)", display_path.display());
}
let installation_dir_str = shim_data.installation_dir.to_string_lossy();
if !is_in_path(&shim_data.installation_dir) {
log::info!("ℹ️ Add {} to PATH", installation_dir_str);
if cfg!(windows) {
log::info!(" set PATH=%PATH%;{}", installation_dir_str);
} else {
log::info!(" export PATH=\"{}:$PATH\"", installation_dir_str);
}
}
Ok(())
}
struct ShimData {
name: String,
installation_dir: PathBuf,
file_path: PathBuf,
args: Vec<String>,
extra_files: Vec<(PathBuf, String)>,
}
async fn resolve_shim_data(
flags: &Flags,
install_flags_global: &InstallFlagsGlobal,
) -> Result<ShimData, AnyError> {
let cwd = std::env::current_dir().context("Unable to get CWD")?;
let root = if let Some(root) = &install_flags_global.root {
canonicalize_path_maybe_not_exists(&cwd.join(root))?
} else {
get_installer_root()?
};
let installation_dir = root.join("bin");
// Check if module_url is remote
let module_url = resolve_url_or_path(&install_flags_global.module_url, &cwd)?;
let name = if install_flags_global.name.is_some() {
install_flags_global.name.clone()
} else {
infer_name_from_url(&module_url).await
};
let name = match name {
Some(name) => name,
None => return Err(generic_error(
"An executable name was not provided. One could not be inferred from the URL. Aborting.",
)),
};
validate_name(name.as_str())?;
let mut file_path = installation_dir.join(&name);
if cfg!(windows) {
file_path = file_path.with_extension("cmd");
}
let mut extra_files: Vec<(PathBuf, String)> = vec![];
let mut executable_args = vec!["run".to_string()];
executable_args.extend_from_slice(&flags.to_permission_args());
if let Some(url) = flags.location.as_ref() {
executable_args.push("--location".to_string());
executable_args.push(url.to_string());
}
if let Some(CaData::File(ca_file)) = &flags.ca_data {
executable_args.push("--cert".to_string());
executable_args.push(ca_file.to_owned())
}
if let Some(log_level) = flags.log_level {
if log_level == Level::Error {
executable_args.push("--quiet".to_string());
} else {
executable_args.push("--log-level".to_string());
let log_level = match log_level {
Level::Debug => "debug",
Level::Info => "info",
_ => {
return Err(generic_error(format!("invalid log level {log_level}")))
}
};
executable_args.push(log_level.to_string());
}
}
// we should avoid a default branch here to ensure we continue to cover any
// changes to this flag.
match flags.type_check_mode {
TypeCheckMode::All => executable_args.push("--check=all".to_string()),
TypeCheckMode::None => {}
TypeCheckMode::Local => executable_args.push("--check".to_string()),
}
if flags.unstable_config.legacy_flag_enabled {
executable_args.push("--unstable".to_string());
}
for feature in &flags.unstable_config.features {
executable_args.push(format!("--unstable-{}", feature));
}
if flags.no_remote {
executable_args.push("--no-remote".to_string());
}
if flags.no_npm {
executable_args.push("--no-npm".to_string());
}
if flags.lock_write {
executable_args.push("--lock-write".to_string());
}
if flags.cached_only {
executable_args.push("--cached-only".to_string());
}
if resolve_no_prompt(&flags.permissions) {
executable_args.push("--no-prompt".to_string());
}
if !flags.v8_flags.is_empty() {
executable_args.push(format!("--v8-flags={}", flags.v8_flags.join(",")));
}
if let Some(seed) = flags.seed {
executable_args.push("--seed".to_string());
executable_args.push(seed.to_string());
}
if let Some(inspect) = flags.inspect {
executable_args.push(format!("--inspect={inspect}"));
}
if let Some(inspect_brk) = flags.inspect_brk {
executable_args.push(format!("--inspect-brk={inspect_brk}"));
}
if let Some(import_map_path) = &flags.import_map_path {
let import_map_url = resolve_url_or_path(import_map_path, &cwd)?;
executable_args.push("--import-map".to_string());
executable_args.push(import_map_url.to_string());
}
if let ConfigFlag::Path(config_path) = &flags.config_flag {
let copy_path = get_hidden_file_with_ext(&file_path, "deno.json");
executable_args.push("--config".to_string());
executable_args.push(copy_path.to_str().unwrap().to_string());
extra_files.push((
copy_path,
fs::read_to_string(config_path)
.with_context(|| format!("error reading {config_path}"))?,
));
} else {
executable_args.push("--no-config".to_string());
}
if flags.no_lock {
executable_args.push("--no-lock".to_string());
} else if flags.lock.is_some()
// always use a lockfile for an npm entrypoint unless --no-lock
|| NpmPackageReqReference::from_specifier(&module_url).is_ok()
{
let copy_path = get_hidden_file_with_ext(&file_path, "lock.json");
executable_args.push("--lock".to_string());
executable_args.push(copy_path.to_str().unwrap().to_string());
if let Some(lock_path) = &flags.lock {
extra_files.push((
copy_path,
fs::read_to_string(lock_path)
.with_context(|| format!("error reading {}", lock_path))?,
));
} else {
// Provide an empty lockfile so that this overwrites any existing lockfile
// from a previous installation. This will get populated on first run.
extra_files.push((copy_path, "{}".to_string()));
}
}
executable_args.push(module_url.to_string());
executable_args.extend_from_slice(&install_flags_global.args);
Ok(ShimData {
name,
installation_dir,
file_path,
args: executable_args,
extra_files,
})
}
fn get_hidden_file_with_ext(file_path: &Path, ext: &str) -> PathBuf {
// use a dot file to prevent the file from showing up in some
// users shell auto-complete since this directory is on the PATH
file_path
.with_file_name(format!(
".{}",
file_path.file_name().unwrap().to_string_lossy()
))
.with_extension(ext)
}
fn is_in_path(dir: &Path) -> bool {
if let Some(paths) = env::var_os("PATH") {
for p in env::split_paths(&paths) {
if *dir == p {
return true;
}
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::args::PermissionFlags;
use crate::args::UninstallFlagsGlobal;
use crate::args::UnstableConfig;
use crate::util::fs::canonicalize_path;
use deno_config::ConfigFlag;
use std::process::Command;
use test_util::testdata_path;
use test_util::TempDir;
#[tokio::test]
async fn install_infer_name_from_url() {
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc/server.ts").unwrap()
)
.await,
Some("server".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc/main.ts").unwrap()
)
.await,
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc/mod.ts").unwrap()
)
.await,
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/ab%20c/mod.ts").unwrap()
)
.await,
Some("ab c".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc/index.ts").unwrap()
)
.await,
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc/cli.ts").unwrap()
)
.await,
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("https://example.com/main.ts").unwrap())
.await,
Some("main".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("https://example.com").unwrap()).await,
None
);
assert_eq!(
infer_name_from_url(&Url::parse("file:https:///abc/server.ts").unwrap()).await,
Some("server".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("file:https:///abc/main.ts").unwrap()).await,
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("file:https:///ab%20c/main.ts").unwrap()).await,
Some("ab c".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("file:https:///main.ts").unwrap()).await,
Some("main".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("file:https:///").unwrap()).await,
None
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/[email protected]").unwrap()
)
.await,
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/[email protected]/main.ts").unwrap()
)
.await,
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc@def@ghi").unwrap()
)
.await,
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("https://example.com/@abc.ts").unwrap())
.await,
Some("@abc".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/@abc/mod.ts").unwrap()
)
.await,
Some("@abc".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("file:https:///@abc.ts").unwrap()).await,
Some("@abc".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("file:https:///@abc/cli.ts").unwrap()).await,
Some("@abc".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("npm:[email protected]/cowthink").unwrap())
.await,
Some("cowthink".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("npm:[email protected]/cowthink/test").unwrap())
.await,
Some("cowsay".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("npm:[email protected]").unwrap()).await,
Some("cowsay".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("npm:@types/[email protected]").unwrap()).await,
None
);
}
#[tokio::test]
async fn install_unstable() {
let temp_dir = TempDir::new();
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
create_install_shim(
Flags {
unstable_config: UnstableConfig {
legacy_flag_enabled: true,
..Default::default()
},
..Flags::default()
},
InstallFlagsGlobal {
module_url: "https://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_string()),
force: false,
},
)
.await
.unwrap();
let mut file_path = bin_dir.join("echo_test");
if cfg!(windows) {
file_path = file_path.with_extension("cmd");
}
assert!(file_path.exists());
let content = fs::read_to_string(file_path).unwrap();
if cfg!(windows) {
assert!(content.contains(
r#""run" "--unstable" "--no-config" "https://localhost:4545/echo_server.ts""#
));
} else {
assert!(content.contains(
r#"run --unstable --no-config 'https://localhost:4545/echo_server.ts'"#
));
}
}
#[tokio::test]
async fn install_inferred_name() {
let shim_data = resolve_shim_data(
&Flags::default(),
&InstallFlagsGlobal {
module_url: "https://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: None,
root: Some(env::temp_dir().to_string_lossy().to_string()),
force: false,
},
)
.await
.unwrap();
assert_eq!(shim_data.name, "echo_server");
assert_eq!(
shim_data.args,
vec!["run", "--no-config", "https://localhost:4545/echo_server.ts",]
);
}
#[tokio::test]
async fn install_unstable_legacy() {
let shim_data = resolve_shim_data(
&Flags {
unstable_config: UnstableConfig {
legacy_flag_enabled: true,
..Default::default()
},
..Default::default()
},
&InstallFlagsGlobal {
module_url: "https://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: None,
root: Some(env::temp_dir().to_string_lossy().to_string()),
force: false,
},
)
.await
.unwrap();
assert_eq!(shim_data.name, "echo_server");
assert_eq!(
shim_data.args,
vec![
"run",
"--unstable",
"--no-config",
"https://localhost:4545/echo_server.ts",
]
);
}
#[tokio::test]
async fn install_unstable_features() {
let shim_data = resolve_shim_data(
&Flags {
unstable_config: UnstableConfig {
features: vec!["kv".to_string(), "cron".to_string()],
..Default::default()
},
..Default::default()
},
&InstallFlagsGlobal {
module_url: "https://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: None,
root: Some(env::temp_dir().to_string_lossy().to_string()),
force: false,
},
)
.await
.unwrap();
assert_eq!(shim_data.name, "echo_server");
assert_eq!(
shim_data.args,
vec![
"run",
"--unstable-kv",
"--unstable-cron",
"--no-config",
"https://localhost:4545/echo_server.ts",
]
);
}
#[tokio::test]
async fn install_inferred_name_from_parent() {
let shim_data = resolve_shim_data(
&Flags::default(),
&InstallFlagsGlobal {
module_url: "https://localhost:4545/subdir/main.ts".to_string(),
args: vec![],
name: None,
root: Some(env::temp_dir().to_string_lossy().to_string()),
force: false,
},
)
.await
.unwrap();
assert_eq!(shim_data.name, "subdir");
assert_eq!(
shim_data.args,
vec!["run", "--no-config", "https://localhost:4545/subdir/main.ts",]
);
}
#[tokio::test]
async fn install_inferred_name_after_redirect_for_no_path_url() {
let _http_server_guard = test_util::http_server();
let shim_data = resolve_shim_data(
&Flags::default(),
&InstallFlagsGlobal {
module_url: "https://localhost:4550/?redirect_to=/subdir/redirects/a.ts"
.to_string(),
args: vec![],
name: None,
root: Some(env::temp_dir().to_string_lossy().to_string()),
force: false,
},
)
.await
.unwrap();
assert_eq!(shim_data.name, "a");
assert_eq!(
shim_data.args,
vec![
"run",
"--no-config",
"https://localhost:4550/?redirect_to=/subdir/redirects/a.ts",
]
);
}
#[tokio::test]
async fn install_custom_dir_option() {
let shim_data = resolve_shim_data(
&Flags::default(),
&InstallFlagsGlobal {
module_url: "https://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(env::temp_dir().to_string_lossy().to_string()),
force: false,
},
)
.await
.unwrap();
assert_eq!(shim_data.name, "echo_test");
assert_eq!(
shim_data.args,
vec!["run", "--no-config", "https://localhost:4545/echo_server.ts",]
);
}
#[tokio::test]
async fn install_with_flags() {
let shim_data = resolve_shim_data(
&Flags {
permissions: PermissionFlags {
allow_net: Some(vec![]),
allow_read: Some(vec![]),
..Default::default()
},
type_check_mode: TypeCheckMode::None,
log_level: Some(Level::Error),
..Flags::default()
},
&InstallFlagsGlobal {
module_url: "https://localhost:4545/echo_server.ts".to_string(),
args: vec!["--foobar".to_string()],
name: Some("echo_test".to_string()),
root: Some(env::temp_dir().to_string_lossy().to_string()),
force: false,
},
)
.await
.unwrap();
assert_eq!(shim_data.name, "echo_test");
assert_eq!(
shim_data.args,
vec![
"run",
"--allow-read",
"--allow-net",
"--quiet",
"--no-config",
"https://localhost:4545/echo_server.ts",
"--foobar",
]
);
}
#[tokio::test]
async fn install_prompt() {
let shim_data = resolve_shim_data(
&Flags {
permissions: PermissionFlags {
no_prompt: true,
..Default::default()
},
..Flags::default()
},
&InstallFlagsGlobal {
module_url: "https://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(env::temp_dir().to_string_lossy().to_string()),
force: false,
},
)
.await
.unwrap();
assert_eq!(
shim_data.args,
vec![
"run",
"--no-prompt",
"--no-config",
"https://localhost:4545/echo_server.ts",
]
);
}
#[tokio::test]
async fn install_allow_all() {
let shim_data = resolve_shim_data(
&Flags {
permissions: PermissionFlags {
allow_all: true,
..Default::default()
},
..Flags::default()
},
&InstallFlagsGlobal {
module_url: "https://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(env::temp_dir().to_string_lossy().to_string()),
force: false,
},
)
.await
.unwrap();
assert_eq!(
shim_data.args,
vec![
"run",
"--allow-all",
"--no-config",
"https://localhost:4545/echo_server.ts",
]
);