Skip to content

Commit

Permalink
Modify yaml2json-rs to take &str instead of String
Browse files Browse the repository at this point in the history
  • Loading branch information
nessex committed Jul 25, 2021
1 parent 0b4d01d commit 50dee52
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 65 deletions.
8 changes: 5 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/yaml-split/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "yaml-split"
description = "provides an iterator over individual YAML documents in a YAML file or stream"
version = "0.2.8"
version = "0.3.0"
authors = ["Nathan Essex <nathan@essex.id.au>"]
edition = "2018"
license = "Apache-2.0 OR MIT"
Expand Down
24 changes: 12 additions & 12 deletions crates/yaml-split/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ mod tests {
let mut doc_iter = DocumentIterator::new(reader);

let next = doc_iter.next().unwrap().unwrap();
assert_eq!(next.as_str(), "abc: def");
assert_eq!(&next, "abc: def");

let fin = doc_iter.next().is_none();
assert_eq!(true, fin);
Expand All @@ -314,7 +314,7 @@ abc: def

let next = doc_iter.next().unwrap().unwrap();
assert_eq!(
next.as_str(),
&next,
r#"
---
abc: def
Expand All @@ -338,7 +338,7 @@ abc: def

let next = doc_iter.next().unwrap().unwrap();
assert_eq!(
next.as_str(),
&next,
r#"
%YAML 1.2
---
Expand All @@ -361,11 +361,11 @@ aaa: bbb
let mut doc_iter = DocumentIterator::new(reader);

let mut next = doc_iter.next().unwrap().unwrap();
assert_eq!(next.as_str(), "abc: def\n");
assert_eq!(&next, "abc: def\n");

next = doc_iter.next().unwrap().unwrap();
assert_eq!(
next.as_str(),
&next,
r#"---
aaa: bbb
"#
Expand All @@ -392,7 +392,7 @@ aaa: bbb

let mut next = doc_iter.next().unwrap().unwrap();
assert_eq!(
next.as_str(),
&next,
r#"%YAML 1.2
---
abc: def
Expand All @@ -401,7 +401,7 @@ abc: def

next = doc_iter.next().unwrap().unwrap();
assert_eq!(
next.as_str(),
&next,
r#"
%YAML 1.2
---
Expand Down Expand Up @@ -434,7 +434,7 @@ final: "document"

let mut next = doc_iter.next().unwrap().unwrap();
assert_eq!(
next.as_str(),
&next,
r#"%YAML 1.2
---
abc: def
Expand All @@ -443,29 +443,29 @@ abc: def

next = doc_iter.next().unwrap().unwrap();
assert_eq!(
next.as_str(),
&next,
r#"---
%YAML: "not a real directive"
"#
);
next = doc_iter.next().unwrap().unwrap();
assert_eq!(
next.as_str(),
&next,
r#"---
aaa: bbb
"#
);

next = doc_iter.next().unwrap().unwrap();
assert_eq!(
next.as_str(),
&next,
r#"---
"#
);

next = doc_iter.next().unwrap().unwrap();
assert_eq!(
next.as_str(),
&next,
r#"---
final: "document"
"#
Expand Down
6 changes: 3 additions & 3 deletions crates/yaml2json-rs-bin/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "yaml2json-rs-bin"
description = "Command line utility to convert YAML files to JSON."
version = "0.2.8"
version = "0.3.0"
authors = ["Nathan Essex <nathan@essex.id.au>"]
edition = "2018"
license = "Apache-2.0 OR MIT"
Expand All @@ -19,5 +19,5 @@ path = "src/main.rs"
[dependencies]
clap = "2.33.3"
anyhow = "1.0.38"
yaml-split = { path = "../yaml-split", version = "=0.2.8" }
yaml2json-rs = { path = "../yaml2json-rs", version = "=0.2.8" }
yaml-split = { path = "../yaml-split", version = "=0.3.0" }
yaml2json-rs = { path = "../yaml2json-rs", version = "=0.3.0" }
36 changes: 14 additions & 22 deletions crates/yaml2json-rs-bin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use std::{io, process};
use clap::{App, Arg};

use std::error::Error;
use std::fmt::Display;
use yaml2json_rs::{Style, Yaml2Json};
use yaml_split::{DocumentIterator, YamlSplitError};

Expand Down Expand Up @@ -63,21 +64,17 @@ impl ErrorPrinter {
}
}

fn print(&mut self, err: impl Error) {
self.print_string(err.to_string());
}

fn print_string(&mut self, s: String) {
fn print(&mut self, d: impl Display) {
match self.print_style {
ErrorStyle::SILENT => {}
ErrorStyle::STDERR => write_or_exit(&mut self.stderr, format!("{}\n", s).as_str()),
ErrorStyle::STDERR => write_or_exit(&mut self.stderr, &format!("{}\n", d)),
ErrorStyle::JSON => {
let s = if self.pretty {
format!("{{\n \"yaml-error\": \"{}\"\n}}\n", s)
format!("{{\n \"yaml-error\": \"{}\"\n}}\n", d)
} else {
format!("{{\"yaml-error\":\"{}\"}}\n", s)
format!("{{\"yaml-error\":\"{}\"}}\n", d)
};
write_or_exit(&mut self.stdout, s.as_str());
write_or_exit(&mut self.stdout, &s);
}
};
}
Expand Down Expand Up @@ -109,7 +106,7 @@ fn write(yaml2json: &Yaml2Json, ep: &mut ErrorPrinter, read: impl Read) {
printed_last = false;

match res {
Ok(doc) => match yaml2json.document_to_writer(doc, &mut stdout) {
Ok(doc) => match yaml2json.document_to_writer(&doc, &mut stdout) {
Ok(_) => printed_last = true,
Err(e) => ep.print(e),
},
Expand Down Expand Up @@ -149,10 +146,10 @@ fn main() {
.takes_value(true)
.short("e")
.long("error")
.default_value(default_err_style.as_str())
.possible_value(ErrorStyle::SILENT.to_string().as_str())
.possible_value(ErrorStyle::STDERR.to_string().as_str())
.possible_value(ErrorStyle::JSON.to_string().as_str())
.default_value(&default_err_style)
.possible_value(&ErrorStyle::SILENT.to_string())
.possible_value(&ErrorStyle::STDERR.to_string())
.possible_value(&ErrorStyle::JSON.to_string())
)
.arg(
Arg::with_name("file")
Expand All @@ -179,19 +176,14 @@ fn main() {
let path = Path::new(f);

if !path.exists() {
ep.print_string(format!(
"file {} does not exist",
path.display().to_string()
));
ep.print(format!("file {} does not exist", path.display()));
} else if path.is_dir() {
ep.print_string(format!("{} is a directory", path.display().to_string()))
ep.print(format!("{} is a directory", path.display()))
} else {
let file = File::open(f);

match file {
Ok(f) => {
write(&yaml2json, &mut ep, f);
}
Ok(f) => write(&yaml2json, &mut ep, f),
Err(e) => ep.print(e),
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/yaml2json-rs/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "yaml2json-rs"
description = "Convert YAML documents to JSON"
version = "0.2.8"
version = "0.3.0"
authors = ["Nathan Essex <nathan@essex.id.au>"]
edition = "2018"
license = "Apache-2.0 OR MIT"
Expand Down
40 changes: 17 additions & 23 deletions crates/yaml2json-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub enum Style {
/// use yaml2json_rs::{Yaml2Json, Style};
///
/// let y2j = Yaml2Json::new(Style::COMPACT);
/// let input = String::from("hello: world");
/// let input = "hello: world";
/// let output = y2j.document_to_string(input).unwrap();
///
/// assert_eq!(output, r#"{"hello":"world"}"#);
Expand All @@ -79,7 +79,7 @@ pub enum Style {
/// use std::io;
///
/// let y2j = Yaml2Json::new(Style::COMPACT);
/// let input = String::from("hello: world");
/// let input = "hello: world";
/// let mut stdout = io::stdout();
///
/// y2j.document_to_writer(input, &mut stdout);
Expand All @@ -102,18 +102,18 @@ impl Yaml2Json {
Self { style }
}

/// `document_to_string()` takes a YAML document String and converts it to a JSON String.
/// `document_to_string()` takes a YAML document &str and converts it to a JSON String.
/// ```
/// use yaml2json_rs::{Yaml2Json, Style};
///
/// let y2j = Yaml2Json::new(Style::COMPACT);
/// let input = String::from("hello: world");
/// let input = "hello: world";
/// let output = y2j.document_to_string(input).unwrap();
///
/// assert_eq!(output, r#"{"hello":"world"}"#);
/// ```
pub fn document_to_string(&self, document: String) -> Result<String, Yaml2JsonError> {
let s: serde_json::Value = serde_yaml::from_str(document.as_str())?;
pub fn document_to_string(&self, document: &str) -> Result<String, Yaml2JsonError> {
let s: serde_json::Value = serde_yaml::from_str(document)?;

let res = match self.style {
COMPACT => serde_json::to_string(&s),
Expand All @@ -134,7 +134,7 @@ impl Yaml2Json {
/// use std::io;
///
/// let y2j = Yaml2Json::new(Style::COMPACT);
/// let input = String::from("hello: world");
/// let input = "hello: world";
/// let mut stdout = io::stdout();
///
/// y2j.document_to_writer(input, &mut stdout);
Expand All @@ -143,10 +143,10 @@ impl Yaml2Json {
/// ```
pub fn document_to_writer<W: io::Write>(
&self,
document: String,
document: &str,
w: &mut W,
) -> Result<(), Yaml2JsonError> {
let s: serde_json::Value = serde_yaml::from_str(document.as_str())?;
let s: serde_json::Value = serde_yaml::from_str(document)?;

let res = match self.style {
PRETTY => serde_json::to_writer_pretty(w, &s),
Expand All @@ -168,26 +168,23 @@ mod tests {
#[test]
fn document_to_string_compact() {
let yaml2json = Yaml2Json::new(Style::COMPACT);
let input = String::new()
+ r#"
let input = r#"
---
abc: def
"#;
let expected = String::new() + r#"{"abc":"def"}"#;
let expected = r#"{"abc":"def"}"#;
let res = yaml2json.document_to_string(input).unwrap();
assert_eq!(expected, res);
}

#[test]
fn document_to_string_pretty() {
let yaml2json = Yaml2Json::new(Style::PRETTY);
let input = String::new()
+ r#"
let input = r#"
---
abc: def
"#;
let expected = String::new()
+ r#"{
let expected = r#"{
"abc": "def"
}"#;
let res = yaml2json.document_to_string(input).unwrap();
Expand All @@ -197,12 +194,11 @@ abc: def
#[test]
fn document_to_writer_compact() {
let yaml2json = Yaml2Json::new(Style::COMPACT);
let input = String::new()
+ r#"
let input = r#"
---
abc: def
"#;
let expected = String::new() + r#"{"abc":"def"}"#;
let expected = r#"{"abc":"def"}"#;

let mut buf = Cursor::new(Vec::<u8>::new());
yaml2json.document_to_writer(input, buf.get_mut()).unwrap();
Expand All @@ -214,13 +210,11 @@ abc: def
#[test]
fn document_to_writer_pretty() {
let yaml2json = Yaml2Json::new(Style::PRETTY);
let input = String::new()
+ r#"
let input = r#"
---
abc: def
"#;
let expected = String::new()
+ r#"{
let expected = r#"{
"abc": "def"
}"#;

Expand Down

0 comments on commit 50dee52

Please sign in to comment.