aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/downloader/vcs_downloader.rs
blob: 1219ab1518b9899d8e05fa5d410e399d2c603ab9 (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
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! ref: composer/src/Composer/Downloader/VcsDownloader.php

use crate::io::io_interface;
use anyhow::Result;
use indexmap::IndexMap;
use shirabe_php_shim::{
    InvalidArgumentException, PhpMixed, RuntimeException, array_map, array_shift, count, explode,
    get_class, get_class_err, implode, rawurldecode, realpath, str_replace, strlen, strpos, substr,
    trim,
};

use crate::config::Config;
use crate::dependency_resolver::operation::InstallOperation;
use crate::dependency_resolver::operation::UninstallOperation;
use crate::dependency_resolver::operation::UpdateOperation;
use crate::downloader::ChangeReportInterface;
use crate::downloader::DownloaderInterface;
use crate::downloader::VcsCapableDownloaderInterface;
use crate::io::IOInterface;
use crate::package::PackageInterface;
use crate::package::dumper::ArrayDumper;
use crate::package::version::VersionGuesser;
use crate::package::version::VersionParser;
use crate::util::Filesystem;
use crate::util::ProcessExecutor;

#[derive(Debug)]
pub struct VcsDownloaderBase {
    pub io: Box<dyn IOInterface>,
    pub config: std::rc::Rc<std::cell::RefCell<Config>>,
    pub process: std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
    pub filesystem: std::rc::Rc<std::cell::RefCell<Filesystem>>,
    pub has_cleaned_changes: IndexMap<String, bool>,
}

impl VcsDownloaderBase {
    pub fn new(
        io: Box<dyn IOInterface>,
        config: std::rc::Rc<std::cell::RefCell<Config>>,
        process: Option<std::rc::Rc<std::cell::RefCell<ProcessExecutor>>>,
        fs: Option<std::rc::Rc<std::cell::RefCell<Filesystem>>>,
    ) -> Self {
        let process = process
            .unwrap_or_else(|| std::rc::Rc::new(std::cell::RefCell::new(ProcessExecutor::new(()))));
        let filesystem =
            fs.unwrap_or_else(|| std::rc::Rc::new(std::cell::RefCell::new(Filesystem::new(None))));
        Self {
            io,
            config,
            process,
            filesystem,
            has_cleaned_changes: IndexMap::new(),
        }
    }

    /// Equivalent of PHP `parent::cleanChanges()`. Subclasses that override the trait method
    /// call this when they need to invoke the base behavior. Since this lives on the data struct,
    /// it cannot consult subclass-specific `get_local_changes`; it assumes any callers have
    /// already verified that no local changes exist.
    pub async fn clean_changes(
        &self,
        _package: &dyn PackageInterface,
        _path: &str,
        _update: bool,
    ) -> Result<Option<PhpMixed>> {
        // TODO(phase-b): parent::cleanChanges() rechecks getLocalChanges via dynamic dispatch.
        // Callers in subclasses must do that check themselves (they already have).
        Ok(shirabe_external_packages::react::promise::resolve(None))
    }
}

pub trait VcsDownloader:
    DownloaderInterface + ChangeReportInterface + VcsCapableDownloaderInterface
{
    fn io(&self) -> &dyn IOInterface;
    fn io_mut(&mut self) -> &mut dyn IOInterface;
    fn config(&self) -> &std::rc::Rc<std::cell::RefCell<Config>>;
    fn config_mut(&mut self) -> &mut std::rc::Rc<std::cell::RefCell<Config>>;
    fn process(&self) -> &std::rc::Rc<std::cell::RefCell<ProcessExecutor>>;
    fn process_mut(&mut self) -> &mut std::rc::Rc<std::cell::RefCell<ProcessExecutor>>;
    fn filesystem(&self) -> &std::rc::Rc<std::cell::RefCell<Filesystem>>;
    fn filesystem_mut(&mut self) -> &mut std::rc::Rc<std::cell::RefCell<Filesystem>>;
    fn has_cleaned_changes(&self) -> &IndexMap<String, bool>;
    fn has_cleaned_changes_mut(&mut self) -> &mut IndexMap<String, bool>;

    /// Downloads data needed to run an install/update later
    async fn do_download(
        &mut self,
        package: &dyn PackageInterface,
        path: &str,
        url: &str,
        prev_package: Option<&dyn PackageInterface>,
    ) -> Result<Option<PhpMixed>>;

    /// Downloads specific package into specific folder.
    async fn do_install(
        &mut self,
        package: &dyn PackageInterface,
        path: &str,
        url: &str,
    ) -> Result<Option<PhpMixed>>;

    /// Updates specific package in specific folder from initial to target version.
    async fn do_update(
        &mut self,
        initial: &dyn PackageInterface,
        target: &dyn PackageInterface,
        path: &str,
        url: &str,
    ) -> Result<Option<PhpMixed>>;

    /// Fetches the commit logs between two commits
    fn get_commit_logs(&self, from_reference: &str, to_reference: &str, path: &str) -> String;

    /// Checks if VCS metadata repository has been initialized
    /// repository example: .git|.svn|.hg
    fn has_metadata_repository(&self, path: &str) -> bool;

    fn get_installation_source(&self) -> String {
        "source".to_string()
    }

    async fn download(
        &mut self,
        package: &dyn PackageInterface,
        path: &str,
        prev_package: Option<&dyn PackageInterface>,
    ) -> Result<Option<PhpMixed>> {
        if package.get_source_reference().is_none() {
            return Err(InvalidArgumentException {
                message: format!(
                    "Package {} is missing reference information",
                    package.get_pretty_name(),
                ),
                code: 0,
            }
            .into());
        }

        let mut urls = self.prepare_urls(package.get_source_urls());

        while let Some(url) = array_shift(&mut urls) {
            // TODO(phase-b): use anyhow::Result<Result<T, E>> to model PHP try/catch
            let attempt: Result<Option<PhpMixed>> =
                self.do_download(package, path, &url, prev_package);
            match attempt {
                Ok(promise) => return Ok(promise),
                Err(e) => {
                    // rethrow phpunit exceptions to avoid hard to debug bug failures
                    // TODO(phase-b): downcast to PHPUnit\Framework\Exception
                    let is_phpunit_exception = false;
                    if is_phpunit_exception {
                        return Err(e);
                    }
                    if self.io().is_debug() {
                        self.io_mut().write_error3(
                            &format!("Failed: [{}] {}", get_class_err(&e), e,),
                            true,
                            io_interface::NORMAL,
                        );
                    } else if count(&PhpMixed::List(
                        urls.iter()
                            .map(|s| Box::new(PhpMixed::String(s.clone())))
                            .collect(),
                    )) > 0
                    {
                        self.io_mut().write_error3(
                            "    Failed, trying the next URL",
                            true,
                            io_interface::NORMAL,
                        );
                    }
                    if count(&PhpMixed::List(
                        urls.iter()
                            .map(|s| Box::new(PhpMixed::String(s.clone())))
                            .collect(),
                    )) == 0
                    {
                        return Err(e);
                    }
                }
            }
        }

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

    async fn prepare(
        &mut self,
        r#type: &str,
        package: &dyn PackageInterface,
        path: &str,
        prev_package: Option<&dyn PackageInterface>,
    ) -> Result<Option<PhpMixed>> {
        if r#type == "update" {
            self.clean_changes(prev_package.unwrap(), path, true)?;
            self.has_cleaned_changes_mut()
                .insert(prev_package.unwrap().get_unique_name(), true);
        } else if r#type == "install" {
            self.filesystem_mut()
                .borrow_mut()
                .empty_directory(path, true)?;
        } else if r#type == "uninstall" {
            self.clean_changes(package, path, false)?;
        }

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

    async fn cleanup(
        &mut self,
        r#type: &str,
        _package: &dyn PackageInterface,
        path: &str,
        prev_package: Option<&dyn PackageInterface>,
    ) -> Result<Option<PhpMixed>> {
        if r#type == "update"
            && prev_package
                .map(|p| {
                    self.has_cleaned_changes()
                        .contains_key(&p.get_unique_name())
                })
                .unwrap_or(false)
        {
            self.reapply_changes(path);
            self.has_cleaned_changes_mut()
                .shift_remove(&prev_package.unwrap().get_unique_name());
        }

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

    async fn install(
        &mut self,
        package: &dyn PackageInterface,
        path: &str,
    ) -> Result<Option<PhpMixed>> {
        if package.get_source_reference().is_none() {
            return Err(InvalidArgumentException {
                message: format!(
                    "Package {} is missing reference information",
                    package.get_pretty_name(),
                ),
                code: 0,
            }
            .into());
        }

        self.io_mut().write_error3(
            &format!("  - {}: ", InstallOperation::format(package, false)),
            false,
            io_interface::NORMAL,
        );

        let mut urls = self.prepare_urls(package.get_source_urls());
        while let Some(url) = array_shift(&mut urls) {
            // TODO(phase-b): use anyhow::Result<Result<T, E>> to model PHP try/catch
            let attempt: Result<Option<PhpMixed>> = self.do_install(package, path, &url);
            match attempt {
                Ok(_) => break,
                Err(e) => {
                    // rethrow phpunit exceptions to avoid hard to debug bug failures
                    // TODO(phase-b): downcast to PHPUnit\Framework\Exception
                    let is_phpunit_exception = false;
                    if is_phpunit_exception {
                        return Err(e);
                    }
                    if self.io().is_debug() {
                        self.io_mut().write_error3(
                            &format!("Failed: [{}] {}", get_class_err(&e), e,),
                            true,
                            io_interface::NORMAL,
                        );
                    } else if count(&PhpMixed::List(
                        urls.iter()
                            .map(|s| Box::new(PhpMixed::String(s.clone())))
                            .collect(),
                    )) > 0
                    {
                        self.io_mut().write_error3(
                            "    Failed, trying the next URL",
                            true,
                            io_interface::NORMAL,
                        );
                    }
                    if count(&PhpMixed::List(
                        urls.iter()
                            .map(|s| Box::new(PhpMixed::String(s.clone())))
                            .collect(),
                    )) == 0
                    {
                        return Err(e);
                    }
                }
            }
        }

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

    async fn update(
        &mut self,
        initial: &dyn PackageInterface,
        target: &dyn PackageInterface,
        path: &str,
    ) -> Result<Option<PhpMixed>> {
        if target.get_source_reference().is_none() {
            return Err(InvalidArgumentException {
                message: format!(
                    "Package {} is missing reference information",
                    target.get_pretty_name(),
                ),
                code: 0,
            }
            .into());
        }

        self.io_mut().write_error3(
            &format!("  - {}: ", UpdateOperation::format(initial, target, false),),
            false,
            io_interface::NORMAL,
        );

        let mut urls = self.prepare_urls(target.get_source_urls());

        let mut exception: Option<anyhow::Error> = None;
        while let Some(url) = array_shift(&mut urls) {
            // TODO(phase-b): use anyhow::Result<Result<T, E>> to model PHP try/catch
            let attempt: Result<Option<PhpMixed>> = self.do_update(initial, target, path, &url);
            match attempt {
                Ok(_) => {
                    exception = None;
                    break;
                }
                Err(e) => {
                    // rethrow phpunit exceptions to avoid hard to debug bug failures
                    // TODO(phase-b): downcast to PHPUnit\Framework\Exception
                    let is_phpunit_exception = false;
                    if is_phpunit_exception {
                        return Err(e);
                    }
                    if self.io().is_debug() {
                        self.io_mut().write_error3(
                            &format!("Failed: [{}] {}", get_class_err(&e), e,),
                            true,
                            io_interface::NORMAL,
                        );
                    } else if count(&PhpMixed::List(
                        urls.iter()
                            .map(|s| Box::new(PhpMixed::String(s.clone())))
                            .collect(),
                    )) > 0
                    {
                        self.io_mut().write_error3(
                            "    Failed, trying the next URL",
                            true,
                            io_interface::NORMAL,
                        );
                    }
                    exception = Some(e);
                }
            }
        }

        // print the commit logs if in verbose mode and VCS metadata is present
        // because in case of missing metadata code would trigger another exception
        if exception.is_none() && self.io().is_verbose() && self.has_metadata_repository(path) {
            let mut message = "Pulling in changes:";
            let mut logs = self.get_commit_logs(
                initial.get_source_reference().unwrap_or(""),
                target.get_source_reference().unwrap_or(""),
                path,
            );

            if trim(&logs, None) == "" {
                message = "Rolling back changes:";
                logs = self.get_commit_logs(
                    target.get_source_reference().unwrap_or(""),
                    initial.get_source_reference().unwrap_or(""),
                    path,
                );
            }

            if trim(&logs, None) != "" {
                let prefixed: Vec<String> = array_map(
                    |line: &String| format!("      {}", line),
                    &explode("\n", &logs),
                );
                logs = implode("\n", &prefixed);

                // escape angle brackets for proper output in the console
                logs = str_replace("<", "\\<", &logs);

                self.io_mut()
                    .write_error3(&format!("    {}", message), true, io_interface::NORMAL);
                self.io_mut()
                    .write_error3(&logs, true, io_interface::NORMAL);
            }
        }

        if urls.is_empty() {
            if let Some(e) = exception {
                return Err(e);
            }
        }

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

    async fn remove(
        &mut self,
        package: &dyn PackageInterface,
        path: &str,
    ) -> Result<Option<PhpMixed>> {
        self.io_mut().write_error3(
            &format!("  - {}", UninstallOperation::format(package, false)),
            true,
            io_interface::NORMAL,
        );

        let promise = self
            .filesystem_mut()
            .borrow_mut()
            .remove_directory_async(path)?;

        let path = path.to_string();
        // TODO(phase-b): closure return type mismatches PromiseInterface::then signature.
        Ok(promise.then(
            Some(Box::new(
                move |result: Option<PhpMixed>| -> Option<PhpMixed> {
                    let result_bool = result.as_ref().and_then(|v| v.as_bool()).unwrap_or(false);
                    if !result_bool {
                        let _: RuntimeException = RuntimeException {
                            message: format!("Could not completely delete {}, aborting.", path),
                            code: 0,
                        };
                    }
                    None
                },
            )),
            None,
        ))
    }

    fn get_vcs_reference(&self, package: &dyn PackageInterface, path: &str) -> Option<String> {
        let parser = VersionParser::new();
        let guesser = VersionGuesser::new(
            self.config().clone(),
            self.process().clone(),
            parser.clone(),
            Some(self.io().clone_box()),
        );
        let dumper = ArrayDumper::new();

        let package_config = dumper.dump(package);
        let mut guesser = guesser;
        if let Ok(Some(package_version)) = guesser.guess_version(&package_config, path) {
            return package_version.commit.clone();
        }

        None
    }

    /// Prompt the user to check if changes should be stashed/removed or the operation aborted
    ///
    /// @param  bool $update  if true (update) the changes can be stashed and reapplied after an update,
    ///                       if false (remove) the changes should be assumed to be lost if the operation is not aborted
    async fn clean_changes(
        &self,
        package: &dyn PackageInterface,
        path: &str,
        _update: bool,
    ) -> Result<Option<PhpMixed>> {
        // the default implementation just fails if there are any changes, override in child classes to provide stash-ability
        if self.get_local_changes(package, path)?.is_some() {
            return Err(RuntimeException {
                message: format!("Source directory {} has uncommitted changes.", path),
                code: 0,
            }
            .into());
        }

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

    /// Reapply previously stashed changes if applicable, only called after an update (regardless if successful or not)
    fn reapply_changes(&self, _path: &str) {}

    fn prepare_urls(&self, mut urls: Vec<String>) -> Vec<String> {
        for index in 0..urls.len() {
            let mut url = urls[index].clone();
            if Filesystem::is_local_path(&url) {
                // realpath() below will not understand
                // url that starts with "file://"
                let file_protocol = "file://";
                let mut is_file_protocol = false;
                if strpos(&url, file_protocol) == Some(0) {
                    url = substr(&url, strlen(file_protocol), None);
                    is_file_protocol = true;
                }

                // realpath() below will not understand %20 spaces etc.
                if strpos(&url, "%").is_some() {
                    url = rawurldecode(&url);
                }

                urls[index] = realpath(&url).unwrap_or_default();

                if is_file_protocol {
                    urls[index] = format!("{}{}", file_protocol, urls[index]);
                }
            }
        }

        urls
    }
}