return string rather than writing to buffer

This commit is contained in:
ConnorSkees 2020-04-21 05:25:08 -04:00
parent 93bd950940
commit a339499c9b
5 changed files with 35 additions and 43 deletions

View File

@ -11,12 +11,11 @@ Spec progress as of 2020-04-21:
## Use as library ## Use as library
``` ```
use std::io::{BufWriter, stdout};
use grass::{SassResult, StyleSheet}; use grass::{SassResult, StyleSheet};
fn main() -> SassResult<()> { fn main() -> SassResult<()> {
let mut buf = BufWriter::new(stdout()); let sass = StyleSheet::new("a { b { color: &; } }".to_string())?;
StyleSheet::new("a { color: red; }".to_string(), &mut buf)?; assert_eq!(sass, "a b {\n color: a b;\n}\n");
Ok(()) Ok(())
} }
``` ```
@ -82,7 +81,6 @@ grass input.scss
#![cfg_attr(feature = "nightly", feature(track_caller))] #![cfg_attr(feature = "nightly", feature(track_caller))]
use std::fmt::{self, Display}; use std::fmt::{self, Display};
use std::fs; use std::fs;
use std::io::Write;
use std::iter::Iterator; use std::iter::Iterator;
use std::path::Path; use std::path::Path;
@ -207,17 +205,16 @@ impl StyleSheet {
/// Write CSS to `buf`, constructed from a string /// Write CSS to `buf`, constructed from a string
/// ///
/// ``` /// ```
/// use std::io::{BufWriter, stdout};
/// use grass::{SassResult, StyleSheet}; /// use grass::{SassResult, StyleSheet};
/// ///
/// fn main() -> SassResult<()> { /// fn main() -> SassResult<()> {
/// let mut buf = BufWriter::new(stdout()); /// let sass = StyleSheet::new("a { b { color: red; } }".to_string())?;
/// StyleSheet::new("a { color: red; }".to_string(), &mut buf)?; /// assert_eq!(sass, "a b {\n color: red;\n}\n");
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
#[inline] #[inline]
pub fn new<W: Write>(input: String, buf: &mut W) -> SassResult<()> { pub fn new(input: String) -> SassResult<String> {
let mut map = CodeMap::new(); let mut map = CodeMap::new();
let file = map.add_file("stdin".into(), input); let file = map.add_file("stdin".into(), input);
Css::from_stylesheet(StyleSheet( Css::from_stylesheet(StyleSheet(
@ -231,28 +228,22 @@ impl StyleSheet {
.0, .0,
)) ))
.map_err(|e| raw_to_parse_error(&map, e))? .map_err(|e| raw_to_parse_error(&map, e))?
.pretty_print(buf) .pretty_print()
.map_err(|e| raw_to_parse_error(&map, e))?; .map_err(|e| raw_to_parse_error(&map, e))
Ok(())
} }
/// Write CSS to `buf`, constructed from a path /// Write CSS to `buf`, constructed from a path
/// ///
/// ``` /// ```
/// use std::io::{BufWriter, stdout};
/// use grass::{SassResult, StyleSheet}; /// use grass::{SassResult, StyleSheet};
/// ///
/// fn main() -> SassResult<()> { /// fn main() -> SassResult<()> {
/// let mut buf = BufWriter::new(stdout()); /// let sass = StyleSheet::from_path("input.scss")?;
/// StyleSheet::from_path("input.scss", &mut buf)?;
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
#[inline] #[inline]
pub fn from_path<P: AsRef<Path> + Into<String> + Clone, W: Write>( pub fn from_path<P: AsRef<Path> + Into<String> + Clone>(p: P) -> SassResult<String> {
p: P,
buf: &mut W,
) -> SassResult<()> {
let mut map = CodeMap::new(); let mut map = CodeMap::new();
let file = map.add_file(p.clone().into(), String::from_utf8(fs::read(p.as_ref())?)?); let file = map.add_file(p.clone().into(), String::from_utf8(fs::read(p.as_ref())?)?);
Css::from_stylesheet(StyleSheet( Css::from_stylesheet(StyleSheet(
@ -266,9 +257,8 @@ impl StyleSheet {
.0, .0,
)) ))
.map_err(|e| raw_to_parse_error(&map, e))? .map_err(|e| raw_to_parse_error(&map, e))?
.pretty_print(buf) .pretty_print()
.map_err(|e| raw_to_parse_error(&map, e))?; .map_err(|e| raw_to_parse_error(&map, e))
Ok(())
} }
pub(crate) fn export_from_path<P: AsRef<Path> + Into<String> + Clone>( pub(crate) fn export_from_path<P: AsRef<Path> + Into<String> + Clone>(

View File

@ -1,4 +1,4 @@
use std::io::{stdout, BufWriter}; use std::io::{stdout, BufWriter, Write};
use clap::{App, Arg}; use clap::{App, Arg};
@ -64,10 +64,16 @@ fn main() {
let mut stdout = BufWriter::new(stdout()); let mut stdout = BufWriter::new(stdout());
if let Some(inputs) = matches.values_of("INPUT") { if let Some(inputs) = matches.values_of("INPUT") {
for name in inputs { for name in inputs {
StyleSheet::from_path(name, &mut stdout).unwrap_or_else(|e| { stdout
.write_all(
StyleSheet::from_path(name)
.unwrap_or_else(|e| {
eprintln!("{}", e); eprintln!("{}", e);
std::process::exit(1) std::process::exit(1)
}); })
.as_bytes(),
)
.unwrap();
} }
} }
} }

View File

@ -123,14 +123,16 @@ impl Css {
Ok(self) Ok(self)
} }
pub fn pretty_print<W: Write>(self, buf: &mut W) -> SassResult<()> { pub fn pretty_print(self) -> SassResult<String> {
let mut string = Vec::new(); let mut string = Vec::new();
self._inner_pretty_print(&mut string, 0)?; self._inner_pretty_print(&mut string, 0)?;
if string.iter().any(|s| !s.is_ascii()) { if string.iter().any(|s| !s.is_ascii()) {
writeln!(buf, "@charset \"UTF-8\";")?; return Ok(format!(
"@charset \"UTF-8\";\n{}",
String::from_utf8(string)?
));
} }
write!(buf, "{}", String::from_utf8(string).unwrap())?; Ok(String::from_utf8(string)?)
Ok(())
} }
fn _inner_pretty_print(self, buf: &mut Vec<u8>, nesting: usize) -> SassResult<()> { fn _inner_pretty_print(self, buf: &mut Vec<u8>, nesting: usize) -> SassResult<()> {

View File

@ -11,12 +11,11 @@ macro_rules! test_import {
let mut f = Builder::new().rand_bytes(0).prefix("").suffix($name).tempfile_in("").unwrap(); let mut f = Builder::new().rand_bytes(0).prefix("").suffix($name).tempfile_in("").unwrap();
write!(f, $content).unwrap(); write!(f, $content).unwrap();
)* )*
let mut buf = Vec::new(); let sass = StyleSheet::new($input.to_string())
StyleSheet::new($input.to_string(), &mut buf)
.expect(concat!("failed to parse on ", $input)); .expect(concat!("failed to parse on ", $input));
assert_eq!( assert_eq!(
String::from($output), String::from($output),
String::from_utf8(buf).expect("produced invalid utf8") sass
); );
} }
} }

View File

@ -7,14 +7,11 @@ macro_rules! test {
#[test] #[test]
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn $func() { fn $func() {
let mut buf = Vec::new(); let sass = grass::StyleSheet::new($input.to_string())
grass::StyleSheet::new($input.to_string(), &mut buf)
.expect(concat!("failed to parse on ", $input)); .expect(concat!("failed to parse on ", $input));
// .print_as_css()
// .expect(concat!("failed to pretty print on ", $input));
assert_eq!( assert_eq!(
String::from($input), String::from($input),
String::from_utf8(buf).expect("produced invalid utf8") sass
); );
} }
}; };
@ -23,12 +20,11 @@ macro_rules! test {
#[test] #[test]
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn $func() { fn $func() {
let mut buf = Vec::new(); let sass = grass::StyleSheet::new($input.to_string())
grass::StyleSheet::new($input.to_string(), &mut buf)
.expect(concat!("failed to parse on ", $input)); .expect(concat!("failed to parse on ", $input));
assert_eq!( assert_eq!(
String::from($output), String::from($output),
String::from_utf8(buf).expect("produced invalid utf8") sass
); );
} }
}; };
@ -43,8 +39,7 @@ macro_rules! error {
#[test] #[test]
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn $func() { fn $func() {
let mut buf = Vec::new(); match grass::StyleSheet::new($input.to_string()) {
match grass::StyleSheet::new($input.to_string(), &mut buf) {
Ok(..) => panic!("did not fail"), Ok(..) => panic!("did not fail"),
Err(e) => assert_eq!($err, e.to_string() Err(e) => assert_eq!($err, e.to_string()
.chars() .chars()