oma-pm 0.60.0

APT package manager API abstraction library
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
490
491
use std::{borrow::Cow, cmp::Ordering, path::Path};

use bon::Builder;
use cxx::UniquePtr;
use glob_match::glob_match;
use oma_apt::{
    Package, Version,
    cache::{Cache, PackageSort},
    raw::{IntoRawIter, PkgIterator},
    records::RecordField,
};
use oma_utils::{
    dpkg::{DpkgError, dpkg_arch},
    url_no_escape::url_no_escape,
};
use once_cell::sync::OnceCell;
use spdlog::{debug, info};

use crate::pkginfo::{OmaPackage, OmaPackageWithoutVersion, PtrIsNone};

#[derive(Debug, thiserror::Error)]
pub enum MatcherError {
    #[error("Invalid pattern: {0}")]
    InvalidPattern(String),
    #[error("Can not find package {0} from database")]
    NoPackage(String),
    #[error("Pkg {0} has no version {1}")]
    NoVersion(String, String),
    #[error("Pkg {0} No candidate")]
    NoCandidate(String),
    #[error("Can not find path for local package {0}")]
    NoPath(String),
    #[error(transparent)]
    PtrIsNone(#[from] PtrIsNone),
    #[error(transparent)]
    DpkgError(#[from] DpkgError),
}

/// Type of package search engine to use.
pub enum SearchEngine {
    Indicium(Box<dyn Fn(usize)>),
    Strsim,
    Text,
}

/// Method of getting system architecture.
pub enum GetArchMethod<'a> {
    SpecifySysroot(&'a Path),
    SpecifyArch(&'a str),
    DirectRoot,
}

#[derive(Builder)]

pub struct PackagesMatcher<'a> {
    /// Summary of all pending APT operations in rust-apt
    cache: &'a Cache,
    #[builder(default = true)]
    /// If true, filter and only display matching candidates (defaults to true).
    /// Defaults to true.
    filter_candidate: bool,
    #[builder(default = false)]
    /// Use (defaults to x) to save some space.
    /// Defaults to false
    select_dbg: bool,
    #[builder(default = false)]
    ///If true, filter and only display downloadable candidates.
    /// Defaults to false
    filter_downloadable_candidate: bool,
    #[builder(default = GetArchMethod::DirectRoot)]
    /// Method to determine the native architecture.
    /// Defaults to `GetArchMethod::DirectRoot`.
    native_arch: GetArchMethod<'a>,
    #[builder(skip)]
    arch: OnceCell<Cow<'a, str>>,
}

pub type MatcherResult<T> = Result<T, MatcherError>;

impl<'a> PackagesMatcher<'a> {
    /// Matches packages and versions against the search pattern.
    pub fn match_pkgs_and_versions(
        &self,
        keywords: impl IntoIterator<Item = &'a str>,
    ) -> MatcherResult<(Vec<OmaPackage>, Vec<&'a str>)> {
        let mut pkgs = vec![];
        let mut no_result = vec![];
        for keyword in keywords {
            let res = match keyword {
                x if x.ends_with(".deb") => self.match_local_glob(x)?,
                x if x.split_once('/').is_some() => self.match_from_branch(x)?,
                x if x.split_once('=').is_some() => self.match_from_version(x)?,
                x => self.match_pkgs_and_versions_from_glob(x)?,
            };

            for i in &res {
                debug!("{} {}", i.raw_pkg.fullname(true), i.version_raw.version());
            }

            if res.is_empty() {
                no_result.push(keyword);
                continue;
            }

            pkgs.extend(res);
        }

        Ok((pkgs, no_result))
    }

    /// Query package from give local file glob
    pub fn match_local_glob(&self, file_glob: &str) -> MatcherResult<Vec<OmaPackage>> {
        let mut res = vec![];
        let sort = PackageSort::default().only_virtual();

        let glob = self
            .cache
            .packages(&sort)
            .filter(|x| glob_match::glob_match(file_glob, x.name()));

        for i in glob {
            let real_pkg = real_pkg(&i);
            if let Some(real_pkg) = real_pkg {
                let pkg = Package::new(self.cache, real_pkg);
                let path = url_no_escape(&format!(
                    "file:{}",
                    Path::new(i.name())
                        .canonicalize()
                        .map_err(|_| MatcherError::NoPath(pkg.fullname(true)))?
                        .to_str()
                        .unwrap_or(pkg.name())
                ));

                let versions = pkg.versions();

                for ver in versions {
                    let info = OmaPackage::new(&ver, &pkg);

                    let has = ver.uris().iter().any(|x| url_no_escape(x) == path);
                    if has {
                        res.push(info);
                    }
                }
            }
        }

        Ok(res.into_iter().flatten().collect())
    }

    /// Query package based on a given pattern (without matching version)
    pub fn match_pkgs_from_glob(&self, glob: &str) -> MatcherResult<Vec<OmaPackageWithoutVersion>> {
        let sort = PackageSort::default().include_virtual();

        if glob == "266" {
            info!("吃我一拳!!!");
        }

        let native_arch = self.get_native_arch()?;

        let pkgs = self.cache.packages(&sort).filter(|x| {
            if glob.contains(':') {
                glob_match(glob, &x.fullname(false))
            } else {
                glob_match(glob, x.name()) && x.arch() == native_arch
            }
        });

        let pkgs = pkgs
            .filter_map(|pkg| real_pkg(&pkg))
            .map(|raw_pkg| OmaPackageWithoutVersion { raw_pkg })
            .collect::<Vec<_>>();

        Ok(pkgs)
    }

    fn get_native_arch(&self) -> MatcherResult<&str> {
        Ok(self.arch.get_or_try_init(|| -> MatcherResult<Cow<str>> {
            match self.native_arch {
                GetArchMethod::SpecifySysroot(sysroot) => Ok(Cow::Owned(dpkg_arch(sysroot)?)),
                GetArchMethod::SpecifyArch(arch) => Ok(Cow::Borrowed(arch)),
                GetArchMethod::DirectRoot => Ok(Cow::Owned(dpkg_arch("/")?)),
            }
        })?)
    }

    /// Query package and version from give glob (like: apt*)
    pub fn match_pkgs_and_versions_from_glob(&self, glob: &str) -> MatcherResult<Vec<OmaPackage>> {
        let mut res = vec![];
        let sort = PackageSort::default().include_virtual();

        if glob == "266" {
            info!("吃我一拳!!!");
        }

        let arch = self.get_native_arch()?;

        let pkgs = self.cache.packages(&sort).filter(|x| {
            if glob.contains(':') {
                glob_match(glob, &x.fullname(false))
            } else {
                glob_match(glob, x.name()) && x.arch() == arch
            }
        });

        let pkgs = pkgs
            .filter_map(|x| real_pkg(&x))
            .map(|x| Package::new(self.cache, x));

        for pkg in pkgs {
            debug!("Select pkg: {}", pkg.fullname(true));
            let versions = pkg.versions();
            let mut candidated = false;
            for ver in versions {
                let pkginfo = OmaPackage::new(&ver, &pkg)?;
                let has_dbg = has_dbg(self.cache, &pkg, &ver);

                let is_cand = pkg.candidate().map(|x| x == ver).unwrap_or(false);

                debug!("version: {}, is cand: {}", ver, is_cand);

                if self.filter_candidate && is_cand {
                    if !self.filter_downloadable_candidate || ver.is_downloadable() {
                        // 存在 Packages 文件中版本相同、路径相同、内容不同的情况,因此一个包可能有两个 candidate 对象
                        // 这里只上传其中一个
                        if !candidated {
                            res.push(pkginfo);
                        }

                        candidated = true;
                    } else {
                        let ver = pkg.versions().find(|x| x.is_downloadable());

                        if let Some(ver) = ver {
                            res.push(OmaPackage::new(&ver, &pkg)?);
                        }
                    }
                } else if !self.filter_candidate {
                    res.push(pkginfo);
                }

                if has_dbg && self.select_dbg && (is_cand || !self.filter_candidate) {
                    self.match_debug_packages(&pkg, &ver, &mut res)?;
                }
            }
        }

        // 确保数组第一个是 candidate version
        if !self.filter_candidate {
            res.sort_by(|a, b| {
                b.is_candidate_version(self.cache)
                    .cmp(&a.is_candidate_version(self.cache))
            });
        }

        Ok(res)
    }

    /// Query package from give package and version (like: apt=2.5.4)
    pub fn match_from_version(&self, pat: &str) -> MatcherResult<Vec<OmaPackage>> {
        let (pkgname, version_str) = pat
            .split_once('=')
            .ok_or_else(|| MatcherError::InvalidPattern(pat.to_string()))?;

        let pkg = self
            .cache
            .get(pkgname)
            .ok_or_else(|| MatcherError::NoPackage(pat.to_string()))?;

        let version = pkg
            .get_version(version_str)
            .ok_or_else(|| MatcherError::NoVersion(pkgname.to_string(), version_str.to_string()))?;

        let mut res = vec![];

        let pkginfo = OmaPackage::new(&version, &pkg)?;
        let has_dbg = has_dbg(self.cache, &pkg, &version);

        res.push(pkginfo);

        if has_dbg && self.select_dbg {
            self.match_debug_packages(&pkg, &version, &mut res)?;
        }

        Ok(res)
    }

    /// Query package from give package and branch (like: apt/stable)
    pub fn match_from_branch(&self, pat: &str) -> MatcherResult<Vec<OmaPackage>> {
        let mut res = vec![];
        let (pkgname, branch) = pat
            .split_once('/')
            .ok_or_else(|| MatcherError::InvalidPattern(pat.to_string()))?;

        let pkg = self
            .cache
            .get(pkgname)
            .ok_or_else(|| MatcherError::NoPackage(pat.to_string()))?;

        let mut sort = vec![];

        for i in pkg.versions() {
            let item = i.get_record(RecordField::Filename);

            if let Some(item) = item
                && item.split('/').nth(1) == Some(branch)
            {
                sort.push(i)
            }
        }

        sort.sort_by(|x, y| {
            oma_apt::util::cmp_versions(x.version(), y.version()).unwrap_or(Ordering::Equal)
        });

        if self.filter_candidate {
            let version = sort.last();
            if let Some(version) = version {
                let pkginfo = OmaPackage::new(version, &pkg)?;
                let has_dbg = has_dbg(self.cache, &pkg, version);

                if has_dbg && self.select_dbg {
                    self.match_debug_packages(&pkg, version, &mut res)?;
                }

                res.push(pkginfo);
            }
        } else {
            for i in sort {
                let pkginfo = OmaPackage::new(&i, &pkg)?;
                let has_dbg = has_dbg(self.cache, &pkg, &i);

                if has_dbg && self.select_dbg {
                    self.match_debug_packages(&pkg, &i, &mut res)?;
                }

                res.push(pkginfo);
            }
        }

        Ok(res)
    }

    /// Select -dpg package
    fn match_debug_packages(
        &self,
        pkg: &Package,
        version: &Version,
        res: &mut Vec<OmaPackage>,
    ) -> MatcherResult<()> {
        let dbg_pkg_name = format!("{}-dbg:{}", pkg.name(), version.arch());
        let version_str = version.version();

        if let Some(dbg_pkg) = self.cache.get(&dbg_pkg_name)
            && let Some(dbg_ver) = dbg_pkg.get_version(version_str)
        {
            let pkginfo_dbg = OmaPackage::new(&dbg_ver, &dbg_pkg)?;
            res.push(pkginfo_dbg);
        }

        Ok(())
    }

    /// Find mirror candidate and downloadable package version.
    pub fn find_candidate_by_pkgname(&self, pkg: &str) -> MatcherResult<OmaPackage> {
        if let Some(pkg) = self.cache.get(pkg) {
            // candidate 版本不一定是源中能下载的版本
            // 所以要一个个版本遍历直到找到能下载的版本中最高的版本
            for version in pkg.versions() {
                if version.is_downloadable() {
                    let pkginfo = OmaPackage::new(&version, &pkg)?;
                    debug!(
                        "Pkg: {} selected version: {}",
                        pkg.fullname(true),
                        version.version(),
                    );
                    return Ok(pkginfo);
                }
            }
        }

        Err(MatcherError::NoCandidate(pkg.to_string()))
    }
}

/// Get real pkg from real pkg or virtual package
pub fn real_pkg(pkg: &Package) -> Option<UniquePtr<PkgIterator>> {
    if !pkg.has_versions()
        && let Some(provide) = pkg.provides().next()
    {
        return unsafe { provide.target_pkg() }.make_safe();
    }

    unsafe { pkg.unique() }.make_safe()
}

/// Report whether a specified package provides a matching package for debug symbols.
pub fn has_dbg(cache: &Cache, pkg: &Package<'_>, ver: &Version) -> bool {
    let dbg_pkg = format!("{}-dbg:{}", pkg.name(), ver.arch());
    let dbg_pkg = cache.get(&dbg_pkg);

    if let Some(dbg_pkg) = dbg_pkg {
        dbg_pkg.versions().any(|x| x.version() == ver.version())
    } else {
        false
    }
}

#[cfg(test)]
mod test {
    use crate::{matches::GetArchMethod, test::TEST_LOCK};

    use super::PackagesMatcher;
    use oma_apt::new_cache;

    #[test]
    fn test_glob_search() {
        let _lock = TEST_LOCK.lock().unwrap();
        let cache = new_cache!().unwrap();
        let matcher = PackagesMatcher::builder()
            .cache(&cache)
            .filter_candidate(true)
            .filter_downloadable_candidate(false)
            .select_dbg(false)
            .native_arch(GetArchMethod::DirectRoot)
            .build();

        let res_filter = matcher.match_pkgs_and_versions_from_glob("apt*").unwrap();

        let matcher = PackagesMatcher::builder()
            .cache(&cache)
            .filter_candidate(false)
            .filter_downloadable_candidate(false)
            .select_dbg(false)
            .native_arch(GetArchMethod::DirectRoot)
            .build();

        let res = matcher.match_pkgs_and_versions_from_glob("apt*").unwrap();

        for i in res_filter {
            i.pkg_info(&cache).unwrap();
        }

        println!("---\n");

        for i in res {
            i.pkg_info(&cache).unwrap();
        }
    }

    #[test]
    fn test_virtual_pkg_search() {
        let _lock = TEST_LOCK.lock().unwrap();
        let cache = new_cache!().unwrap();

        let matcher = PackagesMatcher::builder()
            .cache(&cache)
            .filter_candidate(true)
            .filter_downloadable_candidate(false)
            .select_dbg(false)
            .native_arch(GetArchMethod::DirectRoot)
            .build();

        let res_filter = matcher
            .match_pkgs_and_versions_from_glob("telegram")
            .unwrap();

        for i in res_filter {
            i.pkg_info(&cache).unwrap();
        }
    }

    #[test]
    fn test_branch_search() {
        let _lock = TEST_LOCK.lock().unwrap();
        let cache = new_cache!().unwrap();

        let matcher = PackagesMatcher::builder()
            .cache(&cache)
            .filter_candidate(true)
            .filter_downloadable_candidate(false)
            .select_dbg(false)
            .native_arch(GetArchMethod::DirectRoot)
            .build();

        let res_filter = matcher.match_from_branch("apt/stable").unwrap();

        for i in res_filter {
            i.pkg_info(&cache).unwrap();
        }
    }
}