forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
installer.rs
636 lines (566 loc) · 17.9 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
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use crate::flags::Flags;
use log::Level;
use regex::{Regex, RegexBuilder};
use std::env;
use std::fs;
use std::fs::File;
use std::io::Error;
use std::io::ErrorKind;
use std::io::Write;
#[cfg(not(windows))]
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use url::Url;
lazy_static! {
static ref EXEC_NAME_RE: Regex = RegexBuilder::new(
r"^[a-z][\w-]*$"
).case_insensitive(true).build().unwrap();
// Regular expression to test disk driver letter. eg "C:\\User\username\path\to"
static ref DRIVE_LETTER_REG: Regex = RegexBuilder::new(
r"^[c-z]:"
).case_insensitive(true).build().unwrap();
}
pub fn is_remote_url(module_url: &str) -> bool {
let lower = module_url.to_lowercase();
lower.starts_with("http:https://") || lower.starts_with("https://")
}
fn validate_name(exec_name: &str) -> Result<(), Error> {
if EXEC_NAME_RE.is_match(exec_name) {
Ok(())
} else {
Err(Error::new(
ErrorKind::Other,
format!("Invalid executable name: {}", exec_name),
))
}
}
#[cfg(windows)]
/// On Windows if user is using Powershell .cmd extension is need to run the
/// installed module.
/// Generate batch script to satisfy that.
fn generate_executable_file(
file_path: PathBuf,
args: Vec<String>,
) -> Result<(), Error> {
let args: Vec<String> = args.iter().map(|c| format!("\"{}\"", c)).collect();
let template = format!(
"% generated by deno install %\[email protected] {} %*\n",
args.join(" ")
);
let mut file = File::create(&file_path)?;
file.write_all(template.as_bytes())?;
Ok(())
}
#[cfg(not(windows))]
fn generate_executable_file(
file_path: PathBuf,
args: Vec<String>,
) -> Result<(), Error> {
let args: Vec<String> = args.iter().map(|c| format!("\"{}\"", c)).collect();
let template = format!(
r#"#!/bin/sh
# generated by deno install
deno {} "$@"
"#,
args.join(" "),
);
let mut file = File::create(&file_path)?;
file.write_all(template.as_bytes())?;
let _metadata = fs::metadata(&file_path)?;
let mut permissions = _metadata.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&file_path, permissions)?;
Ok(())
}
fn get_installer_root() -> Result<PathBuf, Error> {
if let Ok(env_dir) = env::var("DENO_INSTALL_ROOT") {
if !env_dir.is_empty() {
return PathBuf::from(env_dir).canonicalize();
}
}
// In Windows's Powershell $HOME environmental variable maybe null
// if so use $USERPROFILE instead.
let home = env::var("HOME")
.map(String::into)
.unwrap_or_else(|_| "".to_string());
let user_profile = env::var("USERPROFILE")
.map(String::into)
.unwrap_or_else(|_| "".to_string());
if home.is_empty() && user_profile.is_empty() {
return Err(Error::new(ErrorKind::Other, "$HOME is not defined"));
}
let home_path = if !home.is_empty() { home } else { user_profile };
let mut home_path = PathBuf::from(home_path);
home_path.push(".deno");
Ok(home_path)
}
fn infer_name_from_url(url: &Url) -> Option<String> {
let path = PathBuf::from(url.path());
let stem = match path.file_stem() {
Some(stem) => stem.to_string_lossy().to_string(),
None => return None,
};
if let Some(parent_path) = path.parent() {
if stem == "main" || stem == "mod" || stem == "index" || stem == "cli" {
if let Some(parent_name) = parent_path.file_name() {
return Some(parent_name.to_string_lossy().to_string());
}
}
}
Some(stem)
}
pub fn install(
flags: Flags,
module_url: &str,
args: Vec<String>,
name: Option<String>,
root: Option<PathBuf>,
force: bool,
) -> Result<(), Error> {
let root = if let Some(root) = root {
root.canonicalize()?
} 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(Error::new(
ErrorKind::Other,
"Installation path is not a directory",
));
}
} else {
fs::create_dir_all(&installation_dir)?;
};
// Check if module_url is remote
let module_url = if is_remote_url(module_url) {
Url::parse(module_url).expect("Should be valid url")
} else {
let module_path = PathBuf::from(module_url);
let module_path = if module_path.is_absolute() {
module_path
} else {
let cwd = env::current_dir().unwrap();
cwd.join(module_path)
};
Url::from_file_path(module_path).expect("Path should be absolute")
};
let name = name.or_else(|| infer_name_from_url(&module_url));
let name = match name {
Some(name) => name,
None => return Err(Error::new(
ErrorKind::Other,
"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");
}
if file_path.exists() && !force {
return Err(Error::new(
ErrorKind::Other,
"Existing installation found. Aborting (Use -f to overwrite).",
));
};
let mut executable_args = vec!["run".to_string()];
executable_args.extend_from_slice(&flags.to_permission_args());
if let Some(ca_file) = flags.ca_file {
executable_args.push("--cert".to_string());
executable_args.push(ca_file)
}
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(Error::new(
ErrorKind::Other,
format!("invalid log level {}", log_level),
))
}
};
executable_args.push(log_level.to_string());
}
}
if flags.unstable {
executable_args.push("--unstable".to_string());
}
executable_args.push(module_url.to_string());
executable_args.extend_from_slice(&args);
generate_executable_file(file_path.to_owned(), executable_args)?;
println!("✅ Successfully installed {}", name);
println!("{}", file_path.to_string_lossy());
let installation_dir_str = installation_dir.to_string_lossy();
if !is_in_path(&installation_dir) {
println!("ℹ️ Add {} to PATH", installation_dir_str);
if cfg!(windows) {
println!(" set PATH=%PATH%;{}", installation_dir_str);
} else {
println!(" export PATH=\"{}:$PATH\"", installation_dir_str);
}
}
Ok(())
}
fn is_in_path(dir: &PathBuf) -> 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 std::sync::Mutex;
use tempfile::TempDir;
lazy_static! {
pub static ref ENV_LOCK: Mutex<()> = Mutex::new(());
}
#[test]
fn test_is_remote_url() {
assert!(is_remote_url("https://deno.land/std/http/file_server.ts"));
assert!(is_remote_url("http:https://deno.land/std/http/file_server.ts"));
assert!(is_remote_url("HTTP:https://deno.land/std/http/file_server.ts"));
assert!(is_remote_url("HTTp:https://deno.land/std/http/file_server.ts"));
assert!(!is_remote_url("file:https:///dev/deno_std/http/file_server.ts"));
assert!(!is_remote_url("./dev/deno_std/http/file_server.ts"));
}
#[test]
fn install_infer_name_from_url() {
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc/server.ts").unwrap()
),
Some("server".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc/main.ts").unwrap()
),
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc/mod.ts").unwrap()
),
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc/index.ts").unwrap()
),
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(
&Url::parse("https://example.com/abc/cli.ts").unwrap()
),
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("https://example.com/main.ts").unwrap()),
Some("main".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("https://example.com").unwrap()),
None
);
assert_eq!(
infer_name_from_url(&Url::parse("file:https:///abc/server.ts").unwrap()),
Some("server".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("file:https:///abc/main.ts").unwrap()),
Some("abc".to_string())
);
assert_eq!(
infer_name_from_url(&Url::parse("file:https:///main.ts").unwrap()),
Some("main".to_string())
);
assert_eq!(infer_name_from_url(&Url::parse("file:https:///").unwrap()), None);
}
#[test]
fn install_basic() {
let _guard = ENV_LOCK.lock().ok();
let temp_dir = TempDir::new().expect("tempdir fail");
let temp_dir_str = temp_dir.path().to_string_lossy().to_string();
// NOTE: this test overrides environmental variables
// don't add other tests in this file that mess with "HOME" and "USEPROFILE"
// otherwise transient failures are possible because tests are run in parallel.
// It means that other test can override env vars when this test is running.
let original_home = env::var_os("HOME");
let original_user_profile = env::var_os("HOME");
let original_install_root = env::var_os("DENO_INSTALL_ROOT");
env::set_var("HOME", &temp_dir_str);
env::set_var("USERPROFILE", &temp_dir_str);
env::set_var("DENO_INSTALL_ROOT", "");
install(
Flags::default(),
"http:https://localhost:4545/cli/tests/echo_server.ts",
vec![],
Some("echo_test".to_string()),
None,
false,
)
.expect("Install failed");
let mut file_path = temp_dir.path().join(".deno/bin/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();
// It's annoying when shell scripts don't have NL at the end.
assert_eq!(content.chars().last().unwrap(), '\n');
assert!(content
.contains(r#""run" "http:https://localhost:4545/cli/tests/echo_server.ts""#));
if let Some(home) = original_home {
env::set_var("HOME", home);
}
if let Some(user_profile) = original_user_profile {
env::set_var("USERPROFILE", user_profile);
}
if let Some(install_root) = original_install_root {
env::set_var("DENO_INSTALL_ROOT", install_root);
}
}
#[test]
fn install_unstable() {
let temp_dir = TempDir::new().expect("tempdir fail");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
install(
Flags {
unstable: true,
..Flags::default()
},
"http:https://localhost:4545/cli/tests/echo_server.ts",
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
)
.expect("Install failed");
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();
println!("this is the file path {:?}", content);
assert!(content.contains(
r#""run" "--unstable" "http:https://localhost:4545/cli/tests/echo_server.ts"#
));
}
#[test]
fn install_inferred_name() {
let temp_dir = TempDir::new().expect("tempdir fail");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
install(
Flags::default(),
"http:https://localhost:4545/cli/tests/echo_server.ts",
vec![],
None,
Some(temp_dir.path().to_path_buf()),
false,
)
.expect("Install failed");
let mut file_path = bin_dir.join("echo_server");
if cfg!(windows) {
file_path = file_path.with_extension("cmd");
}
assert!(file_path.exists());
let content = fs::read_to_string(file_path).unwrap();
assert!(content
.contains(r#""run" "http:https://localhost:4545/cli/tests/echo_server.ts""#));
}
#[test]
fn install_inferred_name_from_parent() {
let temp_dir = TempDir::new().expect("tempdir fail");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
install(
Flags::default(),
"http:https://localhost:4545/cli/tests/subdir/main.ts",
vec![],
None,
Some(temp_dir.path().to_path_buf()),
false,
)
.expect("Install failed");
let mut file_path = bin_dir.join("subdir");
if cfg!(windows) {
file_path = file_path.with_extension("cmd");
}
assert!(file_path.exists());
let content = fs::read_to_string(file_path).unwrap();
assert!(content
.contains(r#""run" "http:https://localhost:4545/cli/tests/subdir/main.ts""#));
}
#[test]
fn install_custom_dir_option() {
let temp_dir = TempDir::new().expect("tempdir fail");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
install(
Flags::default(),
"http:https://localhost:4545/cli/tests/echo_server.ts",
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
)
.expect("Install failed");
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();
assert!(content
.contains(r#""run" "http:https://localhost:4545/cli/tests/echo_server.ts""#));
}
#[test]
fn install_custom_dir_env_var() {
let _guard = ENV_LOCK.lock().ok();
let temp_dir = TempDir::new().expect("tempdir fail");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
let original_install_root = env::var_os("DENO_INSTALL_ROOT");
env::set_var("DENO_INSTALL_ROOT", temp_dir.path().to_path_buf());
install(
Flags::default(),
"http:https://localhost:4545/cli/tests/echo_server.ts",
vec![],
Some("echo_test".to_string()),
None,
false,
)
.expect("Install failed");
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();
assert!(content
.contains(r#""run" "http:https://localhost:4545/cli/tests/echo_server.ts""#));
if let Some(install_root) = original_install_root {
env::set_var("DENO_INSTALL_ROOT", install_root);
}
}
#[test]
fn install_with_flags() {
let temp_dir = TempDir::new().expect("tempdir fail");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
install(
Flags {
allow_net: true,
allow_read: true,
log_level: Some(Level::Error),
..Flags::default()
},
"http:https://localhost:4545/cli/tests/echo_server.ts",
vec!["--foobar".to_string()],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
)
.expect("Install failed");
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();
assert!(content.contains(r#""run" "--allow-read" "--allow-net" "--quiet" "http:https://localhost:4545/cli/tests/echo_server.ts" "--foobar""#));
}
#[test]
fn install_local_module() {
let temp_dir = TempDir::new().expect("tempdir fail");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
let local_module = env::current_dir().unwrap().join("echo_server.ts");
let local_module_url = Url::from_file_path(&local_module).unwrap();
let local_module_str = local_module.to_string_lossy();
install(
Flags::default(),
&local_module_str,
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
)
.expect("Install failed");
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();
assert!(content.contains(&local_module_url.to_string()));
}
#[test]
fn install_force() {
let temp_dir = TempDir::new().expect("tempdir fail");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir(&bin_dir).unwrap();
install(
Flags::default(),
"http:https://localhost:4545/cli/tests/echo_server.ts",
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
)
.expect("Install failed");
let mut file_path = bin_dir.join("echo_test");
if cfg!(windows) {
file_path = file_path.with_extension("cmd");
}
assert!(file_path.exists());
// No force. Install failed.
let no_force_result = install(
Flags::default(),
"http:https://localhost:4545/cli/tests/cat.ts", // using a different URL
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
);
assert!(no_force_result.is_err());
assert!(no_force_result
.unwrap_err()
.to_string()
.contains("Existing installation found"));
// Assert not modified
let file_content = fs::read_to_string(&file_path).unwrap();
assert!(file_content.contains("echo_server.ts"));
// Force. Install success.
let force_result = install(
Flags::default(),
"http:https://localhost:4545/cli/tests/cat.ts", // using a different URL
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
true,
);
assert!(force_result.is_ok());
// Assert modified
let file_content_2 = fs::read_to_string(&file_path).unwrap();
assert!(file_content_2.contains("cat.ts"));
}
}