-
Notifications
You must be signed in to change notification settings - Fork 330
Expand file tree
/
Copy pathexecutor.rs
More file actions
575 lines (501 loc) · 18.3 KB
/
executor.rs
File metadata and controls
575 lines (501 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
use std::collections::HashMap;
use std::ffi::OsStr;
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt;
#[cfg(windows)]
use std::os::windows::process::ExitStatusExt;
use std::process::{Command, ExitStatus};
use super::{RECURSION_ENV_VAR, RECURSION_LIMIT};
use crate::command::{command_on_path, create_command};
use crate::error::{Context, ErrorKind, Fallible};
use crate::layout::volta_home;
use crate::platform::{CliPlatform, Platform, System};
use crate::session::Session;
use crate::signal::pass_control_to_shim;
use crate::style::{note_prefix, tool_version};
use crate::sync::VoltaLock;
use crate::tool::package::{DirectInstall, InPlaceUpgrade, PackageConfig, PackageManager};
use crate::tool::Spec;
use log::{info, warn};
pub enum Executor {
Tool(Box<ToolCommand>),
PackageInstall(Box<PackageInstallCommand>),
PackageLink(Box<PackageLinkCommand>),
PackageUpgrade(Box<PackageUpgradeCommand>),
InternalInstall(Box<InternalInstallCommand>),
Uninstall(Box<UninstallCommand>),
Multiple(Vec<Executor>),
}
impl Executor {
pub fn envs<K, V, S>(&mut self, envs: &HashMap<K, V, S>)
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
match self {
Executor::Tool(cmd) => cmd.envs(envs),
Executor::PackageInstall(cmd) => cmd.envs(envs),
Executor::PackageLink(cmd) => cmd.envs(envs),
Executor::PackageUpgrade(cmd) => cmd.envs(envs),
// Internal installs use Volta's logic and don't rely on the environment variables
Executor::InternalInstall(_) => {}
// Uninstalls use Volta's logic and don't rely on environment variables
Executor::Uninstall(_) => {}
Executor::Multiple(executors) => {
for exe in executors {
exe.envs(envs);
}
}
}
}
pub fn cli_platform(&mut self, cli: CliPlatform) {
match self {
Executor::Tool(cmd) => cmd.cli_platform(cli),
Executor::PackageInstall(cmd) => cmd.cli_platform(cli),
Executor::PackageLink(cmd) => cmd.cli_platform(cli),
Executor::PackageUpgrade(cmd) => cmd.cli_platform(cli),
// Internal installs use Volta's logic and don't rely on the Node platform
Executor::InternalInstall(_) => {}
// Uninstall use Volta's logic and don't rely on the Node platform
Executor::Uninstall(_) => {}
Executor::Multiple(executors) => {
for exe in executors {
exe.cli_platform(cli.clone());
}
}
}
}
pub fn execute(self, session: &mut Session) -> Fallible<ExitStatus> {
match self {
Executor::Tool(cmd) => cmd.execute(session),
Executor::PackageInstall(cmd) => cmd.execute(session),
Executor::PackageLink(cmd) => cmd.execute(session),
Executor::PackageUpgrade(cmd) => cmd.execute(session),
Executor::InternalInstall(cmd) => cmd.execute(session),
Executor::Uninstall(cmd) => cmd.execute(),
Executor::Multiple(executors) => {
info!(
"{} Volta is processing each package separately",
note_prefix()
);
for exe in executors {
let status = exe.execute(session)?;
// If any of the sub-commands fail, then we should stop installing and return
// that failure.
if !status.success() {
return Ok(status);
}
}
// If we get here, then all of the sub-commands succeeded, so we should report success
Ok(ExitStatus::from_raw(0))
}
}
}
}
impl From<Vec<Executor>> for Executor {
fn from(mut executors: Vec<Executor>) -> Self {
if executors.len() == 1 {
executors.pop().unwrap()
} else {
Executor::Multiple(executors)
}
}
}
/// Process builder for launching a Volta-managed tool
///
/// Tracks the Platform as well as what kind of tool is being executed, to allow individual tools
/// to customize the behavior before execution.
pub struct ToolCommand {
command: Command,
platform: Option<Platform>,
kind: ToolKind,
}
/// The kind of tool being executed, used to determine the correct execution context
pub enum ToolKind {
Node,
Npm,
Npx,
Pnpm,
Yarn,
ProjectLocalBinary(String),
DefaultBinary(String),
Bypass(String),
}
impl ToolCommand {
pub fn new<E, A, S>(exe: E, args: A, platform: Option<Platform>, kind: ToolKind) -> Self
where
E: AsRef<OsStr>,
A: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut command = create_command(exe);
command.args(args);
Self {
command,
platform,
kind,
}
}
/// Adds or updates environment variables that the command will use
pub fn envs<E, K, V>(&mut self, envs: E)
where
E: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.command.envs(envs);
}
/// Adds or updates a single environment variable that the command will use
pub fn env<K, V>(&mut self, key: K, value: V)
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.command.env(key, value);
}
/// Updates the Platform for the command to include values from the command-line
pub fn cli_platform(&mut self, cli: CliPlatform) {
self.platform = match self.platform.take() {
Some(base) => Some(cli.merge(base)),
None => cli.into(),
};
}
/// Runs the command, returning the `ExitStatus` if it successfully launches
pub fn execute(self, session: &mut Session) -> Fallible<ExitStatus> {
let (path, on_failure) = match self.kind {
ToolKind::Node => super::node::execution_context(self.platform, session)?,
ToolKind::Npm => super::npm::execution_context(self.platform, session)?,
ToolKind::Npx => super::npx::execution_context(self.platform, session)?,
ToolKind::Pnpm => super::pnpm::execution_context(self.platform, session)?,
ToolKind::Yarn => super::yarn::execution_context(self.platform, session)?,
ToolKind::DefaultBinary(bin) => {
super::binary::default_execution_context(bin, self.platform, session)?
}
ToolKind::ProjectLocalBinary(bin) => {
super::binary::local_execution_context(bin, self.platform, session)?
}
ToolKind::Bypass(command) => (System::path()?, ErrorKind::BypassError { command }),
};
// Do recursive call limit check
let recursion = match std::env::var(RECURSION_ENV_VAR) {
Err(_) => 1u8,
Ok(var) => var
.parse::<u8>()
.with_context(|| ErrorKind::ParseRecursionEnvError)?,
};
if recursion > RECURSION_LIMIT {
return Err(ErrorKind::RecursionLimit.into());
}
command_on_path(self.command, path)
.and_then(|mut command| {
command.env(RECURSION_ENV_VAR, (recursion + 1).to_string());
pass_control_to_shim();
command.status().with_context(|| ErrorKind::BinaryExecError)
})
.with_context(|| on_failure)
}
}
impl From<ToolCommand> for Executor {
fn from(cmd: ToolCommand) -> Self {
Executor::Tool(Box::new(cmd))
}
}
/// Process builder for launching a package install command (e.g. `npm install --global`)
///
/// This will use a `DirectInstall` instance to modify the command before running to point it to
/// the Volta directory. It will also complete the install, writing config files and shims
pub struct PackageInstallCommand {
/// The command that will ultimately be executed
command: Command,
/// The installer that modifies the command as necessary and provides the completion method
installer: DirectInstall,
/// The platform to use when running the command.
platform: Platform,
}
impl PackageInstallCommand {
pub fn new<A, S>(args: A, platform: Platform, manager: PackageManager) -> Fallible<Self>
where
A: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let installer = DirectInstall::new(manager)?;
let mut command = match manager {
PackageManager::Npm => create_command("npm"),
PackageManager::Pnpm => create_command("pnpm"),
PackageManager::Yarn => create_command("yarn"),
};
command.args(args);
Ok(PackageInstallCommand {
command,
installer,
platform,
})
}
pub fn for_npm_link<A, S>(args: A, platform: Platform, name: String) -> Fallible<Self>
where
A: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let installer = DirectInstall::with_name(PackageManager::Npm, name)?;
let mut command = create_command("npm");
command.args(args);
Ok(PackageInstallCommand {
command,
installer,
platform,
})
}
/// Adds or updates environment variables that the command will use
pub fn envs<E, K, V>(&mut self, envs: E)
where
E: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.command.envs(envs);
}
/// Updates the Platform for the command to include values from the command-line
pub fn cli_platform(&mut self, cli: CliPlatform) {
self.platform = cli.merge(self.platform.clone());
}
/// Runs the install command, applying the necessary modifications to install into the Volta
/// data directory
pub fn execute(self, session: &mut Session) -> Fallible<ExitStatus> {
let _lock = VoltaLock::acquire();
let image = self.platform.checkout(session)?;
let path = image.path()?;
let mut command = command_on_path(self.command, path)?;
command.env(RECURSION_ENV_VAR, "1");
self.installer.setup_command(&mut command);
let status = command
.status()
.with_context(|| ErrorKind::BinaryExecError)?;
if status.success() {
self.installer.complete_install(&image)?;
}
Ok(status)
}
}
impl From<PackageInstallCommand> for Executor {
fn from(cmd: PackageInstallCommand) -> Self {
Executor::PackageInstall(Box::new(cmd))
}
}
/// Process builder for launching a `npm link <package>` command
///
/// This will set the appropriate environment variables to ensure that the linked package can be
/// found.
pub struct PackageLinkCommand {
/// The command that will ultimately be executed
command: Command,
/// The tool the user wants to link
tool: String,
/// The platform to use when running the command
platform: Platform,
}
impl PackageLinkCommand {
pub fn new<A, S>(args: A, platform: Platform, tool: String) -> Self
where
A: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut command = create_command("npm");
command.args(args);
PackageLinkCommand {
command,
tool,
platform,
}
}
/// Adds or updates environment variables that the command will use
pub fn envs<E, K, V>(&mut self, envs: E)
where
E: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.command.envs(envs);
}
/// Updates the Platform for the command to include values from the command-line
pub fn cli_platform(&mut self, cli: CliPlatform) {
self.platform = cli.merge(self.platform.clone());
}
/// Runs the link command, applying the necessary modifications to pull from the Volta data
/// directory.
///
/// This will also check for some common failure cases and alert the user
pub fn execute(self, session: &mut Session) -> Fallible<ExitStatus> {
self.check_linked_package(session)?;
let image = self.platform.checkout(session)?;
let path = image.path()?;
let mut command = command_on_path(self.command, path)?;
command.env(RECURSION_ENV_VAR, "1");
let package_root = volta_home()?.package_image_dir(&self.tool);
PackageManager::Npm.setup_global_command(&mut command, package_root);
command.status().with_context(|| ErrorKind::BinaryExecError)
}
/// Check for possible failure cases with the linked package:
/// - The package is not found as a global
/// - The package exists, but was linked using a different package manager
/// - The package is using a different version of Node than the current project (warning)
fn check_linked_package(&self, session: &mut Session) -> Fallible<()> {
let config =
PackageConfig::from_file(volta_home()?.default_package_config_file(&self.tool))
.with_context(|| ErrorKind::NpmLinkMissingPackage {
package: self.tool.clone(),
})?;
if config.manager != PackageManager::Npm {
return Err(ErrorKind::NpmLinkWrongManager {
package: self.tool.clone(),
}
.into());
}
if let Some(platform) = session.project_platform()? {
if platform.node.major != config.platform.node.major {
warn!(
"the current project is using {}, but package '{}' was linked using {}. These might not interact correctly.",
tool_version("node", &platform.node),
self.tool,
tool_version("node", &config.platform.node)
);
}
}
Ok(())
}
}
impl From<PackageLinkCommand> for Executor {
fn from(cmd: PackageLinkCommand) -> Self {
Executor::PackageLink(Box::new(cmd))
}
}
/// Process builder for launching a global package upgrade command (e.g. `npm update -g`)
///
/// This will use an `InPlaceUpgrade` instance to modify the command and point at the appropriate
/// image directory. It will also complete the install, writing any updated configs and shims
pub struct PackageUpgradeCommand {
/// The command that will ultimately be executed
command: Command,
/// Helper utility to modify the command and provide the completion method
upgrader: InPlaceUpgrade,
/// The platform to run the command under
platform: Platform,
}
impl PackageUpgradeCommand {
pub fn new<A, S>(
args: A,
package: String,
platform: Platform,
manager: PackageManager,
) -> Fallible<Self>
where
A: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let upgrader = InPlaceUpgrade::new(package, manager)?;
let mut command = match manager {
PackageManager::Npm => create_command("npm"),
PackageManager::Pnpm => create_command("pnpm"),
PackageManager::Yarn => create_command("yarn"),
};
command.args(args);
Ok(PackageUpgradeCommand {
command,
upgrader,
platform,
})
}
/// Adds or updates environment variables that the command will use
pub fn envs<E, K, V>(&mut self, envs: E)
where
E: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.command.envs(envs);
}
/// Updates the Platform for the command to include values from the command-line
pub fn cli_platform(&mut self, cli: CliPlatform) {
self.platform = cli.merge(self.platform.clone());
}
/// Runs the upgrade command, applying the necessary modifications to point at the Volta image
/// directory
///
/// Will also check for common failure cases, such as non-existant package or wrong package
/// manager
pub fn execute(self, session: &mut Session) -> Fallible<ExitStatus> {
self.upgrader.check_upgraded_package()?;
let _lock = VoltaLock::acquire();
let image = self.platform.checkout(session)?;
let path = image.path()?;
let mut command = command_on_path(self.command, path)?;
command.env(RECURSION_ENV_VAR, "1");
self.upgrader.setup_command(&mut command);
let status = command
.status()
.with_context(|| ErrorKind::BinaryExecError)?;
if status.success() {
self.upgrader.complete_upgrade(&image)?;
}
Ok(status)
}
}
impl From<PackageUpgradeCommand> for Executor {
fn from(cmd: PackageUpgradeCommand) -> Self {
Executor::PackageUpgrade(Box::new(cmd))
}
}
/// Executor for running an internal install (installing Node, npm, pnpm or Yarn using the `volta
/// install` logic)
///
/// Note: This is not intended to be used for Package installs. Those should go through the
/// `PackageInstallCommand` above, to more seamlessly integrate with the package manager
pub struct InternalInstallCommand {
tool: Spec,
}
impl InternalInstallCommand {
pub fn new(tool: Spec) -> Self {
InternalInstallCommand { tool }
}
/// Runs the install, using Volta's internal install logic for the appropriate tool
fn execute(self, session: &mut Session) -> Fallible<ExitStatus> {
info!(
"{} using Volta to install {}",
note_prefix(),
self.tool.name()
);
self.tool.resolve(session)?.install(session)?;
Ok(ExitStatus::from_raw(0))
}
}
impl From<InternalInstallCommand> for Executor {
fn from(cmd: InternalInstallCommand) -> Self {
Executor::InternalInstall(Box::new(cmd))
}
}
/// Executor for running a tool uninstall command.
///
/// This will use the `volta uninstall` logic to correctly ensure that the package is fully
/// uninstalled
pub struct UninstallCommand {
tool: Spec,
}
impl UninstallCommand {
pub fn new(tool: Spec) -> Self {
UninstallCommand { tool }
}
/// Runs the uninstall with Volta's internal uninstall logic
fn execute(self) -> Fallible<ExitStatus> {
info!(
"{} using Volta to uninstall {}",
note_prefix(),
self.tool.name()
);
self.tool.uninstall()?;
Ok(ExitStatus::from_raw(0))
}
}
impl From<UninstallCommand> for Executor {
fn from(cmd: UninstallCommand) -> Self {
Executor::Uninstall(Box::new(cmd))
}
}