use scrusted_feel::Value;
pub fn to_yaml(value: &Value) -> String {
let mut out = String::new();
write(value, 0, &mut out, true);
if !out.ends_with('\n') {
out.push('\n');
}
out
}
fn plain_ok(s: &str) -> bool {
if s.is_empty() || s.trim() != s {
return false;
}
let first = s.chars().next().unwrap_or(' ');
if "!&*-?:,[]{}#|>@`\"'%".contains(first) {
return false;
}
if s.contains(": ") || s.contains(" #") || s.ends_with(':') || s.contains('\n') || s.contains('\t') {
return false;
}
!matches!(crate::reader::plain(s), Value::Null | Value::Bool(_) | Value::Number(_))
}
fn scalar(value: &Value) -> String {
match value {
Value::Null => "null".into(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => scrusted_feel::value::format_number(n),
Value::String(s) => {
if plain_ok(s) {
s.to_string()
} else {
serde_json::Value::String(s.to_string()).to_string()
}
}
other => serde_json::Value::String(other.to_text()).to_string(),
}
}
fn key(k: &str) -> String {
if plain_ok(k) || (k.starts_with('$') && !k.contains(": ")) || (k.contains('!') && !k.starts_with('!') && !k.contains(' ')) {
k.to_string()
} else {
serde_json::Value::String(k.to_string()).to_string()
}
}
fn write(value: &Value, indent: usize, out: &mut String, top: bool) {
let pad = " ".repeat(indent);
match value {
Value::Map(map) if !map.is_empty() => {
for (k, v) in map.iter() {
out.push_str(&pad);
out.push_str(&key(k));
out.push(':');
match v {
Value::Map(m) if !m.is_empty() => {
out.push('\n');
write(v, indent + 2, out, false);
}
Value::List(l) if !l.is_empty() => {
out.push('\n');
write(v, indent, out, false);
}
other => {
out.push(' ');
out.push_str(&inline(other));
out.push('\n');
}
}
}
}
Value::List(items) if !items.is_empty() => {
for item in items.iter() {
out.push_str(&pad);
out.push('-');
match item {
Value::Map(m) if !m.is_empty() => {
let mut inner = String::new();
write(item, indent + 2, &mut inner, false);
out.push(' ');
out.push_str(inner.trim_start());
}
Value::List(l) if !l.is_empty() => {
out.push('\n');
write(item, indent + 2, out, false);
}
other => {
out.push(' ');
out.push_str(&inline(other));
out.push('\n');
}
}
}
}
other => {
if !top {
out.push_str(&pad);
}
out.push_str(&inline(other));
out.push('\n');
}
}
}
fn inline(value: &Value) -> String {
match value {
Value::Map(m) if m.is_empty() => "{}".into(),
Value::List(l) if l.is_empty() => "[]".into(),
Value::String(s) if s.contains('\n') && !s.trim_end_matches('\n').contains("\n\n\n") => {
serde_json::Value::String(s.to_string()).to_string()
}
other => scalar(other),
}
}