| 1 | package colophon |
| 2 | |
| 3 | // The collectors: each turns one kind of build's own record of what it |
| 4 | // used into Packages, with each package's licence files read from where |
| 5 | // the build read the package. Go modules come from credits/catalog.Collect |
| 6 | // (go list -deps of the production entry point) through FromComponents. |
| 7 | |
| 8 | import ( |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "os" |
| 14 | "path/filepath" |
| 15 | "sort" |
| 16 | "strings" |
| 17 | "unicode/utf8" |
| 18 | |
| 19 | "amadan.net/oficina/estilo.git/credits" |
| 20 | "amadan.net/oficina/estilo.git/credits/catalog" |
| 21 | ) |
| 22 | |
| 23 | // FromComponents is credits components (catalog.Collect's inventory) as |
| 24 | // Packages of ecosystem. |
| 25 | func FromComponents(ecosystem string, components []credits.Component) []Package { |
| 26 | out := make([]Package, 0, len(components)) |
| 27 | for _, c := range components { |
| 28 | out = append(out, Package{Ecosystem: ecosystem, Name: c.Name, Version: c.Version, Notices: append([]credits.Notice{}, c.Notices...)}) |
| 29 | } |
| 30 | return out |
| 31 | } |
| 32 | |
| 33 | var sourceSuffixes = []string{".go", ".rs", ".js", ".mjs", ".cjs", ".ts", ".c", ".h", ".py", ".swift", ".json", ".toml"} |
| 34 | |
| 35 | // DirNotices reads the licence files at the top of dir, the names |
| 36 | // credits/catalog recognises (LICENSE, LICENCE, COPYING, NOTICE, and those |
| 37 | // with a suffix), skipping source files. A symlink, an oversized file, an |
| 38 | // empty one or one that is not UTF-8 is refused rather than skipped. |
| 39 | func DirNotices(dir string) ([]credits.Notice, error) { |
| 40 | entries, err := os.ReadDir(dir) |
| 41 | if err != nil { |
| 42 | return nil, err |
| 43 | } |
| 44 | notices := []credits.Notice{} |
| 45 | for _, entry := range entries { |
| 46 | name := entry.Name() |
| 47 | lower := strings.ToLower(name) |
| 48 | source := false |
| 49 | for _, s := range sourceSuffixes { |
| 50 | source = source || strings.HasSuffix(lower, s) |
| 51 | } |
| 52 | if entry.IsDir() || source || !catalog.NoticeFilename(name) { |
| 53 | continue |
| 54 | } |
| 55 | full := filepath.Join(dir, name) |
| 56 | info, err := os.Lstat(full) |
| 57 | if err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | if !info.Mode().IsRegular() || info.Size() > 2<<20 { |
| 61 | return nil, fmt.Errorf("colophon: %s is not a bounded regular file", full) |
| 62 | } |
| 63 | raw, err := os.ReadFile(full) |
| 64 | if err != nil { |
| 65 | return nil, err |
| 66 | } |
| 67 | if !utf8.Valid(raw) || strings.TrimSpace(string(raw)) == "" { |
| 68 | return nil, fmt.Errorf("colophon: %s is empty or not UTF-8", full) |
| 69 | } |
| 70 | notices = append(notices, credits.Notice{Name: name, Text: string(raw)}) |
| 71 | } |
| 72 | sort.Slice(notices, func(i, j int) bool { return notices[i].Name < notices[j].Name }) |
| 73 | return notices, nil |
| 74 | } |
| 75 | |
| 76 | type cargoMetadata struct { |
| 77 | Packages []struct { |
| 78 | ID, Name, Version string |
| 79 | ManifestPath string `json:"manifest_path"` |
| 80 | Targets []struct { |
| 81 | Kind []string |
| 82 | } |
| 83 | } |
| 84 | Resolve *struct { |
| 85 | Root string |
| 86 | Nodes []struct { |
| 87 | ID string |
| 88 | Deps []struct { |
| 89 | Pkg string |
| 90 | DepKinds []struct { |
| 91 | Kind *string |
| 92 | } `json:"dep_kinds"` |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | func readCargoMetadata(metadata io.Reader) (cargoMetadata, error) { |
| 99 | var m cargoMetadata |
| 100 | if err := json.NewDecoder(metadata).Decode(&m); err != nil { |
| 101 | return m, err |
| 102 | } |
| 103 | if m.Resolve == nil || m.Resolve.Root == "" { |
| 104 | return m, errors.New("colophon: cargo metadata has no resolve graph with a root") |
| 105 | } |
| 106 | return m, nil |
| 107 | } |
| 108 | |
| 109 | func (m cargoMetadata) pkg(id string) (Package, error) { |
| 110 | for _, p := range m.Packages { |
| 111 | if p.ID == id { |
| 112 | notices := []credits.Notice{} |
| 113 | if _, err := os.Stat(filepath.Dir(p.ManifestPath)); err == nil { |
| 114 | var e error |
| 115 | if notices, e = DirNotices(filepath.Dir(p.ManifestPath)); e != nil { |
| 116 | return Package{}, e |
| 117 | } |
| 118 | } |
| 119 | return Package{Ecosystem: Cargo, Name: p.Name, Version: p.Version, Notices: notices}, nil |
| 120 | } |
| 121 | } |
| 122 | return Package{}, fmt.Errorf("colophon: cargo metadata has no package %s", id) |
| 123 | } |
| 124 | |
| 125 | // CollectCargoTools is a crate's direct dev-dependencies, as tools: what |
| 126 | // its tests are built with, unless it ships them anyway. Their own |
| 127 | // dependencies are theirs, not the app's. |
| 128 | func CollectCargoTools(metadata io.Reader) ([]Package, error) { |
| 129 | m, err := readCargoMetadata(metadata) |
| 130 | if err != nil { |
| 131 | return nil, err |
| 132 | } |
| 133 | var out []Package |
| 134 | for _, n := range m.Resolve.Nodes { |
| 135 | if n.ID != m.Resolve.Root { |
| 136 | continue |
| 137 | } |
| 138 | for _, d := range n.Deps { |
| 139 | dev := len(d.DepKinds) > 0 |
| 140 | for _, k := range d.DepKinds { |
| 141 | dev = dev && k.Kind != nil && *k.Kind == "dev" |
| 142 | } |
| 143 | if !dev { |
| 144 | continue |
| 145 | } |
| 146 | p, err := m.pkg(d.Pkg) |
| 147 | if err != nil { |
| 148 | return nil, err |
| 149 | } |
| 150 | p.Tool = true |
| 151 | out = append(out, p) |
| 152 | } |
| 153 | } |
| 154 | sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) |
| 155 | return out, nil |
| 156 | } |
| 157 | |
| 158 | // CollectCargo is the crates one build uses, from `cargo metadata --locked |
| 159 | // --format-version 1 --filter-platform <target>` run on its manifest: |
| 160 | // everything the root reaches through normal and build dependencies, never |
| 161 | // through a dev-dependency, and not the root itself. A crate the build only |
| 162 | // runs while compiling (a proc-macro, a build dependency, or anything |
| 163 | // reached only through one) is not linked into what ships, so it is marked |
| 164 | // Tool; one also reached through ordinary dependencies ships. |
| 165 | func CollectCargo(metadata io.Reader) ([]Package, error) { |
| 166 | m, err := readCargoMetadata(metadata) |
| 167 | if err != nil { |
| 168 | return nil, err |
| 169 | } |
| 170 | nodes := map[string]int{} |
| 171 | for i, n := range m.Resolve.Nodes { |
| 172 | nodes[n.ID] = i |
| 173 | } |
| 174 | seen := map[string]bool{} |
| 175 | pending := []string{m.Resolve.Root} |
| 176 | for len(pending) > 0 { |
| 177 | id := pending[len(pending)-1] |
| 178 | pending = pending[:len(pending)-1] |
| 179 | if seen[id] { |
| 180 | continue |
| 181 | } |
| 182 | seen[id] = true |
| 183 | n, ok := nodes[id] |
| 184 | if !ok { |
| 185 | return nil, fmt.Errorf("colophon: cargo metadata has no node for %s", id) |
| 186 | } |
| 187 | for _, d := range m.Resolve.Nodes[n].Deps { |
| 188 | for _, k := range d.DepKinds { |
| 189 | if k.Kind == nil || *k.Kind != "dev" { |
| 190 | pending = append(pending, d.Pkg) |
| 191 | break |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | // linked: reached from the root through normal dependencies only, |
| 197 | // without passing through a proc-macro (which runs in the compiler and |
| 198 | // is not linked, nor is anything only it uses). |
| 199 | macro := map[string]bool{} |
| 200 | for _, p := range m.Packages { |
| 201 | for _, t := range p.Targets { |
| 202 | for _, k := range t.Kind { |
| 203 | macro[p.ID] = macro[p.ID] || k == "proc-macro" |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | linked := map[string]bool{} |
| 208 | pending = []string{m.Resolve.Root} |
| 209 | for len(pending) > 0 { |
| 210 | id := pending[len(pending)-1] |
| 211 | pending = pending[:len(pending)-1] |
| 212 | if linked[id] || macro[id] { |
| 213 | continue |
| 214 | } |
| 215 | linked[id] = true |
| 216 | for _, d := range m.Resolve.Nodes[nodes[id]].Deps { |
| 217 | for _, k := range d.DepKinds { |
| 218 | if k.Kind == nil { |
| 219 | pending = append(pending, d.Pkg) |
| 220 | break |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | // users: each crate's direct dependents in the walked graph, by name; |
| 226 | // the root is the app itself, not a dependent to name. |
| 227 | users := map[string][]string{} |
| 228 | for id := range seen { |
| 229 | if id == m.Resolve.Root { |
| 230 | continue |
| 231 | } |
| 232 | var name string |
| 233 | for _, p := range m.Packages { |
| 234 | if p.ID == id { |
| 235 | name = p.Name |
| 236 | } |
| 237 | } |
| 238 | for _, d := range m.Resolve.Nodes[nodes[id]].Deps { |
| 239 | for _, k := range d.DepKinds { |
| 240 | if k.Kind == nil || *k.Kind != "dev" { |
| 241 | users[d.Pkg] = union(users[d.Pkg], []string{name}) |
| 242 | break |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | var out []Package |
| 248 | for id := range seen { |
| 249 | if id == m.Resolve.Root { |
| 250 | continue |
| 251 | } |
| 252 | p, err := m.pkg(id) |
| 253 | if err != nil { |
| 254 | return nil, err |
| 255 | } |
| 256 | p.Tool = !linked[id] |
| 257 | p.Via = users[id] |
| 258 | out = append(out, p) |
| 259 | } |
| 260 | sort.Slice(out, func(i, j int) bool { |
| 261 | if out[i].Name != out[j].Name { |
| 262 | return out[i].Name < out[j].Name |
| 263 | } |
| 264 | return out[i].Version < out[j].Version |
| 265 | }) |
| 266 | return out, nil |
| 267 | } |
| 268 | |
| 269 | // CollectNPM is the packages a bundle was built from. inputs are the input paths |
| 270 | // of esbuild's metafile, relative to root; those outside node_modules are |
| 271 | // the app's own and are skipped. Each package is the directory after the |
| 272 | // last node_modules in a path, with its own package.json and licence. |
| 273 | func CollectNPM(root string, inputs []string) ([]Package, error) { |
| 274 | dirs := map[string]bool{} |
| 275 | for _, input := range inputs { |
| 276 | clean := filepath.ToSlash(filepath.Clean(input)) |
| 277 | if clean != input || filepath.IsAbs(input) { |
| 278 | return nil, fmt.Errorf("colophon: bundle input %q is not a plain relative path", input) |
| 279 | } |
| 280 | at := strings.LastIndex(clean, "node_modules/") |
| 281 | if at < 0 { |
| 282 | continue // the app's own source |
| 283 | } |
| 284 | if strings.HasPrefix(clean, "../") { |
| 285 | return nil, fmt.Errorf("colophon: bundle input %q is a package outside %s", input, root) |
| 286 | } |
| 287 | rest := strings.Split(clean[at+len("node_modules/"):], "/") |
| 288 | n := 1 |
| 289 | if strings.HasPrefix(rest[0], "@") { |
| 290 | n = 2 |
| 291 | } |
| 292 | if len(rest) <= n { |
| 293 | return nil, fmt.Errorf("colophon: bundle input %q is not inside a package", input) |
| 294 | } |
| 295 | dirs[clean[:at+len("node_modules/")]+strings.Join(rest[:n], "/")] = true |
| 296 | } |
| 297 | var out []Package |
| 298 | for dir := range dirs { |
| 299 | full := filepath.Join(root, filepath.FromSlash(dir)) |
| 300 | raw, err := os.ReadFile(filepath.Join(full, "package.json")) |
| 301 | if err != nil { |
| 302 | return nil, err |
| 303 | } |
| 304 | var manifest struct{ Name, Version string } |
| 305 | if err := json.Unmarshal(raw, &manifest); err != nil { |
| 306 | return nil, fmt.Errorf("colophon: %s/package.json: %w", dir, err) |
| 307 | } |
| 308 | if want := dir[strings.LastIndex(dir, "node_modules/")+len("node_modules/"):]; manifest.Name != want || manifest.Version == "" { |
| 309 | return nil, fmt.Errorf("colophon: %s/package.json names %q %q", dir, manifest.Name, manifest.Version) |
| 310 | } |
| 311 | notices, err := DirNotices(full) |
| 312 | if err != nil { |
| 313 | return nil, err |
| 314 | } |
| 315 | out = append(out, Package{Ecosystem: NPM, Name: manifest.Name, Version: manifest.Version, Notices: notices}) |
| 316 | } |
| 317 | sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) |
| 318 | return out, nil |
| 319 | } |
| 320 | |