libscoop 0.1.0-beta.7

Rust library implementation of Scoop
Documentation
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
pub(crate) mod download;
pub(crate) mod manifest;
pub(crate) mod query;
pub(crate) mod resolve;
pub(crate) mod sync;

use once_cell::unsync::OnceCell;
use std::{fmt, path::PathBuf};

pub use manifest::{HashString, InstallInfo, License, Manifest};
pub use query::QueryOption;
pub use sync::SyncOption;

use crate::{constant::ISOLATED_PACKAGE_BUCKET, internal};

/// A Scoop package.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Package {
    /// The bucket name of this package.
    bucket: String,

    /// The name of this package.
    name: String,

    /// The manifest of this package.
    manifest: Manifest,

    #[serde(skip)]
    origin: OnceCell<OriginateFrom>,

    /// The install state of the package.
    #[serde(skip)]
    install_state: OnceCell<InstallState>,

    /// The upgradable package, if any.
    ///
    /// This field is never serialized.
    #[serde(skip)]
    upgradable: OnceCell<Option<Box<Package>>>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum OriginateFrom {
    Bucket(String),
    File(String),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum InstallState {
    NotInstalled,
    Installed(InstallStateInstalled),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InstallStateInstalled {
    pub version: String,
    pub bucket: Option<String>,
    pub arch: String,
    pub held: bool,
    pub url: Option<String>,
}

impl InstallStateInstalled {
    #[inline]
    pub fn bucket(&self) -> Option<&str> {
        self.bucket.as_deref()
    }

    #[inline]
    pub fn held(&self) -> bool {
        self.held
    }

    #[inline]
    pub fn url(&self) -> Option<&str> {
        self.url.as_deref()
    }

    #[inline]
    pub fn version(&self) -> &str {
        self.version.as_str()
    }
}

impl Package {
    pub fn from(name: &str, bucket: &str, manifest: Manifest) -> Package {
        Package {
            bucket: bucket.to_owned(),
            name: name.to_owned(),
            manifest,
            origin: OnceCell::new(),
            install_state: OnceCell::new(),
            upgradable: OnceCell::new(),
        }
    }

    /// The identity of this package.
    ///
    /// # Returns
    ///
    /// The package identity in the form of `bucket/name`, which is unique for
    /// each package across all buckets.
    #[inline]
    pub fn ident(&self) -> String {
        format!("{}/{}", self.bucket, self.name)
    }

    /// Get the name of this package.
    #[inline]
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    /// Get the bucket name of this package.
    ///
    /// # Note
    ///
    /// Although this method in some cases returns a bucket namer which can be
    /// the same as the bucket name from the install state of a package, it is
    /// not guaranteed to be.
    ///
    /// This method is not identical to `installed_bucket()`, which is designed
    /// to returns the precise installed bucket name if any.
    #[inline]
    pub fn bucket(&self) -> &str {
        self.bucket.as_str()
    }

    /// Get the version of this package.
    ///
    /// # Note
    ///
    /// Although this method in some cases returns a version number which can be
    /// the same as the version number from the installe state of a package, it
    /// is not guaranteed to be.
    ///
    /// This method is not identical to `installed_version()`, which is designed
    /// to returns the precise installed version number if any.
    #[inline]
    pub fn version(&self) -> &str {
        self.manifest.version()
    }

    /// Get the description of this package.
    #[inline]
    pub fn description(&self) -> Option<&str> {
        self.manifest.description()
    }

    /// Get the homepage of this package.
    #[inline]
    pub fn homepage(&self) -> &str {
        self.manifest.homepage()
    }

    /// Get the license of this package.
    pub fn license(&self) -> &License {
        self.manifest.license()
    }

    /// Get the cookie of this package.
    pub fn cookie(&self) -> Option<Vec<(&str, &str)>> {
        self.manifest.cookie().map(|c| {
            c.iter()
                .map(|(k, v)| (k.as_str(), v.as_str()))
                .collect::<Vec<_>>()
        })
    }

    /// Get the dependencies of this package.
    ///
    /// # Note
    ///
    /// There is no guarantee that whether a dependency is represented as a
    /// format of `bucket/name` or `name`.
    ///
    /// # Returns
    ///
    /// A list of dependencies of this package.
    pub fn dependencies(&self) -> Vec<String> {
        self.manifest.dependencies()
    }

    /// Get download urls of this package.
    ///
    /// # Note
    ///
    /// This method will return the actual download urls without the `#/dl.7z`
    /// fragment which is used to fake the file extension of the download urls.
    pub(crate) fn download_urls(&self) -> Vec<&str> {
        self.manifest
            .url()
            .into_iter()
            .map(|u| u.split_once('#').map(|s| s.0).unwrap_or(u))
            .collect::<Vec<_>>()
    }

    /// Get download urls of this package.
    pub(crate) fn download_filenames(&self) -> Vec<String> {
        self.manifest
            .url()
            .into_iter()
            .map(|u| {
                let mut hasher = scoop_hash::ChecksumBuilder::new().sha256().build();
                hasher.consume(u.as_bytes());
                let mut hash = hasher.finalize();
                hash.truncate(7);
                let path = PathBuf::from(u);
                let mut ext = path
                    .extension()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string();
                if !ext.is_empty() {
                    ext.insert(0, '.');
                }

                format!("{}#{}#{}{}", self.name(), self.version(), hash, ext)
            })
            .collect::<Vec<_>>()
    }

    pub(crate) fn download_hashes(&self) -> Vec<&HashString> {
        self.manifest.hash()
    }

    /// Get the installed bucket of this package.
    ///
    /// # Returns
    ///
    /// The installed bucket of this package, if any.
    pub fn installed_bucket(&self) -> Option<&str> {
        match self.install_state.get() {
            None => None,
            Some(state) => match state {
                InstallState::NotInstalled => None,
                InstallState::Installed(info) => {
                    Some(info.bucket().unwrap_or(ISOLATED_PACKAGE_BUCKET))
                }
            },
        }
    }

    /// Get the installed version of this package.
    ///
    /// # Returns
    ///
    /// The installed version of this package, if any.
    pub fn installed_version(&self) -> Option<&str> {
        match self.install_state.get() {
            None => None,
            Some(state) => match state {
                InstallState::NotInstalled => None,
                InstallState::Installed(info) => Some(info.version()),
            },
        }
    }

    /// Check if the package is held.
    ///
    /// # Note
    ///
    /// Only installed package can be held, therefore this method will always
    /// return `false` if the package is not installed.
    pub fn is_held(&self) -> bool {
        match self.install_state.get() {
            None => false,
            Some(state) => match state {
                InstallState::NotInstalled => false,
                InstallState::Installed(info) => info.held(),
            },
        }
    }

    /// Check if the package is installed.
    pub fn is_installed(&self) -> bool {
        self.installed_version().is_some()
    }

    #[inline]
    pub fn is_nightly(&self) -> bool {
        self.version() == "nightly"
    }

    /// Check if the package is strictly installed, which means the package is
    /// installed from the bucket it belongs to rather than from other buckets.
    pub fn is_strictly_installed(&self) -> bool {
        match self.install_state.get() {
            None => false,
            Some(state) => match state {
                InstallState::NotInstalled => false,
                InstallState::Installed(info) => match info.bucket() {
                    Some(bucket) => bucket == self.bucket(),
                    None => false,
                },
            },
        }
    }

    /// Get the manifest of this package.
    ///
    /// # Returns
    ///
    /// The manifest reference of this package.
    #[inline]
    pub fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    /// Get the upgradable version of this package.
    ///
    /// # Returns
    ///
    /// The upgradable version when the package is upgradable, otherwise `None`.
    pub fn upgradable_version(&self) -> Option<&str> {
        let origin_pkg = self.upgradable.get();

        if let Some(Some(pkg)) = origin_pkg {
            return Some(pkg.version());
        } else if let Some(installed_version) = self.installed_version() {
            let this_version = self.version();
            let is_upgradable = internal::compare_versions(this_version, installed_version)
                == std::cmp::Ordering::Greater;
            if is_upgradable {
                return Some(this_version);
            }
        }

        None
    }

    /// Check if this package is upgradable.
    ///
    /// # Returns
    ///
    /// The reference to the upgradable package of this package when it is
    /// upgradable, otherwise `None`.
    pub fn upgradable(&self) -> Option<&Package> {
        if let Some(Some(pkg)) = self.upgradable.get() {
            return Some(pkg.as_ref());
        }
        None
    }

    /// Get shims defined in this package.
    ///
    /// # Returns
    ///
    /// A list of shims defined in this package.
    pub fn shims(&self) -> Option<Vec<&str>> {
        self.manifest.shims()
    }

    pub fn supported_arch(&self) -> Vec<String> {
        let mut ret = vec![];
        if let Some(arch) = self.manifest.architecture() {
            if arch.ia32.is_some() {
                ret.push("ia32".to_string());
            }
            if arch.amd64.is_some() {
                ret.push("amd64".to_string());
            }
            if arch.aarch64.is_some() {
                ret.push("aarch64".to_string());
            }
        }
        ret
    }

    /// Check if this package defines install hooks (powershell scripts) in its
    /// manifest.
    pub(crate) fn has_install_script(&self) -> bool {
        [
            self.manifest.pre_install(),
            self.manifest.post_install(),
            self.manifest
                .installer()
                .map(|i| i.script())
                .unwrap_or_default(),
        ]
        .into_iter()
        .any(|h| h.is_some())
    }

    /// Check if this package defines uninstall hooks (powershell scripts) in its
    /// manifest.
    pub(crate) fn has_uninstall_script(&self) -> bool {
        [
            self.manifest
                .uninstaller()
                .map(|u| u.script())
                .unwrap_or_default(),
            self.manifest.pre_uninstall(),
            self.manifest.post_uninstall(),
        ]
        .into_iter()
        .any(|h| h.is_some())
    }

    pub(crate) fn fill_install_state(&self, state: InstallState) {
        let origin = match &state {
            InstallState::NotInstalled => OriginateFrom::Bucket(self.bucket.clone()),
            InstallState::Installed(info) => match info.url() {
                Some(url) => OriginateFrom::File(url.to_owned()),
                None => OriginateFrom::Bucket(
                    info.bucket().unwrap_or(ISOLATED_PACKAGE_BUCKET).to_owned(),
                ),
            },
        };

        let _ = self.origin.set(origin);
        let _ = self.install_state.set(state);
    }

    pub(crate) fn fill_upgradable(&self, upgradable: Package) {
        let upgradable = Some(Box::new(upgradable));
        let _ = self.upgradable.set(upgradable);
    }
}

impl PartialEq for Package {
    fn eq(&self, other: &Package) -> bool {
        self.name() == other.name()
    }
}

/// Extact `name` from `bucket/name`.
pub(super) fn extract_name<S: AsRef<str>>(input: S) -> String {
    input
        .as_ref()
        .split_once('/')
        .map(|(_, n)| n)
        .unwrap_or(input.as_ref())
        .to_owned()
}

/// Hash mismatch context.
#[derive(Clone, Debug)]
pub struct HashMismatchContext {
    name: String,
    url: String,
    expected: String,
    actual: String,
}

impl fmt::Display for HashMismatchContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Hash mismatch for package '{}':\n     Url: {}\nExpected: {}\n  Actual: {}",
            self.name(),
            self.url(),
            self.expected(),
            self.actual()
        )
    }
}

impl HashMismatchContext {
    /// Create a new hash mismatch context.
    pub fn new(name: String, url: String, expected: String, actual: String) -> HashMismatchContext {
        HashMismatchContext {
            name,
            url,
            expected,
            actual,
        }
    }

    /// name of the package.
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    /// url of corresponding hash mismatched file.
    pub fn url(&self) -> &str {
        self.url.as_str()
    }

    /// Expected hash.
    pub fn expected(&self) -> &str {
        self.expected.as_str()
    }

    /// Actual hash.
    pub fn actual(&self) -> &str {
        self.actual.as_str()
    }
}