1use std::{fs::read_to_string, str::FromStr};23use clap::Parser;4use jrsonnet_evaluator::{error::Result, trace::PathResolver, State};5use jrsonnet_stdlib::ContextInitializer;67#[derive(Clone)]8pub struct ExtStr {9 pub name: String,10 pub value: String,11}1213impl FromStr for ExtStr {14 type Err = &'static str;15 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {16 match s.find('=') {17 Some(idx) => Ok(ExtStr {18 name: s[..idx].to_owned(),19 value: s[idx + 1..].to_owned(),20 }),21 None => Ok(ExtStr {22 name: s.to_owned(),23 value: std::env::var(s).or(Err("missing env var"))?,24 }),25 }26 }27}2829#[derive(Clone)]30pub struct ExtFile {31 pub name: String,32 pub value: String,33}3435impl FromStr for ExtFile {36 type Err = String;3738 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {39 let out: Vec<&str> = s.split('=').collect();40 if out.len() != 2 {41 return Err("bad ext-file syntax".to_owned());42 }43 let file = read_to_string(out[1]);44 match file {45 Ok(content) => Ok(Self {46 name: out[0].into(),47 value: content,48 }),49 Err(e) => Err(format!("{e}")),50 }51 }52}5354#[derive(Parser)]55#[clap(next_help_heading = "STANDARD LIBRARY")]56pub struct StdOpts {57 58 59 #[clap(long)]60 no_stdlib: bool,61 62 63 64 65 66 #[clap(long, short = 'V', name = "name[=var data]", number_of_values = 1)]67 ext_str: Vec<ExtStr>,68 69 70 #[clap(long, name = "name=var path", number_of_values = 1)]71 ext_str_file: Vec<ExtFile>,72 73 74 #[clap(long, name = "name[=var source]", number_of_values = 1)]75 ext_code: Vec<ExtStr>,76 77 78 #[clap(long, name = "name=var code path", number_of_values = 1)]79 ext_code_file: Vec<ExtFile>,80}81impl StdOpts {82 pub fn context_initializer(&self, s: &State) -> Result<Option<ContextInitializer>> {83 if self.no_stdlib {84 return Ok(None);85 }86 let ctx = ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback());87 for ext in self.ext_str.iter() {88 ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());89 }90 for ext in self.ext_str_file.iter() {91 ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());92 }93 for ext in self.ext_code.iter() {94 ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;95 }96 for ext in self.ext_code_file.iter() {97 ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;98 }99 Ok(Some(ctx))100 }101}