github.com/ratrocket/u-root@v0.0.0-20180201221235-1cf9f48ee2cf/scripts/checklicenses/checklicenses.go (about) 1 // Copyright 2017 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Run with `go run checklicenses.go`. This script has one drawback: 6 // - It does not correct the licenses; it simply outputs a list of files which 7 // do not conform and returns 1 if the list is non-empty. 8 package main 9 10 import ( 11 "flag" 12 "fmt" 13 "io/ioutil" 14 "log" 15 "os" 16 "path/filepath" 17 "regexp" 18 "strings" 19 ) 20 21 var absPath = flag.Bool("a", false, "Print absolute paths") 22 23 const uroot = "$GOPATH/src/github.com/u-root/u-root" 24 25 // The first few lines of every go file is expected to contain this license. 26 var license = regexp.MustCompile( 27 `^// Copyright [\d\-, ]+ the u-root Authors\. All rights reserved 28 // Use of this source code is governed by a BSD-style 29 // license that can be found in the LICENSE file\. 30 `) 31 32 type rule struct { 33 *regexp.Regexp 34 invert bool 35 } 36 37 func accept(s string) rule { 38 return rule{ 39 regexp.MustCompile("^" + s + "$"), 40 false, 41 } 42 } 43 44 func reject(s string) rule { 45 return rule{ 46 regexp.MustCompile("^" + s + "$"), 47 true, 48 } 49 } 50 51 // A file is checked iff all the accepts and none of the rejects match. 52 var rules = []rule{ 53 accept(`.*\.go`), 54 reject(`/vendor/.*`), // Various authors 55 reject(`/cmds/dhcp/.*`), // Graham King 56 reject(`/cmds/ectool/.*`), // Chromium authors 57 reject(`/cmds/ldd/.*`), // Go authors 58 reject(`/cmds/ping/.*`), // Go authors 59 reject(`/netlink/.*`), // Docker (Apache license) 60 } 61 62 func main() { 63 flag.Parse() 64 uroot := os.ExpandEnv(uroot) 65 incorrect := []string{} 66 67 // Walk u-root tree. 68 err := filepath.Walk(uroot, func(path string, info os.FileInfo, err error) error { 69 if info.IsDir() { 70 return nil 71 } 72 // Test rules 73 trimmedPath := strings.TrimPrefix(path, uroot) 74 for _, r := range rules { 75 if r.MatchString(trimmedPath) == r.invert { 76 return nil 77 } 78 } 79 // Read from the file. 80 r, err := os.Open(path) 81 if err != nil { 82 return err 83 } 84 defer r.Close() 85 contents, err := ioutil.ReadAll(r) 86 if err != nil { 87 return err 88 } 89 if !license.Match(contents) { 90 p := trimmedPath 91 if *absPath { 92 p = path 93 } 94 incorrect = append(incorrect, p) 95 } 96 return nil 97 }) 98 if err != nil { 99 log.Fatal(err) 100 } 101 102 // Print files with incorrect licenses. 103 if len(incorrect) > 0 { 104 fmt.Println(strings.Join(incorrect, "\n")) 105 os.Exit(1) 106 } 107 }