Skip to main content

script/
unminify.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::borrow::Cow;
6use std::env;
7use std::fs::{File, create_dir_all};
8use std::io::{Error, ErrorKind, Read, Seek, Write};
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use servo_config::opts;
13use servo_url::ServoUrl;
14use tempfile::NamedTempFile;
15use uuid::Uuid;
16
17pub(crate) struct ScriptSource<'a> {
18    pub source: Cow<'a, str>,
19    pub url: &'a ServoUrl,
20    pub external: bool,
21}
22
23pub(crate) fn create_temp_files() -> Option<(NamedTempFile, File)> {
24    // Write the minified code to a temporary file and pass its path as an argument
25    // to js-beautify to read from. Meanwhile, redirect the process' stdout into
26    // another temporary file and read that into a string. This avoids some hangs
27    // observed on macOS when using direct input/output pipes with very large
28    // unminified content.
29    let (input, output) = (NamedTempFile::new(), tempfile::tempfile());
30    if let (Ok(input), Ok(output)) = (input, output) {
31        Some((input, output))
32    } else {
33        log::warn!("Error creating input and output temp files");
34        None
35    }
36}
37
38#[derive(Debug)]
39pub(crate) enum BeautifyFileType {
40    Css,
41    Js,
42}
43
44pub(crate) fn execute_js_beautify(input: &Path, output: File, file_type: BeautifyFileType) -> bool {
45    let mut cmd = Command::new("js-beautify");
46    match file_type {
47        BeautifyFileType::Js => (),
48        BeautifyFileType::Css => {
49            cmd.arg("--type").arg("css");
50        },
51    }
52    match cmd.arg(input).stdout(output).status() {
53        Ok(status) => status.success(),
54        _ => {
55            log::warn!(
56                "Failed to execute js-beautify --type {:?}, Will store unmodified script",
57                file_type
58            );
59            false
60        },
61    }
62}
63
64pub fn create_output_file(
65    unminified_dir: String,
66    url: &ServoUrl,
67    external: Option<bool>,
68) -> Result<File, Error> {
69    let (path, _tmp_dir) = if opts::get().temporary_storage {
70        let tempfile = tempfile::tempdir()?;
71        (tempfile.path().to_owned(), Some(tempfile))
72    } else {
73        (PathBuf::from(unminified_dir), None)
74    };
75
76    if url.scheme() == "data" {
77        return Err(Error::new(
78            ErrorKind::InvalidInput,
79            "data URLs cannot be written as unminified files",
80        ));
81    }
82
83    // Strip the query string from the URL before using it as a file path.
84    // '?' is a reserved character on Windows and causes file creation to fail
85    // silently. BeforeHost..AfterPath stops the slice before the '?' separator.
86    let url_path = &url[url::Position::BeforeHost..url::Position::AfterPath];
87
88    let (base, has_name) = match url.as_str().ends_with('/') {
89        true => (path.join(url_path).as_path().to_owned(), false),
90        false => (path.join(url_path).parent().unwrap().to_owned(), true),
91    };
92
93    create_dir_all(&base)?;
94
95    let path = if external.unwrap_or(true) && has_name {
96        // External.
97        path.join(url_path)
98    } else {
99        // Inline file or url ends with '/'
100        base.join(Uuid::new_v4().to_string())
101    };
102
103    debug!("Unminified files will be stored in {:?}", path);
104
105    File::create(path)
106}
107
108pub(crate) fn unminify_js(script: &mut ScriptSource, unminified_js_dir: String) {
109    if let Some((mut input, mut output)) = create_temp_files() {
110        input.write_all(script.source.as_bytes()).unwrap();
111
112        if execute_js_beautify(
113            input.path(),
114            output.try_clone().unwrap(),
115            BeautifyFileType::Js,
116        ) {
117            let mut script_content = String::new();
118            output.seek(std::io::SeekFrom::Start(0)).unwrap();
119            output.read_to_string(&mut script_content).unwrap();
120            script.source = script_content.into();
121        }
122    }
123
124    match create_output_file(unminified_js_dir, script.url, Some(script.external)) {
125        Ok(mut file) => file.write_all(script.source.as_bytes()).unwrap(),
126        Err(why) => warn!("Could not store script {:?}", why),
127    }
128}
129
130pub(crate) fn unminified_path(dir: &str) -> String {
131    let mut path = env::current_dir().unwrap();
132    path.push(dir);
133    path.into_os_string().into_string().unwrap()
134}