aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/downloader/svn_downloader.rs
blob: eb4de655d2b356fc065c2693eedf9da1dd075ea3 (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
//! ref: composer/src/Composer/Downloader/SvnDownloader.php

use crate::io::io_interface;
use shirabe_external_packages::composer::pcre::preg::Preg;
use shirabe_external_packages::react::promise;
use shirabe_external_packages::react::promise::promise_interface::PromiseInterface;
use shirabe_php_shim::{PhpMixed, RuntimeException, is_dir, version_compare};

use crate::downloader::vcs_downloader::VcsDownloaderBase;
use crate::io::io_interface::IOInterface;
use crate::package::package_interface::PackageInterface;
use crate::repository::vcs_repository::VcsRepository;
use crate::util::svn::Svn as SvnUtil;

#[derive(Debug)]
pub struct SvnDownloader {
    inner: VcsDownloaderBase,
    pub(crate) cache_credentials: bool,
}

impl SvnDownloader {
    pub(crate) fn do_download(
        &mut self,
        package: &dyn PackageInterface,
        path: &str,
        url: &str,
        prev_package: Option<&dyn PackageInterface>,
    ) -> anyhow::Result<Box<dyn PromiseInterface>> {
        SvnUtil::clean_env();
        let util = SvnUtil::new(
            url,
            &*self.inner.io,
            &self.inner.config,
            &self.inner.process,
        );
        if util.binary_version().is_none() {
            return Err(RuntimeException {
                message: "svn was not found in your PATH, skipping source download".to_string(),
                code: 0,
            }
            .into());
        }

        Ok(promise::resolve(None))
    }

    pub(crate) fn do_install(
        &mut self,
        package: &dyn PackageInterface,
        path: &str,
        url: &str,
    ) -> anyhow::Result<Box<dyn PromiseInterface>> {
        SvnUtil::clean_env();
        let r#ref = package.get_source_reference();

        let repo = package.get_repository();
        if let Some(repo) = repo {
            if let Some(vcs_repo) = repo.as_any().downcast_ref::<VcsRepository>() {
                let repo_config = vcs_repo.get_repo_config();
                if repo_config.contains_key("svn-cache-credentials") {
                    if let Some(val) = repo_config
                        .get("svn-cache-credentials")
                        .and_then(|v| v.as_bool())
                    {
                        self.cache_credentials = val;
                    }
                }
            }
        }

        self.inner.io.write_error(
            PhpMixed::String(format!(" Checking out {}", package.get_source_reference())),
            true,
            io_interface::NORMAL,
        );
        self.execute(
            package,
            url,
            vec!["svn".to_string(), "co".to_string()],
            &format!("{}/{}", url, r#ref),
            None,
            Some(path),
        )?;

        Ok(promise::resolve(None))
    }

    pub(crate) fn do_update(
        &mut self,
        initial: &dyn PackageInterface,
        target: &dyn PackageInterface,
        path: &str,
        url: &str,
    ) -> anyhow::Result<Box<dyn PromiseInterface>> {
        SvnUtil::clean_env();
        let r#ref = target.get_source_reference();

        if !self.has_metadata_repository(path) {
            return Err(RuntimeException {
                message: format!(
                    "The .svn directory is missing from {}, see https://getcomposer.org/commit-deps for more information",
                    path
                ),
                code: 0,
            }
            .into());
        }

        let util = SvnUtil::new(
            url,
            &*self.inner.io,
            &self.inner.config,
            &self.inner.process,
        );
        let mut flags: Vec<String> = vec![];
        if version_compare(&util.binary_version().unwrap_or_default(), "1.7.0", ">=") {
            flags.push("--ignore-ancestry".to_string());
        }

        self.inner.io.write_error(
            PhpMixed::String(format!(" Checking out {}", r#ref)),
            true,
            io_interface::NORMAL,
        );
        let mut command = vec!["svn".to_string(), "switch".to_string()];
        command.extend(flags);
        self.execute(
            target,
            url,
            command,
            &format!("{}/{}", url, r#ref),
            Some(path),
            None,
        )?;

        Ok(promise::resolve(None))
    }

    pub fn get_local_changes(&self, package: &dyn PackageInterface, path: &str) -> Option<String> {
        if !self.has_metadata_repository(path) {
            return None;
        }

        let mut output = String::new();
        self.inner.process.execute(
            &["svn", "status", "--ignore-externals"]
                .map(|s| s.to_string())
                .to_vec(),
            &mut output,
            Some(path.to_string()),
        );

        if Preg::is_match("{^ *[^X ] +}m", &output).unwrap_or(false) {
            Some(output)
        } else {
            None
        }
    }

    pub(crate) fn execute(
        &self,
        package: &dyn PackageInterface,
        base_url: &str,
        command: Vec<String>,
        url: &str,
        cwd: Option<&str>,
        path: Option<&str>,
    ) -> anyhow::Result<String> {
        let mut util = SvnUtil::new(
            base_url,
            &*self.inner.io,
            &self.inner.config,
            &self.inner.process,
        );
        util.set_cache_credentials(self.cache_credentials);
        util.execute(command, url, cwd, path, self.inner.io.is_verbose())
            .map_err(|e| {
                anyhow::anyhow!(
                    "{} could not be downloaded, {}",
                    package.get_pretty_name(),
                    e
                )
            })
    }

    pub(crate) fn clean_changes(
        &mut self,
        package: &dyn PackageInterface,
        path: &str,
        update: bool,
    ) -> anyhow::Result<Box<dyn PromiseInterface>> {
        let changes = self.get_local_changes(package, path);
        if changes.is_none() {
            return Ok(promise::resolve(None));
        }

        if !self.inner.io.is_interactive() {
            if self.inner.config.get("discard-changes").as_bool() == Some(true) {
                return self.discard_changes(path);
            }

            return self.inner.clean_changes(package, path, update);
        }

        let changes_str = changes.unwrap();
        let changes: Vec<String> = Preg::split(r"{\s*\r?\n\s*}", &changes_str)
            .into_iter()
            .map(|elem| format!("    {}", elem))
            .collect();
        let count_changes = changes.len() as i64;
        self.inner.io.write_error(
            PhpMixed::String(format!(
                "    <error>{} has modified file{}:</error>",
                package.get_pretty_name(),
                if count_changes == 1 { "" } else { "s" }
            )),
            true,
            io_interface::NORMAL,
        );
        let slice_end = 10_usize.min(changes.len());
        self.inner.io.write_error(
            PhpMixed::List(
                changes[..slice_end]
                    .iter()
                    .map(|s| Box::new(PhpMixed::String(s.clone())))
                    .collect(),
            ),
            true,
            io_interface::NORMAL,
        );
        if count_changes > 10 {
            let remaining_changes = count_changes - 10;
            self.inner.io.write_error(
                PhpMixed::String(format!(
                    "    <info>{} more file{} modified, choose \"v\" to view the full list</info>",
                    remaining_changes,
                    if remaining_changes == 1 { "" } else { "s" }
                )),
                true,
                io_interface::NORMAL,
            );
        }

        loop {
            match self
                .inner
                .io
                .ask(
                    "    <info>Discard changes [y,n,v,?]?</info> ".to_string(),
                    PhpMixed::String("?".to_string()),
                )
                .as_string()
            {
                Some("y") => {
                    self.discard_changes(path)?;
                    break;
                }
                Some("n") => {
                    return Err(RuntimeException {
                        message: "Update aborted".to_string(),
                        code: 0,
                    }
                    .into());
                }
                Some("v") => {
                    self.inner.io.write_error(
                        PhpMixed::List(
                            changes
                                .iter()
                                .map(|s| Box::new(PhpMixed::String(s.clone())))
                                .collect(),
                        ),
                        true,
                        io_interface::NORMAL,
                    );
                }
                _ => {
                    self.inner.io.write_error(
                        PhpMixed::List(vec![
                            Box::new(PhpMixed::String(format!(
                                "    y - discard changes and apply the {}",
                                if update { "update" } else { "uninstall" }
                            ))),
                            Box::new(PhpMixed::String(format!(
                                "    n - abort the {} and let you manually clean things up",
                                if update { "update" } else { "uninstall" }
                            ))),
                            Box::new(PhpMixed::String("    v - view modified files".to_string())),
                            Box::new(PhpMixed::String("    ? - print help".to_string())),
                        ]),
                        true,
                        io_interface::NORMAL,
                    );
                }
            }
        }

        Ok(promise::resolve(None))
    }

    pub(crate) fn get_commit_logs(
        &self,
        from_reference: &str,
        to_reference: &str,
        path: &str,
    ) -> anyhow::Result<String> {
        if Preg::is_match(r"{@(\d+)$}", from_reference).unwrap_or(false)
            && Preg::is_match(r"{@(\d+)$}", to_reference).unwrap_or(false)
        {
            // retrieve the svn base url from the checkout folder
            let command = vec![
                "svn".to_string(),
                "info".to_string(),
                "--non-interactive".to_string(),
                "--xml".to_string(),
                "--".to_string(),
                path.to_string(),
            ];
            let mut output = String::new();
            if self
                .inner
                .process
                .execute(&command, &mut output, Some(path.to_string()))
                != 0
            {
                return Err(RuntimeException {
                    message: format!(
                        "Failed to execute {}\n\n{}",
                        command.join(" "),
                        self.inner.process.get_error_output()
                    ),
                    code: 0,
                }
                .into());
            }

            let url_pattern = "#<url>(.*)</url>#";
            let base_url = if let Some(matches) = Preg::match_strict_groups(url_pattern, &output) {
                matches.get("1").cloned().unwrap_or_default()
            } else {
                return Err(RuntimeException {
                    message: format!("Unable to determine svn url for path {}", path),
                    code: 0,
                }
                .into());
            };

            // strip paths from references and only keep the actual revision
            let from_revision = Preg::replace(r"{.*@(\d+)$}", "$1", from_reference.to_string());
            let to_revision = Preg::replace(r"{.*@(\d+)$}", "$1", to_reference.to_string());

            let command = vec![
                "svn".to_string(),
                "log".to_string(),
                "-r".to_string(),
                format!("{}:{}", from_revision, to_revision),
                "--incremental".to_string(),
            ];

            let mut util = SvnUtil::new(
                &base_url,
                &*self.inner.io,
                &self.inner.config,
                &self.inner.process,
            );
            util.set_cache_credentials(self.cache_credentials);
            util.execute_local(command.clone(), path, None, self.inner.io.is_verbose())
                .map_err(|e| {
                    RuntimeException {
                        message: format!("Failed to execute {}\n\n{}", command.join(" "), e),
                        code: 0,
                    }
                    .into()
                })
        } else {
            Ok(format!(
                "Could not retrieve changes between {} and {} due to missing revision information",
                from_reference, to_reference
            ))
        }
    }

    pub(crate) fn discard_changes(&self, path: &str) -> anyhow::Result<Box<dyn PromiseInterface>> {
        let mut output = String::new();
        if self.inner.process.execute(
            &["svn", "revert", "-R", "."].map(|s| s.to_string()).to_vec(),
            &mut output,
            Some(path.to_string()),
        ) != 0
        {
            return Err(RuntimeException {
                message: format!(
                    "Could not reset changes\n\n:{}",
                    self.inner.process.get_error_output()
                ),
                code: 0,
            }
            .into());
        }

        Ok(promise::resolve(None))
    }

    pub(crate) fn has_metadata_repository(&self, path: &str) -> bool {
        is_dir(&format!("{}/.svn", path))
    }
}