forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

repo_stats.rs381 lines, 12.0 KiBHistoryRawDownload
1//! Repo statistics from a tree listing: the language shares shown on a repo page, and the license
2//! a root file holds. These are pure functions over paths, sizes and text, so the caller does the
3//! git reads.
4
5use std::collections::BTreeMap;
6
7/// One language's share of the tree.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct LangShare {
10 /// "Rust", or "Other" for the remainder row.
11 pub name: String,
12 pub files: u64,
13 pub bytes: u64,
14 /// Rounded, 0..=100. The shares sum to 100 when there is any code.
15 pub percent: u32,
16 /// Only on the "Other" row: the names of the languages folded into it, biggest first.
17 pub others: Vec<String>,
18}
19
20/// Extensions (lowercase, without the dot) and the language each one counts as.
21const EXTENSIONS: &[(&str, &str)] = &[
22 ("rs", "Rust"),
23 ("js", "JavaScript"),
24 ("mjs", "JavaScript"),
25 ("cjs", "JavaScript"),
26 ("jsx", "JavaScript"),
27 ("ts", "TypeScript"),
28 ("mts", "TypeScript"),
29 ("cts", "TypeScript"),
30 ("tsx", "TypeScript"),
31 ("py", "Python"),
32 ("pyi", "Python"),
33 ("pyw", "Python"),
34 ("go", "Go"),
35 ("c", "C"),
36 ("h", "C"),
37 ("cc", "C++"),
38 ("cpp", "C++"),
39 ("cxx", "C++"),
40 ("c++", "C++"),
41 ("hpp", "C++"),
42 ("hh", "C++"),
43 ("hxx", "C++"),
44 ("cs", "C#"),
45 ("java", "Java"),
46 ("kt", "Kotlin"),
47 ("kts", "Kotlin"),
48 ("swift", "Swift"),
49 ("rb", "Ruby"),
50 ("php", "PHP"),
51 ("sh", "Shell"),
52 ("bash", "Shell"),
53 ("zsh", "Shell"),
54 ("fish", "Shell"),
55 ("lua", "Lua"),
56 ("zig", "Zig"),
57 ("nim", "Nim"),
58 ("hs", "Haskell"),
59 ("ml", "OCaml"),
60 ("mli", "OCaml"),
61 ("ex", "Elixir"),
62 ("exs", "Elixir"),
63 ("erl", "Erlang"),
64 ("hrl", "Erlang"),
65 ("clj", "Clojure"),
66 ("cljs", "Clojure"),
67 ("cljc", "Clojure"),
68 ("scala", "Scala"),
69 ("dart", "Dart"),
70 ("r", "R"),
71 ("jl", "Julia"),
72 ("sql", "SQL"),
73 ("html", "HTML"),
74 ("htm", "HTML"),
75 ("css", "CSS"),
76 ("scss", "SCSS"),
77 ("sass", "Sass"),
78 ("less", "Less"),
79 ("vue", "Vue"),
80 ("svelte", "Svelte"),
81 ("nix", "Nix"),
82 ("dockerfile", "Dockerfile"),
83 ("mk", "Makefile"),
84 ("cmake", "CMake"),
85 ("glsl", "GLSL"),
86 ("vert", "GLSL"),
87 ("frag", "GLSL"),
88 ("comp", "GLSL"),
89 ("wgsl", "WGSL"),
90 ("hlsl", "HLSL"),
91 ("hlsli", "HLSL"),
92 ("s", "Assembly"),
93 ("asm", "Assembly"),
94 ("pl", "Perl"),
95 ("pm", "Perl"),
96 ("ps1", "PowerShell"),
97 ("psm1", "PowerShell"),
98 ("vim", "Vim script"),
99 ("el", "Emacs Lisp"),
100 ("f77", "Fortran"),
101 ("f90", "Fortran"),
102 ("f95", "Fortran"),
103 ("f03", "Fortran"),
104 ("f08", "Fortran"),
105 ("d", "D"),
106 ("v", "V"),
107 ("gleam", "Gleam"),
108 ("odin", "Odin"),
109];
110
111/// Directory names whose contents are vendored or built, so they never count.
112const SKIPPED_SEGMENTS: &[&str] = &[
113 "vendor",
114 "node_modules",
115 "third_party",
116 "dist",
117 "target",
118 ".git",
119];
120
121/// The language a path counts as, by its exact file name or its extension. None for anything
122/// unknown, vendored, generated or prose.
123fn language_of(path: &str) -> Option<&'static str> {
124 if path.split('/').any(|seg| SKIPPED_SEGMENTS.contains(&seg)) {
125 return None;
126 }
127 let name = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase();
128 if name.ends_with(".min.js")
129 || name.ends_with(".min.css")
130 || name.ends_with(".lock")
131 || name == "package-lock.json"
132 || name == "pnpm-lock.yaml"
133 || name.contains(".generated.")
134 || name.ends_with(".pb.go")
135 {
136 return None;
137 }
138 match name.as_str() {
139 "dockerfile" => return Some("Dockerfile"),
140 "makefile" | "gnumakefile" => return Some("Makefile"),
141 "justfile" => return Some("Just"),
142 "cmakelists.txt" => return Some("CMake"),
143 _ => {}
144 }
145 let (_, ext) = name.rsplit_once('.')?;
146 EXTENSIONS
147 .iter()
148 .find(|(e, _)| *e == ext)
149 .map(|(_, lang)| *lang)
150}
151
152/// The languages of a tree from `(path, size)` pairs, biggest first: the top `top` languages, then
153/// one "Other" row folding the rest (left out when nothing is folded). Unknown files, vendored or
154/// generated paths and prose do not count.
155pub fn languages(files: &[(String, u64)], top: usize) -> Vec<LangShare> {
156 let mut by_lang: BTreeMap<&'static str, (u64, u64)> = BTreeMap::new();
157 for (path, size) in files {
158 if let Some(lang) = language_of(path) {
159 let entry = by_lang.entry(lang).or_default();
160 entry.0 += 1;
161 entry.1 += size;
162 }
163 }
164 let mut rows: Vec<LangShare> = by_lang
165 .into_iter()
166 .map(|(name, (files, bytes))| LangShare {
167 name: name.to_string(),
168 files,
169 bytes,
170 percent: 0,
171 others: Vec::new(),
172 })
173 .collect();
174 // Biggest first; equal sizes keep their name order, which the BTreeMap gave.
175 rows.sort_by_key(|a| std::cmp::Reverse(a.bytes));
176
177 if rows.len() > top {
178 let rest = rows.split_off(top);
179 rows.push(LangShare {
180 name: "Other".to_string(),
181 files: rest.iter().map(|r| r.files).sum(),
182 bytes: rest.iter().map(|r| r.bytes).sum(),
183 percent: 0,
184 others: rest.into_iter().map(|r| r.name).collect(),
185 });
186 }
187
188 let total: u64 = rows.iter().map(|r| r.bytes).sum();
189 assign_percents(&mut rows, total);
190 rows
191}
192
193/// Sets each row's percent from its bytes by largest remainder, so the rounded shares sum to 100.
194/// Leaves every percent at 0 when there are no bytes.
195fn assign_percents(rows: &mut [LangShare], total: u64) {
196 if total == 0 {
197 return;
198 }
199 let total = u128::from(total);
200 let mut remainders: Vec<(usize, u128)> = Vec::with_capacity(rows.len());
201 let mut floor_sum = 0u32;
202 for (i, row) in rows.iter_mut().enumerate() {
203 let scaled = u128::from(row.bytes) * 100;
204 row.percent = u32::try_from(scaled / total).unwrap_or(100);
205 floor_sum += row.percent;
206 remainders.push((i, scaled % total));
207 }
208 remainders.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
209 let missing = 100u32.saturating_sub(floor_sum) as usize;
210 for (i, _) in remainders.into_iter().take(missing) {
211 rows[i].percent += 1;
212 }
213}
214
215/// The SPDX id a license text matches, such as "MIT", "Apache-2.0", "GPL-3.0", "AGPL-3.0",
216/// "LGPL-3.0", "MPL-2.0", "BSD-3-Clause", "BSD-2-Clause", "ISC", "Unlicense", "GPL-2.0",
217/// "LGPL-2.1", "BSL-1.0", "0BSD". None when it matches none.
218pub fn license_id(text: &str) -> Option<&'static str> {
219 let t = normalise(text);
220 if t.contains("permission is hereby granted, free of charge") {
221 return Some("MIT");
222 }
223 if t.contains("this is free and unencumbered software released into the public domain") {
224 return Some("Unlicense");
225 }
226 if t.contains("boost software license") {
227 return Some("BSL-1.0");
228 }
229 if t.contains("apache license") && t.contains("version 2.0") {
230 return Some("Apache-2.0");
231 }
232 if t.contains("mozilla public license") && t.contains("2.0") {
233 return Some("MPL-2.0");
234 }
235 if t.contains("permission to use, copy, modify, and/or distribute this software for any purpose with or without fee") {
236 // The ISC text adds the copyright notice requirement that 0BSD drops.
237 return Some(if t.contains("provided that the above copyright notice") {
238 "ISC"
239 } else {
240 "0BSD"
241 });
242 }
243 if t.contains("redistribution and use in source and binary forms") {
244 return Some(if t.contains("neither the name") {
245 "BSD-3-Clause"
246 } else {
247 "BSD-2-Clause"
248 });
249 }
250 copyleft_id(&t)
251}
252
253/// The GPL family id for normalised (lowercase, single-spaced) text. The title that comes first
254/// in the text is the license's own: a GPL text names the LGPL later on.
255fn copyleft_id(t: &str) -> Option<&'static str> {
256 const TITLES: [(&str, &str); 3] = [
257 ("gnu affero general public license", "AGPL"),
258 ("gnu lesser general public license", "LGPL"),
259 ("gnu general public license", "GPL"),
260 ];
261 let (pos, title, family) = TITLES
262 .iter()
263 .filter_map(|(title, family)| t.find(title).map(|pos| (pos, *title, *family)))
264 .min_by_key(|(pos, _, _)| *pos)?;
265 // The version follows the title, as in "Version 3, 29 June 2007".
266 let after: String = t[pos + title.len()..].chars().take(40).collect();
267 let version = if after.contains("version 2.1") {
268 "2.1"
269 } else if after.contains("version 3") {
270 "3"
271 } else if after.contains("version 2") {
272 "2"
273 } else {
274 ""
275 };
276 match (family, version) {
277 ("AGPL", "3") => Some("AGPL-3.0"),
278 ("LGPL", "3") => Some("LGPL-3.0"),
279 ("LGPL", "2.1") => Some("LGPL-2.1"),
280 ("GPL", "3") => Some("GPL-3.0"),
281 ("GPL", "2") => Some("GPL-2.0"),
282 _ => None,
283 }
284}
285
286/// Lowercases the text and collapses every run of whitespace, so line wrapping does not split a
287/// phrase.
288fn normalise(text: &str) -> String {
289 text.split_whitespace()
290 .collect::<Vec<_>>()
291 .join(" ")
292 .to_lowercase()
293}
294
295/// File names that hold a license at the repo root, in preference order (lowercase).
296const LICENSE_NAMES: &[&str] = &[
297 "license",
298 "license.md",
299 "license.txt",
300 "license.rst",
301 "licence",
302 "licence.md",
303 "licence.txt",
304 "copying",
305 "copying.md",
306 "copying.txt",
307 "license-mit",
308 "license-apache",
309 "license-apache-2.0",
310 "license-bsd",
311 "license-gpl",
312];
313
314/// The root entry that holds the license, if any: LICENSE, LICENSE.md, LICENSE.txt, LICENCE,
315/// COPYING, LICENSE-MIT ... (case-insensitive). The first match in a fixed preference order.
316pub fn license_file(root_names: &[String]) -> Option<&str> {
317 LICENSE_NAMES.iter().find_map(|want| {
318 root_names
319 .iter()
320 .find(|name| name.eq_ignore_ascii_case(want))
321 .map(String::as_str)
322 })
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 #[test]
330 fn languages_skip_vendored_and_fold_the_rest() {
331 let files: Vec<(String, u64)> = [
332 ("src/main.rs", 1000),
333 ("src/lib.rs", 500),
334 ("web/app.ts", 300),
335 ("web/view.tsx", 200),
336 ("scripts/run.py", 100),
337 ("README.md", 9999),
338 ("vendor/crate/lib.rs", 50000),
339 ("node_modules/x/index.js", 50000),
340 ("web/app.min.js", 40000),
341 ("Dockerfile", 60),
342 ]
343 .iter()
344 .map(|(p, s)| (p.to_string(), *s))
345 .collect();
346
347 let shares = languages(&files, 1);
348 assert_eq!(shares.len(), 2);
349 assert_eq!(shares[0].name, "Rust");
350 assert_eq!((shares[0].files, shares[0].bytes), (2, 1500));
351 assert_eq!(shares[1].name, "Other");
352 assert_eq!((shares[1].files, shares[1].bytes), (4, 660));
353 assert_eq!(shares[1].others, ["TypeScript", "Python", "Dockerfile"]);
354 assert_eq!(shares.iter().map(|s| s.percent).sum::<u32>(), 100);
355 }
356
357 #[test]
358 fn license_id_matches_mit_and_agpl() {
359 let mit = "MIT License\n\nCopyright (c) 2026 Someone\n\nPermission is hereby granted, free of\ncharge, to any person obtaining a copy";
360 assert_eq!(license_id(mit), Some("MIT"));
361
362 // The AGPL text also names the GPL later on, which must not win.
363 let agpl = " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n ... version 3 of the GNU General Public License ...";
364 assert_eq!(license_id(agpl), Some("AGPL-3.0"));
365 }
366
367 #[test]
368 fn license_file_prefers_license_over_copying() {
369 let names: Vec<String> = ["README.md", "COPYING", "license.txt"]
370 .iter()
371 .map(|s| s.to_string())
372 .collect();
373 assert_eq!(license_file(&names), Some("license.txt"));
374
375 let names: Vec<String> = ["src", "LICENSE.md", "LICENSE"]
376 .iter()
377 .map(|s| s.to_string())
378 .collect();
379 assert_eq!(license_file(&names), Some("LICENSE"));
380 }
381}