package colophon // The collectors: each turns one kind of build's own record of what it // used into Packages, with each package's licence files read from where // the build read the package. Go modules come from credits/catalog.Collect // (go list -deps of the production entry point) through FromComponents. import ( "encoding/json" "errors" "fmt" "io" "os" "path/filepath" "sort" "strings" "unicode/utf8" "amadan.net/oficina/estilo.git/credits" "amadan.net/oficina/estilo.git/credits/catalog" ) // FromComponents is credits components (catalog.Collect's inventory) as // Packages of ecosystem. func FromComponents(ecosystem string, components []credits.Component) []Package { out := make([]Package, 0, len(components)) for _, c := range components { out = append(out, Package{Ecosystem: ecosystem, Name: c.Name, Version: c.Version, Notices: append([]credits.Notice{}, c.Notices...)}) } return out } var sourceSuffixes = []string{".go", ".rs", ".js", ".mjs", ".cjs", ".ts", ".c", ".h", ".py", ".swift", ".json", ".toml"} // DirNotices reads the licence files at the top of dir, the names // credits/catalog recognises (LICENSE, LICENCE, COPYING, NOTICE, and those // with a suffix), skipping source files. A symlink, an oversized file, an // empty one or one that is not UTF-8 is refused rather than skipped. func DirNotices(dir string) ([]credits.Notice, error) { entries, err := os.ReadDir(dir) if err != nil { return nil, err } notices := []credits.Notice{} for _, entry := range entries { name := entry.Name() lower := strings.ToLower(name) source := false for _, s := range sourceSuffixes { source = source || strings.HasSuffix(lower, s) } if entry.IsDir() || source || !catalog.NoticeFilename(name) { continue } full := filepath.Join(dir, name) info, err := os.Lstat(full) if err != nil { return nil, err } if !info.Mode().IsRegular() || info.Size() > 2<<20 { return nil, fmt.Errorf("colophon: %s is not a bounded regular file", full) } raw, err := os.ReadFile(full) if err != nil { return nil, err } if !utf8.Valid(raw) || strings.TrimSpace(string(raw)) == "" { return nil, fmt.Errorf("colophon: %s is empty or not UTF-8", full) } notices = append(notices, credits.Notice{Name: name, Text: string(raw)}) } sort.Slice(notices, func(i, j int) bool { return notices[i].Name < notices[j].Name }) return notices, nil } type cargoMetadata struct { Packages []struct { ID, Name, Version string ManifestPath string `json:"manifest_path"` Targets []struct { Kind []string } } Resolve *struct { Root string Nodes []struct { ID string Deps []struct { Pkg string DepKinds []struct { Kind *string } `json:"dep_kinds"` } } } } func readCargoMetadata(metadata io.Reader) (cargoMetadata, error) { var m cargoMetadata if err := json.NewDecoder(metadata).Decode(&m); err != nil { return m, err } if m.Resolve == nil || m.Resolve.Root == "" { return m, errors.New("colophon: cargo metadata has no resolve graph with a root") } return m, nil } func (m cargoMetadata) pkg(id string) (Package, error) { for _, p := range m.Packages { if p.ID == id { notices := []credits.Notice{} if _, err := os.Stat(filepath.Dir(p.ManifestPath)); err == nil { var e error if notices, e = DirNotices(filepath.Dir(p.ManifestPath)); e != nil { return Package{}, e } } return Package{Ecosystem: Cargo, Name: p.Name, Version: p.Version, Notices: notices}, nil } } return Package{}, fmt.Errorf("colophon: cargo metadata has no package %s", id) } // CollectCargoTools is a crate's direct dev-dependencies, as tools: what // its tests are built with, unless it ships them anyway. Their own // dependencies are theirs, not the app's. func CollectCargoTools(metadata io.Reader) ([]Package, error) { m, err := readCargoMetadata(metadata) if err != nil { return nil, err } var out []Package for _, n := range m.Resolve.Nodes { if n.ID != m.Resolve.Root { continue } for _, d := range n.Deps { dev := len(d.DepKinds) > 0 for _, k := range d.DepKinds { dev = dev && k.Kind != nil && *k.Kind == "dev" } if !dev { continue } p, err := m.pkg(d.Pkg) if err != nil { return nil, err } p.Tool = true out = append(out, p) } } sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) return out, nil } // CollectCargo is the crates one build uses, from `cargo metadata --locked // --format-version 1 --filter-platform ` run on its manifest: // everything the root reaches through normal and build dependencies, never // through a dev-dependency, and not the root itself. A crate the build only // runs while compiling (a proc-macro, a build dependency, or anything // reached only through one) is not linked into what ships, so it is marked // Tool; one also reached through ordinary dependencies ships. func CollectCargo(metadata io.Reader) ([]Package, error) { m, err := readCargoMetadata(metadata) if err != nil { return nil, err } nodes := map[string]int{} for i, n := range m.Resolve.Nodes { nodes[n.ID] = i } seen := map[string]bool{} pending := []string{m.Resolve.Root} for len(pending) > 0 { id := pending[len(pending)-1] pending = pending[:len(pending)-1] if seen[id] { continue } seen[id] = true n, ok := nodes[id] if !ok { return nil, fmt.Errorf("colophon: cargo metadata has no node for %s", id) } for _, d := range m.Resolve.Nodes[n].Deps { for _, k := range d.DepKinds { if k.Kind == nil || *k.Kind != "dev" { pending = append(pending, d.Pkg) break } } } } // linked: reached from the root through normal dependencies only, // without passing through a proc-macro (which runs in the compiler and // is not linked, nor is anything only it uses). macro := map[string]bool{} for _, p := range m.Packages { for _, t := range p.Targets { for _, k := range t.Kind { macro[p.ID] = macro[p.ID] || k == "proc-macro" } } } linked := map[string]bool{} pending = []string{m.Resolve.Root} for len(pending) > 0 { id := pending[len(pending)-1] pending = pending[:len(pending)-1] if linked[id] || macro[id] { continue } linked[id] = true for _, d := range m.Resolve.Nodes[nodes[id]].Deps { for _, k := range d.DepKinds { if k.Kind == nil { pending = append(pending, d.Pkg) break } } } } // users: each crate's direct dependents in the walked graph, by name; // the root is the app itself, not a dependent to name. users := map[string][]string{} for id := range seen { if id == m.Resolve.Root { continue } var name string for _, p := range m.Packages { if p.ID == id { name = p.Name } } for _, d := range m.Resolve.Nodes[nodes[id]].Deps { for _, k := range d.DepKinds { if k.Kind == nil || *k.Kind != "dev" { users[d.Pkg] = union(users[d.Pkg], []string{name}) break } } } } var out []Package for id := range seen { if id == m.Resolve.Root { continue } p, err := m.pkg(id) if err != nil { return nil, err } p.Tool = !linked[id] p.Via = users[id] out = append(out, p) } sort.Slice(out, func(i, j int) bool { if out[i].Name != out[j].Name { return out[i].Name < out[j].Name } return out[i].Version < out[j].Version }) return out, nil } // CollectNPM is the packages a bundle was built from. inputs are the input paths // of esbuild's metafile, relative to root; those outside node_modules are // the app's own and are skipped. Each package is the directory after the // last node_modules in a path, with its own package.json and licence. func CollectNPM(root string, inputs []string) ([]Package, error) { dirs := map[string]bool{} for _, input := range inputs { clean := filepath.ToSlash(filepath.Clean(input)) if clean != input || filepath.IsAbs(input) { return nil, fmt.Errorf("colophon: bundle input %q is not a plain relative path", input) } at := strings.LastIndex(clean, "node_modules/") if at < 0 { continue // the app's own source } if strings.HasPrefix(clean, "../") { return nil, fmt.Errorf("colophon: bundle input %q is a package outside %s", input, root) } rest := strings.Split(clean[at+len("node_modules/"):], "/") n := 1 if strings.HasPrefix(rest[0], "@") { n = 2 } if len(rest) <= n { return nil, fmt.Errorf("colophon: bundle input %q is not inside a package", input) } dirs[clean[:at+len("node_modules/")]+strings.Join(rest[:n], "/")] = true } var out []Package for dir := range dirs { full := filepath.Join(root, filepath.FromSlash(dir)) raw, err := os.ReadFile(filepath.Join(full, "package.json")) if err != nil { return nil, err } var manifest struct{ Name, Version string } if err := json.Unmarshal(raw, &manifest); err != nil { return nil, fmt.Errorf("colophon: %s/package.json: %w", dir, err) } if want := dir[strings.LastIndex(dir, "node_modules/")+len("node_modules/"):]; manifest.Name != want || manifest.Version == "" { return nil, fmt.Errorf("colophon: %s/package.json names %q %q", dir, manifest.Name, manifest.Version) } notices, err := DirNotices(full) if err != nil { return nil, err } out = append(out, Package{Ecosystem: NPM, Name: manifest.Name, Version: manifest.Version, Notices: notices}) } sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) return out, nil }