difftreelog
refactor remove ManifestFormat from state
in: master
7 files changed
cmds/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);
}
crates/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
+ })
}
}
crates/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.
crates/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;
}
}
crates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth1use std::{borrow::Cow, fmt::Write};21use crate::{3use crate::{2 error::{Error::*, Result},4 error::{Error::*, Result},3 throw, State, Val,5 throw, ManifestFormat, State, Val,4};6};576#[derive(PartialEq, Eq, Clone, Copy)]8#[derive(PartialEq, Eq, Clone, Copy)]16 Minify,18 Minify,17}19}182019pub struct ManifestJsonOptions<'s> {21pub struct JsonFormat<'s> {20 pub padding: &'s str,22 padding: Cow<'s, str>,21 pub mtype: ManifestType,23 mtype: ManifestType,22 pub newline: &'s str,24 newline: &'s str,23 pub key_val_sep: &'s str,25 key_val_sep: &'s str,24 #[cfg(feature = "exp-preserve-order")]26 #[cfg(feature = "exp-preserve-order")]25 pub preserve_order: bool,27 preserve_order: bool,26}28}2930impl<'s> JsonFormat<'s> {31 // Minifying format32 pub fn minify(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {33 Self {34 padding: Cow::Borrowed(""),35 mtype: ManifestType::Minify,36 newline: "\n",37 key_val_sep: ":",38 #[cfg(feature = "exp-preserve-order")]39 preserve_order,40 }41 }42 // Same format as std.toString43 pub fn std_to_string() -> Self {44 Self {45 padding: Cow::Borrowed(""),46 mtype: ManifestType::ToString,47 newline: "\n",48 key_val_sep: ": ",49 #[cfg(feature = "exp-preserve-order")]50 preserve_order: false,51 }52 }53 pub fn std_to_json(54 padding: String,55 newline: &'s str,56 key_val_sep: &'s str,57 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,58 ) -> Self {59 Self {60 padding: Cow::Owned(padding),61 mtype: ManifestType::Std,62 newline,63 key_val_sep,64 #[cfg(feature = "exp-preserve-order")]65 preserve_order,66 }67 }68 // Same format as CLI manifestification69 pub fn cli(70 padding: usize,71 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,72 ) -> Self {73 if padding == 0 {74 return Self::minify(75 #[cfg(feature = "exp-preserve-order")]76 preserve_order,77 );78 }79 Self {80 padding: Cow::Owned(" ".repeat(padding)),81 mtype: ManifestType::Manifest,82 newline: "\n",83 key_val_sep: ": ",84 #[cfg(feature = "exp-preserve-order")]85 preserve_order,86 }87 }88}89impl Default for JsonFormat<'static> {90 fn default() -> Self {91 Self {92 padding: Cow::Borrowed(" "),93 mtype: ManifestType::Manifest,94 newline: "\n",95 key_val_sep: ": ",96 #[cfg(feature = "exp-preserve-order")]97 preserve_order: false,98 }99 }100}2710128pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {102pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {29 let mut out = String::new();103 let mut out = String::new();30 manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;104 manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;31 Ok(out)105 Ok(out)34 val: &Val,108 val: &Val,35 buf: &mut String,109 buf: &mut String,36 cur_padding: &mut String,110 cur_padding: &mut String,37 options: &ManifestJsonOptions<'_>,111 options: &JsonFormat<'_>,38) -> Result<()> {112) -> Result<()> {39 use std::fmt::Write;40 let mtype = options.mtype;113 let mtype = options.mtype;41 match val {114 match val {42 Val::Bool(v) => {115 Val::Bool(v) => {57 }130 }5813159 let old_len = cur_padding.len();132 let old_len = cur_padding.len();60 cur_padding.push_str(options.padding);133 cur_padding.push_str(&options.padding);61 for (i, item) in items.iter().enumerate() {134 for (i, item) in items.iter().enumerate() {62 if i != 0 {135 if i != 0 {63 buf.push(',');136 buf.push(',');97 }170 }9817199 let old_len = cur_padding.len();172 let old_len = cur_padding.len();100 cur_padding.push_str(options.padding);173 cur_padding.push_str(&options.padding);101 for (i, field) in fields.into_iter().enumerate() {174 for (i, field) in fields.into_iter().enumerate() {102 if i != 0 {175 if i != 0 {103 buf.push(',');176 buf.push(',');138 Ok(())211 Ok(())139}212}213214impl ManifestFormat for JsonFormat<'_> {215 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {216 manifest_json_ex_buf(&val, buf, &mut String::new(), &self)217 }218}219220pub struct ToStringFormat;221impl ManifestFormat for ToStringFormat {222 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {223 JsonFormat::std_to_string().manifest_buf(val, out)224 }225}226pub struct StringFormat;227impl ManifestFormat for StringFormat {228 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {229 let Val::Str(s) = val else {230 throw!("output should be string for string manifest format, got {}", val.value_type())231 };232 out.write_str(&s).unwrap();233 Ok(())234 }235}236237pub struct YamlStreamFormat<I>(pub I);238impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {239 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {240 let Val::Arr(arr) = val else {241 throw!("output should be array for yaml stream format, got {}", val.value_type())242 };243 if !arr.is_empty() {244 for v in arr.iter() {245 let v = v?;246 out.push_str("---\n");247 self.0.manifest_buf(v, out)?;248 out.push('\n');249 }250 out.push_str("...");251 }252 Ok(())253 }254}140255141pub fn escape_string_json(s: &str) -> String {256pub fn escape_string_json(s: &str) -> String {142 let mut buf = String::new();257 let mut buf = String::new();145}260}146261147fn escape_string_json_buf(s: &str, buf: &mut String) {262fn escape_string_json_buf(s: &str, buf: &mut String) {148 use std::fmt::Write;149 buf.push('"');263 buf.push('"');150 for c in s.chars() {264 for c in s.chars() {151 match c {265 match c {165 buf.push('"');279 buf.push('"');166}280}167281168pub struct ManifestYamlOptions<'s> {282pub struct YamlFormat<'s> {169 /// Padding before fields, i.e283 /// Padding before fields, i.e170 /// ```yaml284 /// ```yaml171 /// a:285 /// a:172 /// b:286 /// b:173 /// ## <- this287 /// ## <- this174 /// ```288 /// ```175 pub padding: &'s str,289 padding: Cow<'s, str>,176 /// Padding before array elements in objects290 /// Padding before array elements in objects177 /// ```yaml291 /// ```yaml178 /// a:292 /// a:179 /// - 1293 /// - 1180 /// ## <- this294 /// ## <- this181 /// ```295 /// ```182 pub arr_element_padding: &'s str,296 arr_element_padding: Cow<'s, str>,183 /// Should yaml keys appear unescaped, when possible297 /// Should yaml keys appear unescaped, when possible184 /// ```yaml298 /// ```yaml185 /// "safe_key": 1299 /// "safe_key": 1186 /// # vs300 /// # vs187 /// safe_key: 1301 /// safe_key: 1188 /// ```302 /// ```189 pub quote_keys: bool,303 quote_keys: bool,190 /// If true - then order of fields is preserved as written,304 /// If true - then order of fields is preserved as written,191 /// instead of sorting alphabetically305 /// instead of sorting alphabetically192 #[cfg(feature = "exp-preserve-order")]306 #[cfg(feature = "exp-preserve-order")]193 pub preserve_order: bool,307 preserve_order: bool,194}308}309impl YamlFormat<'_> {310 pub fn cli(311 padding: usize,312 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,313 ) -> Self {314 let padding = " ".repeat(padding);315 Self {316 padding: Cow::Owned(padding.clone()),317 arr_element_padding: Cow::Owned(padding),318 quote_keys: false,319 #[cfg(feature = "exp-preserve-order")]320 preserve_order,321 }322 }323 pub fn std_to_yaml(324 indent_array_in_object: bool,325 quote_keys: bool,326 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,327 ) -> Self {328 Self {329 padding: Cow::Borrowed(" "),330 arr_element_padding: Cow::Borrowed(if indent_array_in_object { " " } else { "" }),331 quote_keys,332 #[cfg(feature = "exp-preserve-order")]333 preserve_order,334 }335 }336}337impl ManifestFormat for YamlFormat<'_> {338 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {339 manifest_yaml_ex_buf(&val, buf, &mut String::new(), self)340 }341}195342196/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>343/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>197/// With added date check344/// With added date check221 || string.parse::<f64>().is_ok()368 || string.parse::<f64>().is_ok()222}369}223370224pub fn manifest_yaml_ex(val: &Val, options: &ManifestYamlOptions<'_>) -> Result<String> {371pub fn manifest_yaml_ex(val: &Val, options: &YamlFormat<'_>) -> Result<String> {225 let mut out = String::new();372 let mut out = String::new();226 manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;373 manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;227 Ok(out)374 Ok(out)232 val: &Val,379 val: &Val,233 buf: &mut String,380 buf: &mut String,234 cur_padding: &mut String,381 cur_padding: &mut String,235 options: &ManifestYamlOptions<'_>,382 options: &YamlFormat<'_>,236) -> Result<()> {383) -> Result<()> {237 use std::fmt::Write;238 match val {384 match val {239 Val::Bool(v) => {385 Val::Bool(v) => {240 if *v {386 if *v {252 for line in s.split('\n') {398 for line in s.split('\n') {253 buf.push('\n');399 buf.push('\n');254 buf.push_str(cur_padding);400 buf.push_str(cur_padding);255 buf.push_str(options.padding);401 buf.push_str(&options.padding);256 buf.push_str(line);402 buf.push_str(line);257 }403 }258 } else if !options.quote_keys && !yaml_needs_quotes(s) {404 } else if !options.quote_keys && !yaml_needs_quotes(s) {277 Val::Arr(a) if !a.is_empty() => {423 Val::Arr(a) if !a.is_empty() => {278 buf.push('\n');424 buf.push('\n');279 buf.push_str(cur_padding);425 buf.push_str(cur_padding);280 buf.push_str(options.padding);426 buf.push_str(&options.padding);281 }427 }282 _ => buf.push(' '),428 _ => buf.push(' '),283 }429 }288 };434 };289 let prev_len = cur_padding.len();435 let prev_len = cur_padding.len();290 if extra_padding {436 if extra_padding {291 cur_padding.push_str(options.padding);437 cur_padding.push_str(&options.padding);292 }438 }293 manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;439 manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;294 cur_padding.truncate(prev_len);440 cur_padding.truncate(prev_len);323 Val::Arr(a) if !a.is_empty() => {469 Val::Arr(a) if !a.is_empty() => {324 buf.push('\n');470 buf.push('\n');325 buf.push_str(cur_padding);471 buf.push_str(cur_padding);326 buf.push_str(options.arr_element_padding);472 buf.push_str(&options.arr_element_padding);327 cur_padding.push_str(options.arr_element_padding);473 cur_padding.push_str(&options.arr_element_padding);328 }474 }329 Val::Obj(o) if !o.is_empty() => {475 Val::Obj(o) if !o.is_empty() => {330 buf.push('\n');476 buf.push('\n');331 buf.push_str(cur_padding);477 buf.push_str(cur_padding);332 buf.push_str(options.padding);478 buf.push_str(&options.padding);333 cur_padding.push_str(options.padding);479 cur_padding.push_str(&options.padding);334 }480 }335 _ => buf.push(' '),481 _ => buf.push(' '),336 }482 }crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -1,4 +1,4 @@
-use std::{cell::RefCell, fmt::Debug, rc::Rc};
+use std::{cell::RefCell, fmt::Debug};
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::{IBytes, IStr};
@@ -8,9 +8,6 @@
error::{Error::*, LocError},
function::FuncVal,
gc::{GcHashMap, TraceBox},
- stdlib::manifest::{
- manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,
- },
throw,
typed::BoundedUsize,
ObjValue, Result, Unbound, WeakObjValue,
@@ -122,34 +119,32 @@
}
}
-#[derive(Clone, Trace)]
-pub enum ManifestFormat {
- YamlStream(Box<ManifestFormat>),
- Yaml {
- padding: usize,
- #[cfg(feature = "exp-preserve-order")]
- preserve_order: bool,
- },
- Json {
- padding: usize,
- #[cfg(feature = "exp-preserve-order")]
- preserve_order: bool,
- },
- ToString,
- String,
+pub trait ManifestFormat {
+ fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
+ fn manifest(&self, val: Val) -> Result<String> {
+ let mut out = String::new();
+ self.manifest_buf(val, &mut out)?;
+ Ok(out)
+ }
}
-impl ManifestFormat {
- #[cfg(feature = "exp-preserve-order")]
- fn preserve_order(&self) -> bool {
- match self {
- ManifestFormat::YamlStream(s) => s.preserve_order(),
- ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,
- ManifestFormat::Json { preserve_order, .. } => *preserve_order,
- ManifestFormat::ToString => false,
- ManifestFormat::String => false,
- }
+impl<T> ManifestFormat for Box<T>
+where
+ T: ManifestFormat + ?Sized,
+{
+ fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
+ let inner = &**self;
+ inner.manifest_buf(val, buf)
}
}
+impl<T> ManifestFormat for &'_ T
+where
+ T: ManifestFormat + ?Sized,
+{
+ fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
+ let inner = &**self;
+ inner.manifest_buf(val, buf)
+ }
+}
#[derive(Debug, Clone, Trace)]
pub struct Slice {
@@ -641,172 +636,25 @@
}
}
+ pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {
+ fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {
+ manifest.manifest(val.clone())
+ }
+ manifest_dyn(self, &format)
+ }
+
pub fn to_string(&self) -> Result<IStr> {
Ok(match self {
Self::Bool(true) => "true".into(),
Self::Bool(false) => "false".into(),
Self::Null => "null".into(),
Self::Str(s) => s.clone(),
- v => manifest_json_ex(
- v,
- &ManifestJsonOptions {
- padding: "",
- mtype: ManifestType::ToString,
- newline: "\n",
- key_val_sep: ": ",
- #[cfg(feature = "exp-preserve-order")]
- preserve_order: false,
- },
- )?
- .into(),
- })
- }
-
- /// Expects value to be object, outputs (key, manifested value) pairs
- pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {
- let Self::Obj(obj) = self else {
- throw!(MultiManifestOutputIsNotAObject);
- };
- let keys = obj.fields(
- #[cfg(feature = "exp-preserve-order")]
- ty.preserve_order(),
- );
- let mut out = Vec::with_capacity(keys.len());
- for key in keys {
- let value = obj
- .get(key.clone())?
- .expect("item in object")
- .manifest(ty)?;
- out.push((key, value));
- }
- Ok(out)
- }
-
- /// Expects value to be array, outputs manifested values
- pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {
- let Self::Arr(arr) = self else {
- throw!(StreamManifestOutputIsNotAArray);
- };
- let mut out = Vec::with_capacity(arr.len());
- for i in arr.iter() {
- out.push(i?.manifest(ty)?);
- }
- Ok(out)
- }
-
- pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {
- Ok(match ty {
- ManifestFormat::YamlStream(format) => {
- let Self::Arr(arr) = self else {
- throw!(StreamManifestOutputIsNotAArray)
- };
- let mut out = String::new();
-
- match format as &ManifestFormat {
- ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),
- ManifestFormat::String => throw!(StreamManifestCannotNestString),
- _ => {}
- };
-
- if !arr.is_empty() {
- for v in arr.iter() {
- out.push_str("---\n");
- out.push_str(&v?.manifest(format)?);
- out.push('\n');
- }
- out.push_str("...");
- }
-
- out.into()
- }
- ManifestFormat::Yaml {
- padding,
- #[cfg(feature = "exp-preserve-order")]
- preserve_order,
- } => self.to_yaml(
- *padding,
- #[cfg(feature = "exp-preserve-order")]
- *preserve_order,
- )?,
- ManifestFormat::Json {
- padding,
- #[cfg(feature = "exp-preserve-order")]
- preserve_order,
- } => self.to_json(
- *padding,
- #[cfg(feature = "exp-preserve-order")]
- *preserve_order,
- )?,
- ManifestFormat::ToString => self.to_string()?,
- ManifestFormat::String => match self {
- Self::Str(s) => s.clone(),
- _ => throw!(StringManifestOutputIsNotAString),
- },
+ _ => self
+ .manifest(crate::stdlib::manifest::ToStringFormat)
+ .map(IStr::from)?,
})
- }
-
- /// For manifestification
- pub fn to_json(
- &self,
- padding: usize,
- #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
- ) -> Result<IStr> {
- manifest_json_ex(
- self,
- &ManifestJsonOptions {
- padding: &" ".repeat(padding),
- mtype: if padding == 0 {
- ManifestType::Minify
- } else {
- ManifestType::Manifest
- },
- newline: "\n",
- key_val_sep: ": ",
- #[cfg(feature = "exp-preserve-order")]
- preserve_order,
- },
- )
- .map(Into::into)
}
- /// Calls `std.manifestJson`
- pub fn to_std_json(
- &self,
- padding: usize,
- #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
- ) -> Result<Rc<str>> {
- manifest_json_ex(
- self,
- &ManifestJsonOptions {
- padding: &" ".repeat(padding),
- mtype: ManifestType::Std,
- newline: "\n",
- key_val_sep: ": ",
- #[cfg(feature = "exp-preserve-order")]
- preserve_order,
- },
- )
- .map(Into::into)
- }
-
- pub fn to_yaml(
- &self,
- padding: usize,
- #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
- ) -> Result<IStr> {
- let padding = &" ".repeat(padding);
- manifest_yaml_ex(
- self,
- &ManifestYamlOptions {
- padding,
- arr_element_padding: padding,
- quote_keys: false,
- #[cfg(feature = "exp-preserve-order")]
- preserve_order,
- },
- )
- .map(Into::into)
- }
pub fn into_indexable(self) -> Result<IndexableVal> {
Ok(match self {
Val::Str(s) => IndexableVal::Str(s),
crates/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),
+ ))
}