git.delta.rocks / jrsonnet / refs/commits / 2ec9a620e466

difftreelog

feat configurable array element padding

Yaroslav Bolyukin2021-10-25parent: #ebba949.patch.diff
in: master

3 files changed

modifiedcrates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/builtin/manifest.rs
1use crate::error::Error::*;2use crate::error::Result;3use crate::{throw, Val};45#[derive(PartialEq, Clone, Copy)]6pub enum ManifestType {7	// Applied in manifestification8	Manifest,9	/// Used for std.manifestJson10	/// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest11	Std,12	/// No line breaks, used in `obj+''`13	ToString,14	/// Minified json15	Minify,16}1718pub struct ManifestJsonOptions<'s> {19	pub padding: &'s str,20	pub mtype: ManifestType,21}2223pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {24	let mut out = String::new();25	manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;26	Ok(out)27}28fn manifest_json_ex_buf(29	val: &Val,30	buf: &mut String,31	cur_padding: &mut String,32	options: &ManifestJsonOptions<'_>,33) -> Result<()> {34	use std::fmt::Write;35	let mtype = options.mtype;36	match val {37		Val::Bool(v) => {38			if *v {39				buf.push_str("true");40			} else {41				buf.push_str("false");42			}43		}44		Val::Null => buf.push_str("null"),45		Val::Str(s) => escape_string_json_buf(s, buf),46		Val::Num(n) => write!(buf, "{}", n).unwrap(),47		Val::Arr(items) => {48			buf.push('[');49			if !items.is_empty() {50				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {51					buf.push('\n');52				}5354				let old_len = cur_padding.len();55				cur_padding.push_str(options.padding);56				for (i, item) in items.iter().enumerate() {57					if i != 0 {58						buf.push(',');59						if mtype == ManifestType::ToString {60							buf.push(' ');61						} else if mtype != ManifestType::Minify {62							buf.push('\n');63						}64					}65					buf.push_str(cur_padding);66					manifest_json_ex_buf(&item?, buf, cur_padding, options)?;67				}68				cur_padding.truncate(old_len);6970				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {71					buf.push('\n');72					buf.push_str(cur_padding);73				}74			} else if mtype == ManifestType::Std {75				buf.push_str("\n\n");76				buf.push_str(cur_padding);77			} else if mtype == ManifestType::ToString || mtype == ManifestType::Manifest {78				buf.push(' ');79			}80			buf.push(']');81		}82		Val::Obj(obj) => {83			obj.run_assertions()?;84			buf.push('{');85			let fields = obj.fields();86			if !fields.is_empty() {87				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {88					buf.push('\n');89				}9091				let old_len = cur_padding.len();92				cur_padding.push_str(options.padding);93				for (i, field) in fields.into_iter().enumerate() {94					if i != 0 {95						buf.push(',');96						if mtype == ManifestType::ToString {97							buf.push(' ');98						} else if mtype != ManifestType::Minify {99							buf.push('\n');100						}101					}102					buf.push_str(cur_padding);103					escape_string_json_buf(&field, buf);104					buf.push_str(": ");105					crate::push(106						None,107						|| format!("field <{}> manifestification", field.clone()),108						|| {109							let value = obj.get(field.clone())?.unwrap();110							manifest_json_ex_buf(&value, buf, cur_padding, options)111						},112					)?;113				}114				cur_padding.truncate(old_len);115116				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {117					buf.push('\n');118					buf.push_str(cur_padding);119				}120			} else if mtype == ManifestType::Std {121				buf.push_str("\n\n");122				buf.push_str(cur_padding);123			} else if mtype == ManifestType::ToString || mtype == ManifestType::Manifest {124				buf.push(' ');125			}126			buf.push('}');127		}128		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),129	};130	Ok(())131}132133pub fn escape_string_json(s: &str) -> String {134	let mut buf = String::new();135	escape_string_json_buf(s, &mut buf);136	buf137}138139fn escape_string_json_buf(s: &str, buf: &mut String) {140	use std::fmt::Write;141	buf.push('"');142	for c in s.chars() {143		match c {144			'"' => buf.push_str("\\\""),145			'\\' => buf.push_str("\\\\"),146			'\u{0008}' => buf.push_str("\\b"),147			'\u{000c}' => buf.push_str("\\f"),148			'\n' => buf.push_str("\\n"),149			'\r' => buf.push_str("\\r"),150			'\t' => buf.push_str("\\t"),151			c if c < 32 as char || (c >= 127 as char && c <= 159 as char) => {152				write!(buf, "\\u{:04x}", c as u32).unwrap()153			}154			c => buf.push(c),155		}156	}157	buf.push('"');158}159160pub struct ManifestYamlOptions<'s> {161	pub padding: &'s str,162	pub pad_arrays: bool,163}164165pub fn manifest_yaml_ex(val: &Val, options: &ManifestYamlOptions<'_>) -> Result<String> {166	let mut out = String::new();167	manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;168	Ok(out)169}170fn manifest_yaml_ex_buf(171	val: &Val,172	buf: &mut String,173	cur_padding: &mut String,174	options: &ManifestYamlOptions<'_>,175) -> Result<()> {176	use std::fmt::Write;177	match val {178		Val::Bool(v) => {179			if *v {180				buf.push_str("true")181			} else {182				buf.push_str("false")183			}184		}185		Val::Null => buf.push_str("null"),186		Val::Str(s) => {187			if s.is_empty() {188				buf.push_str("\"\"");189			} else if let Some(s) = s.strip_suffix('\n') {190				buf.push('|');191				for line in s.split('\n') {192					buf.push('\n');193					buf.push_str(options.padding);194					buf.push_str(line);195				}196			} else {197				escape_string_json_buf(s, buf)198			}199		}200		Val::Num(n) => write!(buf, "{}", *n).unwrap(),201		Val::Arr(a) => {202			if a.is_empty() {203				buf.push_str("[]");204			} else {205				for (i, item) in a.iter().enumerate() {206					if i != 0 {207						buf.push('\n');208						buf.push_str(cur_padding);209					}210					let item = item?;211					buf.push('-');212					if let Val::Arr(a) = &item {213						if !a.is_empty() {214							buf.push('\n');215							buf.push_str(cur_padding);216							buf.push_str(options.padding);217						} else {218							buf.push(' ');219						}220					} else {221						buf.push(' ');222					}223					let extra_padding = if let Val::Arr(a) = &item {224						!a.is_empty()225					} else if let Val::Obj(a) = &item {226						!a.is_empty()227					} else {228						false229					};230					let prev_len = cur_padding.len();231					if extra_padding {232						cur_padding.push_str(options.padding);233					}234					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;235					cur_padding.truncate(prev_len);236				}237			}238		}239		Val::Obj(o) => {240			if o.is_empty() {241				buf.push_str("{}");242			} else {243				for (i, key) in o.fields().iter().enumerate() {244					if i != 0 {245						buf.push('\n');246						buf.push_str(cur_padding);247					}248					escape_string_json_buf(key, buf);249					buf.push(':');250					let item = o.get(key.clone())?.expect("field exists");251					if let Val::Arr(a) = &item {252						if !a.is_empty() {253							buf.push('\n');254							buf.push_str(cur_padding);255							if options.pad_arrays {256								buf.push_str(options.padding);257							}258						} else {259							buf.push(' ');260						}261					} else if let Val::Obj(o) = &item {262						if !o.is_empty() {263							buf.push('\n');264							buf.push_str(cur_padding);265							buf.push_str(options.padding);266						} else {267							buf.push(' ');268						}269					} else {270						buf.push(' ');271					}272					let prev_len = cur_padding.len();273					if let Val::Arr(a) = &item {274						if !a.is_empty() && options.pad_arrays {275							cur_padding.push_str(options.padding);276						}277					} else if let Val::Obj(a) = &item {278						if !a.is_empty() {279							cur_padding.push_str(options.padding);280						}281					};282					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;283					cur_padding.truncate(prev_len);284				}285			}286		}287		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),288	}289	Ok(())290}
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -781,7 +781,7 @@
 	], {
 		Ok(Val::Str(manifest_yaml_ex(&value, &ManifestYamlOptions {
 			padding: "  ",
-			pad_arrays: indent_array_in_object,
+			arr_element_padding: if indent_array_in_object { "  " } else { "" },
 		})?.into()))
 	})
 }
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -553,11 +553,12 @@
 	}
 
 	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {
+		let padding = &" ".repeat(padding);
 		manifest_yaml_ex(
 			self,
 			&ManifestYamlOptions {
-				padding: &" ".repeat(padding),
-				pad_arrays: true,
+				padding,
+				arr_element_padding: padding,
 			},
 		)
 		.map(|s| s.into())