UNPKG

1.54 kBtext/coffeescriptView Raw
1fs = require 'fs'
2glob = require 'globber'
3debug = require('debug') 'license'
4
5SOURCE_FILES = {
6 'coffee':
7 startComment: '###'
8 endComment: '###'
9 'js':
10 startComment: '/*'
11 endComment: '*/'
12}
13
14module.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
25readFile = (filePath) ->
26 if (fs.existsSync filePath)
27 buffer = fs.readFileSync filePath
28 buffer.toString()
29
30getExtension = (path) ->
31 path.split('.').pop()
32
33getSourceFiles = (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
49ensureLicense = (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
60prepend = (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