/
external.rs
309 lines (283 loc) · 10.5 KB
/
external.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
use crate::build_info::*;
use crate::commands::plugins::{update, Install};
use crate::opts::PLUGIN_OVERRIDE_COMPATIBILITY_CHECK_FLAG;
use anyhow::{anyhow, Result};
use spin_plugins::{
badger::BadgerChecker, error::Error as PluginError, manifest::warn_unsupported_version,
PluginStore,
};
use std::{collections::HashMap, env, process};
use tokio::process::Command;
use tracing::log;
const BADGER_GRACE_PERIOD_MILLIS: u64 = 50;
fn override_flag() -> String {
format!("--{}", PLUGIN_OVERRIDE_COMPATIBILITY_CHECK_FLAG)
}
// Returns true if the argument was removed from the list
fn remove_arg(arg: &str, args: &mut Vec<String>) -> bool {
let contained = args.contains(&arg.to_owned());
args.retain(|a| a != arg);
contained
}
// Parses the subcommand to get the plugin name, args, and override compatibility check flag
fn parse_subcommand(mut cmd: Vec<String>) -> anyhow::Result<(String, Vec<String>, bool)> {
let override_compatibility_check = remove_arg(&override_flag(), &mut cmd);
let (plugin_name, args) = cmd
.split_first()
.ok_or_else(|| anyhow!("Expected subcommand"))?;
Ok((
plugin_name.into(),
args.to_vec(),
override_compatibility_check,
))
}
const PREDEFINED_EXTERNALS: &[(&str, &str)] = &[(
"cloud",
"Commands for publishing applications to the Fermyon Cloud.",
)];
pub fn predefined_externals() -> Vec<(String, String)> {
PREDEFINED_EXTERNALS
.iter()
.map(|(name, desc)| (name.to_string(), desc.to_string()))
.collect()
}
/// Executes a Spin plugin as a subprocess, expecting the first argument to
/// indicate the plugin to execute. Passes all subsequent arguments on to the
/// subprocess.
pub async fn execute_external_subcommand(
cmd: Vec<String>,
app: clap::App<'_>,
) -> anyhow::Result<()> {
let (plugin_name, args, override_compatibility_check) = parse_subcommand(cmd)?;
let plugin_store = PluginStore::try_default()?;
let plugin_version = match plugin_store.read_plugin_manifest(&plugin_name) {
Ok(manifest) => {
if let Err(e) =
warn_unsupported_version(&manifest, SPIN_VERSION, override_compatibility_check)
{
eprintln!("{e}");
// TODO: consider running the update checked?
process::exit(1);
}
Some(manifest.version().to_owned())
}
Err(PluginError::NotFound(e)) => {
if predefined_externals()
.iter()
.any(|(name, _)| name == &plugin_name)
{
println!("The `{plugin_name}` plugin is required. Installing now.");
let plugin_installer = Install {
name: Some(plugin_name.clone()),
yes_to_all: true,
local_manifest_src: None,
remote_manifest_src: None,
override_compatibility_check: false,
version: None,
};
// Automatically update plugins if the cloud plugin manifest does not exist
// TODO: remove this eventually once very unlikely to not have updated
if let Err(e) = plugin_installer.run().await {
if let Some(PluginError::NotFound(_)) = e.downcast_ref::<PluginError>() {
update().await?;
}
plugin_installer.run().await?;
}
None // No update badgering needed if we just updated/installed it!
} else {
tracing::debug!("Tried to resolve {plugin_name} to plugin, got {e}");
terminal::error!("'{plugin_name}' is not a known Spin command. See spin --help.\n");
print_similar_commands(app, &plugin_name);
process::exit(2);
}
}
Err(e) => return Err(e.into()),
};
let mut command = Command::new(plugin_store.installed_binary_path(&plugin_name));
command.args(args);
command.envs(get_env_vars_map()?);
let badger = BadgerChecker::start(&plugin_name, plugin_version, SPIN_VERSION);
log::info!("Executing command {:?}", command);
// Allow user to interact with stdio/stdout of child process
let status = command.status().await?;
log::info!("Exiting process with {}", status);
report_badger_result(badger).await;
if !status.success() {
match status.code() {
Some(code) => process::exit(code),
_ => process::exit(1),
}
}
Ok(())
}
async fn report_badger_result(badger: tokio::task::JoinHandle<BadgerChecker>) {
// The badger task should be short-running, and has likely already finished by
// the time we get here (after the plugin has completed). But we don't want
// the user to have to wait if something goes amiss and it takes a long time.
// Therefore, allow it only a short grace period before killing it.
let grace_period = tokio::time::sleep(tokio::time::Duration::from_millis(
BADGER_GRACE_PERIOD_MILLIS,
));
let badger = tokio::select! {
_ = grace_period => { return; }
b = badger => match b {
Ok(b) => b,
Err(e) => {
tracing::info!("Badger update thread error {e:#}");
return;
}
}
};
let ui = badger.check().await;
match ui {
Ok(spin_plugins::badger::BadgerUI::None) => (),
Ok(spin_plugins::badger::BadgerUI::Eligible(to)) => {
eprintln!();
terminal::einfo!(
"This plugin can be upgraded.",
"Version {to} is available and compatible."
);
eprintln!("To upgrade, run `{}`.", to.upgrade_command());
}
Ok(spin_plugins::badger::BadgerUI::Questionable(to)) => {
eprintln!();
terminal::einfo!("This plugin can be upgraded.", "Version {to} is available,");
eprintln!("but may not be backward compatible with your current plugin.");
eprintln!("To upgrade, run `{}`.", to.upgrade_command());
}
Ok(spin_plugins::badger::BadgerUI::Both {
eligible,
questionable,
}) => {
eprintln!();
terminal::einfo!(
"This plugin can be upgraded.",
"Version {eligible} is available and compatible."
);
eprintln!("Version {questionable} is also available, but may not be backward compatible with your current plugin.");
eprintln!("To upgrade, run `{}`.", eligible.upgrade_command());
}
Err(e) => {
tracing::info!("Error running update badger: {e:#}");
}
}
}
fn print_similar_commands(app: clap::App, plugin_name: &str) {
let similar = similar_commands(app, plugin_name);
match similar.len() {
0 => (),
1 => eprintln!("The most similar command is:"),
_ => eprintln!("The most similar commands are:"),
}
for cmd in &similar {
eprintln!(" {cmd}");
}
if !similar.is_empty() {
eprintln!();
}
}
fn similar_commands(app: clap::App, target: &str) -> Vec<String> {
app.get_subcommands()
.filter_map(|sc| {
let actual_name = undecorate(sc.get_name());
if levenshtein::levenshtein(&actual_name, target) <= 2 {
Some(actual_name)
} else {
None
}
})
.collect()
}
fn undecorate(decorated_name: &str) -> String {
match decorated_name.strip_suffix('*') {
Some(name) => name.to_owned(),
None => decorated_name.to_owned(),
}
}
fn get_env_vars_map() -> Result<HashMap<String, String>> {
let map: HashMap<String, String> = vec![
("SPIN_VERSION", SPIN_VERSION),
("SPIN_VERSION_MAJOR", SPIN_VERSION_MAJOR),
("SPIN_VERSION_MINOR", SPIN_VERSION_MINOR),
("SPIN_VERSION_PATCH", SPIN_VERSION_PATCH),
("SPIN_VERSION_PRE", SPIN_VERSION_PRE),
("SPIN_COMMIT_SHA", SPIN_COMMIT_SHA),
("SPIN_COMMIT_DATE", SPIN_COMMIT_DATE),
("SPIN_BRANCH", SPIN_BRANCH),
("SPIN_BUILD_DATE", SPIN_BUILD_DATE),
("SPIN_TARGET_TRIPLE", SPIN_TARGET_TRIPLE),
("SPIN_DEBUG", SPIN_DEBUG),
(
"SPIN_BIN_PATH",
env::current_exe()?
.to_str()
.ok_or_else(|| anyhow!("Could not convert binary path to string"))?,
),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
Ok(map)
}
#[cfg(test)]
mod test {
use super::{override_flag, parse_subcommand};
#[test]
fn test_remove_arg() {
let override_flag = override_flag();
let plugin_name = "example";
let cmd = vec![plugin_name.to_string()];
assert_eq!(
parse_subcommand(cmd).unwrap(),
(plugin_name.to_string(), vec![], false)
);
let cmd_with_args = "example arg1 arg2"
.split(' ')
.map(|s| s.to_string())
.collect::<Vec<String>>();
assert_eq!(
parse_subcommand(cmd_with_args).unwrap(),
(
plugin_name.to_string(),
vec!["arg1".to_string(), "arg2".to_string()],
false
)
);
let cmd_with_args_override = format!("example arg1 arg2 {}", override_flag)
.split(' ')
.map(|s| s.to_string())
.collect::<Vec<String>>();
assert_eq!(
parse_subcommand(cmd_with_args_override).unwrap(),
(
plugin_name.to_string(),
vec!["arg1".to_string(), "arg2".to_string()],
true
)
);
let cmd_with_args_override = format!("example {} arg1 arg2", override_flag)
.split(' ')
.map(|s| s.to_string())
.collect::<Vec<String>>();
assert_eq!(
parse_subcommand(cmd_with_args_override).unwrap(),
(
plugin_name.to_string(),
vec!["arg1".to_string(), "arg2".to_string()],
true
)
);
let cmd_with_args_override = format!("{} example arg1 arg2", override_flag)
.split(' ')
.map(|s| s.to_string())
.collect::<Vec<String>>();
assert_eq!(
parse_subcommand(cmd_with_args_override).unwrap(),
(
plugin_name.to_string(),
vec!["arg1".to_string(), "arg2".to_string()],
true
)
);
}
}