git.delta.rocks / jrsonnet / refs/commits / a292d3c2f0f5

difftreelog

source

crates/jrsonnet-stdlib/src/manifest/yaml.rs6.1 KiBsourcehistory
1use std::{borrow::Cow, fmt::Write};23use jrsonnet_evaluator::{4	manifest::{escape_string_json_buf, ManifestFormat},5	throw, Result, Val,6};78pub struct YamlFormat<'s> {9	/// Padding before fields, i.e10	/// ```yaml11	/// a:12	///   b:13	/// ## <- this14	/// ```15	padding: Cow<'s, str>,16	/// Padding before array elements in objects17	/// ```yaml18	/// a:19	///   - 120	/// ## <- this21	/// ```22	arr_element_padding: Cow<'s, str>,23	/// Should yaml keys appear unescaped, when possible24	/// ```yaml25	/// "safe_key": 126	/// # vs27	/// safe_key: 128	/// ```29	quote_keys: bool,30	/// If true - then order of fields is preserved as written,31	/// instead of sorting alphabetically32	#[cfg(feature = "exp-preserve-order")]33	preserve_order: bool,34}35impl YamlFormat<'_> {36	pub fn cli(37		padding: usize,38		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,39	) -> Self {40		let padding = " ".repeat(padding);41		Self {42			padding: Cow::Owned(padding.clone()),43			arr_element_padding: Cow::Owned(padding),44			quote_keys: false,45			#[cfg(feature = "exp-preserve-order")]46			preserve_order,47		}48	}49	pub fn std_to_yaml(50		indent_array_in_object: bool,51		quote_keys: bool,52		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,53	) -> Self {54		Self {55			padding: Cow::Borrowed("  "),56			arr_element_padding: Cow::Borrowed(if indent_array_in_object { "  " } else { "" }),57			quote_keys,58			#[cfg(feature = "exp-preserve-order")]59			preserve_order,60		}61	}62}63impl ManifestFormat for YamlFormat<'_> {64	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {65		manifest_yaml_ex_buf(&val, buf, &mut String::new(), self)66	}67}6869/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>70/// With added date check71fn yaml_needs_quotes(string: &str) -> bool {72	fn need_quotes_spaces(string: &str) -> bool {73		string.starts_with(' ') || string.ends_with(' ')74	}7576	string.is_empty()77		|| need_quotes_spaces(string)78		|| string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))79		|| string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))80		|| [81			// http://yaml.org/type/bool.html82			"yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",83			"on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html84			"null", "Null", "NULL", "~",85			// > Quoted in std.jsonnet, however, in serde_yaml they were quoted:86			// > Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse87			// > them as string, not booleans, although it is violating the YAML 1.1 specification.88			// > See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.89			"y", "Y", "n", "N",90			"-.inf", "+.inf", ".inf",91			"-", "---", ""92		].contains(&string)93		|| (string.chars().all(|c| matches!(c, '0'..='9' | '-'))94			&& string.chars().filter(|c| *c == '-').count() == 2)95		|| string.starts_with('.')96		|| string.starts_with("0x")97		|| string.parse::<i64>().is_ok()98		|| string.parse::<f64>().is_ok()99}100101#[allow(dead_code)]102fn manifest_yaml_ex(val: &Val, options: &YamlFormat<'_>) -> Result<String> {103	let mut out = String::new();104	manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;105	Ok(out)106}107108#[allow(clippy::too_many_lines)]109fn manifest_yaml_ex_buf(110	val: &Val,111	buf: &mut String,112	cur_padding: &mut String,113	options: &YamlFormat<'_>,114) -> Result<()> {115	match val {116		Val::Bool(v) => {117			if *v {118				buf.push_str("true");119			} else {120				buf.push_str("false");121			}122		}123		Val::Null => buf.push_str("null"),124		Val::Str(s) => {125			let s = s.clone().into_flat();126			if s.is_empty() {127				buf.push_str("\"\"");128			} else if let Some(s) = s.strip_suffix('\n') {129				buf.push('|');130				for line in s.split('\n') {131					buf.push('\n');132					buf.push_str(cur_padding);133					buf.push_str(&options.padding);134					buf.push_str(line);135				}136			} else if !options.quote_keys && !yaml_needs_quotes(&s) {137				buf.push_str(&s);138			} else {139				escape_string_json_buf(&s, buf);140			}141		}142		Val::Num(n) => write!(buf, "{}", *n).unwrap(),143		Val::Arr(a) => {144			if a.is_empty() {145				buf.push_str("[]");146			} else {147				for (i, item) in a.iter().enumerate() {148					if i != 0 {149						buf.push('\n');150						buf.push_str(cur_padding);151					}152					let item = item?;153					buf.push('-');154					match &item {155						Val::Arr(a) if !a.is_empty() => {156							buf.push('\n');157							buf.push_str(cur_padding);158							buf.push_str(&options.padding);159						}160						_ => buf.push(' '),161					}162					let extra_padding = match &item {163						Val::Arr(a) => !a.is_empty(),164						Val::Obj(o) => !o.is_empty(),165						_ => false,166					};167					let prev_len = cur_padding.len();168					if extra_padding {169						cur_padding.push_str(&options.padding);170					}171					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;172					cur_padding.truncate(prev_len);173				}174			}175		}176		Val::Obj(o) => {177			if o.is_empty() {178				buf.push_str("{}");179			} else {180				for (i, key) in o181					.fields(182						#[cfg(feature = "exp-preserve-order")]183						options.preserve_order,184					)185					.iter()186					.enumerate()187				{188					if i != 0 {189						buf.push('\n');190						buf.push_str(cur_padding);191					}192					if !options.quote_keys && !yaml_needs_quotes(key) {193						buf.push_str(key);194					} else {195						escape_string_json_buf(key, buf);196					}197					buf.push(':');198					let prev_len = cur_padding.len();199					let item = o.get(key.clone())?.expect("field exists");200					match &item {201						Val::Arr(a) if !a.is_empty() => {202							buf.push('\n');203							buf.push_str(cur_padding);204							buf.push_str(&options.arr_element_padding);205							cur_padding.push_str(&options.arr_element_padding);206						}207						Val::Obj(o) if !o.is_empty() => {208							buf.push('\n');209							buf.push_str(cur_padding);210							buf.push_str(&options.padding);211							cur_padding.push_str(&options.padding);212						}213						_ => buf.push(' '),214					}215					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;216					cur_padding.truncate(prev_len);217				}218			}219		}220		Val::Func(_) => throw!("tried to manifest function"),221	}222	Ok(())223}