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

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