Add shell extension

This commit is contained in:
Federico Terzi 2019-09-15 14:33:27 +02:00
parent b70d99c7ab
commit 7122bd37eb
3 changed files with 52 additions and 1 deletions

View File

@ -1,6 +1,7 @@
use serde_yaml::Mapping;
mod date;
mod shell;
pub trait Extension {
fn name(&self) -> String;
@ -10,5 +11,6 @@ pub trait Extension {
pub fn get_extensions() -> Vec<Box<dyn Extension>> {
vec![
Box::new(date::DateExtension::new()),
Box::new(shell::ShellExtension::new()),
]
}

49
src/extension/shell.rs Normal file
View File

@ -0,0 +1,49 @@
use serde_yaml::{Mapping, Value};
use std::process::Command;
use log::{warn, error};
pub struct ShellExtension {}
impl ShellExtension {
pub fn new() -> ShellExtension {
ShellExtension{}
}
}
impl super::Extension for ShellExtension {
fn name(&self) -> String {
String::from("shell")
}
fn calculate(&self, params: &Mapping) -> Option<String> {
let cmd = params.get(&Value::from("cmd"));
if cmd.is_none() {
warn!("No 'cmd' parameter specified for shell variable");
return None
}
let cmd = cmd.unwrap().as_str().unwrap();
let output = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(&["/C", cmd])
.output()
} else {
Command::new("sh")
.arg("-c")
.arg(cmd)
.output()
};
match output {
Ok(output) => {
let output_str = String::from_utf8_lossy(output.stdout.as_slice());
Some(output_str.into_owned())
},
Err(e) => {
error!("Could not execute cmd '{}', error: {}", cmd, e);
None
},
}
}
}

View File

@ -23,7 +23,7 @@ matches:
# Accented letters
- trigger: "e'"
replace: "è"
- trigger: "e/"
- trigger: "e//"
replace: "é"
- trigger: "a'"
replace: "à"