git.delta.rocks / jrsonnet / refs/commits / 9c0fa0107dd8

difftreelog

source

crates/jrsonnet-evaluator/src/builtin/manifest.rs8.8 KiBsourcehistory
1use crate::error::Error::*;2use crate::error::Result;3use crate::push_description_frame;4use crate::{throw, Val};56#[derive(PartialEq, Clone, Copy)]7pub enum ManifestType {8	// Applied in manifestification9	Manifest,10	/// Used for std.manifestJson11	/// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest12	Std,13	/// No line breaks, used in `obj+''`14	ToString,15	/// Minified json16	Minify,17}1819pub struct ManifestJsonOptions<'s> {20	pub padding: &'s str,21	pub mtype: ManifestType,22	pub newline: &'s str,23	pub key_val_sep: &'s str,24}2526pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {27	let mut out = String::new();28	manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;29	Ok(out)30}31fn manifest_json_ex_buf(32	val: &Val,33	buf: &mut String,34	cur_padding: &mut String,35	options: &ManifestJsonOptions<'_>,36) -> Result<()> {37	use std::fmt::Write;38	let mtype = options.mtype;39	match val {40		Val::Bool(v) => {41			if *v {42				buf.push_str("true");43			} else {44				buf.push_str("false");45			}46		}47		Val::Null => buf.push_str("null"),48		Val::Str(s) => escape_string_json_buf(s, buf),49		Val::Num(n) => write!(buf, "{}", n).unwrap(),50		Val::Arr(items) => {51			buf.push('[');52			if !items.is_empty() {53				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {54					buf.push_str(options.newline);55				}5657				let old_len = cur_padding.len();58				cur_padding.push_str(options.padding);59				for (i, item) in items.iter().enumerate() {60					if i != 0 {61						buf.push(',');62						if mtype == ManifestType::ToString {63							buf.push(' ');64						} else if mtype != ManifestType::Minify {65							buf.push_str(options.newline);66						}67					}68					buf.push_str(cur_padding);69					manifest_json_ex_buf(&item?, buf, cur_padding, options)?;70				}71				cur_padding.truncate(old_len);7273				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {74					buf.push_str(options.newline);75					buf.push_str(cur_padding);76				}77			} else if mtype == ManifestType::Std {78				buf.push_str("\n\n");79				buf.push_str(cur_padding);80			} else if mtype == ManifestType::ToString || mtype == ManifestType::Manifest {81				buf.push(' ');82			}83			buf.push(']');84		}85		Val::Obj(obj) => {86			obj.run_assertions()?;87			buf.push('{');88			let fields = obj.fields();89			if !fields.is_empty() {90				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {91					buf.push_str(options.newline);92				}9394				let old_len = cur_padding.len();95				cur_padding.push_str(options.padding);96				for (i, field) in fields.into_iter().enumerate() {97					if i != 0 {98						buf.push(',');99						if mtype == ManifestType::ToString {100							buf.push(' ');101						} else if mtype != ManifestType::Minify {102							buf.push_str(options.newline);103						}104					}105					buf.push_str(cur_padding);106					escape_string_json_buf(&field, buf);107					buf.push_str(options.key_val_sep);108					push_description_frame(109						|| format!("field <{}> manifestification", field.clone()),110						|| {111							let value = obj.get(field.clone())?.unwrap();112							manifest_json_ex_buf(&value, buf, cur_padding, options)?;113							Ok(Val::Null)114						},115					)?;116				}117				cur_padding.truncate(old_len);118119				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {120					buf.push_str(options.newline);121					buf.push_str(cur_padding);122				}123			} else if mtype == ManifestType::Std {124				buf.push_str("\n\n");125				buf.push_str(cur_padding);126			} else if mtype == ManifestType::ToString || mtype == ManifestType::Manifest {127				buf.push(' ');128			}129			buf.push('}');130		}131		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),132	};133	Ok(())134}135136pub fn escape_string_json(s: &str) -> String {137	let mut buf = String::new();138	escape_string_json_buf(s, &mut buf);139	buf140}141142fn escape_string_json_buf(s: &str, buf: &mut String) {143	use std::fmt::Write;144	buf.push('"');145	for c in s.chars() {146		match c {147			'"' => buf.push_str("\\\""),148			'\\' => buf.push_str("\\\\"),149			'\u{0008}' => buf.push_str("\\b"),150			'\u{000c}' => buf.push_str("\\f"),151			'\n' => buf.push_str("\\n"),152			'\r' => buf.push_str("\\r"),153			'\t' => buf.push_str("\\t"),154			c if c < 32 as char || (c >= 127 as char && c <= 159 as char) => {155				write!(buf, "\\u{:04x}", c as u32).unwrap()156			}157			c => buf.push(c),158		}159	}160	buf.push('"');161}162163pub struct ManifestYamlOptions<'s> {164	/// Padding before fields, i.e165	/// ```yaml166	/// a:167	///   b:168	/// ## <- this169	/// ```170	pub padding: &'s str,171	/// Padding before array elements in objects172	/// ```yaml173	/// a:174	///   - 1175	/// ## <- this176	/// ```177	pub arr_element_padding: &'s str,178	/// Should yaml keys appear unescaped, when possible179	/// ```yaml180	/// "safe_key": 1181	/// # vs182	/// safe_key: 1183	/// ```184	pub quote_keys: bool,185}186187/// From https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289188/// With added date check189fn yaml_needs_quotes(string: &str) -> bool {190	fn need_quotes_spaces(string: &str) -> bool {191		string.starts_with(' ') || string.ends_with(' ')192	}193194	string.is_empty()195		|| need_quotes_spaces(string)196		|| string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))197		|| string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))198		|| [199			// http://yaml.org/type/bool.html200			// Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse201			// them as string, not booleans, although it is violating the YAML 1.1 specification.202			// See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.203			"yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",204			"on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html205			"null", "Null", "NULL", "~",206		].contains(&string)207		|| (string.chars().all(|c| matches!(c, '0'..='9' | '-'))208			&& string.chars().filter(|c| *c == '-').count() == 2)209		|| string.starts_with('.')210		|| string.starts_with("0x")211		|| string.parse::<i64>().is_ok()212		|| string.parse::<f64>().is_ok()213}214215pub fn manifest_yaml_ex(val: &Val, options: &ManifestYamlOptions<'_>) -> Result<String> {216	let mut out = String::new();217	manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;218	Ok(out)219}220fn manifest_yaml_ex_buf(221	val: &Val,222	buf: &mut String,223	cur_padding: &mut String,224	options: &ManifestYamlOptions<'_>,225) -> Result<()> {226	use std::fmt::Write;227	match val {228		Val::Bool(v) => {229			if *v {230				buf.push_str("true")231			} else {232				buf.push_str("false")233			}234		}235		Val::Null => buf.push_str("null"),236		Val::Str(s) => {237			if s.is_empty() {238				buf.push_str("\"\"");239			} else if let Some(s) = s.strip_suffix('\n') {240				buf.push('|');241				for line in s.split('\n') {242					buf.push('\n');243					buf.push_str(options.padding);244					buf.push_str(line);245				}246			} else if !options.quote_keys && !yaml_needs_quotes(s) {247				buf.push_str(s);248			} else {249				escape_string_json_buf(s, buf);250			}251		}252		Val::Num(n) => write!(buf, "{}", *n).unwrap(),253		Val::Arr(a) => {254			if a.is_empty() {255				buf.push_str("[]");256			} else {257				for (i, item) in a.iter().enumerate() {258					if i != 0 {259						buf.push('\n');260						buf.push_str(cur_padding);261					}262					let item = item?;263					buf.push('-');264					match &item {265						Val::Arr(a) if !a.is_empty() => {266							buf.push('\n');267							buf.push_str(cur_padding);268							buf.push_str(options.padding);269						}270						_ => buf.push(' '),271					}272					let extra_padding = match &item {273						Val::Arr(a) => !a.is_empty(),274						Val::Obj(o) => !o.is_empty(),275						_ => false,276					};277					let prev_len = cur_padding.len();278					if extra_padding {279						cur_padding.push_str(options.padding);280					}281					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;282					cur_padding.truncate(prev_len);283				}284			}285		}286		Val::Obj(o) => {287			if o.is_empty() {288				buf.push_str("{}");289			} else {290				for (i, key) in o.fields().iter().enumerate() {291					if i != 0 {292						buf.push('\n');293						buf.push_str(cur_padding);294					}295					if !options.quote_keys && !yaml_needs_quotes(key) {296						buf.push_str(key);297					} else {298						escape_string_json_buf(key, buf);299					}300					buf.push(':');301					let prev_len = cur_padding.len();302					let item = o.get(key.clone())?.expect("field exists");303					match &item {304						Val::Arr(a) if !a.is_empty() => {305							buf.push('\n');306							buf.push_str(cur_padding);307							buf.push_str(options.arr_element_padding);308							cur_padding.push_str(options.arr_element_padding);309						}310						Val::Obj(o) if !o.is_empty() => {311							buf.push('\n');312							buf.push_str(cur_padding);313							buf.push_str(options.padding);314							cur_padding.push_str(options.padding);315						}316						_ => buf.push(' '),317					}318					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;319					cur_padding.truncate(prev_len);320				}321			}322		}323		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),324	}325	Ok(())326}