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