difftreelog
fix make yaml bare-key safe list closer to original impl
in: master
2 files changed
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -23,6 +23,9 @@
/// Target shell name
shell: Shell,
},
+ Deps {
+ path: String,
+ },
}
#[derive(Parser)]
@@ -83,6 +86,7 @@
if let Some(sub) = opts.sub {
match sub {
+ SubOpts::Deps { path } => todo!(),
SubOpts::Generate { shell } => {
use clap_complete::generate;
let app = &mut Opts::command();
crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth1use 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}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 "yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",83 "on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html84 "null", "Null", "NULL", "~",85 // > Quoted in std.jsonnet, however, in serde_yaml they were quoted:86 // > Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse87 // > them as string, not booleans, although it is violating the YAML 1.1 specification.88 // > See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.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}