steid

@jamesgill /

steid/src/application/summary.rs
Rust18.4 KBCode·Blame·History·Raw
1//! The facts a repository's landing page states about itself.
2//!
3//! A read that composes several git calls, given a home in the application layer
4//! rather than left in a component. `architecture.md` allows a straightforward read to
5//! query directly; this is not one — it is five questions whose answers are gathered
6//! concurrently and whose licence detection is a rule rather than a lookup, and a page
7//! is the wrong place for either.
8//!
9//! Authorization is not re-implemented: like everything in
10//! [`browse`](super::browse), it goes through
11//! [`visible_repo`](super::access::visible_repo), so an invisible repository has no facts.
12
13use crate::domain::{
14 Actor, CommitSummary, EntryKind, OrgName, RefName, RepoName, RepoPath, TagSummary, TreeEntry,
15 repository::{MembershipRepository, OrgRepository, RepoRepository},
16};
17
18use super::{
19 access::{Stores, visible_repo},
20 browse::{MAX_BLOB_BYTES, RefList, organise_refs},
21 error::Result,
22 port::GitQuery,
23};
24
25/// What the About sidebar states about a repository.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct RepoFacts {
28 /// The most recent commit on the revision being shown, for the commit bar.
29 pub latest_commit: Option<CommitSummary>,
30 pub commits: u64,
31 /// Carried whole rather than as two counts, because the page that wants the counts
32 /// also draws the revision switcher — and asking git for the ref list twice on one
33 /// page would be a whole process spent on a number it already had.
34 pub refs: RefList,
35 pub latest_tag: Option<TagSummary>,
36 pub licence: Option<Licence>,
37}
38
39/// The licence a repository appears to be under.
40///
41/// `name` is `None` when a licence file is there but its text names nothing
42/// recognisable. That is deliberately not a guess: the page says "Licence" and links to
43/// the file, which is honest, where naming the wrong licence is a claim about someone's
44/// legal terms.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct Licence {
47 /// The file it was found in, so the page can link to it.
48 pub path: RepoPath,
49 pub name: Option<&'static str>,
50}
51
52/// Gathers everything the repository page states about itself.
53///
54/// Takes the revision and the root listing the page has already read, rather than
55/// reading them again: the caller has just browsed the root to render the file list,
56/// and a second `list_tree` would be a `git` process spent on bytes already in hand.
57///
58/// The five git calls run concurrently, so the page waits for the slowest rather than
59/// for the sum. They are still five processes — see this step's note in
60/// `plans/progress.md` for the count and
61/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md) for the bill
62/// that is eventually coming due.
63///
64/// `Ok(None)` on the same terms as [`browse_repo`](super::browse::browse_repo):
65/// invisible and absent are one answer.
66pub async fn repo_summary(
67 handle: &OrgName,
68 name: &RepoName,
69 rev: &RefName,
70 root: &[TreeEntry],
71 actor: &Actor,
72 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
73 queries: &impl GitQuery,
74) -> Result<Option<RepoFacts>> {
75 if visible_repo(actor, handle, name, stores).await?.is_none() {
76 return Ok(None);
77 }
78
79 let licence_path = licence_file(root);
80
81 let (log, commits, refs, latest_tag, licence_text) = tokio::try_join!(
82 // One commit: the bar above the file list shows the latest, and nothing here
83 // needs the rest of the history.
84 queries.log(handle, name, rev, 0, 1),
85 queries.count_commits(handle, name, rev),
86 queries.list_refs(handle, name),
87 queries.latest_tag(handle, name),
88 async {
89 let Some(path) = &licence_path else {
90 return Ok(None);
91 };
92
93 // Read whole rather than capped at the sniffing window: the port has no
94 // partial read, and a cap below a licence's real size comes back as "too
95 // large" — which would leave Apache-2.0, at 11 KB, permanently unnamed.
96 Ok(queries
97 .read_blob(handle, name, rev, path, MAX_BLOB_BYTES)
98 .await?
99 .and_then(|blob| blob.content)
100 .and_then(|bytes| String::from_utf8(bytes).ok()))
101 },
102 )?;
103
104 Ok(Some(RepoFacts {
105 latest_commit: log.into_iter().next(),
106 commits,
107 refs: organise_refs(refs),
108 latest_tag,
109 licence: licence_path.map(|path| Licence {
110 path,
111 name: licence_text.as_deref().and_then(sniff_licence),
112 }),
113 }))
114}
115
116/// The filenames a licence lives under, lowercased.
117///
118/// Filename-only, and a short list: this runs over a listing the page already has, so
119/// it costs nothing, whereas guessing at `LICENSE-MIT` and friends would multiply the
120/// blob reads. A repository with several licence files gets whichever comes first in
121/// this order.
122const LICENCE_FILES: [&str; 4] = ["license", "license.md", "license.txt", "copying"];
123
124/// How much of a licence to look at.
125///
126/// A kilobyte rather than the couple of hundred bytes a title needs, because BSD is
127/// identified by *which clauses it has* and the third one sits about 900 bytes in. Past
128/// that there is nothing left that distinguishes one licence from another.
129const SNIFF_BYTES: usize = 1024;
130
131/// The licence file in a root listing, if there is one.
132///
133/// Case-insensitive, because all of `LICENSE`, `License` and `license` appear in the
134/// wild and mean the same thing.
135fn licence_file(entries: &[TreeEntry]) -> Option<RepoPath> {
136 entries
137 .iter()
138 .filter(|entry| entry.kind == EntryKind::Blob)
139 .filter_map(|entry| {
140 let lowered = entry.name.to_ascii_lowercase();
141 let rank = LICENCE_FILES.iter().position(|name| *name == lowered)?;
142
143 Some((rank, entry))
144 })
145 .min_by_key(|(rank, _)| *rank)
146 // The entry came out of a root listing, so its name is a single component and
147 // the only way this fails is a name `RepoPath` refuses — in which case there is
148 // no link to offer and no licence to name.
149 .and_then(|(_, entry)| RepoPath::new(&entry.name).ok())
150}
151
152/// Which licence a text appears to be, by the phrases only that licence uses.
153///
154/// Deliberately not a classifier. Every arm here is a phrase from the licence's own
155/// preamble, matched case-insensitively, and anything that matches nothing is `None` —
156/// see [`Licence`] for why a guess is worse than silence.
157///
158/// Order matters where one licence's opening is a prefix of another's: ISC and the
159/// Unlicense both read like MIT for the first few words, and Affero opens with the GPL's
160/// own title.
161fn sniff_licence(text: &str) -> Option<&'static str> {
162 let head: String = text
163 .chars()
164 .take(SNIFF_BYTES)
165 .collect::<String>()
166 .to_ascii_lowercase();
167 let has = |needle: &str| head.contains(needle);
168
169 if has("gnu affero general public license") {
170 return Some("AGPL-3.0");
171 }
172
173 if has("gnu general public license") && has("version 3") {
174 return Some("GPL-3.0");
175 }
176
177 if has("apache license") && has("version 2.0") {
178 return Some("Apache-2.0");
179 }
180
181 if has("mozilla public license") && has("version 2.0") {
182 return Some("MPL-2.0");
183 }
184
185 if has("this is free and unencumbered software released into the public domain") {
186 return Some("Unlicense");
187 }
188
189 // ISC's grant is MIT's with "and/or distribute" in place of MIT's much longer list
190 // of verbs, so it has to be ruled out before MIT is considered.
191 if has("permission to use, copy, modify, and/or distribute") {
192 return Some("ISC");
193 }
194
195 if has("mit license") || has("permission is hereby granted, free of charge") {
196 return Some("MIT");
197 }
198
199 // The BSD family shares one opening and differs only in its clauses.
200 if has("redistribution and use in source and binary forms") {
201 return Some(if has("neither the name") {
202 "BSD-3-Clause"
203 } else {
204 "BSD-2-Clause"
205 });
206 }
207
208 None
209}
210
211#[cfg(test)]
212mod tests {
213 use std::time::{Duration, SystemTime, UNIX_EPOCH};
214
215 use super::*;
216 use crate::{
217 domain::{
218 Membership, MembershipId, ObjectId, OrgId, Organization, RepoId, Repository, UserId,
219 Visibility,
220 },
221 infrastructure::{
222 git::InMemoryGitQuery,
223 repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo},
224 },
225 };
226
227 fn entry(name: &str, kind: EntryKind) -> TreeEntry {
228 TreeEntry {
229 name: name.to_owned(),
230 kind,
231 id: ObjectId::from_trusted("0".repeat(40)),
232 size: Some(0),
233 }
234 }
235
236 // --- finding the file ---------------------------------------------------------
237
238 #[test]
239 fn the_usual_licence_filenames_are_all_found() {
240 for name in [
241 "LICENSE",
242 "license",
243 "License.md",
244 "LICENSE.txt",
245 "COPYING",
246 "copying",
247 ] {
248 let entries = [entry(name, EntryKind::Blob)];
249
250 assert_eq!(
251 licence_file(&entries).as_ref().map(RepoPath::as_str),
252 Some(name),
253 "{name} should be a licence"
254 );
255 }
256 }
257
258 #[test]
259 fn files_that_merely_mention_a_licence_are_not_the_licence() {
260 for name in ["LICENSE-MIT", "licensing.md", "NOTICE", "README.md"] {
261 let entries = [entry(name, EntryKind::Blob)];
262
263 assert!(
264 licence_file(&entries).is_none(),
265 "{name} should not be a licence"
266 );
267 }
268 }
269
270 #[test]
271 fn a_directory_called_license_is_not_a_licence() {
272 // Reading it would ask git for a blob at a tree's path and get nothing.
273 let entries = [entry("LICENSE", EntryKind::Tree)];
274
275 assert!(licence_file(&entries).is_none());
276 }
277
278 #[test]
279 fn the_plainest_spelling_wins_when_there_are_several() {
280 let entries = [
281 entry("COPYING", EntryKind::Blob),
282 entry("LICENSE", EntryKind::Blob),
283 ];
284
285 assert_eq!(
286 licence_file(&entries).as_ref().map(RepoPath::as_str),
287 Some("LICENSE")
288 );
289 }
290
291 // --- naming it ----------------------------------------------------------------
292
293 #[test]
294 fn the_common_licences_are_recognised_from_their_own_words() {
295 let cases = [
296 (
297 " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n",
298 "AGPL-3.0",
299 ),
300 (
301 " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n",
302 "GPL-3.0",
303 ),
304 (
305 " Apache License\n Version 2.0, January 2004\n",
306 "Apache-2.0",
307 ),
308 (
309 "Mozilla Public License Version 2.0\n==================================\n",
310 "MPL-2.0",
311 ),
312 (
313 "MIT License\n\nCopyright (c) 2026 Ada\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n",
314 "MIT",
315 ),
316 (
317 "Copyright (c) 2026 Ada\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n",
318 "ISC",
319 ),
320 (
321 "This is free and unencumbered software released into the public domain.\n",
322 "Unlicense",
323 ),
324 ];
325
326 for (text, expected) in cases {
327 assert_eq!(sniff_licence(text), Some(expected), "for {text:?}");
328 }
329 }
330
331 #[test]
332 fn the_bsd_licences_are_told_apart_by_their_third_clause() {
333 let shared = "Copyright (c) 2026 Ada. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice.\n\n2. Redistributions in binary form must reproduce the above copyright notice.\n";
334
335 assert_eq!(sniff_licence(shared), Some("BSD-2-Clause"));
336 assert_eq!(
337 sniff_licence(&format!(
338 "{shared}\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse products.\n"
339 )),
340 Some("BSD-3-Clause")
341 );
342 }
343
344 #[test]
345 fn a_licence_it_does_not_know_is_left_unnamed_rather_than_guessed() {
346 // The page still links to the file — see `Licence`.
347 assert_eq!(sniff_licence("All rights reserved. Ask me nicely.\n"), None);
348 assert_eq!(sniff_licence(""), None);
349 }
350
351 #[test]
352 fn only_the_head_of_a_file_is_read() {
353 // A licence that names another one deep in its text — Apache's appendix, a
354 // vendored notice — must not change what the file itself is.
355 let text = format!(
356 "MIT License\n{}\nGNU AFFERO GENERAL PUBLIC LICENSE\n",
357 "x".repeat(SNIFF_BYTES)
358 );
359
360 assert_eq!(sniff_licence(&text), Some("MIT"));
361 }
362
363 // --- the whole read -----------------------------------------------------------
364
365 struct Fixture {
366 orgs: InMemoryOrgRepo,
367 memberships: InMemoryMembershipRepo,
368 repos: InMemoryRepoRepo,
369 handle: OrgName,
370 owner: Actor,
371 stranger: Actor,
372 }
373
374 /// One organisation with an owner, and a `steid` repository of the given visibility.
375 async fn fixture(visibility: Visibility) -> Fixture {
376 let orgs = InMemoryOrgRepo::new();
377 let memberships = InMemoryMembershipRepo::new();
378 let repos = InMemoryRepoRepo::new();
379
380 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
381 orgs.save(&org).await.expect("save org");
382
383 let owner = UserId::generate();
384 memberships
385 .save(&Membership::new(
386 MembershipId::generate(),
387 org.id.clone(),
388 owner.clone(),
389 crate::domain::Role::Owner,
390 ))
391 .await
392 .expect("save membership");
393
394 repos
395 .save(
396 &Repository::new(
397 RepoId::generate(),
398 org.id.clone(),
399 "steid",
400 None,
401 visibility,
402 SystemTime::now(),
403 )
404 .expect("valid repository"),
405 )
406 .await
407 .expect("save repo");
408
409 Fixture {
410 orgs,
411 memberships,
412 repos,
413 handle: org.name,
414 owner: Actor::User(owner),
415 stranger: Actor::Anonymous,
416 }
417 }
418
419 impl Fixture {
420 async fn facts(
421 &self,
422 actor: &Actor,
423 root: &[TreeEntry],
424 queries: &InMemoryGitQuery,
425 ) -> Result<Option<RepoFacts>> {
426 repo_summary(
427 &self.handle,
428 &RepoName::new("steid").expect("valid repository name"),
429 &RefName::from_trusted("main"),
430 root,
431 actor,
432 &Stores::new(&self.orgs, &self.memberships, &self.repos),
433 queries,
434 )
435 .await
436 }
437 }
438
439 fn commit(summary: &str) -> CommitSummary {
440 CommitSummary {
441 id: ObjectId::from_trusted("a".repeat(40)),
442 summary: summary.to_owned(),
443 author_name: "Ada Lovelace".to_owned(),
444 committed_at: UNIX_EPOCH + Duration::from_secs(1_700_000_000),
445 }
446 }
447
448 #[tokio::test]
449 async fn the_facts_come_back_composed_from_every_source() {
450 let f = fixture(Visibility::Public).await;
451 let root = [
452 entry("src", EntryKind::Tree),
453 entry("LICENSE", EntryKind::Blob),
454 ];
455 let queries = InMemoryGitQuery::new()
456 .with_log(vec![commit("feat: a global top bar")])
457 .with_commit_count(128)
458 .with_branch("main")
459 .with_branch("next")
460 .with_tag("v0.1.0")
461 .with_latest_tag("v0.1.0", UNIX_EPOCH + Duration::from_secs(1_700_000_000))
462 .with_blob(
463 "main",
464 "LICENSE",
465 b" GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n".to_vec(),
466 );
467
468 let facts = f
469 .facts(&f.owner, &root, &queries)
470 .await
471 .expect("should read")
472 .expect("visible");
473
474 assert_eq!(
475 facts.latest_commit.map(|commit| commit.summary),
476 Some("feat: a global top bar".to_owned())
477 );
478 assert_eq!(facts.commits, 128);
479 assert_eq!(facts.refs.branches.len(), 2);
480 assert_eq!(facts.refs.tags.len(), 1);
481 assert_eq!(
482 facts.latest_tag.map(|tag| tag.name.to_string()),
483 Some("v0.1.0".to_owned())
484 );
485 assert_eq!(
486 facts.licence,
487 Some(Licence {
488 path: RepoPath::from_trusted("LICENSE"),
489 name: Some("AGPL-3.0"),
490 })
491 );
492 }
493
494 #[tokio::test]
495 async fn a_repository_with_no_licence_file_states_no_licence() {
496 // The sparse state: nothing is read, and nothing is claimed.
497 let f = fixture(Visibility::Public).await;
498 let root = [entry("src", EntryKind::Tree)];
499
500 let facts = f
501 .facts(&f.owner, &root, &InMemoryGitQuery::new())
502 .await
503 .expect("should read")
504 .expect("visible");
505
506 assert_eq!(facts.licence, None);
507 assert_eq!(facts.latest_commit, None);
508 assert_eq!(facts.commits, 0);
509 }
510
511 #[tokio::test]
512 async fn a_private_repositorys_facts_are_invisible_to_a_stranger() {
513 // A commit count and a branch list are content. Same answer as the page.
514 let f = fixture(Visibility::Private).await;
515 let queries = InMemoryGitQuery::new().with_branch("secret-work");
516
517 assert!(
518 f.facts(&f.stranger, &[], &queries)
519 .await
520 .expect("should read")
521 .is_none()
522 );
523 assert!(
524 f.facts(&f.owner, &[], &queries)
525 .await
526 .expect("should read")
527 .is_some()
528 );
529 }
530}