git.delta.rocks / jrsonnet / refs/heads / master

difftreelog

source

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