Skip to main content

thunderstore_engine/
query.rs

1//! Pure read-side queries over the package index and a profile's installed
2//! packages. Nothing here does IO.
3
4#![deny(missing_docs)]
5
6pub(crate) mod search;
7
8use crate::intern::InternKey;
9use crate::models::PackageIndex;
10use crate::profile::modlist::{ProfileMod, SemVer};
11use crate::util::full_name_prefix;
12use std::collections::{HashMap, HashSet};
13use time::OffsetDateTime;
14
15/// An installed package the index has a newer version of.
16///
17/// `#[non_exhaustive]`: fields may be added, so downstream code cannot
18/// construct or exhaustively destructure this directly.
19#[derive(Debug, Clone, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct OutdatedPackage {
22  /// The package's `Owner-Name` identifier.
23  pub full_name: String,
24  /// The version recorded as installed.
25  pub installed: SemVer,
26  /// The index's most recently published version.
27  pub latest: SemVer,
28}
29
30/// Every installed package whose latest version in `index` is newer than the
31/// installed one, in `installed` order.
32///
33/// "Latest" is the most recently published version, the one
34/// [`Package::latest_version`](crate::models::Package::latest_version) and the
35/// resolver choose, so an update installs what this reports. "Newer" follows
36/// the [`SemVer`] ordering, so a republished older version is never an update.
37/// Packages absent from `index` are never outdated.
38pub fn outdated(installed: &[ProfileMod], index: &PackageIndex) -> Vec<OutdatedPackage> {
39  let by_name: HashMap<&str, usize> = (0..index.len())
40    .filter_map(|idx| Some((index.full_name_at(idx)?, idx)))
41    .collect();
42
43  installed
44    .iter()
45    .filter_map(|package| {
46      let &idx = by_name.get(package.name.as_str())?;
47      let latest = SemVer::parse(index.latest_version_number_at(idx)?);
48
49      (latest > package.version_number).then(|| OutdatedPackage {
50        full_name: package.name.clone(),
51        installed: package.version_number,
52        latest,
53      })
54    })
55    .collect()
56}
57
58/// Every installed package that requires `full_name` (`Owner-Name`), directly
59/// or through other installed packages, in `installed` order.
60///
61/// Reads each package's recorded dependencies, so the result describes what is
62/// installed rather than what the index currently publishes. The package
63/// itself is never listed, even inside a dependency cycle.
64pub fn dependants<'a>(installed: &'a [ProfileMod], full_name: &str) -> Vec<&'a ProfileMod> {
65  let mut required: HashSet<&str> = HashSet::from([full_name]);
66  let mut grew = true;
67
68  while grew {
69    grew = false;
70
71    for package in installed {
72      if required.contains(package.name.as_str()) {
73        continue;
74      }
75
76      if package
77        .dependencies
78        .iter()
79        .any(|dependency| required.contains(full_name_prefix(dependency)))
80      {
81        required.insert(&package.name);
82        grew = true;
83      }
84    }
85  }
86
87  installed
88    .iter()
89    .filter(|package| package.name != full_name && required.contains(package.name.as_str()))
90    .collect()
91}
92
93/// The column [`browse`] orders packages by.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
95pub enum SortKey {
96  /// When the package was last updated.
97  #[default]
98  LastUpdated,
99  /// The short package name, ignoring case.
100  Name,
101  /// Downloads summed over every version.
102  Downloads,
103  /// The rating score. Unset reads as zero.
104  Rating,
105  /// How well a package matches the [search](BrowseQuery::search), best
106  /// first in [`Descending`](SortDirection::Descending) order, ignoring
107  /// community pins. With no search words this sorts like
108  /// [`LastUpdated`](SortKey::LastUpdated), pins included.
109  ///
110  /// The first best-match search on an index folds every package's text and
111  /// keeps it with the index, so later searches only compare.
112  BestMatch,
113}
114
115/// Which way [`browse`] orders its [`SortKey`].
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
117pub enum SortDirection {
118  /// Smallest, earliest, or `A` first.
119  Ascending,
120  /// Largest, latest, or `Z` first.
121  #[default]
122  Descending,
123}
124
125/// What [`browse`] keeps from the package index and in what order.
126#[derive(Debug, Clone)]
127pub struct BrowseQuery<'a> {
128  search: &'a str,
129  show_deprecated: bool,
130  show_nsfw: bool,
131  categories: Vec<&'a str>,
132  sort: SortKey,
133  direction: SortDirection,
134  pinned_first: bool,
135}
136
137impl Default for BrowseQuery<'_> {
138  fn default() -> Self {
139    Self {
140      search: "",
141      show_deprecated: false,
142      show_nsfw: false,
143      categories: Vec::new(),
144      sort: SortKey::default(),
145      direction: SortDirection::default(),
146      pinned_first: true,
147    }
148  }
149}
150
151impl<'a> BrowseQuery<'a> {
152  /// A query with r2modman's browse defaults: deprecated and NSFW packages
153  /// hidden, community-pinned packages first, then most recently updated
154  /// first.
155  pub fn new() -> Self {
156    Self::default()
157  }
158
159  /// Puts packages the community pinned ahead of the rest when `first` is
160  /// true. Each group is sorted on its own.
161  pub fn pinned_first(mut self, first: bool) -> Self {
162    self.pinned_first = first;
163
164    self
165  }
166
167  /// Orders packages by `key` in `direction`. Packages with equal keys keep
168  /// their index order.
169  pub fn sort(mut self, key: SortKey, direction: SortDirection) -> Self {
170    self.sort = key;
171    self.direction = direction;
172
173    self
174  }
175
176  /// Keeps packages marked deprecated when `show` is true.
177  pub fn show_deprecated(mut self, show: bool) -> Self {
178    self.show_deprecated = show;
179
180    self
181  }
182
183  /// Keeps packages marked as having NSFW content when `show` is true.
184  pub fn show_nsfw(mut self, show: bool) -> Self {
185    self.show_nsfw = show;
186
187    self
188  }
189
190  /// Keeps packages matching every word of `search`, split on whitespace and
191  /// underscores. A word matches when the package's name, owner, or latest
192  /// description contains it, ignoring case.
193  ///
194  /// Under [`SortKey::BestMatch`], keeps every package that matches by name,
195  /// owner, description, or a one-letter typo in a word of five or more
196  /// letters, and ranks them: exact name, exact `Owner-Name`, name prefix,
197  /// search words starting name words, name substring, owner prefix, whole
198  /// words, substrings, typos. Packages that rank equally lead with more
199  /// downloads and a better rating. Case, `_`, `-`, spaces, and camelCase
200  /// breaks are ignored, so `valheim plus` matches `ValheimPlus`.
201  pub fn search(mut self, search: &'a str) -> Self {
202    self.search = search;
203
204    self
205  }
206
207  /// Keeps packages in at least one of `categories`. No categories keeps
208  /// every package.
209  pub fn categories(mut self, categories: impl IntoIterator<Item = &'a str>) -> Self {
210    self.categories = categories.into_iter().collect();
211
212    self
213  }
214}
215
216/// The indices of the packages in `index` that `query` keeps, in its order.
217///
218/// Reads only package-level columns and each package's latest version, so it
219/// never builds a [`Package`](crate::models::Package).
220pub fn browse(index: &PackageIndex, query: &BrowseQuery) -> Vec<usize> {
221  let categories: Vec<InternKey> = query
222    .categories
223    .iter()
224    .filter_map(|category| index.interner.get(category))
225    .collect();
226  let shown = |&idx: &usize| {
227    let row = PackageRow { index, idx };
228
229    if (row.is_deprecated() && !query.show_deprecated) || (row.is_nsfw() && !query.show_nsfw) {
230      return false;
231    }
232
233    query.categories.is_empty()
234      || index.categories[idx]
235        .iter()
236        .any(|category| categories.contains(category))
237  };
238
239  if query.sort == SortKey::BestMatch
240    && let Some(needle) = search::Needle::new(query.search)
241  {
242    return search::rank(index, &needle, query.direction, |idx| shown(&idx));
243  }
244
245  let search = match query.sort {
246    SortKey::BestMatch => "",
247    _ => query.search,
248  };
249  let words: Vec<String> = search
250    .split(|c: char| c.is_whitespace() || c == '_')
251    .filter(|word| !word.is_empty())
252    .map(str::to_lowercase)
253    .collect();
254
255  let mut kept: Vec<usize> = (0..index.len())
256    .filter(shown)
257    .filter(|&idx| {
258      let row = PackageRow { index, idx };
259
260      words.iter().all(|word| {
261        let matches =
262          |field: Option<&str>| field.is_some_and(|field| contains_ignoring_case(field, word));
263
264        matches(row.full_name())
265          || matches(row.name())
266          || matches(row.owner())
267          || matches(row.description())
268      })
269    })
270    .collect();
271
272  match query.sort {
273    SortKey::LastUpdated | SortKey::BestMatch => {
274      sort_rows(&mut kept, index, query, |row| row.date_updated())
275    }
276    SortKey::Name => sort_rows(&mut kept, index, query, |row| {
277      IgnoringCase(row.name().unwrap_or_default())
278    }),
279    SortKey::Downloads => sort_rows(&mut kept, index, query, |row| row.downloads()),
280    SortKey::Rating => sort_rows(&mut kept, index, query, |row| row.rating()),
281  }
282
283  kept
284}
285
286/// Stably sorts `kept` by `key` in the query's direction, behind the pinned
287/// group when the query asks for one. Reads each key once.
288fn sort_rows<'a, K: Ord>(
289  kept: &mut [usize],
290  index: &'a PackageIndex,
291  query: &BrowseQuery,
292  key: impl Fn(PackageRow<'a>) -> K,
293) {
294  let mut keyed: Vec<(bool, K, usize)> = kept
295    .iter()
296    .map(|&idx| {
297      let row = PackageRow { index, idx };
298
299      (query.pinned_first && row.is_pinned(), key(row), idx)
300    })
301    .collect();
302
303  keyed.sort_by(|(a_pinned, a, _), (b_pinned, b, _)| {
304    b_pinned.cmp(a_pinned).then_with(|| match query.direction {
305      SortDirection::Ascending => a.cmp(b),
306      SortDirection::Descending => b.cmp(a),
307    })
308  });
309
310  for (slot, (_, _, idx)) in kept.iter_mut().zip(keyed) {
311    *slot = idx;
312  }
313}
314
315/// A string that compares by its lowercase form.
316struct IgnoringCase<'a>(&'a str);
317
318impl PartialEq for IgnoringCase<'_> {
319  fn eq(&self, other: &Self) -> bool {
320    self.cmp(other).is_eq()
321  }
322}
323
324impl Eq for IgnoringCase<'_> {}
325
326impl Ord for IgnoringCase<'_> {
327  fn cmp(&self, other: &Self) -> std::cmp::Ordering {
328    self
329      .0
330      .chars()
331      .flat_map(char::to_lowercase)
332      .cmp(other.0.chars().flat_map(char::to_lowercase))
333  }
334}
335
336impl PartialOrd for IgnoringCase<'_> {
337  fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
338    Some(self.cmp(other))
339  }
340}
341
342/// Whether `haystack` contains `needle`, which must already be lowercase.
343///
344/// Allocates only for a non-ASCII needle: a search runs on every keystroke
345/// over the whole index.
346fn contains_ignoring_case(haystack: &str, needle: &str) -> bool {
347  if !needle.is_ascii() {
348    return haystack.to_lowercase().contains(needle);
349  }
350
351  haystack
352    .as_bytes()
353    .windows(needle.len())
354    .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
355}
356
357/// The fields a package list row shows, read from the index on demand.
358///
359/// Borrows the index and builds nothing up front, so making one per visible
360/// row is free.
361#[derive(Debug, Clone, Copy)]
362pub struct PackageRow<'a> {
363  index: &'a PackageIndex,
364  idx: usize,
365}
366
367impl<'a> PackageRow<'a> {
368  /// The row for the package at `idx`, or `None` if `idx` is out of range.
369  pub fn new(index: &'a PackageIndex, idx: usize) -> Option<Self> {
370    (idx < index.len()).then_some(Self { index, idx })
371  }
372
373  /// The package's position in the index.
374  pub fn index(&self) -> usize {
375    self.idx
376  }
377
378  /// The short package name.
379  pub fn name(&self) -> Option<&'a str> {
380    self.index.name_at(self.idx)
381  }
382
383  /// The `Owner-Name` identifier.
384  pub fn full_name(&self) -> Option<&'a str> {
385    self.index.full_name_at(self.idx)
386  }
387
388  /// The package owner.
389  pub fn owner(&self) -> Option<&'a str> {
390    self.index.owner_at(self.idx)
391  }
392
393  /// The latest version's description.
394  pub fn description(&self) -> Option<&'a str> {
395    let ver_idx = self.index.get_latest_version_at(self.idx)?;
396    let key = self.index.versions.descriptions[ver_idx]?;
397
398    Some(self.index.interner.resolve(&key))
399  }
400
401  /// The latest version's number, such as `1.2.0`.
402  pub fn version_number(&self) -> Option<&'a str> {
403    self.index.latest_version_number_at(self.idx)
404  }
405
406  /// The latest version's icon URL.
407  pub fn icon(&self) -> Option<&'a str> {
408    let ver_idx = self.index.get_latest_version_at(self.idx)?;
409    let key = self.index.versions.icons[ver_idx]?;
410
411    Some(self.index.interner.resolve(&key))
412  }
413
414  /// The package's categories, in index order.
415  pub fn categories(&self) -> impl Iterator<Item = &'a str> + use<'a> {
416    let index = self.index;
417
418    index.categories[self.idx]
419      .iter()
420      .map(move |key| index.interner.resolve(key))
421  }
422
423  /// When the package was last updated.
424  pub fn date_updated(&self) -> OffsetDateTime {
425    self.index.dates_updated[self.idx]
426  }
427
428  /// Downloads summed over every version.
429  pub fn downloads(&self) -> u64 {
430    let (start, end) = self.index.version_ranges[self.idx];
431
432    self.index.versions.downloads[start..end]
433      .iter()
434      .map(|count| u64::from(count.unwrap_or(0)))
435      .sum()
436  }
437
438  /// The rating score. Unset reads as zero.
439  pub fn rating(&self) -> u32 {
440    self.index.rating_scores[self.idx].unwrap_or(0)
441  }
442
443  /// Whether the community pinned the package. Unset reads as false.
444  pub fn is_pinned(&self) -> bool {
445    self.index.is_pinned[self.idx].unwrap_or(false)
446  }
447
448  /// Whether the package is marked deprecated. Unset reads as false.
449  pub fn is_deprecated(&self) -> bool {
450    self.index.is_deprecated[self.idx].unwrap_or(false)
451  }
452
453  /// Whether the package is marked as having NSFW content. Unset reads as
454  /// false.
455  pub fn is_nsfw(&self) -> bool {
456    self.index.has_nsfw_content[self.idx].unwrap_or(false)
457  }
458}
459
460#[cfg(test)]
461mod tests {
462  use super::*;
463  use crate::models::{Package, PackageIndex, Version};
464  use crate::profile::modlist::SemVer;
465  use time::{Duration, OffsetDateTime};
466
467  /// A package whose versions are published in slice order (last is most recent).
468  fn package(full_name: &str, versions: &[&str]) -> Package {
469    let (owner, name) = full_name.split_once('-').unwrap();
470    let start = OffsetDateTime::UNIX_EPOCH;
471
472    Package {
473      name: Some(name.to_string()),
474      full_name: Some(full_name.to_string()),
475      owner: Some(owner.to_string()),
476      package_url: None,
477      date_created: start,
478      date_updated: start,
479      uuid4: None,
480      rating_score: None,
481      is_pinned: None,
482      is_deprecated: None,
483      has_nsfw_content: None,
484      categories: vec![],
485      versions: versions
486        .iter()
487        .enumerate()
488        .map(|(day, version)| Version {
489          name: Some(name.to_string()),
490          full_name: Some(format!("{full_name}-{version}")),
491          description: None,
492          icon: None,
493          version_number: Some(version.to_string()),
494          dependencies: vec![],
495          download_url: None,
496          downloads: None,
497          date_created: start + Duration::days(day as i64),
498          website_url: None,
499          is_active: Some(true),
500          uuid4: None,
501          file_size: None,
502        })
503        .collect(),
504    }
505  }
506
507  fn update(full_name: &str, installed: &str, latest: &str) -> OutdatedPackage {
508    OutdatedPackage {
509      full_name: full_name.to_string(),
510      installed: SemVer::parse(installed),
511      latest: SemVer::parse(latest),
512    }
513  }
514
515  fn installed(full_name: &str, version: &str, dependencies: &[&str]) -> ProfileMod {
516    let (author, name) = full_name.split_once('-').unwrap();
517
518    ProfileMod {
519      manifest_version: 1,
520      name: full_name.to_string(),
521      author_name: author.to_string(),
522      website_url: String::new(),
523      display_name: name.to_string(),
524      description: String::new(),
525      game_version: "0".to_string(),
526      network_mode: "both".to_string(),
527      package_type: "other".to_string(),
528      install_mode: "managed".to_string(),
529      installed_at_time: 0,
530      loaders: vec![],
531      dependencies: dependencies.iter().map(|d| d.to_string()).collect(),
532      incompatibilities: vec![],
533      optional_dependencies: vec![],
534      version_number: SemVer::parse(version),
535      enabled: true,
536      icon: String::new(),
537      online_source: true,
538      trusted_package: false,
539    }
540  }
541
542  fn names(mods: &[&ProfileMod]) -> Vec<String> {
543    mods.iter().map(|m| m.name.clone()).collect()
544  }
545
546  fn profile() -> Vec<ProfileMod> {
547    vec![
548      installed("bbepis-BepInExPack", "5.4.2100", &[]),
549      installed("Owner1-Core", "1.0.0", &["bbepis-BepInExPack-5.4.2100"]),
550      installed("Owner2-UsesCore", "2.0.0", &["Owner1-Core-1.0.0"]),
551      installed("Owner3-Standalone", "1.0.0", &[]),
552      installed(
553        "Owner4-UsesBoth",
554        "1.0.0",
555        &["Owner2-UsesCore-2.0.0", "Owner3-Standalone-1.0.0"],
556      ),
557    ]
558  }
559
560  /// A one-version package listed with `description`, with every flag unset.
561  fn listing(full_name: &str, description: &str) -> Package {
562    let mut listed = package(full_name, &["1.0.0"]);
563    listed.versions[0].description = Some(description.to_string());
564
565    listed
566  }
567
568  pub(super) fn browse_names(index: &PackageIndex, query: &BrowseQuery) -> Vec<String> {
569    browse(index, query)
570      .into_iter()
571      .map(|idx| index.full_name_at(idx).unwrap().to_string())
572      .collect()
573  }
574
575  #[test]
576  fn browse_search_matches_name_owner_or_description_ignoring_case() {
577    let index: PackageIndex = vec![
578      listing("Owner1-MoreCompany", "Lets more players join"),
579      listing("Sigurd-Skins", "Cosmetics"),
580      listing("Owner2-Flashlight", "A brighter LAMP for the ship"),
581      listing("Owner3-Unrelated", "Nothing here"),
582      listing("Owner4-Accents", "ÜBER Café mod"),
583    ]
584    .into();
585
586    let names = |search: &str| browse_names(&index, &BrowseQuery::new().search(search));
587
588    assert_eq!(names("morecomp"), ["Owner1-MoreCompany"]);
589    assert_eq!(names("SIGURD"), ["Sigurd-Skins"]);
590    assert_eq!(names("lamp"), ["Owner2-Flashlight"]);
591    assert_eq!(names("ship brighter"), ["Owner2-Flashlight"]);
592    assert_eq!(names("more_company"), ["Owner1-MoreCompany"]);
593    assert_eq!(names("über CAFÉ"), ["Owner4-Accents"]);
594    assert_eq!(
595      names("sigurd-SKINS"),
596      ["Sigurd-Skins"],
597      "a pasted Owner-Name"
598    );
599    assert_eq!(names("brighter sigurd"), Vec::<String>::new());
600    assert_eq!(names("  ").len(), 5);
601  }
602
603  #[test]
604  fn browse_hides_deprecated_and_nsfw_packages_until_shown() {
605    let mut deprecated = listing("Owner1-Old", "");
606    deprecated.is_deprecated = Some(true);
607    let mut nsfw = listing("Owner2-Lewd", "");
608    nsfw.has_nsfw_content = Some(true);
609    let mut current = listing("Owner3-Current", "");
610    current.is_deprecated = Some(false);
611    current.has_nsfw_content = Some(false);
612    let index: PackageIndex = vec![deprecated, nsfw, current, listing("Owner4-Unset", "")].into();
613
614    let shown = |query: BrowseQuery| browse_names(&index, &query);
615
616    assert_eq!(
617      shown(BrowseQuery::new()),
618      ["Owner3-Current", "Owner4-Unset"]
619    );
620    assert_eq!(
621      shown(BrowseQuery::new().show_deprecated(true)),
622      ["Owner1-Old", "Owner3-Current", "Owner4-Unset"]
623    );
624    assert_eq!(
625      shown(BrowseQuery::new().show_nsfw(true)),
626      ["Owner2-Lewd", "Owner3-Current", "Owner4-Unset"]
627    );
628  }
629
630  #[test]
631  fn browse_keeps_packages_in_any_chosen_category() {
632    let in_categories = |full_name: &str, categories: &[&str]| {
633      let mut listed = listing(full_name, "");
634      listed.categories = categories.iter().map(|c| c.to_string()).collect();
635
636      listed
637    };
638    let index: PackageIndex = vec![
639      in_categories("Owner1-Suits", &["Mods", "Suits"]),
640      in_categories("Owner2-Pack", &["Modpacks"]),
641      in_categories("Owner3-Music", &["Audio", "Mods"]),
642      in_categories("Owner4-None", &[]),
643    ]
644    .into();
645
646    let kept = |categories: &[&str]| {
647      browse_names(
648        &index,
649        &BrowseQuery::new().categories(categories.iter().copied()),
650      )
651    };
652
653    assert_eq!(kept(&["Suits"]), ["Owner1-Suits"]);
654    assert_eq!(
655      kept(&["Audio", "Modpacks"]),
656      ["Owner2-Pack", "Owner3-Music"]
657    );
658    assert_eq!(kept(&["NotACategory"]), Vec::<String>::new());
659    assert_eq!(kept(&[]).len(), 4);
660  }
661
662  /// A package updated `updated_day` days after the epoch, whose versions were
663  /// each downloaded `downloads` times.
664  pub(super) fn ranked(
665    full_name: &str,
666    updated_day: i64,
667    rating: u32,
668    downloads: &[u32],
669  ) -> Package {
670    let numbers: Vec<String> = (0..downloads.len()).map(|n| format!("1.0.{n}")).collect();
671    let numbers: Vec<&str> = numbers.iter().map(String::as_str).collect();
672    let mut listed = package(full_name, &numbers);
673    listed.date_updated = OffsetDateTime::UNIX_EPOCH + Duration::days(updated_day);
674    listed.rating_score = Some(rating);
675
676    for (version, &count) in listed.versions.iter_mut().zip(downloads) {
677      version.downloads = Some(count);
678    }
679
680    listed
681  }
682
683  #[test]
684  fn browse_sorts_by_each_key_in_both_directions() {
685    let index: PackageIndex = vec![
686      ranked("Owner1-bravo", 2, 10, &[50, 60]),
687      ranked("Owner2-Alpha", 3, 30, &[100]),
688      ranked("Owner3-charlie", 1, 20, &[5, 5, 5]),
689    ]
690    .into();
691
692    let sorted = |key: SortKey, direction: SortDirection| {
693      browse_names(&index, &BrowseQuery::new().sort(key, direction))
694    };
695
696    use SortDirection::{Ascending, Descending};
697
698    assert_eq!(
699      sorted(SortKey::LastUpdated, Descending),
700      ["Owner2-Alpha", "Owner1-bravo", "Owner3-charlie"]
701    );
702    assert_eq!(
703      sorted(SortKey::LastUpdated, Ascending),
704      ["Owner3-charlie", "Owner1-bravo", "Owner2-Alpha"]
705    );
706    assert_eq!(
707      sorted(SortKey::Name, Ascending),
708      ["Owner2-Alpha", "Owner1-bravo", "Owner3-charlie"]
709    );
710    assert_eq!(
711      sorted(SortKey::Name, Descending),
712      ["Owner3-charlie", "Owner1-bravo", "Owner2-Alpha"]
713    );
714    assert_eq!(
715      sorted(SortKey::Downloads, Descending),
716      ["Owner1-bravo", "Owner2-Alpha", "Owner3-charlie"]
717    );
718    assert_eq!(
719      sorted(SortKey::Downloads, Ascending),
720      ["Owner3-charlie", "Owner2-Alpha", "Owner1-bravo"]
721    );
722    assert_eq!(
723      sorted(SortKey::Rating, Descending),
724      ["Owner2-Alpha", "Owner3-charlie", "Owner1-bravo"]
725    );
726    assert_eq!(
727      sorted(SortKey::Rating, Ascending),
728      ["Owner1-bravo", "Owner3-charlie", "Owner2-Alpha"]
729    );
730    assert_eq!(
731      browse_names(&index, &BrowseQuery::new()),
732      ["Owner2-Alpha", "Owner1-bravo", "Owner3-charlie"],
733      "newest update first by default"
734    );
735  }
736
737  #[test]
738  fn browse_keeps_index_order_between_equal_keys_in_either_direction() {
739    let index: PackageIndex = vec![
740      ranked("Owner1-First", 1, 5, &[1]),
741      ranked("Owner2-Second", 1, 5, &[1]),
742      ranked("Owner3-Top", 1, 9, &[1]),
743    ]
744    .into();
745
746    assert_eq!(
747      browse_names(
748        &index,
749        &BrowseQuery::new().sort(SortKey::Rating, SortDirection::Descending)
750      ),
751      ["Owner3-Top", "Owner1-First", "Owner2-Second"]
752    );
753    assert_eq!(
754      browse_names(
755        &index,
756        &BrowseQuery::new().sort(SortKey::Rating, SortDirection::Ascending)
757      ),
758      ["Owner1-First", "Owner2-Second", "Owner3-Top"]
759    );
760  }
761
762  #[test]
763  fn browse_leads_with_pinned_packages_sorted_within_each_group() {
764    let pinned = |full_name: &str, rating: u32| {
765      let mut listed = ranked(full_name, 1, rating, &[1]);
766      listed.is_pinned = Some(true);
767
768      listed
769    };
770    let index: PackageIndex = vec![
771      ranked("Owner1-Popular", 1, 90, &[1]),
772      pinned("Owner2-PinnedLow", 10),
773      ranked("Owner3-Middling", 1, 50, &[1]),
774      pinned("Owner4-PinnedHigh", 20),
775    ]
776    .into();
777    let by_rating = BrowseQuery::new().sort(SortKey::Rating, SortDirection::Descending);
778
779    assert_eq!(
780      browse_names(&index, &by_rating),
781      [
782        "Owner4-PinnedHigh",
783        "Owner2-PinnedLow",
784        "Owner1-Popular",
785        "Owner3-Middling"
786      ]
787    );
788    assert_eq!(
789      browse_names(&index, &by_rating.pinned_first(false)),
790      [
791        "Owner1-Popular",
792        "Owner3-Middling",
793        "Owner4-PinnedHigh",
794        "Owner2-PinnedLow"
795      ]
796    );
797  }
798
799  #[test]
800  fn package_row_reads_the_list_fields_of_a_package() {
801    let mut listed = ranked("Owner1-Suits", 4, 12, &[3, 4, 5]);
802    listed.versions[0].description = Some("First release".to_string());
803    listed.versions[2].description = Some("Latest release".to_string());
804    listed.versions[0].icon = Some("https://cdn.example/first.png".to_string());
805    listed.versions[2].icon = Some("https://cdn.example/latest.png".to_string());
806    listed.categories = vec!["Mods".to_string(), "Suits".to_string()];
807    listed.is_pinned = Some(true);
808    listed.is_deprecated = Some(true);
809    listed.has_nsfw_content = Some(false);
810    let index: PackageIndex = vec![listing("Owner0-Other", "Other"), listed].into();
811
812    let row = PackageRow::new(&index, 1).unwrap();
813
814    assert_eq!(row.index(), 1);
815    assert_eq!(row.name(), Some("Suits"));
816    assert_eq!(row.full_name(), Some("Owner1-Suits"));
817    assert_eq!(row.owner(), Some("Owner1"));
818    assert_eq!(row.description(), Some("Latest release"));
819    assert_eq!(row.version_number(), Some("1.0.2"));
820    assert_eq!(row.icon(), Some("https://cdn.example/latest.png"));
821    assert_eq!(row.categories().collect::<Vec<_>>(), ["Mods", "Suits"]);
822    assert_eq!(row.downloads(), 12);
823    assert_eq!(row.rating(), 12);
824    assert_eq!(
825      row.date_updated(),
826      OffsetDateTime::UNIX_EPOCH + Duration::days(4)
827    );
828    assert!(row.is_pinned());
829    assert!(row.is_deprecated());
830    assert!(!row.is_nsfw());
831    assert!(PackageRow::new(&index, 2).is_none());
832  }
833
834  #[test]
835  fn dependants_include_direct_and_transitive_requirers() {
836    let mods = profile();
837
838    assert_eq!(
839      names(&dependants(&mods, "bbepis-BepInExPack")),
840      ["Owner1-Core", "Owner2-UsesCore", "Owner4-UsesBoth"]
841    );
842    assert_eq!(
843      names(&dependants(&mods, "Owner3-Standalone")),
844      ["Owner4-UsesBoth"]
845    );
846  }
847
848  #[test]
849  fn dependants_are_empty_for_a_leaf_or_an_unknown_package() {
850    let mods = profile();
851
852    assert!(dependants(&mods, "Owner4-UsesBoth").is_empty());
853    assert!(dependants(&mods, "Nobody-Missing").is_empty());
854  }
855
856  #[test]
857  fn dependants_terminate_on_a_cycle_and_omit_the_package_itself() {
858    let mods = vec![
859      installed("Owner1-A", "1.0.0", &["Owner2-B-1.0.0"]),
860      installed("Owner2-B", "1.0.0", &["Owner1-A-1.0.0"]),
861      installed("Owner3-C", "1.0.0", &["Owner2-B-1.0.0"]),
862    ];
863
864    assert_eq!(
865      names(&dependants(&mods, "Owner1-A")),
866      ["Owner2-B", "Owner3-C"]
867    );
868  }
869
870  #[test]
871  fn outdated_lists_packages_with_a_newer_version_in_the_index() {
872    let mods = vec![
873      installed("Owner1-Core", "1.0.9", &[]),
874      installed("Owner2-Current", "2.0.0", &[]),
875      installed("Owner3-Behind", "1.2", &[]),
876      installed("Local-NotInIndex", "1.0.0", &[]),
877    ];
878    let index: PackageIndex = vec![
879      package("Owner3-Behind", &["1.2.0", "1.2.1"]),
880      package("Owner1-Core", &["1.0.8", "1.0.9", "1.0.10"]),
881      package("Owner2-Current", &["1.0.0", "2.0.0"]),
882    ]
883    .into();
884
885    assert_eq!(
886      outdated(&mods, &index),
887      [
888        update("Owner1-Core", "1.0.9", "1.0.10"),
889        update("Owner3-Behind", "1.2.0", "1.2.1"),
890      ]
891    );
892  }
893
894  #[test]
895  fn outdated_uses_the_most_recently_published_version_as_latest() {
896    let mods = vec![
897      installed("Owner1-OnHighest", "2.0.0", &[]),
898      installed("Owner2-Behind", "1.0.0", &[]),
899      installed("Owner3-AheadOfIndex", "3.0.0", &[]),
900    ];
901    let index: PackageIndex = vec![
902      package("Owner1-OnHighest", &["1.0.0", "2.0.0", "1.5.0"]),
903      package("Owner2-Behind", &["1.0.0", "2.0.0", "1.5.0"]),
904      package("Owner3-AheadOfIndex", &["2.0.0"]),
905    ]
906    .into();
907
908    assert_eq!(
909      outdated(&mods, &index),
910      [update("Owner2-Behind", "1.0.0", "1.5.0")]
911    );
912  }
913}