asimov_cli/lib.rs
1// This is free and unencumbered software released into the public domain.
2
3pub mod commands;
4pub mod features;
5pub mod options {}
6pub mod registry;
7pub mod shared;
8
9pub(crate) mod timestamps;
10
11use clientele::{StandardOptions, SysexitsError};
12
13pub type Result<T = SysexitsError, E = SysexitsError> = std::result::Result<T, E>;
14
15/// Sorts links from a module's manifest in the order that we'd like to display
16/// them for the command `link` and for choosing the URL to open for the command
17/// `browse`.
18pub(crate) fn sort_links(module_name: &str, links: &mut [impl AsRef<str>]) {
19 use std::cmp::Reverse;
20
21 links.sort_by_cached_key(|link| {
22 let Ok(url) = reqwest::Url::parse(link.as_ref()) else {
23 // it's not even a valid url? put it last
24 return Reverse(0);
25 };
26
27 let Some(host) = url.host_str() else {
28 // it doesn't have a host, put it last
29 return Reverse(0);
30 };
31
32 // give highest priority to github links under our org
33 let our_module = link.as_ref().contains("github.com/asimov-modules/") as i8;
34
35 let host_score =
36 // give priority to github links
37 (host.ends_with("github.com") as i8 * 2)
38 // then any of the package indices
39 + ((host.ends_with("crates.io") ||
40 host.ends_with("pypi.org") ||
41 host.ends_with("rubygems.org") ||
42 host.ends_with("npmjs.com")) as i8);
43
44 let path_score = {
45 let path = url.path();
46 // give highest priority to links which contain the exact module name
47 (path.contains(&format!("asimov-{module_name}-module")) as i8 * 3)
48 // next to links which contain `asimov-`
49 + (((path.contains("asimov-")
50 // and `-module`
51 && path.contains("-module")
52 // but not `/asimov-modules/`
53 && !path.contains("/asimov-modules/")) as i8) * 2)
54 // and finally if the path does contain `/asimov-modules/`
55 + (path.contains("/asimov-modules/") as i8)
56 };
57
58 // add all the scores together, then reverse it because we want the highest scores first (sort is ascending order)
59 // (add 1 to differentiate from the invalid/host-less links that we return early for)
60 Reverse(our_module * 5 + host_score + path_score + 1)
61 });
62}