Skip to content

Commit

Permalink
Add support for multiline string output
Browse files Browse the repository at this point in the history
  • Loading branch information
Pascal Hertleif committed Jul 3, 2019
1 parent a9afa2a commit 0d4d5da
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion src/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pub struct YamlEmitter<'a> {
best_indent: usize,
compact: bool,
escape_all_strings: bool,
multiline_strings: bool,

level: isize,
}
Expand Down Expand Up @@ -119,6 +120,7 @@ impl<'a> YamlEmitter<'a> {
compact: true,
level: -1,
escape_all_strings: false,
multiline_strings: false,
}
}

Expand Down Expand Up @@ -152,6 +154,42 @@ impl<'a> YamlEmitter<'a> {
self.escape_all_strings
}

/// Render strings containing multiple lines in [literal style].
///
/// # Examples
///
/// ```rust
/// use yaml_rust::{Yaml, YamlEmitter, YamlLoader};
///
/// let input = r#"{foo: "bar!\nbar!", baz: 42}"#;
/// let parsed = YamlLoader::load_from_str(input).unwrap();
/// eprintln!("{:?}", parsed);
///
/// let mut output = String::new();
/// # {
/// let mut emitter = YamlEmitter::new(&mut output);
/// emitter.multiline_strings(true);
/// emitter.dump(&parsed[0]).unwrap();
/// # }
///
/// assert_eq!(output.as_str(), "\
/// ---
/// foo: |
/// bar!
/// bar!
/// baz: 42");
/// ```
///
/// [literal style]: https://yaml.org/spec/1.2/spec.html#id2795688
pub fn multiline_strings(&mut self, multiline_strings: bool) {
self.multiline_strings = multiline_strings
}

/// Determine if this emitter will wrap all strings in double-quotes.
pub fn is_multiline_strings(&self) -> bool {
self.multiline_strings
}

pub fn dump(&mut self, doc: &Yaml) -> EmitResult {
// write DocumentStart
writeln!(self.writer, "---")?;
Expand All @@ -176,7 +214,16 @@ impl<'a> YamlEmitter<'a> {
Yaml::Array(ref v) => self.emit_array(v),
Yaml::Hash(ref h) => self.emit_hash(h),
Yaml::String(ref v) => {
if need_quotes(v) | self.escape_all_strings {
if self.multiline_strings && v.contains('\n') {
write!(self.writer, "|")?;
self.level += 1;
for line in v.lines() {
writeln!(self.writer)?;
self.write_indent()?;
write!(self.writer, "{}", line)?;
}
self.level -= 1;
} else if self.escape_all_strings || need_quotes(v) {
escape_str(self.writer, v)?;
} else {
write!(self.writer, "{}", v)?;
Expand Down

0 comments on commit 0d4d5da

Please sign in to comment.