css-inline 0.20.2

High-performance library for inlining CSS into HTML 'style' attributes
Documentation
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#[cfg(not(feature = "cli"))]
fn main() {
    eprintln!("`css-inline` CLI is only available with the `cli` feature");
    std::process::exit(1);
}

#[cfg(feature = "cli")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    use core::fmt;
    use css_inline::{CSSInliner, DefaultStylesheetResolver, InlineOptions};
    use rayon::prelude::*;
    use std::{
        borrow::Cow,
        env,
        error::Error,
        ffi::OsString,
        fmt::Write as FmtWrite,
        fs::{read_to_string, File},
        io::{self, Read, Write},
        path::Path,
        str::FromStr,
        sync::{
            atomic::{AtomicI32, Ordering},
            Arc,
        },
    };

    fn parse_url(url: Option<&str>) -> Result<Option<url::Url>, url::ParseError> {
        Ok(if let Some(url) = url {
            Some(url::Url::parse(url)?)
        } else {
            None
        })
    }

    #[derive(Debug)]
    struct ParseError {
        message: String,
    }

    impl fmt::Display for ParseError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", self.message)
        }
    }

    impl Error for ParseError {}

    struct ParsedArgs {
        help: bool,
        version: bool,
        files: Vec<String>,
        inline_style_tags: bool,
        keep_style_tags: bool,
        keep_link_tags: bool,
        keep_at_rules: bool,
        base_url: Option<String>,
        extra_css: Option<String>,
        extra_css_files: Vec<String>,
        output_filename_prefix: Option<OsString>,
        load_remote_stylesheets: bool,
        #[cfg(feature = "stylesheet-cache")]
        cache_size: Option<usize>,
        minify_css: bool,
        remove_inlined_selectors: bool,
        apply_width_attributes: bool,
        apply_height_attributes: bool,
    }

    impl Default for ParsedArgs {
        fn default() -> Self {
            Self {
                help: false,
                version: false,
                files: Vec::new(),
                inline_style_tags: true,
                keep_style_tags: false,
                keep_link_tags: false,
                keep_at_rules: false,
                base_url: None,
                extra_css: None,
                extra_css_files: Vec::new(),
                output_filename_prefix: None,
                load_remote_stylesheets: false,
                #[cfg(feature = "stylesheet-cache")]
                cache_size: None,
                minify_css: false,
                remove_inlined_selectors: false,
                apply_width_attributes: false,
                apply_height_attributes: false,
            }
        }
    }

    #[cfg(feature = "stylesheet-cache")]
    macro_rules! if_cfg_feature_stylesheet_cache {
        ($val:expr) => {
            $val
        };
    }

    #[cfg(not(feature = "stylesheet-cache"))]
    macro_rules! if_cfg_feature_stylesheet_cache {
        // Empty string that won't match
        ($val:expr) => {
            ""
        };
    }

    fn requires_value(flag: &str) -> bool {
        matches!(
            flag,
            "inline-style-tags"
                | "base-url"
                | "extra-css"
                | "extra-css-file"
                | "output-filename-prefix"
                | if_cfg_feature_stylesheet_cache!("cache-size")
        )
    }

    fn parse_value<T>(value: &str, flag: &str) -> Result<T, ParseError>
    where
        T: FromStr,
        T::Err: fmt::Display,
    {
        value.parse::<T>().map_err(|e| ParseError {
            message: format!("Failed to parse value '{value}' for flag '{flag}': {e}"),
        })
    }

    fn handle_flag_with_value(
        parsed: &mut ParsedArgs,
        flag: &str,
        value: &str,
    ) -> Result<(), ParseError> {
        match flag {
            "inline-style-tags" => parsed.inline_style_tags = parse_value(value, flag)?,
            "load-remote-stylesheets" => parsed.load_remote_stylesheets = parse_value(value, flag)?,
            "base-url" => parsed.base_url = Some(value.to_string()),
            "extra-css" => parsed.extra_css = Some(value.to_string()),
            "extra-css-file" => parsed.extra_css_files.push(value.to_string()),
            "output-filename-prefix" => {
                parsed.output_filename_prefix = Some(value.to_string().into());
            }
            #[cfg(feature = "stylesheet-cache")]
            "cache-size" => parsed.cache_size = Some(parse_value(value, flag)?),
            _ => {
                return Err(ParseError {
                    message: format!("Unknown flag: --{flag}"),
                })
            }
        }
        Ok(())
    }

    fn handle_boolean_flag(parsed: &mut ParsedArgs, flag: &str) -> Result<(), ParseError> {
        match flag {
            "help" | "h" => parsed.help = true,
            "version" | "v" => parsed.version = true,
            "keep-style-tags" => parsed.keep_style_tags = true,
            "keep-link-tags" => parsed.keep_link_tags = true,
            "keep-at-rules" => parsed.keep_at_rules = true,
            "minify-css" => parsed.minify_css = true,
            "remove-inlined-selectors" => parsed.remove_inlined_selectors = true,
            "apply-width-attributes" => parsed.apply_width_attributes = true,
            "apply-height-attributes" => parsed.apply_height_attributes = true,
            _ => {
                return Err(ParseError {
                    message: format!("Unknown flag: {flag}"),
                })
            }
        }
        Ok(())
    }

    fn combine_extra_css(
        extra_css: Option<String>,
        extra_css_files: Vec<String>,
    ) -> Result<Option<String>, Box<dyn std::error::Error>> {
        let mut buffer = extra_css.unwrap_or_default();

        if !buffer.is_empty() {
            buffer.push('\n');
        }

        for path in extra_css_files {
            let mut file =
                File::open(&path).map_err(|e| format!("Failed to read CSS file '{path}': {e}"))?;
            file.read_to_string(&mut buffer)?;
            if !buffer.is_empty() {
                buffer.push('\n');
            }
        }

        Ok(if buffer.is_empty() {
            None
        } else {
            Some(buffer)
        })
    }

    fn format_error(filename: Option<&str>, error: impl fmt::Display) {
        let mut buffer = String::with_capacity(128);
        if let Some(filename) = filename {
            writeln!(buffer, "Filename: {filename}").expect("Failed to write to buffer");
        }
        buffer.push_str("Status: ERROR\n");
        writeln!(buffer, "Details: {error}").expect("Failed to write to buffer");
        eprintln!("{}", buffer.trim());
    }

    const VERSION_MESSAGE: &[u8] =
        concat!("css-inline ", env!("CARGO_PKG_VERSION"), "\n").as_bytes();
    const HELP_MESSAGE: &[u8] = concat!(
        "css-inline ",
        env!("CARGO_PKG_VERSION"),
        r#"
Dmitry Dygalo <dmitry@dygalo.dev>

css-inline inlines CSS into HTML 'style' attributes.

USAGE:
   css-inline [OPTIONS] [PATH ...]
   command | css-inline [OPTIONS]

ARGS:
    <PATH>...
        An HTML document to process. In each specified document "css-inline" will look for
        all relevant "style" and "link" tags, will load CSS from them and then inline it
        to the HTML tags, according to the corresponding CSS selectors.
        When multiple documents are specified, they will be processed in parallel, and each inlined
        file will be saved with "inlined." prefix. E.g., for "example.html", there will be
        "inlined.example.html".

OPTIONS:

    --inline-style-tags
        Whether to inline CSS from "style" tags. The default value is `true`. To disable inlining
        from "style" tags use `--inline-style-tags=false`.

    --keep-style-tags
        Keep "style" tags after inlining.

    --keep-link-tags
        Keep "link" tags after inlining.

    --keep-at-rules
        Keep "at-rules" after inlining.

    --minify-css
        Minify CSS by removing trailing semicolons and spaces between properties and values.

    --remove-inlined-selectors
        Remove selectors that were successfully inlined from inline <style> blocks.

    --apply-width-attributes
        Apply width HTML attributes from CSS width properties on supported elements
        (table, td, th, img). Useful for email compatibility with clients like Outlook.

    --apply-height-attributes
        Apply height HTML attributes from CSS height properties on supported elements
        (table, td, th, img). Useful for email compatibility with clients like Outlook.

    --base-url
        Used for loading external stylesheets via relative URLs.

    --load-remote-stylesheets
        Whether remote stylesheets should be loaded or not.

    --cache-size
        Set the cache size for remote stylesheets.

    --extra-css
        Additional CSS to inline.

    --extra-css-file <PATH>
        Load additional CSS from a file to inline. Can be used multiple times to load
        from several files. The CSS will be processed alongside any existing styles.

    --output-filename-prefix
        Custom prefix for output files. Defaults to `inlined.`.
"#
    )
    .as_bytes();

    let mut raw_args = env::args().skip(1);
    let mut args = ParsedArgs::default();

    while let Some(arg) = raw_args.next() {
        if let Some(flag) = arg.strip_prefix("--") {
            // Handle --key=value format
            if let Some((flag, value)) = flag.split_once('=') {
                if let Err(error) = handle_flag_with_value(&mut args, flag, value) {
                    eprintln!("{error}");
                    std::process::exit(1);
                }
            } else {
                // Handle --key format (boolean or expecting value)
                if requires_value(flag) {
                    // Expects a value
                    if let Some(value) = raw_args.next() {
                        if let Err(error) = handle_flag_with_value(&mut args, flag, &value) {
                            eprintln!("{error}");
                            std::process::exit(1);
                        }
                    } else {
                        eprintln!("Error parsing arguments: Flag --{flag} requires a value");
                        std::process::exit(1);
                    }
                } else {
                    // Boolean flag
                    if let Err(error) = handle_boolean_flag(&mut args, flag) {
                        eprintln!("{error}");
                        std::process::exit(1);
                    }
                }
            }
        } else if let Some(flag) = arg.strip_prefix('-') {
            if flag.len() == 1 {
                // Single character short flag
                if let Err(error) = handle_boolean_flag(&mut args, flag) {
                    eprintln!("{error}");
                    std::process::exit(1);
                }
            } else {
                eprintln!("Error parsing arguments: Invalid flag: -{flag}");
                std::process::exit(1);
            }
        } else {
            // Positional argument (file)
            args.files.push(arg);
        }
    }

    let exit_code = AtomicI32::new(0);
    if args.help {
        io::stdout().write_all(HELP_MESSAGE)?;
    } else if args.version {
        io::stdout().write_all(VERSION_MESSAGE)?;
    } else {
        let base_url = match parse_url(args.base_url.as_deref()) {
            Ok(base_url) => base_url,
            Err(error) => {
                format_error(None, error);
                std::process::exit(1);
            }
        };
        #[cfg(feature = "stylesheet-cache")]
        let cache = if let Some(size) = args.cache_size {
            if size == 0 {
                eprintln!("ERROR: Cache size must be an integer greater than zero");
                std::process::exit(1);
            }
            std::num::NonZeroUsize::new(size)
                .map(css_inline::StylesheetCache::new)
                .map(std::sync::Mutex::new)
        } else {
            None
        };
        let extra_css = match combine_extra_css(args.extra_css, args.extra_css_files) {
            Ok(css) => css,
            Err(error) => {
                format_error(None, error);
                std::process::exit(1);
            }
        };
        let options = InlineOptions {
            inline_style_tags: args.inline_style_tags,
            keep_style_tags: args.keep_style_tags,
            keep_link_tags: args.keep_link_tags,
            keep_at_rules: args.keep_at_rules,
            minify_css: args.minify_css,
            base_url,
            load_remote_stylesheets: args.load_remote_stylesheets,
            #[cfg(feature = "stylesheet-cache")]
            cache,
            extra_css: extra_css.as_deref().map(Cow::Borrowed),
            preallocate_node_capacity: 32,
            resolver: Arc::new(DefaultStylesheetResolver),
            remove_inlined_selectors: args.remove_inlined_selectors,
            apply_width_attributes: args.apply_width_attributes,
            apply_height_attributes: args.apply_height_attributes,
        };
        let inliner = CSSInliner::new(options);
        if args.files.is_empty() {
            let mut buffer = String::new();
            io::stdin().read_to_string(&mut buffer)?;
            if let Err(error) = inliner.inline_to(buffer.as_str().trim(), &mut io::stdout()) {
                format_error(None, error);
                exit_code.store(1, Ordering::SeqCst);
            }
        } else {
            args.files
                .par_iter()
                .map(|file_path| {
                    read_to_string(file_path)
                        .and_then(|contents| {
                            let path = Path::new(file_path);
                            let mut new_filename = args
                                .output_filename_prefix
                                .clone()
                                .unwrap_or_else(|| OsString::from("inlined."));
                            new_filename.push(
                                path.to_path_buf()
                                    .file_name()
                                    .expect("It is already read, therefore it is a file"),
                            );
                            let new_path = path.with_file_name(new_filename);
                            File::create(new_path).map(|file| (file, contents))
                        })
                        .map(|(mut file, contents)| {
                            (file_path, inliner.inline_to(contents.as_str(), &mut file))
                        })
                        .map_err(|error| (file_path, error))
                })
                .for_each(|result| match result {
                    Ok((filename, result)) => match result {
                        Ok(()) => println!("{filename}: SUCCESS"),
                        Err(error) => {
                            format_error(Some(filename.as_str()), error);
                            exit_code.store(1, Ordering::SeqCst);
                        }
                    },
                    Err((filename, error)) => {
                        format_error(Some(filename.as_str()), error);
                        exit_code.store(1, Ordering::SeqCst);
                    }
                });
        }
    }
    std::process::exit(exit_code.into_inner());
}