-
Notifications
You must be signed in to change notification settings - Fork 213
/
exec.rs
172 lines (148 loc) · 5.09 KB
/
exec.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
use std::collections::BTreeMap;
use std::ffi::{OsStr, OsString};
use clap::ValueHint;
use duct::IntoExecutablePath;
#[cfg(not(any(test, windows)))]
use eyre::{bail, Result};
#[cfg(any(test, windows))]
use eyre::{eyre, Result};
use crate::cli::args::ToolArg;
#[cfg(any(test, windows))]
use crate::cmd;
use crate::config::Config;
use crate::env;
use crate::toolset::{InstallOptions, ToolsetBuilder};
/// Execute a command with tool(s) set
///
/// use this to avoid modifying the shell session or running ad-hoc commands with mise tools set.
///
/// Tools will be loaded from .mise.toml/.tool-versions, though they can be overridden with <RUNTIME> args
/// Note that only the plugin specified will be overridden, so if a `.tool-versions` file
/// includes "node 20" but you run `mise exec python@3.11`; it will still load node@20.
///
/// The "--" separates runtimes from the commands to pass along to the subprocess.
#[derive(Debug, clap::Args)]
#[clap(visible_alias = "x", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Exec {
/// Tool(s) to start
/// e.g.: node@20 python@3.10
#[clap(value_name = "TOOL@VERSION")]
pub tool: Vec<ToolArg>,
/// Command string to execute (same as --command)
#[clap(conflicts_with = "c", required_unless_present = "c", last = true)]
pub command: Option<Vec<OsString>>,
/// Command string to execute
#[clap(short, long = "command", value_hint = ValueHint::CommandString, conflicts_with = "command")]
pub c: Option<OsString>,
/// Number of jobs to run in parallel
/// [default: 4]
#[clap(long, short, env = "MISE_JOBS", verbatim_doc_comment)]
pub jobs: Option<usize>,
/// Directly pipe stdin/stdout/stderr from plugin to user
/// Sets --jobs=1
#[clap(long, overrides_with = "jobs")]
pub raw: bool,
}
impl Exec {
pub fn run(self) -> Result<()> {
let config = Config::try_get()?;
let mut ts = ToolsetBuilder::new()
.with_args(&self.tool)
.with_default_to_latest(true)
.build(&config)?;
let opts = InstallOptions {
force: false,
jobs: self.jobs,
raw: self.raw,
latest_versions: false,
};
ts.install_arg_versions(&config, &opts)?;
ts.notify_if_versions_missing();
let (program, args) = parse_command(&env::SHELL, &self.command, &self.c);
let env = ts.env_with_path(&config)?;
self.exec(program, args, env)
}
#[cfg(not(any(test, windows)))]
fn exec<T, U, E>(&self, program: T, args: U, env: BTreeMap<E, E>) -> Result<()>
where
T: IntoExecutablePath,
U: IntoIterator,
U::Item: Into<OsString>,
E: AsRef<OsStr>,
{
for (k, v) in env.iter() {
env::set_var(k, v);
}
let args = args.into_iter().map(Into::into).collect::<Vec<_>>();
let program = program.to_executable();
let err = exec::Command::new(program.clone()).args(&args).exec();
bail!("{:?} {err}", program.to_string_lossy())
}
#[cfg(any(test, windows))]
fn exec<T, U, E>(&self, program: T, args: U, env: BTreeMap<E, E>) -> Result<()>
where
T: IntoExecutablePath,
U: IntoIterator,
U::Item: Into<OsString>,
E: AsRef<OsStr>,
{
let mut cmd = cmd::cmd(program, args);
for (k, v) in env.iter() {
cmd = cmd.env(k, v);
}
let res = cmd.unchecked().run()?;
match res.status.code() {
Some(0) => Ok(()),
Some(code) => Err(eyre!("command failed: exit code {}", code)),
None => Err(eyre!("command failed: terminated by signal")),
}
}
}
fn parse_command(
shell: &str,
command: &Option<Vec<OsString>>,
c: &Option<OsString>,
) -> (OsString, Vec<OsString>) {
match (&command, &c) {
(Some(command), _) => {
let (program, args) = command.split_first().unwrap();
(program.clone(), args.into())
}
_ => (shell.into(), vec!["-c".into(), c.clone().unwrap()]),
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise exec node@20 -- node ./app.js</bold> # launch app.js using node-20.x
$ <bold>mise x node@20 -- node ./app.js</bold> # shorter alias
# Specify command as a string:
$ <bold>mise exec node@20 python@3.11 --command "node -v && python -V"</bold>
# Run a command in a different directory:
$ <bold>mise x -C /path/to/project node@20 -- node ./app.js</bold>
"#
);
#[cfg(test)]
mod tests {
use std::env;
use insta::assert_snapshot;
use test_log::test;
use crate::test::reset;
#[test]
fn test_exec_ok() {
reset();
assert_cli!("exec", "--", "echo");
}
#[test]
fn test_exec_fail() {
reset();
let err = assert_cli_err!("exec", "--", "exit", "1");
assert_snapshot!(err);
}
#[test]
fn test_exec_cd() {
reset();
let cwd = env::current_dir().unwrap();
assert_cli!("exec", "-C", "/tmp", "--", "pwd");
env::set_current_dir(cwd).unwrap();
}
}