aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/downloader/gzip_downloader.rs
blob: 2a485de507e8b6f75c4791dc9596c91cff51e6fc (plain)
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
//! ref: composer/src/Composer/Downloader/GzipDownloader.php

use crate::cache::Cache;
use crate::config::Config;
use crate::downloader::archive_downloader::ArchiveDownloader;
use crate::downloader::file_downloader::FileDownloader;
use crate::event_dispatcher::event_dispatcher::EventDispatcher;
use crate::io::io_interface::IOInterface;
use crate::package::package_interface::PackageInterface;
use crate::util::filesystem::Filesystem;
use crate::util::http_downloader::HttpDownloader;
use crate::util::platform::Platform;
use crate::util::process_executor::ProcessExecutor;
use anyhow::Result;
use indexmap::IndexMap;
use shirabe_external_packages::react::promise::promise_interface::PromiseInterface;
use shirabe_php_shim::{
    DIRECTORY_SEPARATOR, PATHINFO_FILENAME, PHP_URL_PATH, PhpMixed, RuntimeException,
    extension_loaded, fclose, fopen, fwrite, gzclose, gzopen, gzread, implode, parse_url, pathinfo,
    strtr,
};

#[derive(Debug)]
pub struct GzipDownloader {
    inner: FileDownloader,
    cleanup_executed: IndexMap<String, bool>,
}

impl GzipDownloader {
    pub fn new(
        io: Box<dyn IOInterface>,
        config: Config,
        http_downloader: HttpDownloader,
        event_dispatcher: Option<EventDispatcher>,
        cache: Option<Cache>,
        filesystem: Filesystem,
        process: ProcessExecutor,
    ) -> Self {
        Self {
            inner: FileDownloader::new(
                io,
                config,
                http_downloader,
                event_dispatcher,
                cache,
                Some(filesystem),
                Some(process),
            ),
            cleanup_executed: IndexMap::new(),
        }
    }

    pub(crate) fn extract(
        &mut self,
        package: &dyn PackageInterface,
        file: &str,
        path: &str,
    ) -> Result<Box<dyn PromiseInterface>> {
        let filename = pathinfo(
            parse_url(
                &strtr(&package.get_dist_url().unwrap_or_default(), "\\", "/"),
                PHP_URL_PATH,
            ),
            PATHINFO_FILENAME,
        );
        let target_filepath = format!(
            "{}{}{}",
            path,
            DIRECTORY_SEPARATOR,
            filename.as_string().unwrap_or_default()
        );

        if !Platform::is_windows() {
            let command = vec![
                "sh".to_string(),
                "-c".to_string(),
                "gzip -cd -- \"$0\" > \"$1\"".to_string(),
                file.to_string(),
                target_filepath.clone(),
            ];

            let mut process_output = PhpMixed::Null;
            if self.inner.process.execute(
                PhpMixed::List(
                    command
                        .iter()
                        .map(|s| Box::new(PhpMixed::String(s.clone())))
                        .collect(),
                ),
                Some(&mut process_output),
                None,
            )? == 0
            {
                return Ok(shirabe_external_packages::react::promise::resolve(None));
            }

            if extension_loaded("zlib") {
                self.extract_using_ext(file, &target_filepath);
                return Ok(shirabe_external_packages::react::promise::resolve(None));
            }

            let process_error = format!(
                "Failed to execute {}\n\n{}",
                implode(" ", &command),
                self.inner.process.get_error_output(),
            );
            return Err(anyhow::anyhow!(RuntimeException {
                message: process_error,
                code: 0
            }));
        }

        self.extract_using_ext(file, &target_filepath);

        Ok(shirabe_external_packages::react::promise::resolve(None))
    }

    fn extract_using_ext(&self, file: &str, target_filepath: &str) {
        let archive_file = gzopen(file, "rb");
        let target_file = fopen(target_filepath, "wb");
        loop {
            let string = gzread(archive_file.clone(), 4096);
            if string.is_empty() {
                break;
            }
            fwrite(target_file.clone(), &string, Platform::strlen(&string));
        }
        gzclose(archive_file);
        fclose(target_file);
    }
}