-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
69 lines (56 loc) · 1.92 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
const path = require('path')
, fs = require('fs-extra')
, {Gaze} = require('gaze')
, watch = (directory, eventHandler) => (new Gaze(directory + '/**')).on('all', eventHandler)
, getToStaticDirectory = require('refo-directory-to-other-directory')
var staticFilePaths = {}
, fileSources = {}
module.exports.addStaticFilePath = (filePath, staticFilePath) => {
if (!staticFilePaths[filePath])
staticFilePaths[filePath] = staticFilePath
}
module.exports.watchedFileSource = {}
module.exports.watchedFileSource.init = filePath => fileSources[filePath] = []
module.exports.watchedFileSource.add = (filePath, sourceFilePath) => {
if (!fileSources[filePath].includes(sourceFilePath))
fileSources[filePath].push(sourceFilePath)
}
module.exports.watch = (handlers, assetDirectory, siteDirectory, staticDirectory) => {
String.prototype.toStaticDirectory = getToStaticDirectory(siteDirectory, staticDirectory)
const getHandler = filePath => handlers[path.extname(filePath)]
, handleSourceChange = filePath =>
Object.entries(fileSources).forEach(source => {
if (source[1].includes(filePath))
getHandler(source[0])(source[0], true)
})
watch(assetDirectory, (event, filePath) => handleSourceChange(filePath))
watch(siteDirectory, (event, filePath) => {
switch (event) {
case 'added': case 'changed': case 'renamed':
const handle = getHandler(filePath)
if (handle)
handle(filePath)
else {
const staticFilePath = filePath.toStaticDirectory()
if (fs.lstatSync(filePath).isDirectory())
fs.ensureDir(staticFilePath)
else
fs.copy(filePath, staticFilePath)
}
handleSourceChange(filePath)
break;
case 'deleted':
fs.unlink(
staticFilePaths[filePath] ?
staticFilePaths[filePath]
:
filePath.toStaticDirectory()
)
if (staticFilePaths[filePath])
delete staticFilePaths[filePath]
if (fileSources[filePath])
delete fileSources[filePath]
break;
}
})
}