1use jrsonnet_evaluator::{2 bail,3 manifest::{escape_string_json_buf, ManifestFormat, ToStringFormat},4 Result, Val,5};67pub struct PythonFormat {8 #[cfg(feature = "exp-preserve-order")]9 preserve_order: bool,10}1112impl PythonFormat {13 pub fn std(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {14 Self {15 #[cfg(feature = "exp-preserve-order")]16 preserve_order,17 }18 }19}2021impl ManifestFormat for PythonFormat {22 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {23 match val {24 Val::Bool(true) => buf.push_str("True"),25 Val::Bool(false) => buf.push_str("False"),26 Val::Null => buf.push_str("None"),27 Val::Str(s) => escape_string_json_buf(&s.to_string(), buf),28 Val::Num(_) => ToStringFormat.manifest_buf(val, buf)?,29 #[cfg(feature = "exp-bigint")]30 Val::BigInt(_) => ToStringFormat.manifest_buf(val, buf)?,31 Val::Arr(arr) => {32 buf.push('[');33 for (i, el) in arr.iter().enumerate() {34 let el = el?;35 if i != 0 {36 buf.push_str(", ");37 }38 self.manifest_buf(el, buf)?;39 }40 buf.push(']');41 }42 Val::Obj(obj) => {43 obj.run_assertions()?;44 buf.push('{');45 let fields = obj.fields(46 #[cfg(feature = "exp-preserve-order")]47 self.preserve_order,48 );49 for (i, field) in fields.into_iter().enumerate() {50 if i != 0 {51 buf.push_str(", ");52 }53 escape_string_json_buf(&field, buf);54 buf.push_str(": ");55 let value = obj.get(field)?.expect("field exists");56 self.manifest_buf(value, buf)?;57 }58 buf.push('}');59 }60 Val::Func(_) => bail!("tried to manifest function"),61 }62 Ok(())63 }64}6566pub struct PythonVarsFormat {67 #[cfg(feature = "exp-preserve-order")]68 preserve_order: bool,69}7071impl PythonVarsFormat {72 pub fn std(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {73 Self {74 #[cfg(feature = "exp-preserve-order")]75 preserve_order,76 }77 }78}7980impl ManifestFormat for PythonVarsFormat {81 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {82 let inner = PythonFormat {83 #[cfg(feature = "exp-preserve-order")]84 preserve_order: self.preserve_order,85 };86 let Val::Obj(obj) = val else {87 bail!("python vars root should be object");88 };89 obj.run_assertions()?;9091 let fields = obj.fields(92 #[cfg(feature = "exp-preserve-order")]93 self.preserve_order,94 );9596 for field in fields {97 98 buf.push_str(&field);99 buf.push_str(" = ");100 inner.manifest_buf(obj.get(field)?.expect("field exists"), buf)?;101 buf.push('\n');102 }103 Ok(())104 }105}