@@ -5,11 +5,14 @@ import (
5
5
"os"
6
6
"path/filepath"
7
7
"strings"
8
+ "time"
8
9
10
+ "github.com/google/go-licenses/licenses"
9
11
"github.com/spf13/cobra"
10
12
)
11
13
12
14
const rootCmdDesc = "Utilities for license check."
15
+ const licenseConfidence = 0.9
13
16
14
17
type rootOptions struct {
15
18
fileList []string
@@ -37,21 +40,18 @@ func (o *rootOptions) run() error {
37
40
}
38
41
foundErr := false
39
42
for _ , file := range o .fileList {
40
- b , err := os .ReadFile (file )
41
- if err != nil {
42
- return err
43
- }
44
43
ext := filepath .Ext (file )
45
44
if ext != ".tmpl" && ext != ".go" && ext != ".yaml" {
46
45
continue
47
46
}
48
- if ! strings .Contains (string (b ), `Licensed under the Apache License, Version 2.0 (the "License");` ) {
49
- fmt .Fprintf (os .Stderr , "File %s does not contain Apache License.\n " , file )
47
+
48
+ if err := checkLicenseType (file , time .Now ().Year ()); err != nil {
49
+ fmt .Fprintf (os .Stderr , "File %s failed to pass license check %s.\n " , file , err )
50
50
foundErr = true
51
51
}
52
52
}
53
53
if foundErr {
54
- return fmt .Errorf ("found file missing license" )
54
+ return fmt .Errorf ("found file failing license license" )
55
55
}
56
56
return nil
57
57
}
@@ -72,3 +72,27 @@ func Execute() {
72
72
os .Exit (1 )
73
73
}
74
74
}
75
+
76
+ func checkLicenseType (filePath string , year int ) error {
77
+ classifier , err := licenses .NewClassifier (licenseConfidence )
78
+ if err != nil {
79
+ return fmt .Errorf ("failed to create license classifier: %w" , err )
80
+ }
81
+ licenseName , _ , err := classifier .Identify (filePath )
82
+ if err != nil {
83
+ return fmt .Errorf ("failed to identify license for %s: %w" , filePath , err )
84
+ }
85
+ if ! strings .Contains (licenseName , "Apache" ) {
86
+ return fmt .Errorf ("found license type %s, expect Apache" , licenseName )
87
+ }
88
+
89
+ b , err := os .ReadFile (filePath )
90
+ if err != nil {
91
+ return err
92
+ }
93
+ expectStr := fmt .Sprintf ("Copyright %d Google" , year )
94
+ if ! strings .Contains (strings .ToLower (string (b )), strings .ToLower (expectStr )) {
95
+ return fmt .Errorf ("expected copyright string %q not found" , expectStr )
96
+ }
97
+ return nil
98
+ }
0 commit comments