git.delta.rocks / jrsonnet / refs/commits / 062967490618

difftreelog

source

crates/jrsonnet-cli/src/ext.rs1.7 KiBsourcehistory
1use crate::ConfigureState;2use clap::Clap;3use jrsonnet_evaluator::{error::Result, EvaluationState};4use std::str::FromStr;56#[derive(Clone)]7pub struct ExtStr {8	pub name: String,9	pub value: String,10}1112impl FromStr for ExtStr {13	type Err = &'static str;14	fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {15		let out: Vec<_> = s.split('=').collect();16		match out.len() {17			1 => Ok(ExtStr {18				name: out[0].to_owned(),19				value: std::env::var(out[0]).or(Err("missing env var"))?,20			}),21			2 => Ok(ExtStr {22				name: out[0].to_owned(),23				value: out[1].to_owned(),24			}),2526			_ => Err("bad ext-str syntax"),27		}28	}29}3031#[derive(Clap)]32// #[clap(help_heading = "EXTERNAL VARIABLES")]33pub struct ExtVarOpts {34	/// Add string external variable.35	/// External variables are globally available, so prefer to use top level arguments where possible.36	/// If [=data] is not set, then it will be read from `name` env variable.37	/// Can be accessed from code via `std.extVar("name")`38	#[clap(long, short = 'V', name = "name[=var data]", number_of_values = 1)]39	ext_str: Vec<ExtStr>,40	/// Read string external variable from file.41	/// See also `--ext-str`42	// #[clap(long, name = "name[=var path]", number_of_values = 1)]43	// ext_str_file: Vec<ExtStr>,44	/// Add external variable from code.45	/// See also `--ext-str`46	#[clap(long, name = "name[=var source]", number_of_values = 1)]47	ext_code: Vec<ExtStr>,48}49impl ConfigureState for ExtVarOpts {50	fn configure(&self, state: &EvaluationState) -> Result<()> {51		for ext in self.ext_str.iter() {52			state.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());53		}54		for ext in self.ext_code.iter() {55			state.add_ext_code((&ext.name as &str).into(), (&ext.value as &str).into())?;56		}57		Ok(())58	}59}