You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

generate-go-licenses.go 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. //go:build ignore
  4. package main
  5. import (
  6. "encoding/json"
  7. "io/fs"
  8. "os"
  9. goPath "path"
  10. "path/filepath"
  11. "regexp"
  12. "sort"
  13. "strings"
  14. )
  15. // regexp is based on go-license, excluding README and NOTICE
  16. // https://github.com/google/go-licenses/blob/master/licenses/find.go
  17. var licenseRe = regexp.MustCompile(`^(?i)((UN)?LICEN(S|C)E|COPYING).*$`)
  18. type LicenseEntry struct {
  19. Name string `json:"name"`
  20. Path string `json:"path"`
  21. LicenseText string `json:"licenseText"`
  22. }
  23. func main() {
  24. base, out := os.Args[1], os.Args[2]
  25. paths := []string{}
  26. err := filepath.WalkDir(base, func(path string, entry fs.DirEntry, err error) error {
  27. if err != nil {
  28. return err
  29. }
  30. if entry.IsDir() || !licenseRe.MatchString(entry.Name()) {
  31. return nil
  32. }
  33. paths = append(paths, path)
  34. return nil
  35. })
  36. if err != nil {
  37. panic(err)
  38. }
  39. sort.Strings(paths)
  40. entries := []LicenseEntry{}
  41. for _, path := range paths {
  42. path := filepath.ToSlash(path)
  43. licenseText, err := os.ReadFile(path)
  44. if err != nil {
  45. panic(err)
  46. }
  47. path = strings.Replace(path, base+"/", "", 1)
  48. name := goPath.Dir(path)
  49. // There might be a bug somewhere in go-licenses that sometimes interprets the
  50. // root package as "." and sometimes as "code.gitea.io/gitea". Workaround by
  51. // removing both of them for the sake of stable output.
  52. if name == "." || name == "code.gitea.io/gitea" {
  53. continue
  54. }
  55. entries = append(entries, LicenseEntry{
  56. Name: name,
  57. Path: path,
  58. LicenseText: string(licenseText),
  59. })
  60. }
  61. jsonBytes, err := json.MarshalIndent(entries, "", " ")
  62. if err != nil {
  63. panic(err)
  64. }
  65. err = os.WriteFile(out, jsonBytes, 0o644)
  66. if err != nil {
  67. panic(err)
  68. }
  69. }