-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
129 lines (109 loc) · 2.9 KB
/
index.js
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
var fs = require('fs'),
path = require('path'),
cwd = process.cwd()
var defaults = {
styles: ['css', 'styl', 'sass', 'less'],
scripts: ['js', 'coffee'],
templates: ['html', 'jade', 'mustache', 'handlebars'],
images: ['jpg', 'png', 'gif'],
files: [],
indent: 2,
debug: false
}
module.exports = function (jsonPath, options) {
jsonPath = jsonPath || 'component.json'
options = options || {}
if (typeof jsonPath === 'object') {
options = jsonPath
jsonPath = 'component.json'
}
jsonPath = path.relative(cwd, jsonPath)
options = merge(defaults, options)
var project = read(jsonPath),
map = {},
justUpdated = false,
dbTimeout = null
for (var key in options) {
if (Array.isArray(options[key])) {
options[key].forEach(function (ext) {
map[ext] = key
})
}
}
function addFile (file) {
var type = getType(file),
files = project[type]
if (!files) {
files = project[type] = []
}
var i = findFile(files, file)
if (i < 0) {
files.push(file)
write()
}
}
function deleteFile (file) {
var type = getType(file),
files = project[type]
if (!Array.isArray(files)) return
var i = findFile(files, file)
if (i >= 0) {
files.splice(i, 1)
write()
}
}
function getType (file) {
var ext = path.extname(file).slice(1)
return map[ext]
}
function read () {
return JSON.parse(fs.readFileSync(jsonPath, 'utf-8'))
}
function write () {
fs.writeFileSync(jsonPath, JSON.stringify(project, null, 2), 'utf-8')
}
function debounce () {
justUpdated = true
clearTimeout(dbTimeout)
dbTimeout = setTimeout(function () {
justUpdated = false
}, 100)
}
return function (event) {
var p = path.relative(cwd, event.path)
if (event.type === 'added') {
if (options.log) console.log('component.json: +' + p)
debounce()
addFile(p)
}
if (event.type === 'deleted') {
if (options.log) console.log('component.json: -' + p)
debounce()
deleteFile(p)
}
if (event.type === 'changed' && p === jsonPath && !justUpdated) {
if (options.log) console.log('component.json: ^')
project = read()
}
}
}
function findFile (list, file) {
var index = -1
list.some(function (f, i) {
if (path.relative(cwd, f) === file) {
index = i
return true
}
})
return index
}
function merge (a, b) {
var res = {}, key
for (key in a) {
res[key] = a[key]
}
for (key in b) {
res[key] = b[key]
}
return res
}