aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/repository/artifact_repository.rs
blob: 7d9c02b6b7a176f17e9742d68c4c9a9aa9ab76ad (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/ArtifactRepository.php

use crate::io::IOInterface;
use crate::io::IOInterfaceImmutable;
use crate::io::io_interface;
use crate::json::JsonFile;
use crate::package::BasePackageHandle;
use crate::package::PackageInterfaceHandle;
use crate::package::loader::ArrayLoader;
use crate::package::loader::LoaderInterface;
use crate::repository::ArrayRepository;
use crate::repository::ConfigurableRepositoryInterface;
use crate::repository::RepositoryInterfaceWeakHandle;
use crate::repository::{
    FindPackageConstraint, LoadPackagesResult, ProviderInfo, RepositoryInterface, SearchResult,
};
use crate::util::Platform;
use crate::util::Tar;
use crate::util::Zip;
use indexmap::IndexMap;
use shirabe_php_shim::{
    PhpMixed, RuntimeException, UnexpectedValueException, extension_loaded, hash_file,
};
use shirabe_semver::constraint::AnyConstraint;
use std::path::Path;

pub struct ArtifactRepository {
    inner: ArrayRepository,
    pub(crate) loader: Box<dyn LoaderInterface>,
    pub(crate) lookup: String,
    pub(crate) repo_config: IndexMap<String, PhpMixed>,
    io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
}

impl std::fmt::Debug for ArtifactRepository {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ArtifactRepository")
            .field("lookup", &self.lookup)
            .field("repo_config", &self.repo_config)
            .finish()
    }
}

impl ArtifactRepository {
    pub fn new(
        repo_config: IndexMap<String, PhpMixed>,
        io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
    ) -> anyhow::Result<Self> {
        if !extension_loaded("zip") {
            return Err(RuntimeException {
                message: "The artifact repository requires PHP's zip extension".to_string(),
                code: 0,
            }
            .into());
        }

        let url = repo_config["url"].as_string().unwrap_or("").to_string();
        let lookup = Platform::expand_path(&url);
        Ok(Self {
            inner: ArrayRepository::new(Vec::new())?,
            loader: Box::new(ArrayLoader::new(None, true)),
            lookup,
            repo_config,
            io,
        })
    }

    pub fn get_repo_name(&self) -> String {
        format!("artifact repo ({})", self.lookup)
    }

    /// For testing only: drives `initialize` (scanning the lookup directory) and returns the
    /// packages collected by the inner `ArrayRepository`, mirroring the polymorphic
    /// `RepositoryInterface::getPackages` dispatch in PHP.
    pub fn __get_packages(&mut self) -> anyhow::Result<Vec<crate::package::BasePackageHandle>> {
        self.initialize()?;
        use crate::repository::RepositoryInterface;
        self.inner.get_packages()
    }

    fn initialize(&self) -> anyhow::Result<()> {
        self.inner.initialize();
        let lookup = self.lookup.clone();
        self.scan_directory(&lookup)
    }

    // In PHP the inherited ArrayRepository methods lazily call the overridden initialize() to scan
    // the lookup directory. Without virtual dispatch we trigger that scan here before delegating to
    // the inner repository; ArrayRepository's own lazy check then sees the populated array and skips
    // re-initializing it.
    fn ensure_initialized(&self) -> anyhow::Result<()> {
        if !self.inner.is_initialized() {
            self.initialize()?;
        }
        Ok(())
    }

    fn scan_directory(&self, path: &str) -> anyhow::Result<()> {
        let entries = std::fs::read_dir(path)?;
        for entry in entries {
            let entry = entry?;
            let file_path = entry.path();

            if file_path.is_symlink() {
                let resolved = std::fs::canonicalize(&file_path)?;
                if resolved.is_dir() {
                    self.scan_directory(resolved.to_str().unwrap_or(""))?;
                    continue;
                }
            }

            if file_path.is_dir() {
                self.scan_directory(file_path.to_str().unwrap_or(""))?;
                continue;
            }

            if !file_path.is_file() {
                continue;
            }

            let ext = file_path
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("")
                .to_lowercase();
            if !matches!(ext.as_str(), "zip" | "tar" | "gz" | "tgz") {
                continue;
            }

            let package = self.get_composer_information(&file_path)?;
            let basename = file_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            match package {
                None => {
                    self.io.write_error3(
                        &format!(
                            "File <comment>{}</comment> doesn't seem to hold a package",
                            basename
                        ),
                        true,
                        io_interface::VERBOSE,
                    );
                }
                Some(package) => {
                    self.io.write_error3(&format!(
                        "Found package <info>{}</info> (<comment>{}</comment>) in file <info>{}</info>",
                        package.get_name(),
                        package.get_pretty_version(),
                        basename,
                    ), true, io_interface::VERBOSE);
                    self.inner.add_package(package);
                }
            }
        }
        Ok(())
    }

    fn get_composer_information(
        &self,
        file: &Path,
    ) -> anyhow::Result<Option<crate::package::PackageInterfaceHandle>> {
        let mut json: Option<String> = None;
        let file_extension = file
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase();

        let file_type: &str;
        if matches!(file_extension.as_str(), "gz" | "tar" | "tgz") {
            file_type = "tar";
        } else if file_extension == "zip" {
            file_type = "zip";
        } else {
            return Err(RuntimeException {
                message: format!(
                    "Files with \"{}\" extensions aren't supported. Only ZIP and TAR/TAR.GZ/TGZ archives are supported.",
                    file_extension
                ),
                code: 0,
            }
            .into());
        }

        let pathname = file.to_str().unwrap_or("");
        let get_result = if file_type == "tar" {
            Tar::get_composer_json(pathname)
        } else {
            Zip::get_composer_json(pathname)
        };
        match get_result {
            Ok(j) => json = j,
            Err(exception) => {
                self.io.write3(
                    &format!("Failed loading package {}: {}", pathname, exception),
                    false,
                    io_interface::VERBOSE,
                );
            }
        }

        if json.is_none() {
            return Ok(None);
        }

        let json_str = json.unwrap();
        let pathname_label = format!("{}#composer.json", pathname);
        let mut package = JsonFile::parse_json(Some(&json_str), Some(&pathname_label))?;
        let url_normalized = pathname.replace('\\', "/");
        let real_path = file
            .canonicalize()
            .ok()
            .and_then(|p| p.to_str().map(|s| s.to_string()))
            .unwrap_or_default();
        let shasum = hash_file("sha1", &real_path).unwrap_or_default();

        let mut dist = IndexMap::new();
        dist.insert("type".to_string(), PhpMixed::String(file_type.to_string()));
        dist.insert("url".to_string(), PhpMixed::String(url_normalized));
        dist.insert("shasum".to_string(), PhpMixed::String(shasum));
        if let Some(arr) = package.as_array_mut() {
            arr.insert("dist".to_string(), PhpMixed::Array(dist));
        }

        let cfg: IndexMap<String, PhpMixed> = package
            .as_array()
            .cloned()
            .map(|m| m.into_iter().collect())
            .unwrap_or_default();
        match self.loader.load(cfg, None) {
            Ok(package) => Ok(Some(package)),
            Err(exception) => Err(UnexpectedValueException {
                message: format!("Failed loading package in {}: {}", pathname, exception),
                code: 0,
            }
            .into()),
        }
    }
}

impl ConfigurableRepositoryInterface for ArtifactRepository {
    fn get_repo_config(&self) -> IndexMap<String, PhpMixed> {
        self.repo_config.clone()
    }
}

impl RepositoryInterface for ArtifactRepository {
    // The structural methods are inherited from ArrayRepository in PHP, where the lazy directory
    // scan is driven by the overridden initialize(). Here each one first ensures that scan has
    // happened (see ensure_initialized), then delegates to the inner ArrayRepository.
    fn count(&self) -> anyhow::Result<usize> {
        self.ensure_initialized()?;
        self.inner.count()
    }

    fn has_package(&self, package: PackageInterfaceHandle) -> bool {
        // TODO(phase-d): hasPackage returns bool and cannot surface an initialization error; a
        // failed scan leaves the inner repository with whatever packages were added before the
        // failure.
        let _ = self.ensure_initialized();
        self.inner.has_package(package)
    }

    fn find_package(
        &mut self,
        name: &str,
        constraint: FindPackageConstraint,
    ) -> anyhow::Result<Option<BasePackageHandle>> {
        self.ensure_initialized()?;
        self.inner.find_package(name, constraint)
    }

    fn find_packages(
        &mut self,
        name: &str,
        constraint: Option<FindPackageConstraint>,
    ) -> anyhow::Result<Vec<BasePackageHandle>> {
        self.ensure_initialized()?;
        self.inner.find_packages(name, constraint)
    }

    fn get_packages(&mut self) -> anyhow::Result<Vec<BasePackageHandle>> {
        self.ensure_initialized()?;
        self.inner.get_packages()
    }

    fn load_packages(
        &mut self,
        package_name_map: IndexMap<String, Option<AnyConstraint>>,
        acceptable_stabilities: IndexMap<String, i64>,
        stability_flags: IndexMap<String, i64>,
        already_loaded: IndexMap<String, IndexMap<String, PackageInterfaceHandle>>,
    ) -> anyhow::Result<LoadPackagesResult> {
        self.ensure_initialized()?;
        self.inner.load_packages(
            package_name_map,
            acceptable_stabilities,
            stability_flags,
            already_loaded,
        )
    }

    fn search(
        &mut self,
        query: String,
        mode: i64,
        r#type: Option<String>,
    ) -> anyhow::Result<Vec<SearchResult>> {
        self.ensure_initialized()?;
        self.inner.search(query, mode, r#type)
    }

    fn get_providers(
        &mut self,
        package_name: String,
    ) -> anyhow::Result<IndexMap<String, ProviderInfo>> {
        self.ensure_initialized()?;
        self.inner.get_providers(package_name)
    }

    fn get_repo_name(&self) -> String {
        ArtifactRepository::get_repo_name(self)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn set_self_handle(&self, weak: RepositoryInterfaceWeakHandle) {
        self.inner.set_self_handle(weak);
    }
}