oficina / estilo Public

Clone
git clone https://amadan.net/oficina/estilo

Plain git — no account needed to clone.

Download

Download this file

1// Package colophon is the suite's Colophon: every open-source project an
2// app is made with, said in a sentence or two, with who made it, the
3// licence it is under and where it lives.
4//
5// The words are the catalog's (projects.json), one entry per project, so
6// every app that ships Yjs describes Yjs the same way. What an app uses a
7// project for is the entry's usage note for that app. The list is not
8// written by hand: an app collects what it actually ships (Go modules from
9// its production build, JavaScript packages from its bundles, Rust crates
10// from its WebAssembly, fonts, icons and vendored files) and Build matches
11// that against the catalog. Build refuses a shipped package the catalog
12// does not know, a usage note for something the app no longer ships, and
13// a package without its licence text, so an app's own test of Build is
14// the test that the Colophon and the shipped set cannot differ.
15//
16// The page needs no script and downloads no font: it is chrome, set in the
17// system UI face it inherits (AGENTS.md row 9).
18package colophon
19
20import (
21 "bytes"
22 "embed"
23 "encoding/json"
24 "errors"
25 "fmt"
26 "net/url"
27 "regexp"
28 "sort"
29 "strings"
30 "unicode"
31 "unicode/utf8"
32
33 "amadan.net/oficina/estilo.git/credits"
34)
35
36//go:embed projects.json
37var projectsJSON []byte
38
39//go:embed templates/*.html
40var templateFS embed.FS
41
42//go:embed colophon.css
43var stylesheet []byte
44
45// Templates holds "estilo/colophon" (Page) and "estilo/colophon-licence"
46// (LicencePage).
47func Templates() embed.FS { return templateFS }
48
49// CSS is the page's stylesheet, linked after estilo's base.
50func CSS() []byte { return append([]byte(nil), stylesheet...) }
51
52// Kind is what sort of thing a project is, and so which section it is in.
53type Kind string
54
55const (
56 Typeface Kind = "typeface"
57 Library Kind = "library"
58 Icons Kind = "icons"
59 Data Kind = "data"
60 Tool Kind = "tool"
61 Service Kind = "service"
62)
63
64// Ecosystems: where a package's name comes from.
65const (
66 Go = "go" // a Go module path
67 NPM = "npm" // an npm package name
68 Cargo = "cargo" // a crates.io crate name
69 Swift = "swift" // a Swift package's identity in Package.resolved
70 Font = "font" // a font family's name
71 Asset = "asset" // a vendored file or set of files
72 Toolchain = "toolchain" // a language's compiler and standard library
73 Pip = "pip" // a Python package used by a script
74)
75
76// NoAssertion is the licence of a package published with no licence file
77// (SPDX's own word for it). It is the one licence a package may ship
78// without a notice, and the page says so.
79const NoAssertion = "NOASSERTION"
80
81// Licence is a project's licence: its SPDX expression and its name as a
82// person reads it.
83type Licence struct {
84 SPDX string `json:"spdx"`
85 Name string `json:"name"`
86}
87
88// Ref names a package a project publishes.
89type Ref struct {
90 Ecosystem string `json:"ecosystem"`
91 Name string `json:"name"`
92}
93
94func (r Ref) String() string { return r.Ecosystem + ":" + r.Name }
95
96// Project is one catalog entry.
97type Project struct {
98 ID string `json:"id"`
99 Name string `json:"name"`
100 Kind Kind `json:"kind"`
101 // Blurb says what the project is, in one or two sentences.
102 Blurb string `json:"blurb"`
103 // Author is who holds the copyright, as its licence file names them,
104 // not a package manifest's list of maintainers. Where the licence names
105 // no one (many MIT and Apache texts), it is the project's own authors.
106 Author string `json:"author"`
107 Licence Licence `json:"licence"`
108 Home string `json:"home"`
109 Source string `json:"source"`
110 // Packages are every package of the project an app might ship.
111 Packages []Ref `json:"packages"`
112 // Uses is what each app uses it for, keyed by the app's colophon key
113 // ("docs", "docs-native"), one or two sentences each. "*" is the note
114 // for every app without its own ("Yrs uses it."), so a transitive
115 // dependency is written once, not once per app. Only an app's own
116 // note can be stale.
117 Uses map[string]string `json:"uses"`
118 // Via is the projects (catalog ids) a "*" note names as what uses this
119 // one ("serde_json uses it." is via serde-json). A crate's default note
120 // is true in an app only if every one of them uses the crate there,
121 // through a package that ships, so Build checks it against the
122 // dependents CollectCargo records.
123 Via []string `json:"via,omitempty"`
124}
125
126var projects = func() []Project {
127 var file struct {
128 Comment string `json:"comment"`
129 Projects []Project `json:"projects"`
130 }
131 decoder := json.NewDecoder(bytes.NewReader(projectsJSON))
132 decoder.DisallowUnknownFields()
133 if err := decoder.Decode(&file); err != nil {
134 panic("colophon: projects.json: " + err.Error())
135 }
136 if err := Validate(file.Projects); err != nil {
137 panic(err)
138 }
139 return file.Projects
140}()
141
142// Catalog is a copy of every project in the catalog.
143func Catalog() []Project {
144 out := make([]Project, len(projects))
145 for i, p := range projects {
146 p.Packages = append([]Ref(nil), p.Packages...)
147 uses := make(map[string]string, len(p.Uses))
148 for k, v := range p.Uses {
149 uses[k] = v
150 }
151 p.Uses = uses
152 out[i] = p
153 }
154 return out
155}
156
157var (
158 idPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)
159 sentenceEnd = regexp.MustCompile(`[.!?]["”’)]?(\s+|$)`)
160 knownKinds = map[Kind]bool{Typeface: true, Library: true, Icons: true, Data: true, Tool: true, Service: true}
161 knownSystems = map[string]bool{Go: true, NPM: true, Cargo: true, Swift: true, Font: true, Asset: true, Toolchain: true, Pip: true}
162)
163
164// sentences counts the sentences in s, roughly: a full stop, question or
165// exclamation mark followed by a space or the end. Abbreviations count
166// too, which errs towards shorter blurbs.
167func sentences(s string) int { return len(sentenceEnd.FindAllStringIndex(s, -1)) }
168
169// sentence reports whether s is written as sentences: it ends with a full
170// stop. A usage note may open with a project's own lower-case name
171// ("wasmi uses it."); a blurb opens with a capital (capitalised).
172func sentence(s string) bool {
173 s = strings.TrimSpace(s)
174 return s != "" && sentenceEnd.MatchString(s) && strings.HasSuffix(strings.TrimRight(s, `"”’)`), ".")
175}
176
177// capitalised reads the first letter, not the first byte: "Łukasz" is
178// capitalised, and Validate runs at init.
179func capitalised(s string) bool {
180 r, _ := utf8.DecodeRuneInString(strings.TrimSpace(s))
181 return r != utf8.RuneError && !unicode.IsLower(r)
182}
183
184func httpsURL(s string) bool {
185 u, err := url.Parse(s)
186 return err == nil && u.Scheme == "https" && u.Host != ""
187}
188
189// Validate reports every way a list of projects falls short of a catalog:
190// an entry without a blurb of one or two sentences, an author, a licence,
191// an https home and source, or a package; a package two projects claim;
192// and a usage note that is not a sentence.
193func Validate(projects []Project) error {
194 var problems []string
195 ids := map[string]bool{}
196 owner := map[Ref]string{}
197 for _, p := range projects {
198 bad := func(format string, args ...any) {
199 problems = append(problems, p.ID+": "+fmt.Sprintf(format, args...))
200 }
201 if !idPattern.MatchString(p.ID) {
202 bad("id is not lower-case words joined by hyphens")
203 }
204 if ids[p.ID] {
205 bad("id is used twice")
206 }
207 for _, s := range sectionOrder {
208 if p.ID == s {
209 bad("id is a section's, and the page anchors both")
210 }
211 }
212 ids[p.ID] = true
213 if strings.TrimSpace(p.Name) == "" {
214 bad("no name")
215 }
216 if !knownKinds[p.Kind] {
217 bad("unknown kind %q", p.Kind)
218 }
219 if !sentence(p.Blurb) || !capitalised(p.Blurb) || sentences(p.Blurb) > 2 {
220 bad("the blurb must be one or two sentences")
221 }
222 if strings.TrimSpace(p.Author) == "" {
223 bad("no author")
224 }
225 if strings.TrimSpace(p.Licence.SPDX) == "" || strings.TrimSpace(p.Licence.Name) == "" {
226 bad("no licence")
227 }
228 if !httpsURL(p.Home) || !httpsURL(p.Source) {
229 bad("home and source must be https URLs")
230 }
231 if len(p.Packages) == 0 {
232 bad("no packages")
233 }
234 for _, r := range p.Packages {
235 if !knownSystems[r.Ecosystem] || r.Name == "" {
236 bad("unknown package %s", r)
237 continue
238 }
239 if other, taken := owner[r]; taken {
240 bad("%s is also %s's", r, other)
241 }
242 owner[r] = p.ID
243 }
244 cargo := false
245 for _, r := range p.Packages {
246 cargo = cargo || r.Ecosystem == Cargo
247 }
248 if p.Uses["*"] != "" && cargo && len(p.Via) == 0 {
249 bad("a crate's default note must say, in via, which dependents it names")
250 }
251 for app, use := range p.Uses {
252 if !sentence(use) || sentences(use) > 2 {
253 bad("the usage note for %s must be one or two sentences", app)
254 }
255 }
256 }
257 for _, p := range projects {
258 for _, v := range p.Via {
259 if !ids[v] {
260 problems = append(problems, p.ID+": via names "+v+", which is not in the catalog")
261 }
262 }
263 }
264 if len(problems) > 0 {
265 sort.Strings(problems)
266 return errors.New("colophon: catalog:\n " + strings.Join(problems, "\n "))
267 }
268 return nil
269}
270
271// Package is one package an app ships, as its collector found it.
272type Package struct {
273 Ecosystem string `json:"ecosystem"`
274 Name string `json:"name"`
275 Version string `json:"version,omitempty"`
276 // Tool marks a package the app is built or tested with that is not in
277 // what it ships.
278 Tool bool `json:"tool,omitempty"`
279 // Platforms limits a package to some of the app's platforms ("mac");
280 // empty is all of them.
281 Platforms []string `json:"platforms,omitempty"`
282 // Via is the packages (by name, same ecosystem) that use this one
283 // directly in the build that ships it, as CollectCargo records them.
284 Via []string `json:"via,omitempty"`
285 // Notices are the package's own licence files, unaltered.
286 Notices []credits.Notice `json:"notices"`
287}
288
289func (p Package) ref() Ref { return Ref{p.Ecosystem, p.Name} }
290
291// Entry is one project as an app's Colophon shows it.
292type Entry struct {
293 ID string `json:"id"`
294 Name string `json:"name"`
295 Blurb string `json:"blurb"`
296 Usage string `json:"usage"`
297 Author string `json:"author"`
298 Licence Licence `json:"licence"`
299 Home string `json:"home"`
300 Source string `json:"source"`
301 Packages []Package `json:"packages"`
302}
303
304// VersionText is the entry's version, or each package's when they differ.
305func (e Entry) VersionText() string {
306 versions := map[string]bool{}
307 for _, p := range e.Packages {
308 versions[p.Version] = true
309 }
310 if len(versions) == 1 {
311 return e.Packages[0].Version
312 }
313 var parts []string
314 for _, p := range e.Packages {
315 if p.Version != "" {
316 parts = append(parts, p.Name+" "+p.Version)
317 }
318 }
319 return strings.Join(parts, ", ")
320}
321
322// Section is one heading's entries. ID is one of sectionOrder.
323type Section struct {
324 ID string `json:"id"`
325 Entries []Entry `json:"entries"`
326}
327
328// Colophon is an app's Colophon, its sections in sectionOrder and their
329// entries by name.
330type Colophon struct {
331 Sections []Section `json:"sections"`
332}
333
334// sectionOrder is the order sections are shown in.
335var sectionOrder = []string{"typefaces", "go", "javascript", "rust", "swift", "icons", "data", "tools", "services"}
336
337// Entry finds the entry with id.
338func (c Colophon) Entry(id string) (Entry, bool) {
339 for _, s := range c.Sections {
340 for _, e := range s.Entries {
341 if e.ID == id {
342 return e, true
343 }
344 }
345 }
346 return Entry{}, false
347}
348
349func (c Colophon) sectionOf(id string) string {
350 for _, s := range c.Sections {
351 for _, e := range s.Entries {
352 if e.ID == id {
353 return s.ID
354 }
355 }
356 }
357 return ""
358}
359
360// Count is the number of entries in each section, and "total".
361func (c Colophon) Count() map[string]int {
362 n := map[string]int{}
363 for _, s := range c.Sections {
364 n[s.ID] = len(s.Entries)
365 n["total"] += len(s.Entries)
366 }
367 return n
368}
369
370// Build is app's Colophon for what it ships, from the catalog. app is the
371// key of the usage notes it reads ("docs", "docs-native").
372func Build(app string, shipped []Package) (Colophon, error) {
373 return build(projects, app, shipped)
374}
375
376func build(projects []Project, app string, shipped []Package) (Colophon, error) {
377 var problems []string
378 owner := map[Ref]int{}
379 for i, p := range projects {
380 for _, r := range p.Packages {
381 owner[r] = i
382 }
383 }
384 // One package per ecosystem, name and version. A package seen as a tool
385 // in one build and shipped by another ships; a package limited to some
386 // platforms in one and not in another is on all of them.
387 merged := map[string]*Package{}
388 var keys []string
389 for _, p := range shipped {
390 if p.Ecosystem == "" || p.Name == "" {
391 problems = append(problems, "a package without an ecosystem or name")
392 continue
393 }
394 key := p.Ecosystem + ":" + p.Name + "@" + p.Version
395 if have, ok := merged[key]; ok {
396 have.Tool = have.Tool && p.Tool
397 have.Via = union(have.Via, p.Via)
398 if len(have.Platforms) == 0 || len(p.Platforms) == 0 {
399 have.Platforms = nil
400 } else {
401 have.Platforms = union(have.Platforms, p.Platforms)
402 }
403 continue
404 }
405 p.Platforms = append([]string(nil), p.Platforms...)
406 merged[key] = &p
407 keys = append(keys, key)
408 }
409 sort.Strings(keys)
410 byProject := map[int][]Package{}
411 for _, key := range keys {
412 p := *merged[key]
413 i, known := owner[p.ref()]
414 if !known {
415 problems = append(problems, p.ref().String()+" has no catalog entry")
416 continue
417 }
418 if len(p.Notices) == 0 && !p.Tool && projects[i].Licence.SPDX != NoAssertion {
419 problems = append(problems, fmt.Sprintf("%s %s carries no licence text", p.ref(), p.Version))
420 }
421 byProject[i] = append(byProject[i], p)
422 }
423 sections := map[string][]Entry{}
424 for i, p := range projects {
425 packages, ships := byProject[i]
426 own := p.Uses[app]
427 use := own
428 if use == "" {
429 use = p.Uses["*"]
430 }
431 switch {
432 case ships && use == "":
433 problems = append(problems, p.ID+" has no usage note for "+app)
434 continue
435 case !ships && own != "":
436 problems = append(problems, p.ID+" has a usage note for "+app+" but "+app+" does not ship it")
437 continue
438 case !ships:
439 continue
440 }
441 if own == "" && len(p.Via) > 0 && !reachedVia(p, packages, projects, owner, byProject) {
442 problems = append(problems, p.ID+"'s default note names "+strings.Join(p.Via, ", ")+", which "+app+" does not reach it through")
443 continue
444 }
445 section, err := sectionFor(p, packages)
446 if err != nil {
447 problems = append(problems, err.Error())
448 continue
449 }
450 sections[section] = append(sections[section], Entry{ID: p.ID, Name: p.Name, Blurb: p.Blurb, Usage: use, Author: p.Author, Licence: p.Licence, Home: p.Home, Source: p.Source, Packages: packages})
451 }
452 if len(problems) > 0 {
453 sort.Strings(problems)
454 return Colophon{}, errors.New("colophon: " + app + ":\n " + strings.Join(problems, "\n "))
455 }
456 var c Colophon
457 for _, id := range sectionOrder {
458 entries := sections[id]
459 if len(entries) == 0 {
460 continue
461 }
462 sort.SliceStable(entries, func(a, b int) bool {
463 return strings.ToLower(entries[a].Name) < strings.ToLower(entries[b].Name)
464 })
465 c.Sections = append(c.Sections, Section{ID: id, Entries: entries})
466 }
467 return c, nil
468}
469
470// reachedVia reports whether every project p's default note names uses
471// one of packages directly ("DashMap and aHash use it." needs both), each
472// through a package it ships. A dependent the app only builds or tests with
473// counts only when the crate itself is only a tool there too: a shipped
474// crate's note must not rest on something that does not ship.
475func reachedVia(p Project, packages []Package, projects []Project, owner map[Ref]int, byProject map[int][]Package) bool {
476 onlyTool := true
477 for _, pkg := range packages {
478 onlyTool = onlyTool && pkg.Tool
479 }
480 for _, named := range p.Via {
481 uses := false
482 for _, pkg := range packages {
483 for _, user := range pkg.Via {
484 i, ok := owner[Ref{pkg.Ecosystem, user}]
485 if !ok || projects[i].ID != named {
486 continue
487 }
488 for _, shipped := range byProject[i] {
489 if shipped.Name == user && (!shipped.Tool || onlyTool) {
490 uses = true
491 }
492 }
493 }
494 }
495 if !uses {
496 return false
497 }
498 }
499 return true
500}
501
502func union(a, b []string) []string {
503 seen := map[string]bool{}
504 var out []string
505 for _, s := range append(append([]string(nil), a...), b...) {
506 if !seen[s] {
507 seen[s] = true
508 out = append(out, s)
509 }
510 }
511 sort.Strings(out)
512 return out
513}
514
515func sectionFor(p Project, packages []Package) (string, error) {
516 tool := true
517 ecosystem := ""
518 for _, pkg := range packages {
519 if !pkg.Tool {
520 tool = false
521 if ecosystem == "" {
522 ecosystem = pkg.Ecosystem
523 }
524 }
525 }
526 if tool {
527 return "tools", nil
528 }
529 switch p.Kind {
530 case Typeface:
531 return "typefaces", nil
532 case Icons:
533 return "icons", nil
534 case Data:
535 return "data", nil
536 case Tool:
537 return "tools", nil
538 case Service:
539 return "services", nil
540 }
541 switch ecosystem {
542 case Go:
543 return "go", nil
544 case NPM:
545 return "javascript", nil
546 case Cargo:
547 return "rust", nil
548 case Swift:
549 return "swift", nil
550 }
551 return "", fmt.Errorf("%s is a library with no runtime to list it under", p.ID)
552}
553
554// Labels are the page's words, in the caller's locale. Sections is each
555// section's heading, keyed by its ID.
556type Labels struct {
557 Contents string
558 Sections map[string]string
559 By string
560 Licence string
561 Version string
562 Home string
563 Source string
564 HomeAndSource string
565 // Back is the licence page's link back to the Colophon, Missing what
566 // it says for a package published without a licence file, and
567 // NotIncluded what it says for a tool whose text is not copied here.
568 Back string
569 Missing string
570 NotIncluded string
571}
572
573// English is the page's words in English.
574var English = Labels{
575 Contents: "On this page",
576 Sections: map[string]string{
577 "typefaces": "Typefaces",
578 "go": "Go libraries",
579 "javascript": "JavaScript libraries",
580 "rust": "Rust libraries",
581 "swift": "Swift libraries",
582 "icons": "Icons and artwork",
583 "data": "Data",
584 "tools": "Tools",
585 "services": "Services",
586 },
587 By: "By",
588 Licence: "License",
589 Version: "Version",
590 Home: "Home page",
591 Source: "Source",
592 HomeAndSource: "Home page and source",
593 Back: "Back to the colophon",
594 Missing: "This package is published without a license file, so there is no text to show.",
595 NotIncluded: "This is a tool the app is built or tested with, not part of what it ships, so its license text is not copied here. It is in the project's source.",
596}
597
598// Page is "estilo/colophon"'s data. Intro is the paragraphs under the
599// heading. LicenceBase is the path an entry's licence page is under: the
600// entry's ID is appended to it.
601type Page struct {
602 Title string
603 Intro []string
604 Labels Labels
605 LicenceBase string
606 Colophon Colophon
607}
608
609// LicencePage is "estilo/colophon-licence"'s data: one entry's licence
610// texts, every package's own. Back is the Colophon's URL.
611type LicencePage struct {
612 Title string
613 Back string
614 Labels Labels
615 Entry Entry
616}
617