1 |
|
2 | var SOURCE_FILES, debug, ensureLicense, fs, getExtension, getSourceFiles, glob, prepend, readFile,
|
3 | indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
|
4 |
|
5 | fs = require('fs');
|
6 |
|
7 | glob = require('globber');
|
8 |
|
9 | debug = require('debug')('license');
|
10 |
|
11 | SOURCE_FILES = {
|
12 | 'coffee': {
|
13 | startComment: '###',
|
14 | endComment: '###'
|
15 | },
|
16 | 'js': {
|
17 | startComment: '/*',
|
18 | endComment: '*/'
|
19 | }
|
20 | };
|
21 |
|
22 | module.exports = function(directory, log, config) {
|
23 | var file, files, i, len, license, ref, results;
|
24 | if (config == null) {
|
25 | config = {};
|
26 | }
|
27 | license = readFile(directory + "/LICENSE");
|
28 | debug("has license: " + license);
|
29 | if (license == null) {
|
30 | return;
|
31 | }
|
32 | files = getSourceFiles(directory, (ref = config.license) != null ? ref.exclude : void 0);
|
33 | debug("files: " + files);
|
34 | results = [];
|
35 | for (i = 0, len = files.length; i < len; i++) {
|
36 | file = files[i];
|
37 | results.push(ensureLicense(file, license, log));
|
38 | }
|
39 | return results;
|
40 | };
|
41 |
|
42 | readFile = function(filePath) {
|
43 | var buffer;
|
44 | if (fs.existsSync(filePath)) {
|
45 | buffer = fs.readFileSync(filePath);
|
46 | return buffer.toString();
|
47 | }
|
48 | };
|
49 |
|
50 | getExtension = function(path) {
|
51 | return path.split('.').pop();
|
52 | };
|
53 |
|
54 | getSourceFiles = function(directory, exclude) {
|
55 | var files, options;
|
56 | if (exclude == null) {
|
57 | exclude = [];
|
58 | }
|
59 | options = {
|
60 | exclude: ['node_modules'].concat(exclude),
|
61 | recursive: true,
|
62 | includeDirectories: false
|
63 | };
|
64 | files = glob.sync(directory, options);
|
65 | files = files.map(function(file) {
|
66 | return {
|
67 | path: file,
|
68 | ext: getExtension(file)
|
69 | };
|
70 | });
|
71 | return files.filter(function(file) {
|
72 | var ref;
|
73 | return ref = file.ext, indexOf.call(Object.keys(SOURCE_FILES), ref) >= 0;
|
74 | });
|
75 | };
|
76 |
|
77 | ensureLicense = function(file, license, log) {
|
78 | var endComment, newline, ref, startComment;
|
79 | file.content = readFile(file.path);
|
80 | newline = '\n';
|
81 | ref = SOURCE_FILES[file.ext], startComment = ref.startComment, endComment = ref.endComment;
|
82 | license = startComment + newline + license + endComment + newline + newline;
|
83 | if (file.content.indexOf(license) !== 0) {
|
84 | log(file.path + ": adding license");
|
85 | return prepend(file, license);
|
86 | }
|
87 | };
|
88 |
|
89 | prepend = function(file, license) {
|
90 | var newFile, tempFilePath;
|
91 | newFile = license + file.content;
|
92 | tempFilePath = file.path + "_tmp";
|
93 | fs.writeFileSync(tempFilePath, newFile);
|
94 | return fs.renameSync(tempFilePath, file.path);
|
95 | };
|