-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathlib.rs
207 lines (191 loc) · 7.15 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
//! Python bindings for css-inline
#![warn(
clippy::pedantic,
clippy::doc_markdown,
clippy::redundant_closure,
clippy::explicit_iter_loop,
clippy::match_same_arms,
clippy::needless_borrow,
clippy::print_stdout,
clippy::integer_arithmetic,
clippy::cast_possible_truncation,
clippy::unwrap_used,
clippy::map_unwrap_or,
clippy::trivially_copy_pass_by_ref,
clippy::needless_pass_by_value,
missing_debug_implementations,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
variant_size_differences,
rust_2018_idioms,
rust_2018_compatibility
)]
use css_inline as rust_inline;
use pyo3::{create_exception, exceptions, prelude::*, types::PyList, wrap_pyfunction};
use rayon::prelude::*;
use std::borrow::Cow;
const INLINE_ERROR_DOCSTRING: &str = "An error that can occur during CSS inlining";
create_exception!(css_inline, InlineError, exceptions::PyValueError);
struct InlineErrorWrapper(rust_inline::InlineError);
impl From<InlineErrorWrapper> for PyErr {
fn from(error: InlineErrorWrapper) -> Self {
match error.0 {
rust_inline::InlineError::IO(error) => InlineError::new_err(error.to_string()),
rust_inline::InlineError::Network(error) => InlineError::new_err(error.to_string()),
rust_inline::InlineError::ParseError(message) => {
InlineError::new_err(message.to_string())
}
rust_inline::InlineError::MissingStyleSheet { .. } => {
InlineError::new_err(error.0.to_string())
}
}
}
}
struct UrlError(url::ParseError);
impl From<UrlError> for PyErr {
fn from(error: UrlError) -> Self {
exceptions::PyValueError::new_err(error.0.to_string())
}
}
fn parse_url(url: Option<String>) -> PyResult<Option<url::Url>> {
Ok(if let Some(url) = url {
Some(url::Url::parse(url.as_str()).map_err(UrlError)?)
} else {
None
})
}
/// CSSInliner(inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None, styles_as_attributes=False)
///
/// Customizable CSS inliner.
#[pyclass]
#[pyo3(
text_signature = "(inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None, styles_as_attributes=False)"
)]
struct CSSInliner {
inner: rust_inline::CSSInliner<'static>,
}
#[pymethods]
impl CSSInliner {
#[new]
fn new(
inline_style_tags: Option<bool>,
remove_style_tags: Option<bool>,
base_url: Option<String>,
load_remote_stylesheets: Option<bool>,
extra_css: Option<String>,
styles_as_attributes: Option<bool>,
) -> PyResult<Self> {
let options = rust_inline::InlineOptions {
inline_style_tags: inline_style_tags.unwrap_or(true),
remove_style_tags: remove_style_tags.unwrap_or(false),
base_url: parse_url(base_url)?,
load_remote_stylesheets: load_remote_stylesheets.unwrap_or(true),
extra_css: extra_css.map(Cow::Owned),
styles_as_attributes: styles_as_attributes.unwrap_or(false),
};
Ok(CSSInliner {
inner: rust_inline::CSSInliner::new(options),
})
}
/// inline(html)
///
/// Inline CSS in the given HTML document
#[pyo3(text_signature = "(html)")]
fn inline(&self, html: &str) -> PyResult<String> {
Ok(self.inner.inline(html).map_err(InlineErrorWrapper)?)
}
/// inline_many(htmls)
///
/// Inline CSS in multiple HTML documents
#[pyo3(text_signature = "(htmls)")]
fn inline_many(&self, htmls: &PyList) -> PyResult<Vec<String>> {
inline_many_impl(&self.inner, htmls)
}
}
/// inline(html, inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None, styles_as_attributes=False)
///
/// Inline CSS in the given HTML document
#[pyfunction]
#[pyo3(
text_signature = "(html, inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None, styles_as_attributes=False)"
)]
fn inline(
html: &str,
inline_style_tags: Option<bool>,
remove_style_tags: Option<bool>,
base_url: Option<String>,
load_remote_stylesheets: Option<bool>,
extra_css: Option<&str>,
styles_as_attributes: Option<bool>,
) -> PyResult<String> {
let options = rust_inline::InlineOptions {
inline_style_tags: inline_style_tags.unwrap_or(true),
remove_style_tags: remove_style_tags.unwrap_or(false),
base_url: parse_url(base_url)?,
load_remote_stylesheets: load_remote_stylesheets.unwrap_or(true),
extra_css: extra_css.map(Cow::Borrowed),
styles_as_attributes: styles_as_attributes.unwrap_or(false),
};
let inliner = rust_inline::CSSInliner::new(options);
Ok(inliner.inline(html).map_err(InlineErrorWrapper)?)
}
/// inline_many(htmls, inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None, styles_as_attributes=False)
///
/// Inline CSS in multiple HTML documents
#[pyfunction]
#[pyo3(
text_signature = "(htmls, inline_style_tags=True, remove_style_tags=False, base_url=None, load_remote_stylesheets=True, extra_css=None, styles_as_attributes=False)"
)]
fn inline_many(
htmls: &PyList,
inline_style_tags: Option<bool>,
remove_style_tags: Option<bool>,
base_url: Option<String>,
load_remote_stylesheets: Option<bool>,
extra_css: Option<&str>,
styles_as_attributes: Option<bool>,
) -> PyResult<Vec<String>> {
let options = rust_inline::InlineOptions {
inline_style_tags: inline_style_tags.unwrap_or(true),
remove_style_tags: remove_style_tags.unwrap_or(false),
base_url: parse_url(base_url)?,
load_remote_stylesheets: load_remote_stylesheets.unwrap_or(true),
extra_css: extra_css.map(Cow::Borrowed),
styles_as_attributes: styles_as_attributes.unwrap_or(false),
};
let inliner = rust_inline::CSSInliner::new(options);
inline_many_impl(&inliner, htmls)
}
fn inline_many_impl(
inliner: &rust_inline::CSSInliner<'_>,
htmls: &PyList,
) -> PyResult<Vec<String>> {
// Extract strings from the list. It will fail if there is any non-string value
let extracted: Result<Vec<_>, _> = htmls.iter().map(pyo3::PyAny::extract::<&str>).collect();
let output: Result<Vec<_>, _> = extracted?
.par_iter()
.map(|html| inliner.inline(html))
.collect();
Ok(output.map_err(InlineErrorWrapper)?)
}
#[allow(dead_code)]
mod build {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
/// Fast CSS inlining written in Rust
#[pymodule]
fn css_inline(py: Python<'_>, module: &PyModule) -> PyResult<()> {
module.add_class::<CSSInliner>()?;
module.add_wrapped(wrap_pyfunction!(inline))?;
module.add_wrapped(wrap_pyfunction!(inline_many))?;
let inline_error = py.get_type::<InlineError>();
inline_error.setattr("__doc__", INLINE_ERROR_DOCSTRING)?;
module.add("InlineError", inline_error)?;
// Wait until `pyo3_built` is updated
#[allow(deprecated)]
module.add("__build__", pyo3_built::pyo3_built!(py, build))?;
Ok(())
}