1
// Copyright 2022 The Gitea Authors. All rights reserved.
2
// SPDX-License-Identifier: MIT
19
"code.gitea.io/gitea/modules/container"
22
// regexp is based on go-license, excluding README and NOTICE
23
// https://github.com/google/go-licenses/blob/master/licenses/find.go
24
var licenseRe = regexp.MustCompile(`^(?i)((UN)?LICEN(S|C)E|COPYING).*$`)
26
type LicenseEntry struct {
27
Name string `json:"name"`
28
Path string `json:"path"`
29
LicenseText string `json:"licenseText"`
33
if len(os.Args) != 3 {
34
fmt.Println("usage: go run generate-go-licenses.go <base-dir> <out-json-file>")
38
base, out := os.Args[1], os.Args[2]
40
// Add ext for excluded files because license_test.go will be included for some reason.
41
// And there are more files that should be excluded, check with:
43
// go run github.com/google/go-licenses@v1.6.0 save . --force --save_path=.go-licenses 2>/dev/null
44
// find .go-licenses -type f | while read FILE; do echo "${$(basename $FILE)##*.}"; done | sort -u
59
// It could be removed once we have a better regex.
60
excludedExt := container.SetOf(".gitignore", ".go", ".mod", ".sum", ".toml", ".yml")
63
err := filepath.WalkDir(base, func(path string, entry fs.DirEntry, err error) error {
67
if entry.IsDir() || !licenseRe.MatchString(entry.Name()) || excludedExt.Contains(filepath.Ext(entry.Name())) {
70
paths = append(paths, path)
79
var entries []LicenseEntry
80
for _, filePath := range paths {
81
licenseText, err := os.ReadFile(filePath)
86
pkgPath := filepath.ToSlash(filePath)
87
pkgPath = strings.TrimPrefix(pkgPath, base+"/")
88
pkgName := path.Dir(pkgPath)
90
// There might be a bug somewhere in go-licenses that sometimes interprets the
91
// root package as "." and sometimes as "code.gitea.io/gitea". Workaround by
92
// removing both of them for the sake of stable output.
93
if pkgName == "." || pkgName == "code.gitea.io/gitea" {
97
entries = append(entries, LicenseEntry{
100
LicenseText: string(licenseText),
104
jsonBytes, err := json.MarshalIndent(entries, "", " ")
109
// Ensure file has a final newline
110
if jsonBytes[len(jsonBytes)-1] != '\n' {
111
jsonBytes = append(jsonBytes, '\n')
114
err = os.WriteFile(out, jsonBytes, 0o644)