Skip to content

Commit

Permalink
add --variables, -v to set list of key/value script env variables
Browse files Browse the repository at this point in the history
  • Loading branch information
couleurm authored and quietvoid committed Mar 10, 2024
1 parent e855cc9 commit 5ed0246
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ use vs_handler::PreviewedScript;
struct Opt {
#[arg(id = "input", value_hint = ValueHint::FilePath)]
input: PathBuf,

#[arg(
id = "variable",
short = 'v',
help = "Variables to set in the script environment. Example: `-v key=value`",
value_delimiter = ','
)]
variables: Vec<String>,
}

#[tokio::main(flavor = "multi_thread", worker_threads = 1)]
Expand All @@ -28,7 +36,7 @@ async fn main() -> Result<()> {
bail!("Input script file does not exist!");
}

let script = Arc::new(Mutex::new(PreviewedScript::new(opt.input)));
let script = Arc::new(Mutex::new(PreviewedScript::new(opt.input, opt.variables)));
let (cmd_sender, cmd_receiver) = tokio::sync::mpsc::channel(1);

{
Expand Down
21 changes: 20 additions & 1 deletion src/vs_handler/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use itertools::Itertools;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::path::PathBuf;
Expand All @@ -22,6 +23,7 @@ pub use vstransform::*;
pub struct PreviewedScript {
script_file: String,
script_dir: PathBuf,
variables: Vec<String>,

#[serde(skip)]
env: Option<Environment>,
Expand All @@ -45,7 +47,7 @@ pub struct VSMessage {
}

impl PreviewedScript {
pub fn new(script_path: PathBuf) -> Self {
pub fn new(script_path: PathBuf, variables: Vec<String>) -> Self {
let mut script_dir = script_path.clone();
script_dir.pop();

Expand All @@ -57,6 +59,7 @@ impl PreviewedScript {
Self {
script_file,
script_dir,
variables,
env: None,
message_handler_id: None,
vs_messages: Arc::new(Mutex::new(Vec::new())),
Expand Down Expand Up @@ -89,6 +92,22 @@ impl PreviewedScript {
self.message_handler_id = Some(id);
}

if !self.variables.is_empty() {
let mut variables = OwnedMap::new(API::get().unwrap());
let kv_map = self
.variables
.iter()
.filter_map(|s| s.split('=').collect_tuple());
for (name, value) in kv_map {
variables
.append_data(name, value.as_bytes())
.expect("Couldn't append an argument value");
}

env.set_variables(&variables)
.expect("Couldn't set arguments");
}

env.eval_file(&self.script_file, EvalFlags::SetWorkingDir)?;

Ok(())
Expand Down

0 comments on commit 5ed0246

Please sign in to comment.