forked from golang/dep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
201 lines (180 loc) · 4.13 KB
/
main.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
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Checks if all files have the license header, a lot of this is based off
// https://github.com/google/addlicense.
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"sync"
"time"
)
const helpText = `Usage: licenseok [flags] pattern [pattern ...]
This program ensures source code files have copyright license headers
by scanning directory patterns recursively.
The pattern argument can be provided multiple times, and may also refer
to single files.
Flags:
`
const tmpl = `The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.`
var (
update bool
)
type file struct {
path string
mode os.FileMode
}
func init() {
flag.BoolVar(&update, "u", false, "modifies all source files in place and avoids adding a license header to any file that already has one.")
flag.Usage = func() {
fmt.Fprintln(os.Stderr, helpText)
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() == 0 {
flag.Usage()
os.Exit(1)
}
}
func main() {
exitStatus := 0
// process at most 1000 files in parallel
ch := make(chan *file, 1000)
done := make(chan struct{})
go func() {
var wg sync.WaitGroup
for f := range ch {
wg.Add(1)
go func(f *file) {
b, err := ioutil.ReadFile(f.path)
if err != nil {
log.Printf("%s: %v", f.path, err)
exitStatus = 1
}
if !hasLicense(b) {
if !update {
fmt.Fprintln(os.Stderr, f.path)
exitStatus = 1
} else {
fmt.Fprintln(os.Stdout, f.path)
if err := addLicense(b, f.path, f.mode); err != nil {
log.Printf("%s: %v", f.path, err)
exitStatus = 1
}
}
}
wg.Done()
}(f)
}
wg.Wait()
close(done)
}()
for _, d := range flag.Args() {
walk(ch, d)
}
close(ch)
<-done
os.Exit(exitStatus)
}
func walk(ch chan<- *file, start string) {
filepath.Walk(start, func(path string, fi os.FileInfo, err error) error {
if err != nil {
log.Printf("%s error: %v", path, err)
return nil
}
if fi.IsDir() {
return nil
}
ch <- &file{path, fi.Mode()}
return nil
})
}
func addLicense(b []byte, path string, fmode os.FileMode) error {
var lic []byte
var err error
switch filepath.Ext(path) {
default:
return nil
case ".c", ".h":
lic, err = prefix("/*", " * ", " */")
case ".js", ".css":
lic, err = prefix("/**", " * ", " */")
case ".cc", ".cpp", ".cs", ".go", ".hh", ".hpp", ".java", ".m", ".mm", ".proto", ".rs", ".scala", ".swift", ".dart":
lic, err = prefix("", "// ", "")
case ".py", ".sh":
lic, err = prefix("", "# ", "")
case ".el", ".lisp":
lic, err = prefix("", ";; ", "")
case ".erl":
lic, err = prefix("", "% ", "")
case ".hs":
lic, err = prefix("", "-- ", "")
case ".html", ".xml":
lic, err = prefix("<!--", " ", "-->")
case ".php":
lic, err = prefix("<?php", "// ", "?>")
}
if err != nil || lic == nil {
return err
}
line := hashBang(b)
if len(line) > 0 {
b = b[len(line):]
if line[len(line)-1] != '\n' {
line = append(line, '\n')
}
lic = append(line, lic...)
}
b = append(lic, b...)
return ioutil.WriteFile(path, b, fmode)
}
func hashBang(b []byte) []byte {
var line []byte
for _, c := range b {
line = append(line, c)
if c == '\n' {
break
}
}
if bytes.HasPrefix(line, []byte("#!")) {
return line
}
return nil
}
func hasLicense(b []byte) bool {
n := 100
if len(b) < 100 {
n = len(b)
}
return bytes.Contains(bytes.ToLower(b[:n]), []byte("copyright"))
}
// prefix will execute a license template and prefix the result with top, middle and bottom.
func prefix(top, mid, bot string) ([]byte, error) {
buf := bytes.NewBufferString(fmt.Sprintf("Copyright %d %s", time.Now().Year(), tmpl))
var out bytes.Buffer
if top != "" {
out.WriteString(top)
out.WriteRune('\n')
}
out.WriteString(mid)
for _, c := range buf.Bytes() {
out.WriteByte(c)
if c == '\n' {
out.WriteString(mid)
}
}
if bot != "" {
out.WriteRune('\n')
out.WriteString(bot)
}
out.Write([]byte{'\n', '\n'})
return out.Bytes(), nil
}