1use std::collections::HashSet;
15use std::sync::LazyLock;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Ecosystem {
20 Npm,
22 Pypi,
24 Crates,
26 Rubygems,
28 Go,
30}
31
32const MIN_LEN: usize = 5;
35
36impl Ecosystem {
37 #[must_use]
39 pub fn id(self) -> &'static str {
40 match self {
41 Self::Npm => "npm",
42 Self::Pypi => "pypi",
43 Self::Crates => "crates",
44 Self::Rubygems => "rubygems",
45 Self::Go => "go",
46 }
47 }
48
49 fn index(self) -> usize {
50 match self {
51 Self::Npm => 0,
52 Self::Pypi => 1,
53 Self::Crates => 2,
54 Self::Rubygems => 3,
55 Self::Go => 4,
56 }
57 }
58
59 #[must_use]
61 pub fn from_id(id: &str) -> Option<Self> {
62 [
63 Self::Npm,
64 Self::Pypi,
65 Self::Crates,
66 Self::Rubygems,
67 Self::Go,
68 ]
69 .into_iter()
70 .find(|e| e.id() == id)
71 }
72
73 fn lists(self) -> [&'static str; 2] {
76 match self {
77 Self::Npm => [
78 include_str!("../data/top-packages/npm.txt"),
79 include_str!("../data/top-packages/npm-tools.txt"),
80 ],
81 Self::Pypi => [
82 include_str!("../data/top-packages/pypi.txt"),
83 include_str!("../data/top-packages/pypi-tools.txt"),
84 ],
85 Self::Crates => [include_str!("../data/top-packages/crates.txt"), ""],
86 Self::Rubygems => [include_str!("../data/top-packages/rubygems.txt"), ""],
87 Self::Go => [include_str!("../data/top-packages/go.txt"), ""],
88 }
89 }
90
91 fn affixes(self) -> (&'static [&'static str], &'static [&'static str]) {
94 match self {
95 Self::Npm => (
96 &["node-", "nodejs-", "js-"],
97 &["-js", ".js", "js", "-node", "-nodejs"],
98 ),
99 Self::Pypi => (&["python-", "python3-", "py-", "py"], &["-python", "-py"]),
100 Self::Crates => (&["rust-", "rs-"], &["-rs", "-rust"]),
101 Self::Rubygems => (&["ruby-"], &["-ruby", "-rb", ".rb"]),
102 Self::Go => (&[], &[]),
103 }
104 }
105
106 #[must_use]
110 pub fn normalise(self, name: &str) -> String {
111 let lower = name.to_ascii_lowercase();
112 match self {
113 Self::Pypi => {
114 let mut out = String::with_capacity(lower.len());
115 for c in lower.chars() {
116 if matches!(c, '-' | '_' | '.') {
117 if !out.ends_with('-') {
118 out.push('-');
119 }
120 } else {
121 out.push(c);
122 }
123 }
124 out
125 }
126 Self::Crates => lower.replace('_', "-"),
127 Self::Go => match lower.rsplit_once("/v") {
128 Some((module, major))
129 if !major.is_empty() && major.bytes().all(|b| b.is_ascii_digit()) =>
130 {
131 module.to_owned()
132 }
133 _ => lower,
134 },
135 Self::Npm | Self::Rubygems => lower,
136 }
137 }
138}
139
140struct Top {
142 names: Vec<(String, &'static str)>,
143 known: HashSet<String>,
144}
145
146impl Top {
147 fn load(ecosystem: Ecosystem) -> Self {
148 let names: Vec<(String, &'static str)> = ecosystem
149 .lists()
150 .into_iter()
151 .flat_map(str::lines)
152 .map(str::trim)
153 .filter(|l| !l.is_empty() && !l.starts_with('#'))
154 .map(|l| (ecosystem.normalise(l), l))
155 .collect();
156 let known = names.iter().map(|(n, _)| n.clone()).collect();
157 Self { names, known }
158 }
159}
160
161static TOP: LazyLock<[Top; 5]> = LazyLock::new(|| {
162 [
163 Ecosystem::Npm,
164 Ecosystem::Pypi,
165 Ecosystem::Crates,
166 Ecosystem::Rubygems,
167 Ecosystem::Go,
168 ]
169 .map(Top::load)
170});
171
172#[cfg(test)]
174fn list_len(ecosystem: Ecosystem) -> usize {
175 TOP[ecosystem.index()].names.len()
176}
177
178#[must_use]
184pub fn near_miss(ecosystem: Ecosystem, name: &str) -> Option<&'static str> {
185 let top = &TOP[ecosystem.index()];
186 let key = ecosystem.normalise(name);
187 if !key.is_ascii() || top.known.contains(&key) {
188 return None;
189 }
190 let (prefixes, suffixes) = ecosystem.affixes();
191 let stripped = without_separators(&key);
192 let collapsed = collapse_runs(&key);
193 top.names
194 .iter()
195 .filter(|(popular, _)| popular.len() >= MIN_LEN)
196 .find(|(popular, _)| {
197 (stripped.len() >= MIN_LEN && stripped == without_separators(popular))
198 || (collapsed.len() >= MIN_LEN && collapsed == collapse_runs(popular))
199 || one_edit(&key, popular)
200 || affixed(&key, popular, prefixes, suffixes)
201 || (key.len() >= MIN_LEN && affixed(popular, &key, prefixes, suffixes))
202 })
203 .map(|(_, written)| *written)
204}
205
206#[must_use]
209pub fn is_popular(ecosystem: Ecosystem, name: &str) -> bool {
210 TOP[ecosystem.index()]
211 .known
212 .contains(&ecosystem.normalise(name))
213}
214
215fn without_separators(name: &str) -> String {
216 name.chars()
217 .filter(|c| !matches!(c, '-' | '_' | '.'))
218 .collect()
219}
220
221fn collapse_runs(name: &str) -> String {
223 let mut out = String::with_capacity(name.len());
224 for c in name.chars() {
225 if !out.ends_with(c) {
226 out.push(c);
227 }
228 }
229 out
230}
231
232fn affixed(long: &str, base: &str, prefixes: &[&str], suffixes: &[&str]) -> bool {
234 prefixes
235 .iter()
236 .any(|p| long.strip_prefix(p).is_some_and(|rest| rest == base))
237 || suffixes
238 .iter()
239 .any(|s| long.strip_suffix(s).is_some_and(|rest| rest == base))
240}
241
242fn one_edit(a: &str, b: &str) -> bool {
245 let (a, b) = (a.as_bytes(), b.as_bytes());
246 if a == b || a.len().abs_diff(b.len()) > 1 {
247 return false;
248 }
249 let prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();
250 let (a, b) = (&a[prefix..], &b[prefix..]);
251 match (a.len(), b.len()) {
252 (n, m) if n == m => {
253 a[1..] == b[1..] || (n >= 2 && a[0] == b[1] && a[1] == b[0] && a[2..] == b[2..])
255 }
256 (n, m) if n > m => a[1..] == *b,
257 _ => *a == b[1..],
258 }
259}
260
261#[cfg(test)]
262mod tests;