aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/repository/vcs/vcs_driver.rs
blob: b197676bb2487d844b9c83ec7590f5a1230eb0a1 (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
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
//! ref: composer/src/Composer/Repository/Vcs/VcsDriver.php

use chrono::{DateTime, FixedOffset};
use indexmap::IndexMap;
use shirabe_external_packages::composer::pcre::Preg;
use shirabe_php_shim::{DATE_RFC3339, PhpMixed, extension_loaded};

use crate::cache::Cache;
use crate::config::Config;
use crate::downloader::TransportException;
use crate::io::IOInterface;
use crate::json::JsonEncodeOptions;
use crate::json::JsonFile;
use crate::repository::vcs::VcsDriverInterface;
use crate::util::Filesystem;
use crate::util::HttpDownloader;
use crate::util::ProcessExecutor;
use crate::util::http::Response;

#[derive(Debug)]
pub struct VcsDriverBase {
    pub url: String,
    pub origin_url: String,
    pub repo_config: IndexMap<String, PhpMixed>,
    pub io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
    pub config: std::rc::Rc<std::cell::RefCell<Config>>,
    pub process: std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
    pub http_downloader: std::rc::Rc<std::cell::RefCell<HttpDownloader>>,
    pub info_cache: IndexMap<String, Option<IndexMap<String, PhpMixed>>>,
    pub cache: Option<Cache>,
}

impl VcsDriverBase {
    pub fn new(
        repo_config: IndexMap<String, PhpMixed>,
        io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
        config: std::rc::Rc<std::cell::RefCell<Config>>,
        http_downloader: std::rc::Rc<std::cell::RefCell<HttpDownloader>>,
        process: std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
    ) -> Self {
        let url = repo_config
            .get("url")
            .and_then(|v| v.as_string())
            .unwrap_or("")
            .to_string();
        let origin_url = url.clone();
        Self {
            url,
            origin_url,
            repo_config,
            io,
            config,
            process,
            http_downloader,
            info_cache: IndexMap::new(),
            cache: None,
        }
    }

    pub fn should_cache(&self, identifier: &str) -> bool {
        self.cache.is_some() && Preg::is_match("{^[a-f0-9]{40}$}iD", identifier).unwrap_or(false)
    }

    pub fn get_scheme(&self) -> &str {
        if extension_loaded("openssl") {
            return "https";
        }
        "http"
    }

    pub fn get_contents(&self, url: &str) -> anyhow::Result<Response, TransportException> {
        let options_mixed = self
            .repo_config
            .get("options")
            .cloned()
            .unwrap_or(PhpMixed::Array(IndexMap::new()));
        let options: IndexMap<String, PhpMixed> = match options_mixed {
            PhpMixed::Array(a) => a.into_iter().map(|(k, v)| (k, *v)).collect(),
            _ => IndexMap::new(),
        };
        self.http_downloader
            .borrow_mut()
            .get(url, options)
            .map_err(|e| match e.downcast::<TransportException>() {
                Ok(te) => te,
                Err(other) => TransportException::new(other.to_string(), 0),
            })
    }

    // Helper for concrete drivers: produces the same value as the trait default
    // `get_base_composer_information`, but receives a pre-fetched composer.json
    // body and a lazy change-date callback. Concrete drivers in the Rust port
    // wrap `VcsDriverBase` as `self.inner` instead of inheriting from it, so
    // they cannot dispatch back into a base method that calls `get_file_content`
    // / `get_change_date` hooks; the caller threads those calls in itself.
    pub fn finish_base_composer_information(
        identifier: &str,
        composer_file_content: Option<String>,
        change_date: impl FnOnce() -> anyhow::Result<Option<DateTime<FixedOffset>>>,
    ) -> anyhow::Result<Option<IndexMap<String, PhpMixed>>> {
        let content = match composer_file_content {
            None => return Ok(None),
            Some(c) if c.is_empty() => return Ok(None),
            Some(c) => c,
        };

        let parsed = JsonFile::parse_json(
            Some(&content),
            Some(&format!("{}:composer.json", identifier)),
        )?;

        let array = match parsed {
            PhpMixed::Array(a) if !a.is_empty() => a,
            _ => return Ok(None),
        };

        // PHP arrays own their nested values; the Rust representation wraps them
        // in Box<PhpMixed>. Unbox the outer level so callers can mutate keys.
        let mut composer: IndexMap<String, PhpMixed> =
            array.into_iter().map(|(k, v)| (k, *v)).collect();

        if !composer.contains_key("time")
            || composer
                .get("time")
                .map_or(true, |v| v.as_string().map_or(true, |s| s.is_empty()))
        {
            if let Some(d) = change_date()? {
                composer.insert(
                    "time".to_string(),
                    PhpMixed::String(d.format(DATE_RFC3339).to_string()),
                );
            }
        }

        Ok(Some(composer))
    }

    // Caching layer of the base `getComposerInformation`. Concrete drivers that
    // inherit the base implementation thread their own `get_file_content` /
    // `get_change_date` fetch between these two calls; splitting read and write
    // keeps each `self.inner` borrow disjoint from the fetch's `self` borrow.
    // Returns `Some(_)` when the value is already known (in-memory or on-disk
    // cache), or `None` when the caller must fetch it.
    pub fn read_cached_composer(
        &mut self,
        identifier: &str,
    ) -> anyhow::Result<Option<Option<IndexMap<String, PhpMixed>>>> {
        if self.info_cache.contains_key(identifier) {
            return Ok(Some(
                self.info_cache.get(identifier).and_then(|v| v.clone()),
            ));
        }
        if self.should_cache(identifier) {
            if let Some(res) = self.cache.as_mut().and_then(|c| c.read(identifier)) {
                let parsed = JsonFile::parse_json(Some(&res), None)?;
                let composer: Option<IndexMap<String, PhpMixed>> = parsed
                    .as_array()
                    .map(|m| m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect());
                self.info_cache
                    .insert(identifier.to_string(), composer.clone());
                return Ok(Some(composer));
            }
        }
        Ok(None)
    }

    pub fn write_cached_composer(
        &mut self,
        identifier: &str,
        composer: Option<IndexMap<String, PhpMixed>>,
    ) -> anyhow::Result<Option<IndexMap<String, PhpMixed>>> {
        if self.should_cache(identifier) {
            let encoded = JsonFile::encode_with_options(
                &composer
                    .clone()
                    .map(PhpMixed::from)
                    .unwrap_or(PhpMixed::Null),
                JsonEncodeOptions {
                    pretty_print: false,
                    ..Default::default()
                },
            );
            self.cache.as_mut().map(|c| c.write(identifier, &encoded));
        }
        self.info_cache.insert(identifier.to_string(), composer);
        Ok(self.info_cache.get(identifier).and_then(|v| v.clone()))
    }
}

pub trait VcsDriver: VcsDriverInterface {
    fn url(&self) -> &str;
    fn url_mut(&mut self) -> &mut String;
    fn origin_url(&self) -> &str;
    fn origin_url_mut(&mut self) -> &mut String;
    fn repo_config(&self) -> &IndexMap<String, PhpMixed>;
    fn repo_config_mut(&mut self) -> &mut IndexMap<String, PhpMixed>;
    fn io(&self) -> &dyn IOInterface;
    fn io_mut(&mut self) -> &mut dyn IOInterface;
    fn config(&self) -> &Config;
    fn config_mut(&mut self) -> &mut Config;
    fn process(&self) -> &ProcessExecutor;
    fn process_mut(&mut self) -> &mut ProcessExecutor;
    fn http_downloader(&self) -> &std::rc::Rc<std::cell::RefCell<HttpDownloader>>;
    fn info_cache(&self) -> &IndexMap<String, Option<IndexMap<String, PhpMixed>>>;
    fn info_cache_mut(&mut self) -> &mut IndexMap<String, Option<IndexMap<String, PhpMixed>>>;
    fn cache(&self) -> Option<&Cache>;
    fn cache_mut(&mut self) -> Option<&mut Cache>;

    fn should_cache(&self, identifier: &str) -> bool {
        self.cache().is_some() && Preg::is_match("{^[a-f0-9]{40}$}iD", identifier).unwrap_or(false)
    }

    fn get_composer_information(
        &mut self,
        identifier: &str,
    ) -> anyhow::Result<Option<IndexMap<String, PhpMixed>>> {
        if !self.info_cache().contains_key(identifier) {
            if self.should_cache(identifier) {
                if let Some(res) = self.cache_mut().and_then(|c| c.read(identifier)) {
                    let parsed = JsonFile::parse_json(Some(&res), None)?;
                    let parsed_map: Option<IndexMap<String, PhpMixed>> = match parsed {
                        PhpMixed::Array(a) => Some(a.into_iter().map(|(k, v)| (k, *v)).collect()),
                        _ => None,
                    };
                    self.info_cache_mut()
                        .insert(identifier.to_string(), parsed_map);
                    return Ok(self.info_cache().get(identifier).and_then(|v| v.clone()));
                }
            }

            let composer = self.get_base_composer_information(identifier)?;

            if self.should_cache(identifier) {
                if let Some(ref composer_map) = composer {
                    let composer_mixed = PhpMixed::Array(
                        composer_map
                            .iter()
                            .map(|(k, v)| (k.clone(), Box::new(v.clone())))
                            .collect(),
                    );
                    let encoded = JsonFile::encode_with_options(
                        &composer_mixed,
                        JsonEncodeOptions {
                            pretty_print: false,
                            ..Default::default()
                        },
                    );
                    self.cache_mut().map(|c| c.write(identifier, &encoded));
                }
            }

            self.info_cache_mut()
                .insert(identifier.to_string(), composer);
        }

        Ok(self.info_cache().get(identifier).and_then(|v| v.clone()))
    }

    fn get_base_composer_information(
        &mut self,
        identifier: &str,
    ) -> anyhow::Result<Option<IndexMap<String, PhpMixed>>> {
        let composer_file_content = self.get_file_content("composer.json", identifier)?;

        let composer_file_content = match composer_file_content {
            None => return Ok(None),
            Some(c) if c.is_empty() => return Ok(None),
            Some(c) => c,
        };

        let composer = JsonFile::parse_json(
            Some(&composer_file_content),
            Some(&format!("{}:composer.json", identifier)),
        )?;

        let mut composer: IndexMap<String, PhpMixed> = match composer {
            PhpMixed::Array(a) if !a.is_empty() => a.into_iter().map(|(k, v)| (k, *v)).collect(),
            _ => return Ok(None),
        };

        if !composer.contains_key("time")
            || composer
                .get("time")
                .map_or(true, |v| v.as_string().map_or(true, |s| s.is_empty()))
        {
            if let Some(change_date) = self.get_change_date(identifier)? {
                composer.insert(
                    "time".to_string(),
                    PhpMixed::String(change_date.format(DATE_RFC3339).to_string()),
                );
            }
        }

        Ok(Some(composer))
    }

    fn has_composer_file(&mut self, identifier: &str) -> bool {
        match VcsDriver::get_composer_information(self, identifier) {
            Ok(Some(_)) => true,
            _ => false,
        }
    }

    fn get_scheme(&self) -> &str {
        if extension_loaded("openssl") {
            return "https";
        }
        "http"
    }

    fn get_contents(&self, url: &str) -> anyhow::Result<Response, TransportException> {
        let options_mixed = self
            .repo_config()
            .get("options")
            .cloned()
            .unwrap_or(PhpMixed::Array(IndexMap::new()));
        let options: IndexMap<String, PhpMixed> = match options_mixed {
            PhpMixed::Array(a) => a.into_iter().map(|(k, v)| (k, *v)).collect(),
            _ => IndexMap::new(),
        };
        self.http_downloader()
            .borrow_mut()
            .get(url, options)
            .map_err(|e| match e.downcast::<TransportException>() {
                Ok(te) => te,
                Err(other) => TransportException::new(other.to_string(), 0),
            })
    }

    fn cleanup(&self) {}
}