-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
107 lines (96 loc) · 2.99 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
/*
传入 gulp.watch(funciton(event){}) 中的 event(event.path) 、 查找起始字符串(search)、替换字符串(replace) 和 扩展名
扩展名非必填(大部分情况下会自动识别,例如:event.path = 'index.sass' 若 ext 参数为空,ext = 'css')
*/
var path = require('path')
var main = function (event, search, replace, ext) {
var log = function (msg) {
// console.log(msg)
}
var srcFilename, distFilename, srcPath, srcDir, distPath, distDir
var rStringToRegExp, fStringToPrefixRegExp, fStringToSuffixRegExp, rDirname
search = path.join(search)
replace = path.join(replace)
log('\n')
log('search: ' + search)
log('replace: ' + replace)
log('event.path: ' + event.path)
// /Users/nimojs/Documents/code/demo/src/index.js
/*
将字符串转换为正则所需的正则
. $ ^ { 等均需要被转换为 \. \$ \^ \ {
*/
rStringToRegExp = /([.$^{[(|)*+?\/\\])/g
fStringToPrefixRegExp = function (str) {
return new RegExp(
'^' + (
str.replace(rStringToRegExp, '\\$1')
)
);
}
fStringToSuffixRegExp = function (str) {
return new RegExp(
(
str.replace(rStringToRegExp, '\\$1')
) + '$'
);
}
if (typeof search === 'string') {
search = fStringToPrefixRegExp(search) // src/ ==> \src\//
}
srcFilename = path.basename(event.path)
log('srcFilename: ' + srcFilename)
// index.js
if (!ext) {
if (/\.(coffee|node)$/i.test(srcFilename)) {
ext = 'js'
}
else if (/\.(scss|sass|less)$/i.test(srcFilename)) {
ext = 'css'
}
else if (/\.(handlebars|hbs)$/i.test(srcFilename)) {
ext = 'js'
}
}
if (ext) {
if (/\./.test(srcFilename)) {
distFilename = srcFilename.replace(/[^.]+$/, ext);
}
else{
distFilename = srcFilename + '.' + ext
}
}
else {
distFilename = srcFilename;
}
log('distFilename: ' + distFilename)
rDirname = fStringToPrefixRegExp(process.cwd())
log('rDirname: ' + rDirname)
// ^\/Documents\/code\/gulp-watch-path\/
srcPath = event.path.replace(rDirname, '')
.replace(/^[\/\\]/, '')
log('srcPath: ' + srcPath)
// src/js/log.js
srcDir = path.dirname(srcPath)
log('srcDir: ' + srcDir)
// src/js/
distPath = srcPath.replace(search, replace)
log('distPath: ' + distPath)
// dist/js/log.js
if (ext) {
distPath = distPath.replace(/[^.]+$/, ext);
}
distDir = path.dirname(distPath)
log('distDir: ' + distDir)
// dist/js/
log('\n')
return {
srcFilename: srcFilename,
distFilename: distFilename,
srcPath: srcPath,
srcDir: srcDir,
distPath: distPath,
distDir: distDir
}
}
module.exports = main