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

difftreelog

source

crates/jrsonnet-stdlib/src/manifest/yaml.rs5.9 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			// Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse83			// them as string, not booleans, although it is violating the YAML 1.1 specification.84			// See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.85			"yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",86			"on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html87			"null", "Null", "NULL", "~",88		].contains(&string)89		|| (string.chars().all(|c| matches!(c, '0'..='9' | '-'))90			&& string.chars().filter(|c| *c == '-').count() == 2)91		|| string.starts_with('.')92		|| string.starts_with("0x")93		|| string.parse::<i64>().is_ok()94		|| string.parse::<f64>().is_ok()95}9697#[allow(dead_code)]98fn manifest_yaml_ex(val: &Val, options: &YamlFormat<'_>) -> Result<String> {99	let mut out = String::new();100	manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;101	Ok(out)102}103104#[allow(clippy::too_many_lines)]105fn manifest_yaml_ex_buf(106	val: &Val,107	buf: &mut String,108	cur_padding: &mut String,109	options: &YamlFormat<'_>,110) -> Result<()> {111	match val {112		Val::Bool(v) => {113			if *v {114				buf.push_str("true");115			} else {116				buf.push_str("false");117			}118		}119		Val::Null => buf.push_str("null"),120		Val::Str(s) => {121			if s.is_empty() {122				buf.push_str("\"\"");123			} else if let Some(s) = s.strip_suffix('\n') {124				buf.push('|');125				for line in s.split('\n') {126					buf.push('\n');127					buf.push_str(cur_padding);128					buf.push_str(&options.padding);129					buf.push_str(line);130				}131			} else if !options.quote_keys && !yaml_needs_quotes(s) {132				buf.push_str(s);133			} else {134				escape_string_json_buf(s, buf);135			}136		}137		Val::Num(n) => write!(buf, "{}", *n).unwrap(),138		Val::Arr(a) => {139			if a.is_empty() {140				buf.push_str("[]");141			} else {142				for (i, item) in a.iter().enumerate() {143					if i != 0 {144						buf.push('\n');145						buf.push_str(cur_padding);146					}147					let item = item?;148					buf.push('-');149					match &item {150						Val::Arr(a) if !a.is_empty() => {151							buf.push('\n');152							buf.push_str(cur_padding);153							buf.push_str(&options.padding);154						}155						_ => buf.push(' '),156					}157					let extra_padding = match &item {158						Val::Arr(a) => !a.is_empty(),159						Val::Obj(o) => !o.is_empty(),160						_ => false,161					};162					let prev_len = cur_padding.len();163					if extra_padding {164						cur_padding.push_str(&options.padding);165					}166					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;167					cur_padding.truncate(prev_len);168				}169			}170		}171		Val::Obj(o) => {172			if o.is_empty() {173				buf.push_str("{}");174			} else {175				for (i, key) in o176					.fields(177						#[cfg(feature = "exp-preserve-order")]178						options.preserve_order,179					)180					.iter()181					.enumerate()182				{183					if i != 0 {184						buf.push('\n');185						buf.push_str(cur_padding);186					}187					if !options.quote_keys && !yaml_needs_quotes(key) {188						buf.push_str(key);189					} else {190						escape_string_json_buf(key, buf);191					}192					buf.push(':');193					let prev_len = cur_padding.len();194					let item = o.get(key.clone())?.expect("field exists");195					match &item {196						Val::Arr(a) if !a.is_empty() => {197							buf.push('\n');198							buf.push_str(cur_padding);199							buf.push_str(&options.arr_element_padding);200							cur_padding.push_str(&options.arr_element_padding);201						}202						Val::Obj(o) if !o.is_empty() => {203							buf.push('\n');204							buf.push_str(cur_padding);205							buf.push_str(&options.padding);206							cur_padding.push_str(&options.padding);207						}208						_ => buf.push(' '),209					}210					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;211					cur_padding.truncate(prev_len);212				}213			}214		}215		Val::Func(_) => throw!("tried to manifest function"),216	}217	Ok(())218}