-
Notifications
You must be signed in to change notification settings - Fork 31
/
licenses.go
607 lines (568 loc) · 14.1 KB
/
licenses.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"text/tabwriter"
"github.com/pmezard/licenses/assets"
)
type Template struct {
Title string
Nickname string
Words map[string]int
}
func parseTemplate(content string) (*Template, error) {
t := Template{}
text := []byte{}
state := 0
scanner := bufio.NewScanner(strings.NewReader(content))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if state == 0 {
if line == "---" {
state = 1
}
} else if state == 1 {
if line == "---" {
state = 2
} else {
if strings.HasPrefix(line, "title:") {
t.Title = strings.TrimSpace(line[len("title:"):])
} else if strings.HasPrefix(line, "nickname:") {
t.Nickname = strings.TrimSpace(line[len("nickname:"):])
}
}
} else if state == 2 {
text = append(text, scanner.Bytes()...)
text = append(text, []byte("\n")...)
}
}
t.Words = makeWordSet(text)
return &t, scanner.Err()
}
func loadTemplates() ([]*Template, error) {
templates := []*Template{}
for _, a := range assets.Assets {
templ, err := parseTemplate(a.Content)
if err != nil {
return nil, err
}
templates = append(templates, templ)
}
return templates, nil
}
var (
reWords = regexp.MustCompile(`[\w']+`)
reCopyright = regexp.MustCompile(
`(?i)\s*Copyright (?:©|\(c\)|\xC2\xA9)?\s*(?:\d{4}|\[year\]).*`)
)
func cleanLicenseData(data []byte) []byte {
data = bytes.ToLower(data)
data = reCopyright.ReplaceAll(data, nil)
return data
}
func makeWordSet(data []byte) map[string]int {
words := map[string]int{}
data = cleanLicenseData(data)
matches := reWords.FindAll(data, -1)
for i, m := range matches {
s := string(m)
if _, ok := words[s]; !ok {
// Non-matching words are likely in the license header, to mention
// copyrights and authors. Try to preserve the initial sequences,
// to display them later.
words[s] = i
}
}
return words
}
type Word struct {
Text string
Pos int
}
type sortedWords []Word
func (s sortedWords) Len() int {
return len(s)
}
func (s sortedWords) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortedWords) Less(i, j int) bool {
return s[i].Pos < s[j].Pos
}
type MatchResult struct {
Template *Template
Score float64
ExtraWords []string
MissingWords []string
}
func sortAndReturnWords(words []Word) []string {
sort.Sort(sortedWords(words))
tokens := []string{}
for _, w := range words {
tokens = append(tokens, w.Text)
}
return tokens
}
// matchTemplates returns the best license template matching supplied data,
// its score between 0 and 1 and the list of words appearing in license but not
// in the matched template.
func matchTemplates(license []byte, templates []*Template) MatchResult {
bestScore := float64(-1)
var bestTemplate *Template
bestExtra := []Word{}
bestMissing := []Word{}
words := makeWordSet(license)
for _, t := range templates {
extra := []Word{}
missing := []Word{}
common := 0
for w, pos := range words {
_, ok := t.Words[w]
if ok {
common++
} else {
extra = append(extra, Word{
Text: w,
Pos: pos,
})
}
}
for w, pos := range t.Words {
if _, ok := words[w]; !ok {
missing = append(missing, Word{
Text: w,
Pos: pos,
})
}
}
score := 2 * float64(common) / (float64(len(words)) + float64(len(t.Words)))
if score > bestScore {
bestScore = score
bestTemplate = t
bestMissing = missing
bestExtra = extra
}
}
return MatchResult{
Template: bestTemplate,
Score: bestScore,
ExtraWords: sortAndReturnWords(bestExtra),
MissingWords: sortAndReturnWords(bestMissing),
}
}
// fixEnv returns a copy of the process environment where GOPATH is adjusted to
// supplied value. It returns nil if gopath is empty.
func fixEnv(gopath string) []string {
if gopath == "" {
return nil
}
kept := []string{
"GOPATH=" + gopath,
}
for _, env := range os.Environ() {
if !strings.HasPrefix(env, "GOPATH=") {
kept = append(kept, env)
}
}
return kept
}
type MissingError struct {
Err string
}
func (err *MissingError) Error() string {
return err.Err
}
// expandPackages takes a list of package or package expressions and invoke go
// list to expand them to packages. In particular, it handles things like "..."
// and ".".
func expandPackages(gopath string, pkgs []string) ([]string, error) {
args := []string{"list"}
args = append(args, pkgs...)
cmd := exec.Command("go", args...)
cmd.Env = fixEnv(gopath)
out, err := cmd.CombinedOutput()
if err != nil {
output := string(out)
if strings.Contains(output, "cannot find package") ||
strings.Contains(output, "no buildable Go source files") {
return nil, &MissingError{Err: output}
}
return nil, fmt.Errorf("'go %s' failed with:\n%s",
strings.Join(args, " "), output)
}
names := []string{}
for _, s := range strings.Split(string(out), "\n") {
s = strings.TrimSpace(s)
if s != "" {
names = append(names, s)
}
}
return names, nil
}
func listPackagesAndDeps(gopath string, pkgs []string) ([]string, error) {
pkgs, err := expandPackages(gopath, pkgs)
if err != nil {
return nil, err
}
args := []string{"list", "-f", "{{range .Deps}}{{.}}|{{end}}"}
args = append(args, pkgs...)
cmd := exec.Command("go", args...)
cmd.Env = fixEnv(gopath)
out, err := cmd.CombinedOutput()
if err != nil {
output := string(out)
if strings.Contains(output, "cannot find package") ||
strings.Contains(output, "no buildable Go source files") {
return nil, &MissingError{Err: output}
}
return nil, fmt.Errorf("'go %s' failed with:\n%s",
strings.Join(args, " "), output)
}
deps := []string{}
seen := map[string]bool{}
for _, s := range strings.Split(string(out), "|") {
s = strings.TrimSpace(s)
if s != "" && !seen[s] {
deps = append(deps, s)
seen[s] = true
}
}
for _, pkg := range pkgs {
if !seen[pkg] {
seen[pkg] = true
deps = append(deps, pkg)
}
}
sort.Strings(deps)
return deps, nil
}
func listStandardPackages(gopath string) ([]string, error) {
return expandPackages(gopath, []string{"std", "cmd"})
}
type PkgError struct {
Err string
}
type PkgInfo struct {
Name string
Dir string
Root string
ImportPath string
Error *PkgError
}
func getPackagesInfo(gopath string, pkgs []string) ([]*PkgInfo, error) {
args := []string{"list", "-e", "-json"}
// TODO: split the list for platforms which do not support massive argument
// lists.
args = append(args, pkgs...)
cmd := exec.Command("go", args...)
cmd.Env = fixEnv(gopath)
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("go %s failed with:\n%s",
strings.Join(args, " "), string(out))
}
infos := make([]*PkgInfo, 0, len(pkgs))
decoder := json.NewDecoder(bytes.NewBuffer(out))
for _, pkg := range pkgs {
info := &PkgInfo{}
err := decoder.Decode(info)
if err != nil {
return nil, fmt.Errorf("could not retrieve package information for %s", pkg)
}
if pkg != info.ImportPath {
return nil, fmt.Errorf("package information mismatch: asked for %s, got %s",
pkg, info.ImportPath)
}
if info.Error != nil && info.Name == "" {
info.Name = info.ImportPath
}
infos = append(infos, info)
}
return infos, err
}
var (
reLicense = regexp.MustCompile(`(?i)^(?:` +
`((?:un)?licen[sc]e)|` +
`((?:un)?licen[sc]e\.(?:md|markdown|txt))|` +
`(copy(?:ing|right)(?:\.[^.]+)?)|` +
`(licen[sc]e\.[^.]+)` +
`)$`)
)
// scoreLicenseName returns a factor between 0 and 1 weighting how likely
// supplied filename is a license file.
func scoreLicenseName(name string) float64 {
m := reLicense.FindStringSubmatch(name)
switch {
case m == nil:
break
case m[1] != "":
return 1.0
case m[2] != "":
return 0.9
case m[3] != "":
return 0.8
case m[4] != "":
return 0.7
}
return 0.
}
// findLicense looks for license files in package import path, and down to
// parent directories until a file is found or $GOPATH/src is reached. It
// returns the path and score of the best entry, an empty string if none was
// found.
func findLicense(info *PkgInfo) (string, error) {
path := info.ImportPath
for ; path != "."; path = filepath.Dir(path) {
fis, err := ioutil.ReadDir(filepath.Join(info.Root, "src", path))
if err != nil {
return "", err
}
bestScore := float64(0)
bestName := ""
for _, fi := range fis {
if !fi.Mode().IsRegular() {
continue
}
score := scoreLicenseName(fi.Name())
if score > bestScore {
bestScore = score
bestName = fi.Name()
}
}
if bestName != "" {
return filepath.Join(path, bestName), nil
}
}
return "", nil
}
type License struct {
Package string
Score float64
Template *Template
Path string
Err string
ExtraWords []string
MissingWords []string
}
func listLicenses(gopath string, pkgs []string) ([]License, error) {
templates, err := loadTemplates()
if err != nil {
return nil, err
}
deps, err := listPackagesAndDeps(gopath, pkgs)
if err != nil {
if _, ok := err.(*MissingError); ok {
return nil, err
}
return nil, fmt.Errorf("could not list %s dependencies: %s",
strings.Join(pkgs, " "), err)
}
std, err := listStandardPackages(gopath)
if err != nil {
return nil, fmt.Errorf("could not list standard packages: %s", err)
}
stdSet := map[string]bool{}
for _, n := range std {
stdSet[n] = true
}
infos, err := getPackagesInfo(gopath, deps)
if err != nil {
return nil, err
}
// Cache matched licenses by path. Useful for package with a lot of
// subpackages like bleve.
matched := map[string]MatchResult{}
licenses := []License{}
for _, info := range infos {
if info.Error != nil {
licenses = append(licenses, License{
Package: info.Name,
Err: info.Error.Err,
})
continue
}
if stdSet[info.ImportPath] {
continue
}
path, err := findLicense(info)
if err != nil {
return nil, err
}
license := License{
Package: info.ImportPath,
Path: path,
}
if path != "" {
fpath := filepath.Join(info.Root, "src", path)
m, ok := matched[fpath]
if !ok {
data, err := ioutil.ReadFile(fpath)
if err != nil {
return nil, err
}
m = matchTemplates(data, templates)
matched[fpath] = m
}
license.Score = m.Score
license.Template = m.Template
license.ExtraWords = m.ExtraWords
license.MissingWords = m.MissingWords
}
licenses = append(licenses, license)
}
return licenses, nil
}
// longestCommonPrefix returns the longest common prefix over import path
// components of supplied licenses.
func longestCommonPrefix(licenses []License) string {
type Node struct {
Name string
Children map[string]*Node
}
// Build a prefix tree. Not super efficient, but easy to do.
root := &Node{
Children: map[string]*Node{},
}
for _, l := range licenses {
n := root
for _, part := range strings.Split(l.Package, "/") {
c := n.Children[part]
if c == nil {
c = &Node{
Name: part,
Children: map[string]*Node{},
}
n.Children[part] = c
}
n = c
}
}
n := root
prefix := []string{}
for {
if len(n.Children) != 1 {
break
}
for _, c := range n.Children {
prefix = append(prefix, c.Name)
n = c
break
}
}
return strings.Join(prefix, "/")
}
// groupLicenses returns the input licenses after grouping them by license path
// and find their longest import path common prefix. Entries with empty paths
// are left unchanged.
func groupLicenses(licenses []License) ([]License, error) {
paths := map[string][]License{}
for _, l := range licenses {
if l.Path == "" {
continue
}
paths[l.Path] = append(paths[l.Path], l)
}
for k, v := range paths {
if len(v) <= 1 {
continue
}
prefix := longestCommonPrefix(v)
if prefix == "" {
return nil, fmt.Errorf(
"packages share the same license but not common prefix: %v", v)
}
l := v[0]
l.Package = prefix
paths[k] = []License{l}
}
kept := []License{}
for _, l := range licenses {
if l.Path == "" {
kept = append(kept, l)
continue
}
if v, ok := paths[l.Path]; ok {
kept = append(kept, v[0])
delete(paths, l.Path)
}
}
return kept, nil
}
func printLicenses() error {
flag.Usage = func() {
fmt.Println(`Usage: licenses IMPORTPATH...
licenses lists all dependencies of specified packages or commands, excluding
standard library packages, and prints their licenses. Licenses are detected by
looking for files named like LICENSE, COPYING, COPYRIGHT and other variants in
the package directory, and its parent directories until one is found. Files
content is matched against a set of well-known licenses and the best match is
displayed along with its score.
With -a, all individual packages are displayed instead of grouping them by
license files.
With -w, words in package license file not found in the template license are
displayed. It helps assessing the changes importance.
`)
os.Exit(1)
}
all := flag.Bool("a", false, "display all individual packages")
words := flag.Bool("w", false, "display words not matching license template")
flag.Parse()
if flag.NArg() < 1 {
return fmt.Errorf("expect at least one package argument")
}
pkgs := flag.Args()
confidence := 0.9
licenses, err := listLicenses("", pkgs)
if err != nil {
return err
}
if !*all {
licenses, err = groupLicenses(licenses)
if err != nil {
return err
}
}
w := tabwriter.NewWriter(os.Stdout, 1, 4, 2, ' ', 0)
for _, l := range licenses {
license := "?"
if l.Template != nil {
if l.Score > .99 {
license = fmt.Sprintf("%s", l.Template.Title)
} else if l.Score >= confidence {
license = fmt.Sprintf("%s (%2d%%)", l.Template.Title, int(100*l.Score))
if *words && len(l.ExtraWords) > 0 {
license += "\n\t+words: " + strings.Join(l.ExtraWords, ", ")
}
if *words && len(l.MissingWords) > 0 {
license += "\n\t-words: " + strings.Join(l.MissingWords, ", ")
}
} else {
license = fmt.Sprintf("? (%s, %2d%%)", l.Template.Title, int(100*l.Score))
}
} else if l.Err != "" {
license = strings.Replace(l.Err, "\n", " ", -1)
}
_, err = w.Write([]byte(l.Package + "\t" + license + "\n"))
if err != nil {
return err
}
}
return w.Flush()
}
func main() {
err := printLicenses()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1)
}
}