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

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			let s = s.clone().into_flat();122			if s.is_empty() {123				buf.push_str("\"\"");124			} else if let Some(s) = s.strip_suffix('\n') {125				buf.push('|');126				for line in s.split('\n') {127					buf.push('\n');128					buf.push_str(cur_padding);129					buf.push_str(&options.padding);130					buf.push_str(line);131				}132			} else if !options.quote_keys && !yaml_needs_quotes(&s) {133				buf.push_str(&s);134			} else {135				escape_string_json_buf(&s, buf);136			}137		}138		Val::Num(n) => write!(buf, "{}", *n).unwrap(),139		Val::Arr(a) => {140			if a.is_empty() {141				buf.push_str("[]");142			} else {143				for (i, item) in a.iter().enumerate() {144					if i != 0 {145						buf.push('\n');146						buf.push_str(cur_padding);147					}148					let item = item?;149					buf.push('-');150					match &item {151						Val::Arr(a) if !a.is_empty() => {152							buf.push('\n');153							buf.push_str(cur_padding);154							buf.push_str(&options.padding);155						}156						_ => buf.push(' '),157					}158					let extra_padding = match &item {159						Val::Arr(a) => !a.is_empty(),160						Val::Obj(o) => !o.is_empty(),161						_ => false,162					};163					let prev_len = cur_padding.len();164					if extra_padding {165						cur_padding.push_str(&options.padding);166					}167					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;168					cur_padding.truncate(prev_len);169				}170			}171		}172		Val::Obj(o) => {173			if o.is_empty() {174				buf.push_str("{}");175			} else {176				for (i, key) in o177					.fields(178						#[cfg(feature = "exp-preserve-order")]179						options.preserve_order,180					)181					.iter()182					.enumerate()183				{184					if i != 0 {185						buf.push('\n');186						buf.push_str(cur_padding);187					}188					if !options.quote_keys && !yaml_needs_quotes(key) {189						buf.push_str(key);190					} else {191						escape_string_json_buf(key, buf);192					}193					buf.push(':');194					let prev_len = cur_padding.len();195					let item = o.get(key.clone())?.expect("field exists");196					match &item {197						Val::Arr(a) if !a.is_empty() => {198							buf.push('\n');199							buf.push_str(cur_padding);200							buf.push_str(&options.arr_element_padding);201							cur_padding.push_str(&options.arr_element_padding);202						}203						Val::Obj(o) if !o.is_empty() => {204							buf.push('\n');205							buf.push_str(cur_padding);206							buf.push_str(&options.padding);207							cur_padding.push_str(&options.padding);208						}209						_ => buf.push(' '),210					}211					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;212					cur_padding.truncate(prev_len);213				}214			}215		}216		Val::Func(_) => throw!("tried to manifest function"),217	}218	Ok(())219}