1use std::{fs::read_to_string, str::FromStr};23use clap::Parser;4use jrsonnet_evaluator::{error::Result, 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 64 65 #[clap(long)]66 no_stdlib: bool,67 68 69 70 71 72 #[clap(73 long,74 short = 'V',75 name = "name[=var data]",76 number_of_values = 1,77 multiple_occurrences = true78 )]79 ext_str: Vec<ExtStr>,80 81 82 #[clap(83 long,84 name = "name=var path",85 number_of_values = 1,86 multiple_occurrences = true87 )]88 ext_str_file: Vec<ExtFile>,89 90 91 #[clap(92 long,93 name = "name[=var source]",94 number_of_values = 1,95 multiple_occurrences = true96 )]97 ext_code: Vec<ExtStr>,98 99 100 #[clap(101 long,102 name = "name=var code path",103 number_of_values = 1,104 multiple_occurrences = true105 )]106 ext_code_file: Vec<ExtFile>,107}108impl ConfigureState for StdOpts {109 fn configure(&self, s: &State) -> Result<()> {110 if self.no_stdlib {111 return Ok(());112 }113 let ctx = jrsonnet_stdlib::ContextInitializer::new(s.clone());114 for ext in self.ext_str.iter() {115 ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());116 }117 for ext in self.ext_str_file.iter() {118 ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());119 }120 for ext in self.ext_code.iter() {121 ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;122 }123 for ext in self.ext_code_file.iter() {124 ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;125 }126 s.settings_mut().context_initializer = Box::new(ctx);127 Ok(())128 }129}