-
Notifications
You must be signed in to change notification settings - Fork 10
/
gocredits.go
282 lines (265 loc) · 5.89 KB
/
gocredits.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package gocredits
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"text/template"
"unicode/utf8"
)
const (
cmdName = "gocredits"
defaultTmpl = `{{range $_, $elm := .Licenses -}}
{{$elm.Name}}
{{$elm.URL}}
----------------------------------------------------------------
{{$elm.Content}}
================================================================
{{end}}`
)
// Run the gocredits
func Run(argv []string, outStream, errStream io.Writer) error {
log.SetOutput(errStream)
fs := flag.NewFlagSet(
fmt.Sprintf("%s (v%s rev:%s)", cmdName, version, revision), flag.ContinueOnError)
fs.SetOutput(errStream)
ver := fs.Bool("version", false, "display version")
var (
format = fs.String("f", "", "format")
write = fs.Bool("w", false, "write result to CREDITS file instead of stdout")
printJSON = fs.Bool("json", false, "data to be printed in JSON format")
skipMissing = fs.Bool("skip-missing", false, "skip when gocredits can't find the license")
)
if err := fs.Parse(argv); err != nil {
return err
}
if *ver {
return printVersion(outStream)
}
modPath := fs.Arg(0)
if modPath == "" {
modPath = "."
}
licenses, err := takeCredits(modPath, *skipMissing)
if err != nil {
return err
}
data := struct {
Licenses []*license
}{
Licenses: licenses,
}
if *printJSON {
return json.NewEncoder(outStream).Encode(data)
}
tmplStr := *format
if tmplStr == "" {
tmplStr = defaultTmpl
}
tmpl, err := template.New(cmdName).Parse(tmplStr)
if err != nil {
return err
}
out := outStream
if *write {
f, err := os.OpenFile(filepath.Join(modPath, "CREDITS"), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err != nil {
return err
}
defer f.Close()
out = f
}
return tmpl.Execute(out, data)
}
func printVersion(out io.Writer) error {
_, err := fmt.Fprintf(out, "%s v%s (rev:%s)\n", cmdName, version, revision)
return err
}
type license struct {
Name, URL, FilePath, Content string
}
type licenseDir struct {
name, version string
}
type licenseDirs struct {
names []string
dirs map[string][]*licenseDir
}
func (ld *licenseDirs) set(l *licenseDir) {
if ld.dirs == nil {
ld.dirs = make(map[string][]*licenseDir)
}
dirs, ok := ld.dirs[l.name]
if !ok {
ld.names = append(ld.names, l.name)
}
dirs = append(dirs, l)
ld.dirs[l.name] = dirs
}
func takeCredits(dir string, skipMissing bool) ([]*license, error) {
goroot, err := run("go", "env", "GOROOT")
if err != nil {
return nil, err
}
var (
bs []byte
lpath string
)
for _, lpath = range []string{"LICENSE", "../LICENSE"} {
bs, err = os.ReadFile(filepath.Join(goroot, lpath))
if err == nil {
break
}
}
if err != nil {
resp, err := http.Get("https://golang.org/LICENSE?m=text")
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch LICENSE of Go")
}
bs, err = io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
}
ret := []*license{{
Name: "Go (the standard library)",
URL: "https://golang.org/",
FilePath: lpath,
Content: string(bs),
}}
gopath, err := run("go", "env", "GOPATH")
if err != nil {
return nil, err
}
gopkgmod := filepath.Join(gopath, "pkg", "mod")
gosum := filepath.Join(dir, "go.sum")
f, err := os.Open(gosum)
if err != nil {
if os.IsNotExist(err) {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err != nil {
return nil, fmt.Errorf("use go modules")
}
return ret, nil
}
return nil, err
}
defer f.Close()
ld := &licenseDirs{}
scr := bufio.NewScanner(f)
for scr.Scan() {
stuff := strings.Fields(scr.Text())
if len(stuff) != 3 {
continue
}
if strings.HasSuffix(stuff[1], "/go.mod") {
continue
}
ld.set(&licenseDir{
name: stuff[0],
version: stuff[1],
})
}
if err := scr.Err(); err != nil {
return nil, err
}
for _, packageName := range ld.names {
encodedPath, err := encodeString(packageName)
if err != nil {
return nil, err
}
var found bool
dirs := ld.dirs[packageName]
for i := len(dirs) - 1; i >= 0; i-- {
dirInfo := dirs[i]
dir := filepath.Join(gopkgmod, encodedPath+"@"+dirInfo.version)
licenseFile, content, err := findLicense(dir)
if err != nil {
if os.IsNotExist(err) {
continue
}
return nil, err
}
ret = append(ret, &license{
Name: packageName,
URL: fmt.Sprintf("https://%s", packageName),
FilePath: filepath.Join(dir, licenseFile),
Content: content,
})
found = true
break
}
if !found {
if skipMissing {
log.Printf("could not find the license for %q", packageName)
continue
}
return nil, fmt.Errorf("could not find the license for %q", packageName)
}
}
return ret, nil
}
func findLicense(dir string) (string, string, error) {
files, err := os.ReadDir(dir)
if err != nil {
return "", "", err
}
var (
bestScore = 0.0
fileName = ""
)
for _, f := range files {
if f.IsDir() {
continue
}
n := f.Name()
score := scoreLicenseName(n)
if score > bestScore {
bestScore = score
fileName = n
}
}
if fileName == "" {
return "", "", os.ErrNotExist
}
bs, err := os.ReadFile(filepath.Join(dir, fileName))
if err != nil {
return "", "", err
}
return fileName, string(bs), nil
}
// copied from cmd/go/internal/module/module.go
func encodeString(s string) (encoding string, err error) {
haveUpper := false
for _, r := range s {
if r == '!' || r >= utf8.RuneSelf {
// This should be disallowed by CheckPath, but diagnose anyway.
// The correctness of the encoding loop below depends on it.
return "", fmt.Errorf("internal error: inconsistency in EncodePath")
}
if 'A' <= r && r <= 'Z' {
haveUpper = true
}
}
if !haveUpper {
return s, nil
}
var buf []byte
for _, r := range s {
if 'A' <= r && r <= 'Z' {
buf = append(buf, '!', byte(r+'a'-'A'))
} else {
buf = append(buf, byte(r))
}
}
return string(buf), nil
}