1 | fs = require 'fs'
|
2 | glob = require 'globber'
|
3 | debug = require('debug') 'license'
|
4 |
|
5 | SOURCE_FILES = {
|
6 | 'coffee':
|
7 | startComment: '###'
|
8 | endComment: '###'
|
9 | 'js':
|
10 | startComment: '/*'
|
11 | endComment: '*/'
|
12 | }
|
13 |
|
14 | module.exports = (directory, log, config={}) ->
|
15 | license = readFile "#{directory}/LICENSE"
|
16 | debug "has license: #{license}"
|
17 | return unless license?
|
18 |
|
19 | files = getSourceFiles(directory, config.license?.exclude)
|
20 | debug "files: #{files}"
|
21 |
|
22 | for file in files
|
23 | ensureLicense file, license, log
|
24 |
|
25 | readFile = (filePath) ->
|
26 | if (fs.existsSync filePath)
|
27 | buffer = fs.readFileSync filePath
|
28 | buffer.toString()
|
29 |
|
30 | getExtension = (path) ->
|
31 | path.split('.').pop()
|
32 |
|
33 | getSourceFiles = (directory, exclude=[]) ->
|
34 | options =
|
35 | exclude: ['node_modules'].concat(exclude)
|
36 | recursive: true
|
37 | includeDirectories: false
|
38 |
|
39 | files = glob.sync directory, options
|
40 | files = files.map (file) ->
|
41 | {
|
42 | path: file
|
43 | ext: getExtension(file)
|
44 | }
|
45 |
|
46 | files.filter (file) ->
|
47 | file.ext in (Object.keys SOURCE_FILES)
|
48 |
|
49 | ensureLicense = (file, license, log) ->
|
50 | file.content = readFile file.path
|
51 |
|
52 | newline = '\n'
|
53 | {startComment, endComment} = SOURCE_FILES[file.ext]
|
54 | license = startComment + newline + license + endComment + newline + newline
|
55 |
|
56 | if file.content.indexOf(license) != 0
|
57 | log "#{file.path}: adding license"
|
58 | prepend file, license
|
59 |
|
60 | prepend = (file, license) ->
|
61 | newFile = license + file.content
|
62 |
|
63 | tempFilePath = "#{file.path}_tmp"
|
64 | fs.writeFileSync tempFilePath, newFile
|
65 | fs.renameSync tempFilePath, file.path
|
66 |
|