forked from c4milo/licentia
/
licentia.go
346 lines (285 loc) · 8.15 KB
/
licentia.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package main
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/docopt/docopt-go"
)
func main() {
usage := `Licentia.
Usage:
licentia set <type> <owner> <files> <eol-comment-style>
licentia unset <type> <owner> <files> <eol-comment-style>
licentia detect <files>
licentia dump <type> <owner>
licentia list
licentia -h | --help
licentia --version
Supported license types:
* apache2 * gpl3 * gpl2
* mpl2 * cddl * unlicense
* mit * epl
* newbsd * freebsd
* lgpl3 * lgpl2
Actions:
set Sets a license header to the specified files
unset Removes license header from the specified files
detect Detects license type for the specified files
dump Dumps to stdout a given license using the specified owner and the current year
list List supported licenses
Arguments:
type License type to set. Ex: apache2, mpl2, mit, newbsd, lgpl3
owner Copyright owner. Ex: "YourCompany Inc"
files Source files to set the license header. It supports globbing patterns, individual files or folders. Ex: *.go
eol-comment-style End-of-line comment style. Ex: #, ;, //, --, ', etc.
Options:
-h --help Show this screen.
--version Show version.`
args, err := docopt.Parse(usage, nil, true, "Licentia", false)
if err != nil {
panic(err)
}
if val, ok := args["set"]; ok && val.(bool) {
config := &Config{
LicenseType: LicenseType(args["<type>"].(string)),
CopyrightOwner: args["<owner>"].(string),
EOLCommentStyle: args["<eol-comment-style>"].(string),
Files: args["<files>"].(string),
}
err = Set(config)
}
if val, ok := args["unset"]; ok && val.(bool) {
config := &Config{
LicenseType: LicenseType(args["<type>"].(string)),
CopyrightOwner: args["<owner>"].(string),
EOLCommentStyle: args["<eol-comment-style>"].(string),
Files: args["<files>"].(string),
}
err = Unset(config)
}
if val, ok := args["list"]; ok && val.(bool) {
var types []string
types, err = List()
fmt.Println("Supported licenses: ")
for _, t := range types {
fmt.Println("* " + t)
}
}
if val, ok := args["dump"]; ok && val.(bool) {
var license string
license, err = Dump(LicenseType(args["<type>"].(string)), args["<owner>"].(string))
fmt.Println(license)
}
if val, ok := args["detect"]; ok && val.(bool) {
//err = Detect(args["<files>"].(string))
}
if err != nil {
fmt.Println(err)
}
}
// License type
type LicenseType string
const (
Apache2 LicenseType = "apache2"
Freebsd LicenseType = "freebsd"
LGPL3 LicenseType = "lgpl3"
LGPL2 LicenseType = "lgpl2"
MIT LicenseType = "mit"
MPL2 LicenseType = "mpl2"
NewBSD LicenseType = "newbsd"
GPL3 LicenseType = "gpl3"
GPL2 LicenseType = "gpl2"
CDDL LicenseType = "cddl"
EPL LicenseType = "epl"
UNLICENSE LicenseType = "unlicense"
UNKNOWN LicenseType = "unknown"
)
type Config struct {
// The owner of the copyright
CopyrightOwner string
// License type
LicenseType LicenseType
// Invidiviual file or folder as well as glob patterns are recognized
Files string
// Style of end-of-line comment that will be used to insert the license.
// Ex: //, #, --, !, ', ;
EOLCommentStyle string
}
// Dumps license to stdout setting the owner and year in the copyright notice
func Dump(ltype LicenseType, owner string) (string, error) {
replacer := strings.NewReplacer("@@owner@@", owner, "@@year@@", strconv.Itoa(time.Now().Year()))
data, err := Asset(filepath.Join("licenses", string(ltype)))
if err != nil {
return "", err
}
lcopyright, _ := Asset(filepath.Join("licenses", string(ltype)+".copyright"))
data = append(lcopyright, data...)
return replacer.Replace(string(data)), nil
}
// Sets license
func Set(config *Config) error {
files, err := filepath.Glob(config.Files)
if err != nil {
return err
}
// If a specific file was provided use it
if len(files) == 0 {
// if folder
files = append(files, config.Files)
}
errors := new(Error)
var wg sync.WaitGroup
replacer := strings.NewReplacer("@@owner@@", config.CopyrightOwner, "@@year@@", strconv.Itoa(time.Now().Year()))
for _, file := range files {
wg.Add(1)
go func(file string) {
defer wg.Done()
err = insertLicense(file, replacer, config)
if err != nil {
errors.Append(err)
}
}(file)
}
wg.Wait()
if errors.IsEmpty() {
return nil
}
return errors
}
// Removes license
func Unset(config *Config) error {
files, err := filepath.Glob(config.Files)
if err != nil {
return err
}
// If a specific file was provided use it
if len(files) == 0 {
// if folder
files = append(files, config.Files)
}
errors := new(Error)
var wg sync.WaitGroup
for _, file := range files {
wg.Add(1)
go func(file string) {
defer wg.Done()
err = removeLicense(file, config)
if err != nil {
errors.Append(err)
}
}(file)
}
wg.Wait()
if errors.IsEmpty() {
return nil
}
return errors
}
// Removes license header from file represented by filename
func removeLicense(filename string, config *Config) error {
lbuffer := bytes.NewBuffer(nil)
lheader, err := Asset(filepath.Join("licenses", string(config.LicenseType)+".header"))
if err != nil {
// This license does require a license header in the source file.
// Do not remove anything
return nil
}
err = prependEOLComment(lbuffer, config, lheader)
if err != nil {
return err
}
license := lbuffer.String()
licensedFile, err := ioutil.ReadFile(filename)
buf := bytes.NewBuffer(licensedFile)
unlincesedFile := bytes.NewBuffer(nil)
scanner := bufio.NewScanner(buf)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "// Copyright") {
continue
}
_, err := unlincesedFile.WriteString(line + "\n")
if err != nil {
return err
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("Scanner error: %v", err)
}
unlicensedData := unlincesedFile.String()
unlicensedData = strings.Replace(unlicensedData, license, "", -1)
return ioutil.WriteFile(filename, []byte(unlicensedData), 0640)
}
// Inserts license header to file represented by filename
func insertLicense(filename string, replacer *strings.Replacer, config *Config) error {
licensedFile := bytes.NewBuffer(nil)
lcopyright, err := Asset(filepath.Join("licenses", string(config.LicenseType)+".copyright"))
if err == nil {
err = prependEOLComment(licensedFile, config, lcopyright)
if err != nil {
return err
}
}
lheader, err := Asset(filepath.Join("licenses", string(config.LicenseType)+".header"))
if err == nil {
err := prependEOLComment(licensedFile, config, lheader)
if err != nil {
return err
}
}
data, err := ioutil.ReadFile(filename)
_, err = licensedFile.WriteString(string(data))
if err != nil {
return err
}
filedata := replacer.Replace(licensedFile.String())
return ioutil.WriteFile(filename, []byte(filedata), 0640)
}
// Prepends end-of-line comment to newdata and returns it in licensedFile
func prependEOLComment(licensedFile *bytes.Buffer, config *Config, newdata []byte) error {
if len(newdata) == 0 {
return nil
}
buffer := bytes.NewBuffer(newdata)
scanner := bufio.NewScanner(buffer)
for scanner.Scan() {
line := scanner.Text()
eol := strings.TrimSpace(config.EOLCommentStyle + " " + line)
_, err := licensedFile.WriteString(eol + "\n")
if err != nil {
return err
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("Scanner error: %v", err)
}
return nil
}
// List supported license types
func List() ([]string, error) {
licenses, err := AssetDir("licenses")
if err != nil {
return nil, err
}
types := make([]string, 0, len(licenses))
for _, l := range licenses {
if strings.HasSuffix(l, "header") || strings.HasSuffix(l, "copyright") {
continue
}
types = append(types, l)
}
return types, nil
}
// TODO(c4milo): Use go-license
func Detect(filepath string) (LicenseType, error) {
return UNKNOWN, nil
}