oma-pm 0.63.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! oma provides these searching methods:
//! - IndiciumSearch: Index search based on `indicium`.
//! - StrSimSearch: Search method based on similarly score, using `strsim`.
//! - TextSearch: Text match search based on `memmem`
use ahash::{AHashMap, RandomState};
use cxx::UniquePtr;
use glob_match::glob_match;
use indexmap::map::Entry;
use indicium::simple::{Indexable, SearchIndex};
use memchr::memmem;
use oma_apt::{
    Package,
    cache::{Cache, PackageSort},
    raw::{IntoRawIter, PkgIterator},
};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;

type IndexSet<T> = indexmap::IndexSet<T, RandomState>;
type IndexMap<K, V> = indexmap::IndexMap<K, V, RandomState>;

use crate::{
    matches::has_dbg,
    pkginfo::{OmaPackage, PtrIsNone},
};

/// Status of the package.
#[derive(PartialEq, Eq, Debug, Clone, Copy, Serialize, Deserialize)]
pub enum PackageStatus {
    Avail,
    Installed,
    Upgrade,
}

impl PartialOrd for PackageStatus {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for PackageStatus {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        match self {
            PackageStatus::Avail => match other {
                PackageStatus::Avail => std::cmp::Ordering::Equal,
                PackageStatus::Installed => std::cmp::Ordering::Greater,
                PackageStatus::Upgrade => std::cmp::Ordering::Less,
            },
            PackageStatus::Installed => match other {
                PackageStatus::Avail => std::cmp::Ordering::Less,
                PackageStatus::Installed => std::cmp::Ordering::Equal,
                PackageStatus::Upgrade => std::cmp::Ordering::Less,
            },
            PackageStatus::Upgrade => match other {
                PackageStatus::Avail => std::cmp::Ordering::Greater,
                PackageStatus::Installed => std::cmp::Ordering::Greater,
                PackageStatus::Upgrade => std::cmp::Ordering::Equal,
            },
        }
    }
}

/// Entry in the package search results.
pub struct SearchEntry {
    /// The name of the package
    name: String,
    /// The description of the package
    description: String,
    /// The status of the package. See [`PackageStatus`]
    status: PackageStatus,
    /// Alias of the package. eg: `telegram-desktop` provides `telegram`.
    provides: IndexSet<String>,
    /// Whether the package provides a matching package for debug symbols.
    has_dbg: bool,
    raw_pkg: UniquePtr<PkgIterator>,
    /// Whether the package is an AOSC OS metapackage (-base package).
    section_is_base: bool,
}

impl Debug for SearchEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SearchEntry")
            .field("pkgname", &self.name)
            .field("description", &self.description)
            .field("status", &self.status)
            .field("provides", &self.provides)
            .field("has_dbg", &self.has_dbg)
            .field("raw_pkg", &self.raw_pkg.fullname(true))
            .field("section_is_base", &self.section_is_base)
            .finish()
    }
}

impl Indexable for SearchEntry {
    fn strings(&self) -> Vec<String> {
        let mut v = vec![self.name.clone(), self.description.clone()];
        let provides = self.provides.clone().into_iter();
        v.extend(provides);
        v
    }
}

#[derive(Debug, thiserror::Error)]
pub enum OmaSearchError {
    #[error("No result found: {0}")]
    NoResult(String),
    #[error("Failed to get candidate version: {0}")]
    FailedGetCandidate(String),
    #[error(transparent)]
    PtrIsNone(#[from] PtrIsNone),
}

pub type OmaSearchResult<T> = Result<T, OmaSearchError>;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Result of a search process.
pub struct SearchResult {
    /// String contains the name of a package to search for.
    pub name: String,
    /// String contains the description of a package.
    pub desc: String,
    /// Optional string contains the old_version(s) of a package
    pub old_version: Option<String>,
    /// String contains the new_version(s) of a package
    pub new_version: String,
    /// Boolean indicating whether this result is a full match or not.
    pub full_match: bool,
    /// Boolean indicating whether this result has a matching package for debug symbols.
    pub dbg_package: bool,
    /// `PackageStatus` instance which reports the status of the package.
    pub status: PackageStatus,
    /// Boolean indicating whether the package is an AOSC OS metapackage (-base package).
    pub is_base: bool,
}

/// Index search based on `indicium`.
pub struct IndiciumSearch<'a> {
    /// Locally cached index.
    cache: &'a Cache,
    /// Map contains package names and their corresponding search entries.
    pkg_map: IndexMap<String, SearchEntry>,
    /// Index used to perform search operations.
    index: SearchIndex<String>,
}

pub trait OmaSearch {
    fn search(&self, query: &str) -> OmaSearchResult<Vec<SearchResult>>;
}

impl OmaSearch for IndiciumSearch<'_> {
    fn search(&self, query: &str) -> OmaSearchResult<Vec<SearchResult>> {
        let mut search_res = vec![];
        let query = query.to_lowercase();
        let res = self.index.search(&query);

        if res.is_empty() {
            return Err(OmaSearchError::NoResult(query));
        }

        for i in res {
            let entry = self.search_result(i, Some(&query))?;
            search_res.push(entry);
        }

        search_res.sort_by_key(|b| std::cmp::Reverse(b.status));

        for i in 0..search_res.len() {
            if search_res[i].full_match {
                let i = search_res.remove(i);
                search_res.insert(0, i);
            }
        }

        Ok(search_res)
    }
}

impl<'a> IndiciumSearch<'a> {
    pub fn new(cache: &'a Cache, progress: impl Fn(usize)) -> OmaSearchResult<Self> {
        let sort = PackageSort::default().include_virtual();
        let packages = cache.packages(&sort);

        let mut pkg_map = IndexMap::with_hasher(RandomState::new());

        for (i, pkg) in packages.enumerate() {
            let name = pkg.fullname(true);
            progress(i);

            if name.contains("-dbg") {
                continue;
            }

            let status = if pkg.is_upgradable() {
                PackageStatus::Upgrade
            } else if pkg.is_installed() {
                PackageStatus::Installed
            } else {
                PackageStatus::Avail
            };

            if let Some(cand) = pkg.candidate() {
                if let Entry::Vacant(e) = pkg_map.entry(name.clone()) {
                    e.insert(SearchEntry {
                        name,
                        description: cand
                            .summary()
                            .unwrap_or_else(|| "No description".to_string()),
                        status,
                        provides: pkg.provides().map(|x| x.to_string()).collect(),
                        has_dbg: has_dbg(cache, &pkg, &cand),
                        raw_pkg: unsafe { pkg.unique() }
                            .make_safe()
                            .ok_or(OmaSearchError::PtrIsNone(PtrIsNone))?,
                        section_is_base: cand.section().map(|x| x == "Bases").unwrap_or(false),
                    });
                }
            } else {
                // Provides
                let mut real_pkgs = vec![];
                for i in pkg.provides() {
                    real_pkgs.push((
                        i.name().to_string(),
                        unsafe { i.target_pkg() }
                            .make_safe()
                            .ok_or(OmaSearchError::PtrIsNone(PtrIsNone))?,
                    ));
                }

                for (provide, i) in real_pkgs {
                    let pkg = Package::new(cache, i);
                    let name = pkg.fullname(true);

                    let status = if pkg.is_upgradable() {
                        PackageStatus::Upgrade
                    } else if pkg.is_installed() {
                        PackageStatus::Installed
                    } else {
                        PackageStatus::Avail
                    };

                    if let Some(cand) = pkg.candidate() {
                        pkg_map
                            .entry(name.clone())
                            .and_modify(|x| {
                                if !x.provides.contains(&provide) {
                                    x.provides.insert(provide.clone());
                                }
                            })
                            .or_insert(SearchEntry {
                                name,
                                description: cand
                                    .summary()
                                    .unwrap_or_else(|| "No description".to_string()),
                                status,
                                provides: {
                                    let mut set = IndexSet::with_hasher(RandomState::new());
                                    set.insert(provide.clone());
                                    set
                                },
                                has_dbg: has_dbg(cache, &pkg, &cand),
                                raw_pkg: unsafe { pkg.unique() }
                                    .make_safe()
                                    .ok_or(OmaSearchError::PtrIsNone(PtrIsNone))?,
                                section_is_base: cand
                                    .section()
                                    .map(|x| x == "Bases")
                                    .unwrap_or(false),
                            });
                    }
                }
            }
        }

        let mut search_index: SearchIndex<String> = SearchIndex::default();

        pkg_map
            .iter()
            .for_each(|(key, value)| search_index.insert(key, value));

        Ok(Self {
            cache,
            pkg_map,
            index: search_index,
        })
    }

    /// Search for a package in the cache and returns the search result.
    ///
    /// # Arguments
    ///
    /// * `i` - A string holds the name of the package to search.
    /// * `query` - An optional string that holds the search query (or pattern).
    ///
    /// # Returns
    ///
    /// * `Ok(SearchResult)` - If a match is found, returns `SearchResult` containing the package details.
    /// * `Err(OmaSearchError)` - If an error occurs during the search, returns an `OmaSearchError`.
    fn search_result(&self, i: &str, query: Option<&str>) -> Result<SearchResult, OmaSearchError> {
        let entry = self.pkg_map.get(i).unwrap();
        let search_name = entry.name.clone();
        let desc = entry.description.clone();
        let status = entry.status;
        let has_dbg = entry.has_dbg;
        let pkg = unsafe { entry.raw_pkg.unique() }
            .make_safe()
            .ok_or(OmaSearchError::PtrIsNone(PtrIsNone))?;
        let pkg = Package::new(self.cache, pkg);

        let full_match = if let Some(query) = query {
            query == search_name || entry.provides.iter().any(|x| x == query)
        } else {
            false
        };

        let old_version = if status != PackageStatus::Upgrade {
            None
        } else {
            pkg.installed().map(|x| x.version().to_string())
        };

        let new_version = pkg
            .candidate()
            .map(|x| x.version().to_string())
            .ok_or_else(|| OmaSearchError::FailedGetCandidate(pkg.fullname(true)))?;

        let is_base = entry.section_is_base;

        Ok(SearchResult {
            name: pkg.fullname(true),
            desc,
            old_version,
            new_version,
            full_match,
            dbg_package: has_dbg,
            status,
            is_base,
        })
    }
}

/// strsim: Sort search results based on based on string matching similarity (score).
pub struct StrSimSearch<'a> {
    /// Locally cached index.
    cache: &'a Cache,
}

impl OmaSearch for StrSimSearch<'_> {
    fn search(&self, query: &str) -> Result<Vec<SearchResult>, OmaSearchError> {
        let sort = PackageSort::default().include_virtual();
        let pkgs = self.cache.packages(&sort);

        let mut res = AHashMap::new();

        for pkg in pkgs {
            let name = pkg.fullname(true);
            if let Some(cand) = pkg.candidate() {
                if memmem::find(name.as_bytes(), query.as_bytes()).is_some()
                    && !name.ends_with("-dbg")
                    && !res.contains_key(&name)
                {
                    let oma_pkg = OmaPackage::new(&cand, &pkg)?;
                    res.insert(
                        name.clone(),
                        (oma_pkg, cand.is_installed(), pkg.is_upgradable(), false),
                    );
                }

                if cand
                    .description()
                    .is_some_and(|x| memmem::find(x.as_bytes(), query.as_bytes()).is_some())
                    && !res.contains_key(&name)
                    && !name.ends_with("-dbg")
                {
                    let oma_pkg = OmaPackage::new(&cand, &pkg)?;
                    res.insert(
                        name.clone(),
                        (oma_pkg, cand.is_installed(), pkg.is_upgradable(), false),
                    );
                }
            } else if name == query && pkg.has_provides() {
                let real_pkgs = pkg.provides().flat_map(|x| {
                    unsafe { x.target_pkg() }
                        .make_safe()
                        .ok_or(OmaSearchError::PtrIsNone(PtrIsNone))
                });
                for pkg in real_pkgs {
                    let pkg = Package::new(self.cache, pkg);
                    if let Some(cand) = pkg.candidate() {
                        let oma_pkg = OmaPackage::new(&cand, &pkg)?;

                        res.insert(
                            name.clone(),
                            (oma_pkg, cand.is_installed(), pkg.is_upgradable(), true),
                        );
                    }
                }
            }
        }

        let mut res = res.into_values().collect::<Vec<_>>();

        res.sort_unstable_by(|x, y| {
            let x_score = Self::pkg_score(query, &x.0, x.3);
            let y_score = Self::pkg_score(query, &y.0, y.3);

            let c = y_score.cmp(&x_score);

            if c == std::cmp::Ordering::Equal {
                y.0.raw_pkg.fullname(true).cmp(&x.0.raw_pkg.fullname(true))
            } else {
                c
            }
        });

        let mut v = vec![];

        for (pkginfo, install, upgrade, _) in res {
            let pkg = Package::new(self.cache, pkginfo.raw_pkg);
            let cand = pkg
                .candidate()
                .ok_or_else(|| OmaSearchError::FailedGetCandidate(pkg.fullname(true)))?;

            let name = pkg.fullname(true);
            let is_base = name.ends_with("-base");
            let full_match = query == name;

            v.push(SearchResult {
                name,
                desc: cand
                    .summary()
                    .unwrap_or_else(|| "No description".to_string()),
                old_version: {
                    if !upgrade {
                        None
                    } else {
                        pkg.installed().map(|x| x.version().to_string())
                    }
                },
                new_version: cand.version().to_string(),
                full_match,
                dbg_package: has_dbg(self.cache, &pkg, &cand),
                status: if upgrade {
                    PackageStatus::Upgrade
                } else if install {
                    PackageStatus::Installed
                } else {
                    PackageStatus::Avail
                },
                is_base,
            });
        }

        v.sort_by_key(|b| std::cmp::Reverse(b.status));

        for i in 0..v.len() {
            if v[i].full_match {
                let i = v.remove(i);
                v.insert(0, i);
            }
        }

        Ok(v)
    }
}

impl<'a> StrSimSearch<'a> {
    pub fn new(cache: &'a Cache) -> Self {
        Self { cache }
    }
    /// return the string similarity score.
    fn pkg_score(input: &str, pkginfo: &OmaPackage, is_provide: bool) -> u16 {
        if is_provide {
            return 1000;
        }

        (strsim::jaro_winkler(&pkginfo.raw_pkg.fullname(true), input) * 1000.0) as u16
    }
}

/// Text match search based on `memmem`
pub struct TextSearch<'a> {
    cache: &'a Cache,
}

impl<'a> TextSearch<'a> {
    pub fn new(cache: &'a Cache) -> Self {
        Self { cache }
    }
}

impl OmaSearch for TextSearch<'_> {
    fn search(&self, query: &str) -> OmaSearchResult<Vec<SearchResult>> {
        let mut res = vec![];

        let sort = PackageSort::default();
        let pkgs = self.cache.packages(&sort);

        for pkg in pkgs {
            let name = pkg.fullname(true);
            let cand = pkg.candidate();

            if (memmem::find(name.as_bytes(), query.as_bytes()).is_some()
                || glob_match(query, &name))
                && !name.ends_with("-dbg")
            {
                let full_match = query == name;
                let is_base = name.ends_with("-base");
                let upgrade = pkg.is_upgradable();
                let installed = pkg.is_installed();
                if let Some(cand) = cand {
                    res.push(SearchResult {
                        name,
                        desc: cand
                            .summary()
                            .unwrap_or_else(|| "No description".to_string()),
                        old_version: {
                            if !pkg.is_upgradable() {
                                None
                            } else {
                                pkg.installed().map(|x| x.version().to_string())
                            }
                        },
                        new_version: cand.version().to_string(),
                        full_match,
                        dbg_package: has_dbg(self.cache, &pkg, &cand),
                        status: if upgrade {
                            PackageStatus::Upgrade
                        } else if installed {
                            PackageStatus::Installed
                        } else {
                            PackageStatus::Avail
                        },
                        is_base,
                    })
                }
            }
        }

        res.sort_by_key(|b| std::cmp::Reverse(b.status));

        for i in 0..res.len() {
            if res[i].full_match {
                let i = res.remove(i);
                res.insert(0, i);
            }
        }

        Ok(res)
    }
}

#[test]
fn test() {
    use crate::test::TEST_LOCK;
    use oma_apt::new_cache;
    let _lock = TEST_LOCK.lock().unwrap();

    let packages = std::path::Path::new(&std::env::var_os("CARGO_MANIFEST_DIR").unwrap())
        .join("test_file")
        .join("Packages");
    let cache = new_cache!(&[packages.to_string_lossy().to_string()]).unwrap();

    let searcher = IndiciumSearch::new(&cache, |_| {}).unwrap();
    let res = searcher.search("windows-nt-kernel").unwrap();
    let res2 = searcher.search("pwp").unwrap();

    for i in [res, res2] {
        assert!(i.iter().any(|x| x.name == "qaq"));
        assert!(i.iter().any(|x| x.new_version == "9999:1"));
        assert!(i.iter().any(|x| x.full_match));
        assert!(i.iter().filter(|x| x.name == "qaq").count() == 1)
    }

    let res = searcher.search("qwq").unwrap();
    let res2 = searcher.search("qwqdesktop").unwrap();

    for i in [res, res2] {
        assert!(i.iter().any(|x| x.name == "qwq-desktop"));
        assert!(i.iter().any(|x| x.new_version == "9999:114514"));
        assert!(i.iter().any(|x| x.full_match));
        assert!(i.iter().filter(|x| x.name == "qwq-desktop").count() == 1)
    }

    let res = searcher.search("owo").unwrap();
    let res = res.first().unwrap();

    assert_eq!(res.name, "owo".to_string());
    assert_eq!(res.new_version, "9999:2.6.1-2");
    assert!(res.full_match);
}