Skip to content

Commit

Permalink
Converted stylesheet from a String to PathBuf
Browse files Browse the repository at this point in the history
  • Loading branch information
michabay05 committed Dec 26, 2024
1 parent 502591a commit eae24bd
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 10 deletions.
19 changes: 11 additions & 8 deletions crates/resvg/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -551,14 +551,17 @@ fn parse_args() -> Result<Args, String> {
}
};

let style_sheet = match args.style_sheet.as_ref() {
Some(p) => Some(
std::fs::read(&p)
.ok()
.and_then(|s| std::str::from_utf8(&s).ok().map(|s| s.to_string()))
.ok_or("failed to read stylesheet".to_string())?,
),
None => None,
let style_sheet = match args.style_sheet {
Some(ref v) => Some(v.clone()),
None => {
if let InputFrom::File(ref input) = in_svg {
// Get input file absolute directory.
std::fs::canonicalize(input)
.ok()
} else {
None
}
}
};

let usvg = usvg::Options {
Expand Down
19 changes: 18 additions & 1 deletion crates/usvg/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ pub enum Error {

/// Failed to parse an SVG data.
ParsingFailed(roxmltree::Error),

/// Failed to read stylesheet
FailedToReadStylesheet,
}

impl From<roxmltree::Error> for Error {
Expand All @@ -70,6 +73,9 @@ impl std::fmt::Display for Error {
Error::ParsingFailed(ref e) => {
write!(f, "SVG data parsing failed cause {}", e)
}
Error::FailedToReadStylesheet => {
write!(f, "failed to read stylesheet")
}
}
}
}
Expand Down Expand Up @@ -120,7 +126,18 @@ impl crate::Tree {

/// Parses `Tree` from `roxmltree::Document`.
pub fn from_xmltree(doc: &roxmltree::Document, opt: &Options) -> Result<Self, Error> {
let doc = svgtree::Document::parse_tree(doc, opt.style_sheet.as_deref())?;
let content;
let style_sheet = match opt.style_sheet.as_ref() {
Some(p) => Some({
content = std::fs::read(&p)
.map_err(|_| Error::FailedToReadStylesheet)?;
std::str::from_utf8(&content)
.map_err(|_| Error::NotAnUtf8Str)?
}),
None => None,
};

let doc = svgtree::Document::parse_tree(doc, style_sheet)?;
self::converter::convert_doc(&doc, opt)
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/usvg/src/parser/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ pub struct Options<'a> {
pub fontdb: Arc<fontdb::Database>,
/// A CSS stylesheet that should be injected into the SVG. Can be used to overwrite
/// certain attributes.
pub style_sheet: Option<String>,
pub style_sheet: Option<std::path::PathBuf>,
}

impl Default for Options<'_> {
Expand Down

0 comments on commit eae24bd

Please sign in to comment.