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 10 11 12 13 14 15 padding: Cow<'s, str>,16 17 18 19 20 21 22 arr_element_padding: Cow<'s, str>,23 24 25 26 27 28 29 quote_keys: bool,30 31 32 #[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}68697071fn 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 82 "yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",83 "on", "On", "ON", "off", "Off", "OFF", 84 "null", "Null", "NULL", "~",85 86 87 88 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}