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