-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathruntime.rs
More file actions
524 lines (475 loc) · 17.7 KB
/
runtime.rs
File metadata and controls
524 lines (475 loc) · 17.7 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
use std::collections::BTreeMap;
use camino::Utf8PathBuf;
use lazy_regex::{lazy_regex, Lazy};
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::runtime::CommandLine;
use super::{Function, Page};
static ARG_VALUE_PARSER: Lazy<Regex> = lazy_regex!(r"(?m)\$\{\s*([\w\.]+)(\s+or\s+([^}]+))?\}");
const ARG_EXPRESSION_ERROR: &str =
"argument expression must be in the form of ${name} or ${name or default_value}";
#[allow(dead_code)]
pub enum ExecutionFlavor {
Shell(String),
Sudo,
Docker(String),
Error(String),
}
impl ExecutionFlavor {
pub fn shell(shell: String) -> Self {
ExecutionFlavor::Shell(shell)
}
pub fn sudo() -> Self {
ExecutionFlavor::Sudo
}
pub fn docker(image: String) -> Self {
ExecutionFlavor::Docker(image)
}
pub fn error(message: String) -> Self {
ExecutionFlavor::Error(message)
}
fn get_current_shell() -> String {
let shell_name = std::env::var("SHELL")
.map(|s| s.split('/').last().unwrap_or("unknown").to_string())
.unwrap_or_else(|_| "unknown".to_string());
if let Ok(shell_path) = which::which(shell_name.clone()) {
shell_path.to_string_lossy().to_string()
} else {
shell_name
}
}
pub fn for_function(function: &Function) -> anyhow::Result<ExecutionFlavor> {
let mut has_container = false;
if let Some(container) = function.container.as_ref() {
has_container = true;
if container.force {
return Ok(ExecutionFlavor::docker(
container.source.image().to_string(),
));
}
}
match function.execution.get_command_line() {
Ok(raw_parts) => {
let cmdline = CommandLine::from_vec(&raw_parts)?;
if cmdline.sudo {
return Ok(if has_container {
ExecutionFlavor::docker(
function
.container
.as_ref()
.unwrap()
.source
.image()
.to_string(),
)
} else {
ExecutionFlavor::sudo()
});
} else if !cmdline.app_in_path {
return Ok(if has_container {
ExecutionFlavor::docker(
function
.container
.as_ref()
.unwrap()
.source
.image()
.to_string(),
)
} else {
ExecutionFlavor::error("app not in $PATH".to_string())
});
} else {
return Ok(ExecutionFlavor::shell(Self::get_current_shell()));
}
}
Err(e) => Err(e),
}
}
}
impl std::fmt::Display for ExecutionFlavor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::Shell(shell) => shell.to_string(),
Self::Sudo => "sudo".to_string(),
Self::Docker(image) => format!("docker {}", image),
Self::Error(message) => message.to_string(),
};
write!(f, "{}", s)
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum ExecutionContext {
#[serde(rename = "cmdline")]
CommandLine(Vec<String>),
#[serde(rename = "platforms")]
PlatformSpecific(BTreeMap<String, Vec<String>>),
}
impl ExecutionContext {
pub fn get_command_line(&self) -> anyhow::Result<Vec<String>> {
match self {
Self::CommandLine(cmdline) => Ok(cmdline.clone()),
Self::PlatformSpecific(platforms) => {
if let Some(cmdline) = platforms.get(std::env::consts::OS) {
Ok(cmdline.clone())
} else {
Err(anyhow::anyhow!(
"no command line for platform {}",
std::env::consts::OS
))
}
}
}
}
}
#[allow(dead_code)] // we might need path and page in the future
#[derive(Debug)]
pub struct FunctionRef<'a> {
pub name: String,
pub path: &'a Utf8PathBuf,
pub page: &'a Page,
pub function: &'a Function,
}
impl<'a> FunctionRef<'a> {
pub fn validate_arguments(
&self,
provided_arguments: &BTreeMap<String, String>,
) -> anyhow::Result<()> {
// check for missing required arguments
for (arg_name, param) in &self.function.parameters {
if param.required && !provided_arguments.contains_key(arg_name) {
return Err(anyhow::anyhow!(
"missing required argument {} for function {}",
arg_name,
&self.name
));
}
}
// check for extra arguments
for arg_name in provided_arguments.keys() {
if !self.function.parameters.contains_key(arg_name) {
return Err(anyhow::anyhow!(
"unknown argument {} for function {}",
arg_name,
&self.name
));
}
}
Ok(())
}
pub fn resolve_command_line(
&self,
arguments: &BTreeMap<String, String>,
) -> anyhow::Result<CommandLine> {
// determine the command line to execute
let command_line = self.function.execution.get_command_line()?;
let mut env = BTreeMap::new();
// interpolate the arguments
let command_line = {
let mut interpolated = Vec::new();
for arg in command_line {
if ARG_VALUE_PARSER.is_match(&arg) {
// Process args with placeholders by replacing only the matched patterns
let mut processed_arg = arg.clone();
// Find all matches and collect the replacements
let mut replacements = Vec::new();
for caps in ARG_VALUE_PARSER.captures_iter(&arg) {
let full_match = caps.get(0).unwrap().as_str();
let var_name = caps.get(1).ok_or(ARG_EXPRESSION_ERROR).map_err(| e| anyhow!(e))?.as_str();
let var_default = caps.get(3).map(|m| m.as_str());
let replacement = if var_name.starts_with("env.") || var_name. starts_with("ENV.") {
let env_var_name = var_name.replace("env.", "").replace ("ENV.", "");
let env_var = std::env::var(&env_var_name);
let env_var_value = if let Ok(value) = env_var {
value
} else if let Some(def) = var_default {
def.to_string()
} else {
return Err(anyhow::anyhow!(
"environment variable {} not set",
env_var_name
));
};
// add the environment variable to the command line for later use
env.insert(env_var_name, env_var_value.to_owned());
env_var_value
} else if let Some(value) = arguments.get(var_name) {
if value.is_empty() {
if let Some(def) = var_default {
def.to_string()
} else {
value.to_string()
}
} else {
value.to_string()
}
} else if let Some(default_value) = var_default {
default_value.to_string()
} else {
return Err(anyhow::anyhow!("argument {} not provided", var_name));
};
replacements.push((full_match, replacement));
}
// Apply all replacements to the arg string
for (pattern, replacement) in replacements {
processed_arg = processed_arg.replace(pattern, &replacement);
}
interpolated.push(processed_arg);
} else {
// For args without placeholders, use as-is
interpolated.push(arg);
}
}
interpolated
};
// final parsing
CommandLine::from_vec_with_env(&command_line, env)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn test_resolve_command_line_with_valid_arguments() {
let function = Function {
execution: ExecutionContext::CommandLine(vec![
"echo".to_string(),
"${message}".to_string(),
]),
description: "".to_string(),
parameters: BTreeMap::new(),
container: None,
};
let resolver = FunctionRef {
function: &function,
name: "test_function".to_string(),
path: &Utf8PathBuf::from("test/path"),
page: &Page {
name: "test_page".to_string(),
description: None,
categories: Vec::new(),
functions: BTreeMap::new(),
},
};
let mut arguments = BTreeMap::new();
arguments.insert("message".to_string(), "Hello, World!".to_string());
let result = resolver.resolve_command_line(&arguments);
assert!(result.is_ok());
let command_line = result.unwrap();
assert!(command_line.app.ends_with("/echo"));
assert_eq!(command_line.args, vec!["Hello, World!"]);
}
#[test]
fn test_resolve_command_line_with_default_value() {
let function = Function {
execution: ExecutionContext::CommandLine(vec![
"echo".to_string(),
"${message or Default message}".to_string(),
]),
description: "".to_string(),
parameters: BTreeMap::new(),
container: None,
};
let resolver = FunctionRef {
function: &function,
name: "test_function".to_string(),
path: &Utf8PathBuf::from("test/path"),
page: &Page {
name: "test_page".to_string(),
description: None,
categories: Vec::new(),
functions: BTreeMap::new(),
},
};
let arguments = BTreeMap::new();
let result = resolver.resolve_command_line(&arguments);
assert!(result.is_ok());
let command_line = result.unwrap();
assert!(command_line.app.ends_with("/echo"));
assert_eq!(command_line.args, vec!["Default message"]);
}
#[test]
fn test_resolve_command_line_with_empty_value_and_default() {
let function = Function {
execution: ExecutionContext::CommandLine(vec![
"echo".to_string(),
"${message or Default message}".to_string(),
]),
description: "".to_string(),
parameters: BTreeMap::new(),
container: None,
};
let resolver = FunctionRef {
function: &function,
name: "test_function".to_string(),
path: &Utf8PathBuf::from("test/path"),
page: &Page {
name: "test_page".to_string(),
description: None,
categories: Vec::new(),
functions: BTreeMap::new(),
},
};
let mut arguments = BTreeMap::new();
arguments.insert("message".to_string(), "".to_string());
let result = resolver.resolve_command_line(&arguments);
assert!(result.is_ok());
let command_line = result.unwrap();
assert!(command_line.app.ends_with("/echo"));
assert_eq!(command_line.args, vec!["Default message"]);
}
#[test]
fn test_resolve_command_line_with_missing_required_argument() {
let function = Function {
execution: ExecutionContext::CommandLine(vec![
"echo".to_string(),
"${required_arg}".to_string(),
]),
description: "".to_string(),
parameters: BTreeMap::new(),
container: None,
};
let resolver = FunctionRef {
function: &function,
name: "test_function".to_string(),
path: &Utf8PathBuf::from("test/path"),
page: &Page {
name: "test_page".to_string(),
description: None,
categories: Vec::new(),
functions: BTreeMap::new(),
},
};
let arguments = BTreeMap::new();
let result = resolver.resolve_command_line(&arguments);
assert!(result.is_err());
assert_eq!(
result.unwrap_err().to_string(),
"argument required_arg not provided"
);
}
#[test]
fn test_resolve_command_line_with_multiple_arguments() {
let function = Function {
execution: ExecutionContext::CommandLine(vec![
"echo".to_string(),
"${arg1}".to_string(),
"${arg2 or default}".to_string(),
"literal".to_string(),
]),
description: "".to_string(),
parameters: BTreeMap::new(),
container: None,
};
let resolver = FunctionRef {
function: &function,
name: "test_function".to_string(),
path: &Utf8PathBuf::from("test/path"),
page: &Page {
name: "test_page".to_string(),
description: None,
categories: Vec::new(),
functions: BTreeMap::new(),
},
};
let mut arguments = BTreeMap::new();
arguments.insert("arg1".to_string(), "value1".to_string());
let result = resolver.resolve_command_line(&arguments);
assert!(result.is_ok());
let command_line = result.unwrap();
assert!(command_line.app.ends_with("/echo"));
assert_eq!(command_line.args, vec!["value1", "default", "literal"]);
}
#[test]
fn test_resolve_command_line_with_env_variables() {
std::env::set_var("TEST_VAR", "test_value");
let function = Function {
execution: ExecutionContext::CommandLine(vec![
"echo".to_string(),
"${env.TEST_VAR}".to_string(),
"${ENV.TEST_VAR}".to_string(),
]),
description: "".to_string(),
parameters: BTreeMap::new(),
container: None,
};
let resolver = FunctionRef {
function: &function,
name: "test_function".to_string(),
path: &Utf8PathBuf::from("test/path"),
page: &Page {
name: "test_page".to_string(),
description: None,
categories: Vec::new(),
functions: BTreeMap::new(),
},
};
let arguments = BTreeMap::new();
let result = resolver.resolve_command_line(&arguments);
assert!(result.is_ok());
let command_line = result.unwrap();
assert!(command_line.app.ends_with("/echo"));
assert_eq!(command_line.args, vec!["test_value", "test_value"]);
std::env::remove_var("TEST_VAR");
}
#[test]
fn test_resolve_command_line_with_undefined_env_variable() {
let function = Function {
execution: ExecutionContext::CommandLine(vec![
"echo".to_string(),
"${env.UNDEFINED_VAR}".to_string(),
]),
description: "".to_string(),
parameters: BTreeMap::new(),
container: None,
};
let resolver = FunctionRef {
function: &function,
name: "test_function".to_string(),
path: &Utf8PathBuf::from("test/path"),
page: &Page {
name: "test_page".to_string(),
description: None,
categories: Vec::new(),
functions: BTreeMap::new(),
},
};
let arguments = BTreeMap::new();
let result = resolver.resolve_command_line(&arguments);
assert!(result.is_err());
assert_eq!(
result.unwrap_err().to_string(),
"environment variable UNDEFINED_VAR not set"
);
}
#[test]
fn test_resolve_command_line_with_undefined_env_variable_with_default() {
let function = Function {
execution: ExecutionContext::CommandLine(vec![
"echo".to_string(),
"${env.UNDEFINED_VAR or default_value}".to_string(),
]),
description: "".to_string(),
parameters: BTreeMap::new(),
container: None,
};
let resolver = FunctionRef {
function: &function,
name: "test_function".to_string(),
path: &Utf8PathBuf::from("test/path"),
page: &Page {
name: "test_page".to_string(),
description: None,
categories: Vec::new(),
functions: BTreeMap::new(),
},
};
let arguments = BTreeMap::new();
let result = resolver.resolve_command_line(&arguments);
assert!(result.is_ok());
let command_line = result.unwrap();
assert!(command_line.app.ends_with("/echo"));
assert_eq!(command_line.args, vec!["default_value"]);
}
}