aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/repository/repository_factory.rs
blob: 89334a13de9175ac275510e4b766bc9a0b87bea6 (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
//! ref: composer/src/Composer/Repository/RepositoryFactory.php

use indexmap::IndexMap;
use shirabe_external_packages::composer::pcre::Preg;
use shirabe_php_shim::{
    InvalidArgumentException, PhpMixed, UnexpectedValueException, get_debug_type, json_encode,
};

use crate::config::Config;
use crate::event_dispatcher::EventDispatcher;
use crate::factory::Factory;
use crate::io::IOInterface;
use crate::io::IOInterfaceMutable;
use crate::json::JsonFile;
use crate::repository::FilesystemRepository;
use crate::repository::RepositoryInterfaceHandle;
use crate::repository::RepositoryManager;
use crate::util::HttpDownloader;
use crate::util::ProcessExecutor;

pub struct RepositoryFactory;

impl RepositoryFactory {
    pub fn config_from_string(
        io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
        config: &std::rc::Rc<std::cell::RefCell<Config>>,
        repository: &str,
        allow_filesystem: bool,
    ) -> anyhow::Result<IndexMap<String, PhpMixed>> {
        if repository.starts_with("http") {
            let mut repo_config = IndexMap::new();
            repo_config.insert("type".to_string(), PhpMixed::String("composer".to_string()));
            repo_config.insert("url".to_string(), PhpMixed::String(repository.to_string()));
            return Ok(repo_config);
        }

        let extension = std::path::Path::new(repository)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");

        if extension == "json" {
            let mut json = JsonFile::new(
                repository.to_string(),
                Some(std::rc::Rc::new(std::cell::RefCell::new(
                    Factory::create_http_downloader(io.clone(), config, IndexMap::new())?,
                ))),
                Some(io.clone()),
            )?;
            let data = json.read()?;
            let has_packages = data.get("packages").map_or(false, |v| !v.is_null());
            let has_includes = data.get("includes").map_or(false, |v| !v.is_null());
            let has_provider_includes = data
                .get("provider-includes")
                .map_or(false, |v| !v.is_null());
            if has_packages || has_includes || has_provider_includes {
                let real_path = std::fs::canonicalize(repository)
                    .ok()
                    .and_then(|p| p.to_str().map(|s| s.to_string()))
                    .unwrap_or_else(|| repository.to_string())
                    .replace('\\', "/");
                let mut repo_config = IndexMap::new();
                repo_config.insert("type".to_string(), PhpMixed::String("composer".to_string()));
                repo_config.insert(
                    "url".to_string(),
                    PhpMixed::String(format!("file://{}", real_path)),
                );
                return Ok(repo_config);
            } else if allow_filesystem {
                let mut repo_config = IndexMap::new();
                repo_config.insert(
                    "type".to_string(),
                    PhpMixed::String("filesystem".to_string()),
                );
                repo_config.insert("json".to_string(), PhpMixed::String(repository.to_string()));
                return Ok(repo_config);
            } else {
                return Err(InvalidArgumentException {
                    message: format!("Invalid repository URL ({}) given. This file does not contain a valid composer repository.", repository),
                    code: 0,
                }.into());
            }
        }

        if repository.starts_with('{') {
            let parsed = JsonFile::parse_json(Some(repository), None)?;
            let repo_config: IndexMap<String, PhpMixed> = parsed
                .as_array()
                .map(|m| m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect())
                .unwrap_or_default();
            return Ok(repo_config);
        }

        Err(InvalidArgumentException {
            message: format!("Invalid repository url ({}) given. Has to be a .json file, an http url or a JSON object.", repository),
            code: 0,
        }.into())
    }

    pub fn from_string(
        io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
        config: &std::rc::Rc<std::cell::RefCell<Config>>,
        repository: &str,
        allow_filesystem: bool,
        rm: Option<&mut RepositoryManager>,
    ) -> anyhow::Result<RepositoryInterfaceHandle> {
        let repo_config =
            Self::config_from_string(io.clone(), config, repository, allow_filesystem)?;
        Self::create_repo(io, config, repo_config, rm)
    }

    pub fn create_repo(
        io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
        config: &std::rc::Rc<std::cell::RefCell<Config>>,
        repo_config: IndexMap<String, PhpMixed>,
        rm: Option<&mut RepositoryManager>,
    ) -> anyhow::Result<RepositoryInterfaceHandle> {
        let mut owned_rm;
        let rm = if let Some(rm) = rm {
            rm
        } else {
            owned_rm = Self::manager(io, config, None, None, None)?;
            &mut owned_rm
        };
        let repos = Self::create_repos(
            rm,
            vec![PhpMixed::Array(
                repo_config
                    .into_iter()
                    .map(|(k, v)| (k, Box::new(v)))
                    .collect(),
            )],
        )?;
        // PHP: return current($repos);
        let (_, first) = repos
            .into_iter()
            .next()
            .ok_or_else(|| UnexpectedValueException {
                message: "create_repos returned no repository".to_string(),
                code: 0,
            })?;
        Ok(first)
    }

    pub fn default_repos(
        io: Option<std::rc::Rc<std::cell::RefCell<dyn IOInterface>>>,
        config: Option<std::rc::Rc<std::cell::RefCell<Config>>>,
        rm: Option<&mut RepositoryManager>,
    ) -> anyhow::Result<IndexMap<String, RepositoryInterfaceHandle>> {
        let config = match config {
            Some(c) => c,
            None => std::rc::Rc::new(std::cell::RefCell::new(Factory::create_config(None, None)?)),
        };
        if let Some(io) = &io {
            io.borrow_mut()
                .load_configuration(&mut *config.borrow_mut())?;
        }

        let mut owned_rm;
        let rm = if let Some(rm) = rm {
            rm
        } else {
            let io = io.ok_or_else(|| InvalidArgumentException {
                message: "This function requires either an IOInterface or a RepositoryManager"
                    .to_string(),
                code: 0,
            })?;
            owned_rm = Self::manager(
                io.clone(),
                &config,
                Some(std::rc::Rc::new(std::cell::RefCell::new(
                    Factory::create_http_downloader(io, &config, IndexMap::new())?,
                ))),
                None,
                None,
            )?;
            &mut owned_rm
        };

        let repo_configs = config.borrow().get_repositories();
        // PHP: array_values($repoConfigs) — keep ordering, discard keys
        Self::create_repos(rm, repo_configs.into_iter().map(|(_, v)| v).collect())
    }

    pub fn manager(
        io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
        config: &std::rc::Rc<std::cell::RefCell<Config>>,
        http_downloader: Option<std::rc::Rc<std::cell::RefCell<HttpDownloader>>>,
        event_dispatcher: Option<std::rc::Rc<std::cell::RefCell<EventDispatcher>>>,
        process: Option<std::rc::Rc<std::cell::RefCell<ProcessExecutor>>>,
    ) -> anyhow::Result<RepositoryManager> {
        let http_downloader = match http_downloader {
            Some(h) => h,
            None => std::rc::Rc::new(std::cell::RefCell::new(Factory::create_http_downloader(
                io.clone(),
                config,
                IndexMap::new(),
            )?)),
        };
        let process = match process {
            Some(p) => p,
            None => {
                let mut p = ProcessExecutor::new(Some(io.clone()));
                p.enable_async();
                std::rc::Rc::new(std::cell::RefCell::new(p))
            }
        };

        let mut rm = RepositoryManager::new(
            io,
            config.clone(),
            http_downloader,
            event_dispatcher,
            Some(process),
        );
        rm.set_repository_class("composer", "Composer\\Repository\\ComposerRepository");
        rm.set_repository_class("vcs", "Composer\\Repository\\VcsRepository");
        rm.set_repository_class("package", "Composer\\Repository\\PackageRepository");
        rm.set_repository_class("pear", "Composer\\Repository\\PearRepository");
        rm.set_repository_class("git", "Composer\\Repository\\VcsRepository");
        rm.set_repository_class("bitbucket", "Composer\\Repository\\VcsRepository");
        rm.set_repository_class("git-bitbucket", "Composer\\Repository\\VcsRepository");
        rm.set_repository_class("github", "Composer\\Repository\\VcsRepository");
        rm.set_repository_class("gitlab", "Composer\\Repository\\VcsRepository");
        rm.set_repository_class("svn", "Composer\\Repository\\VcsRepository");
        rm.set_repository_class("fossil", "Composer\\Repository\\VcsRepository");
        rm.set_repository_class("perforce", "Composer\\Repository\\VcsRepository");
        rm.set_repository_class("hg", "Composer\\Repository\\VcsRepository");
        rm.set_repository_class("artifact", "Composer\\Repository\\ArtifactRepository");
        rm.set_repository_class("path", "Composer\\Repository\\PathRepository");

        Ok(rm)
    }

    pub fn default_repos_with_default_manager(
        io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
    ) -> anyhow::Result<IndexMap<String, RepositoryInterfaceHandle>> {
        let config = std::rc::Rc::new(std::cell::RefCell::new(Factory::create_config(
            Some(io.clone()),
            None,
        )?));
        let mut manager = Self::manager(io.clone(), &config, None, None, None)?;
        io.borrow_mut()
            .load_configuration(&mut *config.borrow_mut())?;
        Self::default_repos(Some(io), Some(config), Some(&mut manager))
    }

    fn create_repos(
        rm: &mut RepositoryManager,
        repo_configs: Vec<PhpMixed>,
    ) -> anyhow::Result<IndexMap<String, RepositoryInterfaceHandle>> {
        let mut repo_map: IndexMap<String, RepositoryInterfaceHandle> = IndexMap::new();

        for (index, repo) in repo_configs.into_iter().enumerate() {
            match &repo {
                PhpMixed::String(_) => {
                    return Err(UnexpectedValueException {
                        message: "\"repositories\" should be an array of repository definitions, only a single repository was given".to_string(),
                        code: 0,
                    }.into());
                }
                PhpMixed::Array(repo_arr) => {
                    if !repo_arr.contains_key("type") {
                        return Err(UnexpectedValueException {
                            message: format!(
                                "Repository \"{}\" ({}) must have a type defined",
                                index,
                                json_encode(&repo).unwrap_or_default()
                            ),
                            code: 0,
                        }
                        .into());
                    }
                    let repo_type = repo_arr
                        .get("type")
                        .and_then(|v| v.as_string())
                        .unwrap_or("")
                        .to_string();
                    let repo_config_map: IndexMap<String, PhpMixed> = repo_arr
                        .iter()
                        .map(|(k, v)| (k.clone(), *v.clone()))
                        .collect();
                    let name =
                        Self::generate_repository_name_indexed(index, &repo_config_map, &repo_map);

                    if repo_type == "filesystem" {
                        let _json_path = repo_arr
                            .get("json")
                            .and_then(|v| v.as_string())
                            .unwrap_or("")
                            .to_string();
                        // TODO(phase-b): FilesystemRepository does not yet implement
                        // RepositoryInterface; once it does, construct it from JsonFile here.
                        let created: RepositoryInterfaceHandle =
                            todo!("FilesystemRepository as dyn RepositoryInterface");
                        repo_map.insert(name, created);
                    } else {
                        let created = rm.create_repository(
                            &repo_type,
                            repo_config_map,
                            Some(&index.to_string()),
                        )?;
                        repo_map.insert(name, created);
                    }
                }
                _ => {
                    return Err(UnexpectedValueException {
                        message: format!(
                            "Repository \"{}\" ({}) should be an array, {} given",
                            index,
                            json_encode(&repo).unwrap_or_default(),
                            get_debug_type(&repo)
                        ),
                        code: 0,
                    }
                    .into());
                }
            }
        }

        Ok(repo_map)
    }

    pub fn generate_repository_name(
        index: &PhpMixed,
        repo: &IndexMap<String, PhpMixed>,
        existing_repos: &IndexMap<String, RepositoryInterfaceHandle>,
    ) -> String {
        let mut name = match index {
            PhpMixed::Int(_) => {
                if let Some(url) = repo.get("url").and_then(|v| v.as_string()) {
                    Preg::replace("{^https?://}i", "", url).unwrap_or_else(|_| url.to_string())
                } else {
                    index.as_string().unwrap_or("").to_string()
                }
            }
            _ => index.as_string().unwrap_or("").to_string(),
        };
        while existing_repos.contains_key(&name) {
            name.push('2');
        }
        name
    }

    fn generate_repository_name_indexed(
        index: usize,
        repo: &IndexMap<String, PhpMixed>,
        existing_repos: &IndexMap<String, RepositoryInterfaceHandle>,
    ) -> String {
        let mut name = if let Some(url) = repo.get("url").and_then(|v| v.as_string()) {
            Preg::replace("{^https?://}i", "", url).unwrap_or_else(|_| url.to_string())
        } else {
            index.to_string()
        };
        while existing_repos.contains_key(&name) {
            name.push('2');
        }
        name
    }
}