github.com/linuxboot/fiano@v1.2.0/scripts/checklicenses/checklicenses.go (about) 1 // Copyright 2017-2018 the LinuxBoot 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" 14 "log" 15 "os" 16 "os/exec" 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 LinuxBoot 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 } 56 57 func main() { 58 flag.Parse() 59 uroot := os.ExpandEnv(uroot) 60 incorrect := []string{} 61 62 // List files added to u-root. 63 out, err := exec.Command("git", "ls-files").Output() 64 if err != nil { 65 log.Fatalln("error running git ls-files:", err) 66 } 67 files := strings.Fields(string(out)) 68 69 // Iterate over files. 70 outer: 71 for _, file := range files { 72 // Test rules. 73 trimmedPath := strings.TrimPrefix(file, uroot) 74 for _, r := range rules { 75 if r.MatchString(trimmedPath) == r.invert { 76 continue outer 77 } 78 } 79 80 // Make sure it is not a directory. 81 info, err := os.Stat(file) 82 if err != nil { 83 log.Fatalln("cannot stat", file, err) 84 } 85 if info.IsDir() { 86 continue 87 } 88 89 // Read from the file. 90 r, err := os.Open(file) 91 if err != nil { 92 log.Fatalln("cannot open", file, err) 93 } 94 defer r.Close() 95 contents, err := io.ReadAll(r) 96 if err != nil { 97 log.Fatalln("cannot read", file, err) 98 } 99 if !license.Match(contents) { 100 p := trimmedPath 101 if *absPath { 102 p = file 103 } 104 incorrect = append(incorrect, p) 105 } 106 } 107 if err != nil { 108 log.Fatal(err) 109 } 110 111 // Print files with incorrect licenses. 112 if len(incorrect) > 0 { 113 fmt.Println(strings.Join(incorrect, "\n")) 114 os.Exit(1) 115 } 116 }