1use std::{fs::read_to_string, str::FromStr};23use clap::Parser;4use jrsonnet_evaluator::{error::Result, tb, trace::PathResolver, State};56use crate::ConfigureState;78#[derive(Clone)]9pub struct ExtStr {10 pub name: String,11 pub value: String,12}1314impl FromStr for ExtStr {15 type Err = &'static str;16 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {17 let out: Vec<_> = s.split('=').collect();18 match out.len() {19 1 => Ok(ExtStr {20 name: out[0].to_owned(),21 value: std::env::var(out[0]).or(Err("missing env var"))?,22 }),23 2 => Ok(ExtStr {24 name: out[0].to_owned(),25 value: out[1].to_owned(),26 }),2728 _ => Err("bad ext-str syntax"),29 }30 }31}3233#[derive(Clone)]34pub struct ExtFile {35 pub name: String,36 pub value: String,37}3839impl FromStr for ExtFile {40 type Err = String;4142 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {43 let out: Vec<&str> = s.split('=').collect();44 if out.len() != 2 {45 return Err("bad ext-file syntax".to_owned());46 }47 let file = read_to_string(out[1]);48 match file {49 Ok(content) => Ok(Self {50 name: out[0].into(),51 value: content,52 }),53 Err(e) => Err(format!("{}", e)),54 }55 }56}5758#[derive(Parser)]59#[clap(next_help_heading = "STANDARD LIBRARY")]60pub struct StdOpts {61 62 63 #[clap(long)]64 no_stdlib: bool,65 66 67 68 69 70 #[clap(long, short = 'V', name = "name[=var data]", number_of_values = 1)]71 ext_str: Vec<ExtStr>,72 73 74 #[clap(long, name = "name=var path", number_of_values = 1)]75 ext_str_file: Vec<ExtFile>,76 77 78 #[clap(long, name = "name[=var source]", number_of_values = 1)]79 ext_code: Vec<ExtStr>,80 81 82 #[clap(long, name = "name=var code path", number_of_values = 1)]83 ext_code_file: Vec<ExtFile>,84}85impl ConfigureState for StdOpts {86 type Guards = ();87 fn configure(&self, s: &State) -> Result<()> {88 if self.no_stdlib {89 return Ok(());90 }91 let ctx =92 jrsonnet_stdlib::ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback());93 for ext in self.ext_str.iter() {94 ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());95 }96 for ext in self.ext_str_file.iter() {97 ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());98 }99 for ext in self.ext_code.iter() {100 ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;101 }102 for ext in self.ext_code_file.iter() {103 ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;104 }105 s.settings_mut().context_initializer = tb!(ctx);106 Ok(())107 }108}