forked from pydsigner/python-lightningcss
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
199 lines (185 loc) · 6.81 KB
/
lib.rs
File metadata and controls
199 lines (185 loc) · 6.81 KB
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
use std::collections::HashSet;
use std::path::Path;
use pyo3::exceptions::{PyValueError, PyIOError};
use pyo3::prelude::*;
use browserslist::Error as BrowserslistError;
use lightningcss::bundler::{Bundler, FileProvider, BundleErrorKind};
use lightningcss::stylesheet::{
MinifyOptions, ParserFlags, ParserOptions, PrinterOptions, StyleSheet,
};
use lightningcss::targets::{Browsers, Targets};
/// Processes provided CSS and returns as a string.
///
/// If `filename` is supplied, it will be used in parser error messages.
/// If `error_recovery` is True, broken CSS will be omitted rather than
/// producing a parse error. Enable with caution!
/// If `parser_flags` is supplied, it should be a flag created by
/// `calc_parser_flags()`. See that function for more details.
/// If `unused_symbols` is supplied, it should be a set of known unused
/// symbols, like class names, ids, or keyframe names, to be removed from the
/// output. Note that symbols should be specified in bare form, i.e.
/// `unused_symbols={'a', 'b'}`, not `unused_symbols={'.a', '#b'}`, and will
/// remove both ids and classes if they share a name. Use with caution!
/// If `browsers_list` is specified, it should be a list of browserslist
/// targets to be used to determine automatic prefixing and transpilation. If
/// it is not specified, no prefixing/transpilation will occur.
/// If `minify` is True, the final output will be minified. Otherwise, it will
/// be pretty-printed.
#[pyfunction]
#[pyo3(signature = (
code,
/,
filename="",
error_recovery=false,
parser_flags=0,
unused_symbols=None,
browsers_list=None,
minify=true,
))]
fn process_stylesheet(code: &str,
filename: &str,
error_recovery: bool,
parser_flags: u8,
unused_symbols: Option<HashSet<String>>,
browsers_list: Option<Vec<String>>,
minify: bool) -> PyResult<String> {
let targets = match mk_targets(browsers_list) {
Ok(val) => val,
Err(e) => {return Err(PyValueError::new_err(format!("Validation of browsers_list failed: {}", e.to_string())))}
};
let mut stylesheet = match StyleSheet::parse(code, mk_parser_options(filename, error_recovery, parser_flags)) {
Ok(val) => val,
Err(e) => {return Err(PyValueError::new_err(format!("Parsing stylesheet failed: {}", e.to_string())))}
};
match stylesheet.minify(mk_minify_options(unused_symbols, &targets)) {
Ok(_) => {}
Err(e) => {return Err(PyValueError::new_err(format!("Minifying stylesheet failed: {}", e.to_string())));}
}
return match stylesheet.to_css(mk_printer_options(&targets, minify)) {
Ok(val) => Ok(val.code),
Err(e) => Err(PyValueError::new_err(format!("Printing stylesheet failed: {}", e.to_string())))
};
}
/// Calculates parser_flags for process_stylesheet().
#[pyfunction]
#[pyo3(signature = (nesting=false, custom_media=false, deep_selector_combinator=false))]
fn calc_parser_flags(nesting: bool, custom_media: bool, deep_selector_combinator: bool) -> u8 {
let mut flags = 0;
if nesting { flags |= 1 << 0; }
if custom_media { flags |= 1 << 1; }
if deep_selector_combinator { flags |= 1 << 2; }
return flags;
}
fn mk_parser_options(filename: &str,
error_recovery: bool,
parser_flags: u8) -> ParserOptions {
return ParserOptions {
filename: filename.to_string(),
error_recovery: error_recovery,
flags: ParserFlags::from_bits_truncate(parser_flags),
..Default::default()
};
}
fn mk_targets(browsers_list: Option<Vec<String>>) -> Result<Targets, BrowserslistError> {
match browsers_list {
Some(bl) if !bl.is_empty() => Browsers::from_browserslist(bl).map(Targets::from),
_ => Ok(Targets::default()),
}
}
fn mk_minify_options(unused_symbols: Option<HashSet<String>>,
targets: &Targets) -> MinifyOptions {
let mut options = MinifyOptions {targets: *targets, ..Default::default()};
match unused_symbols {
Some(val) => { options.unused_symbols = val; }
None => {}
}
return options;
}
fn mk_printer_options<'a>(targets: &Targets,
minify: bool) -> PrinterOptions<'a> {
return PrinterOptions {
minify: minify,
targets: *targets,
..PrinterOptions::default()
};
}
/// Bundles a CSS file and returns as a string.
#[pyfunction]
#[pyo3(signature = (
path="",
/,
error_recovery=false,
parser_flags=0,
unused_symbols=None,
browsers_list=None,
minify=true,
))]
fn bundle_css(
path: &str,
error_recovery: bool,
parser_flags: u8,
unused_symbols: Option<HashSet<String>>,
browsers_list: Option<Vec<String>>,
minify: bool,
) -> PyResult<String> {
let fs = FileProvider::new();
let mut bundler = Bundler::new(
&fs,
None,
ParserOptions {
error_recovery: error_recovery,
flags: ParserFlags::from_bits_truncate(parser_flags),
..Default::default()
},
);
let mut stylesheet = match bundler.bundle(Path::new(path)) {
Ok(s) => s,
Err(e) => {
let message = e.to_string();
match e.kind {
// Resolver errors, probably related to file I/O
BundleErrorKind::ResolverError(_) => {
return Err(PyIOError::new_err(format!("Bundling failed: {}", message)));
}
// Parser and logical errors
_ => {
return Err(PyValueError::new_err(format!("Bundling failed: {}", message)));
}
}
}
};
let targets = match mk_targets(browsers_list) {
Ok(val) => val,
Err(e) => {
return Err(PyValueError::new_err(format!(
"browsers_list failed validation: {}",
e.to_string()
)))
}
};
match stylesheet.minify(mk_minify_options(unused_symbols, &targets)) {
Ok(_) => {}
Err(e) => {
return Err(PyValueError::new_err(format!(
"Minifying stylesheet failed: {}",
e.to_string()
)));
}
}
return match stylesheet.to_css(mk_printer_options(&targets, minify)) {
Ok(val) => Ok(val.code),
Err(e) => Err(PyValueError::new_err(format!(
"Printing stylesheet failed: {}",
e.to_string()
))),
};
}
/// A python wrapper for core functionality of lightningcss.
#[pymodule]
#[pyo3(name = "lightningcss")]
fn pylightningcss(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(process_stylesheet, m)?)?;
m.add_function(wrap_pyfunction!(calc_parser_flags, m)?)?;
m.add_function(wrap_pyfunction!(bundle_css, m)?)?;
Ok(())
}