git.delta.rocks / jrsonnet / refs/commits / 78be61658f34

difftreelog

refactor remove ManifestFormat from state

Yaroslav Bolyukin2022-11-09parent: #5f620e2.patch.diff
in: master

7 files changed

modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -93,7 +93,7 @@
 enum Error {
 	// Handled differently
 	#[error("evaluation error")]
-	Evaluation(jrsonnet_evaluator::error::LocError),
+	Evaluation(LocError),
 	#[error("io error")]
 	Io(#[from] std::io::Error),
 	#[error("input is not utf8 encoded")]
@@ -106,6 +106,11 @@
 		Self::Evaluation(e)
 	}
 }
+impl From<jrsonnet_evaluator::error::Error> for Error {
+	fn from(e: jrsonnet_evaluator::error::Error) -> Self {
+		Self::from(LocError::from(e))
+	}
+}
 
 fn main_catch(opts: Opts) -> bool {
 	let s = State::default();
@@ -144,9 +149,17 @@
 			dir.pop();
 			create_dir_all(dir)?;
 		}
-		for (file, data) in s.manifest_multi(val)?.iter() {
+		let Val::Obj(obj) = val else {
+			throw!("value should be object for --multi manifest, got {}", val.value_type())
+		};
+		for (field, data) in obj.iter(
+			#[cfg(feature = "exp-preserve-order")]
+			opts.manifest.preserve_order,
+		) {
+			let data = data.with_description(|| format!("getting field {field} for manifest"))?;
+
 			let mut path = multi.clone();
-			path.push(file as &str);
+			path.push(&field as &str);
 			if opts.output.create_output_dirs {
 				let mut dir = path.clone();
 				dir.pop();
@@ -154,7 +167,12 @@
 			}
 			println!("{}", path.to_str().expect("path"));
 			let mut file = File::create(path)?;
-			writeln!(file, "{}", data)?;
+			writeln!(
+				file,
+				"{}",
+				data.manifest(&manifest_format)
+					.with_description(|| format!("manifesting {field}"))?
+			)?;
 		}
 	} else if let Some(path) = opts.output.output_file {
 		if opts.output.create_output_dirs {
@@ -163,9 +181,9 @@
 			create_dir_all(dir)?;
 		}
 		let mut file = File::create(path)?;
-		writeln!(file, "{}", s.manifest(val)?)?;
+		writeln!(file, "{}", val.manifest(manifest_format)?)?;
 	} else {
-		let output = s.manifest(val)?;
+		let output = val.manifest(manifest_format)?;
 		if !output.is_empty() {
 			println!("{}", output);
 		}
modifiedcrates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -1,7 +1,11 @@
 use std::{path::PathBuf, str::FromStr};
 
 use clap::{Parser, ValueEnum};
-use jrsonnet_evaluator::{error::Result, ManifestFormat, State};
+use jrsonnet_evaluator::{
+	error::Result,
+	stdlib::manifest::{JsonFormat, StringFormat, ToStringFormat, YamlFormat, YamlStreamFormat},
+	ManifestFormat, State,
+};
 
 use crate::ConfigureState;
 
@@ -36,7 +40,7 @@
 	#[clap(long, short = 'S', conflicts_with = "format")]
 	string: bool,
 	/// Write output as YAML stream, can be used with --format json/yaml
-	#[clap(long, short = 'y')]
+	#[clap(long, short = 'y', conflicts_with = "string")]
 	yaml_stream: bool,
 	/// Number of spaces to pad output manifest with.
 	/// `0` for hard tabs, `-1` for single line output [default: 3 for json, 2 for yaml]
@@ -45,34 +49,35 @@
 	/// Preserve order in object manifestification
 	#[cfg(feature = "exp-preserve-order")]
 	#[clap(long)]
-	exp_preserve_order: bool,
+	preserve_order: bool,
 }
 impl ConfigureState for ManifestOpts {
-	type Guards = ();
-	fn configure(&self, s: &State) -> Result<()> {
-		if self.string {
-			s.set_manifest_format(ManifestFormat::String);
+	type Guards = Box<dyn ManifestFormat>;
+	fn configure(&self, _s: &State) -> Result<Self::Guards> {
+		let format: Box<dyn ManifestFormat> = if self.string {
+			Box::new(StringFormat)
 		} else {
 			#[cfg(feature = "exp-preserve-order")]
-			let preserve_order = self.exp_preserve_order;
+			let preserve_order = self.preserve_order;
 			match self.format {
-				ManifestFormatName::String => s.set_manifest_format(ManifestFormat::String),
-				ManifestFormatName::Json => s.set_manifest_format(ManifestFormat::Json {
-					padding: self.line_padding.unwrap_or(3),
+				ManifestFormatName::String => Box::new(ToStringFormat),
+				ManifestFormatName::Json => Box::new(JsonFormat::cli(
+					self.line_padding.unwrap_or(3),
 					#[cfg(feature = "exp-preserve-order")]
 					preserve_order,
-				}),
-				ManifestFormatName::Yaml => s.set_manifest_format(ManifestFormat::Yaml {
-					padding: self.line_padding.unwrap_or(2),
+				)),
+				ManifestFormatName::Yaml => Box::new(YamlFormat::cli(
+					self.line_padding.unwrap_or(2),
 					#[cfg(feature = "exp-preserve-order")]
 					preserve_order,
-				}),
+				)),
 			}
-		}
-		if self.yaml_stream {
-			s.set_manifest_format(ManifestFormat::YamlStream(Box::new(s.manifest_format())))
-		}
-		Ok(())
+		};
+		Ok(if self.yaml_stream {
+			Box::new(YamlStreamFormat(format))
+		} else {
+			format
+		})
 	}
 }
 
modifiedcrates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -60,8 +60,6 @@
 pub struct StdOpts {
 	/// Disable standard library.
 	/// By default standard library will be available via global `std` variable.
-	/// Note that standard library will still be loaded
-	/// if chosen manifestification method is not `none`.
 	#[clap(long)]
 	no_stdlib: bool,
 	/// Add string external variable.
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -149,10 +149,6 @@
 	pub context_initializer: TraceBox<dyn ContextInitializer>,
 	/// Used to resolve file locations/contents
 	pub import_resolver: TraceBox<dyn ImportResolver>,
-	/// Used in manifestification functions
-	pub manifest_format: ManifestFormat,
-	/// Used for bindings
-	pub trace_format: TraceBox<dyn TraceFormat>,
 }
 impl Default for EvaluationSettings {
 	fn default() -> Self {
@@ -447,26 +443,5 @@
 	}
 	pub fn context_initializer(&self) -> Ref<'_, dyn ContextInitializer> {
 		Ref::map(self.settings(), |s| &*s.context_initializer)
-	}
-
-	pub fn manifest_format(&self) -> ManifestFormat {
-		self.settings().manifest_format.clone()
-	}
-	pub fn set_manifest_format(&self, format: ManifestFormat) {
-		self.settings_mut().manifest_format = format;
-	}
-
-	pub fn trace_format(&self) -> Ref<'_, dyn TraceFormat> {
-		Ref::map(self.settings(), |s| &*s.trace_format)
-	}
-	pub fn set_trace_format(&self, format: impl TraceFormat) {
-		self.settings_mut().trace_format = tb!(format);
-	}
-
-	pub fn max_trace(&self) -> usize {
-		self.settings().max_trace
-	}
-	pub fn set_max_trace(&self, trace: usize) {
-		self.settings_mut().max_trace = trace;
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -1,6 +1,8 @@
+use std::{borrow::Cow, fmt::Write};
+
 use crate::{
 	error::{Error::*, Result},
-	throw, State, Val,
+	throw, ManifestFormat, State, Val,
 };
 
 #[derive(PartialEq, Eq, Clone, Copy)]
@@ -16,16 +18,88 @@
 	Minify,
 }
 
-pub struct ManifestJsonOptions<'s> {
-	pub padding: &'s str,
-	pub mtype: ManifestType,
-	pub newline: &'s str,
-	pub key_val_sep: &'s str,
+pub struct JsonFormat<'s> {
+	padding: Cow<'s, str>,
+	mtype: ManifestType,
+	newline: &'s str,
+	key_val_sep: &'s str,
 	#[cfg(feature = "exp-preserve-order")]
-	pub preserve_order: bool,
+	preserve_order: bool,
 }
 
-pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {
+impl<'s> JsonFormat<'s> {
+	// Minifying format
+	pub fn minify(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {
+		Self {
+			padding: Cow::Borrowed(""),
+			mtype: ManifestType::Minify,
+			newline: "\n",
+			key_val_sep: ":",
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order,
+		}
+	}
+	// Same format as std.toString
+	pub fn std_to_string() -> Self {
+		Self {
+			padding: Cow::Borrowed(""),
+			mtype: ManifestType::ToString,
+			newline: "\n",
+			key_val_sep: ": ",
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order: false,
+		}
+	}
+	pub fn std_to_json(
+		padding: String,
+		newline: &'s str,
+		key_val_sep: &'s str,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> Self {
+		Self {
+			padding: Cow::Owned(padding),
+			mtype: ManifestType::Std,
+			newline,
+			key_val_sep,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order,
+		}
+	}
+	// Same format as CLI manifestification
+	pub fn cli(
+		padding: usize,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> Self {
+		if padding == 0 {
+			return Self::minify(
+				#[cfg(feature = "exp-preserve-order")]
+				preserve_order,
+			);
+		}
+		Self {
+			padding: Cow::Owned(" ".repeat(padding)),
+			mtype: ManifestType::Manifest,
+			newline: "\n",
+			key_val_sep: ": ",
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order,
+		}
+	}
+}
+impl Default for JsonFormat<'static> {
+	fn default() -> Self {
+		Self {
+			padding: Cow::Borrowed("    "),
+			mtype: ManifestType::Manifest,
+			newline: "\n",
+			key_val_sep: ": ",
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order: false,
+		}
+	}
+}
+
+pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {
 	let mut out = String::new();
 	manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;
 	Ok(out)
@@ -34,9 +108,8 @@
 	val: &Val,
 	buf: &mut String,
 	cur_padding: &mut String,
-	options: &ManifestJsonOptions<'_>,
+	options: &JsonFormat<'_>,
 ) -> Result<()> {
-	use std::fmt::Write;
 	let mtype = options.mtype;
 	match val {
 		Val::Bool(v) => {
@@ -57,7 +130,7 @@
 				}
 
 				let old_len = cur_padding.len();
-				cur_padding.push_str(options.padding);
+				cur_padding.push_str(&options.padding);
 				for (i, item) in items.iter().enumerate() {
 					if i != 0 {
 						buf.push(',');
@@ -97,7 +170,7 @@
 				}
 
 				let old_len = cur_padding.len();
-				cur_padding.push_str(options.padding);
+				cur_padding.push_str(&options.padding);
 				for (i, field) in fields.into_iter().enumerate() {
 					if i != 0 {
 						buf.push(',');
@@ -138,6 +211,48 @@
 	Ok(())
 }
 
+impl ManifestFormat for JsonFormat<'_> {
+	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
+		manifest_json_ex_buf(&val, buf, &mut String::new(), &self)
+	}
+}
+
+pub struct ToStringFormat;
+impl ManifestFormat for ToStringFormat {
+	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
+		JsonFormat::std_to_string().manifest_buf(val, out)
+	}
+}
+pub struct StringFormat;
+impl ManifestFormat for StringFormat {
+	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
+		let Val::Str(s) = val else {
+			throw!("output should be string for string manifest format, got {}", val.value_type())
+		};
+		out.write_str(&s).unwrap();
+		Ok(())
+	}
+}
+
+pub struct YamlStreamFormat<I>(pub I);
+impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {
+	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
+		let Val::Arr(arr) = val else {
+			throw!("output should be array for yaml stream format, got {}", val.value_type())
+		};
+		if !arr.is_empty() {
+			for v in arr.iter() {
+				let v = v?;
+				out.push_str("---\n");
+				self.0.manifest_buf(v, out)?;
+				out.push('\n');
+			}
+			out.push_str("...");
+		}
+		Ok(())
+	}
+}
+
 pub fn escape_string_json(s: &str) -> String {
 	let mut buf = String::new();
 	escape_string_json_buf(s, &mut buf);
@@ -145,7 +260,6 @@
 }
 
 fn escape_string_json_buf(s: &str, buf: &mut String) {
-	use std::fmt::Write;
 	buf.push('"');
 	for c in s.chars() {
 		match c {
@@ -165,33 +279,66 @@
 	buf.push('"');
 }
 
-pub struct ManifestYamlOptions<'s> {
+pub struct YamlFormat<'s> {
 	/// Padding before fields, i.e
 	/// ```yaml
 	/// a:
 	///   b:
 	/// ## <- this
 	/// ```
-	pub padding: &'s str,
+	padding: Cow<'s, str>,
 	/// Padding before array elements in objects
 	/// ```yaml
 	/// a:
 	///   - 1
 	/// ## <- this
 	/// ```
-	pub arr_element_padding: &'s str,
+	arr_element_padding: Cow<'s, str>,
 	/// Should yaml keys appear unescaped, when possible
 	/// ```yaml
 	/// "safe_key": 1
 	/// # vs
 	/// safe_key: 1
 	/// ```
-	pub quote_keys: bool,
+	quote_keys: bool,
 	/// If true - then order of fields is preserved as written,
 	/// instead of sorting alphabetically
 	#[cfg(feature = "exp-preserve-order")]
-	pub preserve_order: bool,
+	preserve_order: bool,
 }
+impl YamlFormat<'_> {
+	pub fn cli(
+		padding: usize,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> Self {
+		let padding = " ".repeat(padding);
+		Self {
+			padding: Cow::Owned(padding.clone()),
+			arr_element_padding: Cow::Owned(padding),
+			quote_keys: false,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order,
+		}
+	}
+	pub fn std_to_yaml(
+		indent_array_in_object: bool,
+		quote_keys: bool,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> Self {
+		Self {
+			padding: Cow::Borrowed("  "),
+			arr_element_padding: Cow::Borrowed(if indent_array_in_object { "  " } else { "" }),
+			quote_keys,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order,
+		}
+	}
+}
+impl ManifestFormat for YamlFormat<'_> {
+	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
+		manifest_yaml_ex_buf(&val, buf, &mut String::new(), self)
+	}
+}
 
 /// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>
 /// With added date check
@@ -221,7 +368,7 @@
 		|| string.parse::<f64>().is_ok()
 }
 
-pub fn manifest_yaml_ex(val: &Val, options: &ManifestYamlOptions<'_>) -> Result<String> {
+pub fn manifest_yaml_ex(val: &Val, options: &YamlFormat<'_>) -> Result<String> {
 	let mut out = String::new();
 	manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;
 	Ok(out)
@@ -232,9 +379,8 @@
 	val: &Val,
 	buf: &mut String,
 	cur_padding: &mut String,
-	options: &ManifestYamlOptions<'_>,
+	options: &YamlFormat<'_>,
 ) -> Result<()> {
-	use std::fmt::Write;
 	match val {
 		Val::Bool(v) => {
 			if *v {
@@ -252,7 +398,7 @@
 				for line in s.split('\n') {
 					buf.push('\n');
 					buf.push_str(cur_padding);
-					buf.push_str(options.padding);
+					buf.push_str(&options.padding);
 					buf.push_str(line);
 				}
 			} else if !options.quote_keys && !yaml_needs_quotes(s) {
@@ -277,7 +423,7 @@
 						Val::Arr(a) if !a.is_empty() => {
 							buf.push('\n');
 							buf.push_str(cur_padding);
-							buf.push_str(options.padding);
+							buf.push_str(&options.padding);
 						}
 						_ => buf.push(' '),
 					}
@@ -288,7 +434,7 @@
 					};
 					let prev_len = cur_padding.len();
 					if extra_padding {
-						cur_padding.push_str(options.padding);
+						cur_padding.push_str(&options.padding);
 					}
 					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;
 					cur_padding.truncate(prev_len);
@@ -323,14 +469,14 @@
 						Val::Arr(a) if !a.is_empty() => {
 							buf.push('\n');
 							buf.push_str(cur_padding);
-							buf.push_str(options.arr_element_padding);
-							cur_padding.push_str(options.arr_element_padding);
+							buf.push_str(&options.arr_element_padding);
+							cur_padding.push_str(&options.arr_element_padding);
 						}
 						Val::Obj(o) if !o.is_empty() => {
 							buf.push('\n');
 							buf.push_str(cur_padding);
-							buf.push_str(options.padding);
-							cur_padding.push_str(options.padding);
+							buf.push_str(&options.padding);
+							cur_padding.push_str(&options.padding);
 						}
 						_ => buf.push(' '),
 					}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
1use std::{cell::RefCell, fmt::Debug, rc::Rc};1use std::{cell::RefCell, fmt::Debug};
22
3use jrsonnet_gcmodule::{Cc, Trace};3use jrsonnet_gcmodule::{Cc, Trace};
4use jrsonnet_interner::{IBytes, IStr};4use jrsonnet_interner::{IBytes, IStr};
8 error::{Error::*, LocError},8 error::{Error::*, LocError},
9 function::FuncVal,9 function::FuncVal,
10 gc::{GcHashMap, TraceBox},10 gc::{GcHashMap, TraceBox},
11 stdlib::manifest::{
12 manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,
13 },
14 throw,11 throw,
15 typed::BoundedUsize,12 typed::BoundedUsize,
16 ObjValue, Result, Unbound, WeakObjValue,13 ObjValue, Result, Unbound, WeakObjValue,
122 }119 }
123}120}
124121
125#[derive(Clone, Trace)]
126pub enum ManifestFormat {122pub trait ManifestFormat {
127 YamlStream(Box<ManifestFormat>),
128 Yaml {
129 padding: usize,123 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
130 #[cfg(feature = "exp-preserve-order")]
131 preserve_order: bool,
132 },
133 Json {
134 padding: usize,124 fn manifest(&self, val: Val) -> Result<String> {
135 #[cfg(feature = "exp-preserve-order")]125 let mut out = String::new();
136 preserve_order: bool,126 self.manifest_buf(val, &mut out)?;
137 },127 Ok(out)
138 ToString,128 }
139 String,
140}129}
130impl<T> ManifestFormat for Box<T>
131where
132 T: ManifestFormat + ?Sized,
133{
134 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
135 let inner = &**self;
136 inner.manifest_buf(val, buf)
137 }
138}
141impl ManifestFormat {139impl<T> ManifestFormat for &'_ T
142 #[cfg(feature = "exp-preserve-order")]140where
141 T: ManifestFormat + ?Sized,
142{
143 fn preserve_order(&self) -> bool {143 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
144 match self {
145 ManifestFormat::YamlStream(s) => s.preserve_order(),
146 ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,
147 ManifestFormat::Json { preserve_order, .. } => *preserve_order,144 let inner = &**self;
148 ManifestFormat::ToString => false,
149 ManifestFormat::String => false,145 inner.manifest_buf(val, buf)
150 }146 }
151 }
152}147}
153148
154#[derive(Debug, Clone, Trace)]149#[derive(Debug, Clone, Trace)]
641 }636 }
642 }637 }
643638
644 pub fn to_string(&self) -> Result<IStr> {639 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {
645 Ok(match self {
646 Self::Bool(true) => "true".into(),
647 Self::Bool(false) => "false".into(),
648 Self::Null => "null".into(),
649 Self::Str(s) => s.clone(),
650 v => manifest_json_ex(
651 v,
652 &ManifestJsonOptions {
653 padding: "",
654 mtype: ManifestType::ToString,
655 newline: "\n",
656 key_val_sep: ": ",
657 #[cfg(feature = "exp-preserve-order")]
658 preserve_order: false,
659 },
660 )?
661 .into(),
662 })
663 }
664
665 /// Expects value to be object, outputs (key, manifested value) pairs
666 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {640 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {
667 let Self::Obj(obj) = self else {
668 throw!(MultiManifestOutputIsNotAObject);
669 };
670 let keys = obj.fields(
671 #[cfg(feature = "exp-preserve-order")]
672 ty.preserve_order(),
673 );
674 let mut out = Vec::with_capacity(keys.len());
675 for key in keys {
676 let value = obj
677 .get(key.clone())?641 manifest.manifest(val.clone())
678 .expect("item in object")
679 .manifest(ty)?;
680 out.push((key, value));
681 }
682 Ok(out)
683 }642 }
684
685 /// Expects value to be array, outputs manifested values
686 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {643 manifest_dyn(self, &format)
687 let Self::Arr(arr) = self else {644 }
688 throw!(StreamManifestOutputIsNotAArray);
689 };
690 let mut out = Vec::with_capacity(arr.len());
691 for i in arr.iter() {
692 out.push(i?.manifest(ty)?);
693 }
694 Ok(out)
695 }
696645
697 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {646 pub fn to_string(&self) -> Result<IStr> {
698 Ok(match ty {647 Ok(match self {
699 ManifestFormat::YamlStream(format) => {
700 let Self::Arr(arr) = self else {648 Self::Bool(true) => "true".into(),
701 throw!(StreamManifestOutputIsNotAArray)
702 };
703 let mut out = String::new();
704
705 match format as &ManifestFormat {
706 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),
707 ManifestFormat::String => throw!(StreamManifestCannotNestString),
708 _ => {}
709 };
710
711 if !arr.is_empty() {
712 for v in arr.iter() {
713 out.push_str("---\n");
714 out.push_str(&v?.manifest(format)?);
715 out.push('\n');
716 }
717 out.push_str("...");
718 }
719
720 out.into()
721 }
722 ManifestFormat::Yaml {649 Self::Bool(false) => "false".into(),
723 padding,
724 #[cfg(feature = "exp-preserve-order")]
725 preserve_order,
726 } => self.to_yaml(
727 *padding,
728 #[cfg(feature = "exp-preserve-order")]
729 *preserve_order,
730 )?,
731 ManifestFormat::Json {
732 padding,
733 #[cfg(feature = "exp-preserve-order")]
734 preserve_order,
735 } => self.to_json(
736 *padding,
737 #[cfg(feature = "exp-preserve-order")]
738 *preserve_order,
739 )?,
740 ManifestFormat::ToString => self.to_string()?,650 Self::Null => "null".into(),
741 ManifestFormat::String => match self {
742 Self::Str(s) => s.clone(),651 Self::Str(s) => s.clone(),
743 _ => throw!(StringManifestOutputIsNotAString),652 _ => self
744 },653 .manifest(crate::stdlib::manifest::ToStringFormat)
654 .map(IStr::from)?,
745 })655 })
746 }656 }
747657
748 /// For manifestification
749 pub fn to_json(
750 &self,
751 padding: usize,
752 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
753 ) -> Result<IStr> {
754 manifest_json_ex(
755 self,
756 &ManifestJsonOptions {
757 padding: &" ".repeat(padding),
758 mtype: if padding == 0 {
759 ManifestType::Minify
760 } else {
761 ManifestType::Manifest
762 },
763 newline: "\n",
764 key_val_sep: ": ",
765 #[cfg(feature = "exp-preserve-order")]
766 preserve_order,
767 },
768 )
769 .map(Into::into)
770 }
771
772 /// Calls `std.manifestJson`
773 pub fn to_std_json(
774 &self,
775 padding: usize,
776 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
777 ) -> Result<Rc<str>> {
778 manifest_json_ex(
779 self,
780 &ManifestJsonOptions {
781 padding: &" ".repeat(padding),
782 mtype: ManifestType::Std,
783 newline: "\n",
784 key_val_sep: ": ",
785 #[cfg(feature = "exp-preserve-order")]
786 preserve_order,
787 },
788 )
789 .map(Into::into)
790 }
791
792 pub fn to_yaml(
793 &self,
794 padding: usize,
795 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
796 ) -> Result<IStr> {
797 let padding = &" ".repeat(padding);
798 manifest_yaml_ex(
799 self,
800 &ManifestYamlOptions {
801 padding,
802 arr_element_padding: padding,
803 quote_keys: false,
804 #[cfg(feature = "exp-preserve-order")]
805 preserve_order,
806 },
807 )
808 .map(Into::into)
809 }
810 pub fn into_indexable(self) -> Result<IndexableVal> {658 pub fn into_indexable(self) -> Result<IndexableVal> {
811 Ok(match self {659 Ok(match self {
812 Val::Str(s) => IndexableVal::Str(s),660 Val::Str(s) => IndexableVal::Str(s),
modifiedcrates/jrsonnet-stdlib/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest.rs
+++ b/crates/jrsonnet-stdlib/src/manifest.rs
@@ -1,10 +1,7 @@
 use jrsonnet_evaluator::{
 	error::Result,
 	function::builtin,
-	stdlib::manifest::{
-		escape_string_json, manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType,
-		ManifestYamlOptions,
-	},
+	stdlib::manifest::{escape_string_json, JsonFormat, YamlFormat},
 	typed::Any,
 	IStr,
 };
@@ -24,17 +21,13 @@
 ) -> Result<String> {
 	let newline = newline.as_deref().unwrap_or("\n");
 	let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");
-	manifest_json_ex(
-		&value.0,
-		&ManifestJsonOptions {
-			padding: &indent,
-			mtype: ManifestType::Std,
-			newline,
-			key_val_sep,
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order: preserve_order.unwrap_or(false),
-		},
-	)
+	value.0.manifest(JsonFormat::std_to_json(
+		indent.to_string(),
+		newline,
+		key_val_sep,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order.unwrap_or(false),
+	))
 }
 
 #[builtin]
@@ -44,18 +37,10 @@
 	quote_keys: Option<bool>,
 	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
 ) -> Result<String> {
-	manifest_yaml_ex(
-		&value.0,
-		&ManifestYamlOptions {
-			padding: "  ",
-			arr_element_padding: if indent_array_in_object.unwrap_or(false) {
-				"  "
-			} else {
-				""
-			},
-			quote_keys: quote_keys.unwrap_or(true),
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order: preserve_order.unwrap_or(false),
-		},
-	)
+	value.0.manifest(YamlFormat::std_to_yaml(
+		indent_array_in_object.unwrap_or(false),
+		quote_keys.unwrap_or(true),
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order.unwrap_or(false),
+	))
 }