-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
306 lines (253 loc) · 10.5 KB
/
Copy pathindex.js
File metadata and controls
306 lines (253 loc) · 10.5 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
var chokidar = require('chokidar');
var npath = require('path');
var fs = require('fs');
var md5 = require('md5');
var _ = require('lodash');
var config = require('./config');
(function () {
var taskDefs = {};
var rgxRawMarker = new RegExp(
'@@\\{' // 预生成标记的起始token
+ '([^{}\\n]*)' // 在 @@{ /* 不应该包含任何的 { 和 } 或 换行 */ } 中
+ '\\}',
'g'
),
rgxExistingMarker = new RegExp(
'@\\{\\{' // 已生成标记的起始token为 @{{
+ '\\s*'
+ '(?:#(\\d+))?' // #DDD 为标记的权重, 目前没有作用
+ '\\s*'
+ '@\\[([^\\[\\]\\n]*)\\]' // 前面是 [ /* 标记名称 */ ]
+ '\\{([^{}\\n]+)\\}' // 后面是 { /* 标记的Key */ }
+ '[^]*?' // 标记中, 可以包含简单的内容
+ '\\}\\}@', // 结束 token
'g'
);
var ensurePath = function (path) {
if (!fs.existsSync(path)) {
ensurePath(npath.dirname(path));
fs.mkdirSync(path);
}
};
var docIndexUpdated = 0, _docIndex;
var getDocIndex = function () {
if (fs.existsSync(config.docIndexFilePath)) {
var stat = fs.statSync(config.docIndexFilePath);
if (stat.mtime.getTime() > docIndexUpdated) {
_docIndex = JSON.parse(fs.readFileSync(config.docIndexFilePath).toString());
docIndexUpdated = stat.atime.getTime();
console.log('index file renewed.');
}
return _docIndex;
} else {
if (!_docIndex) {
_docIndex = {
seq: 0,
keys: {},
files: {}
};
debounceSaveDocIndex();
}
return _docIndex;
}
};
var debounceSaveDocIndex = _.debounce(function () {
fs.writeFileSync(config.docIndexFilePath, JSON.stringify(_docIndex, null, ' '));
docIndexUpdated = new Date().getTime();
}, 800);
var createWatcher = function () {
return chokidar.watch(config.srcPath, {
ignored: config.ignores
});
};
/*@{{
@[ doc 项目监控处理程序 ]{_unbroken_doc_0e9af2478_}
}}@*/
taskDefs.doc = function () {
var allTypeMap = {}, allTypes = [];
var generateKey = function () {
var docIndex = getDocIndex();
docIndex.seq++;
debounceSaveDocIndex();
return '_' + config.projectKey + '_' + md5(Math.random()).substr(0, 8) + docIndex.seq.toString(36) + '_';
};
var fileQueue = {};
/*@{{
@[ 隔时批量索引项目内容 ]{_unbroken_doc_0e5174551_}
在 chokidar 获知文件更改的时候, 不是立即处理, 而是放在一个队列里, 隔时批量处理, 避免多次反复操作.
}}@*/
setInterval(function () {
var docIndex;
for (var path in fileQueue) {
if (!docIndex) {
var docIndex = getDocIndex()
}
if (fs.existsSync(path)) {
var logic = fileQueue[path];
if (typeof logic.comment == 'string') {
logic.comment = config.commentSyntax[logic.comment];
}
if (!logic.comment) {
console.log('No comment syntax set for %s, process next file.', path);
continue;
}
var stat = fs.statSync(path);
//console.log('stat', stat, docIndex.files[path].atime);
// 使用 stat.atime 来检测文件是否需要重新索引
if (!docIndex.files || !docIndex.files[path] || stat.atime.getTime() > docIndex.files[path].atime) {
var fileInfo = docIndex.files[path] = docIndex.files[path] || {atime: stat.atime.getTime()};
var content = fs.readFileSync(path).toString();
var newContent = content.replace(rgxRawMarker, function (match, name) {
name = ' ' + _.trim(name) + ' ';
var key = generateKey();
return logic.comment.start + '@{{\n@[' + name + ']{' + key + '}\n}}@' + logic.comment.end;
});
if (newContent != content) {
fs.writeFileSync(path, newContent);
}
newContent.replace(rgxExistingMarker, function (match, rank, name, key) {
docIndex.keys[key] = {
name: name,
path: path,
rank: rank
};
debounceSaveDocIndex();
console.log('existing - ', name, key, rank);
});
fileInfo.atime = new Date().getTime();
debounceSaveDocIndex();
}
}
}
fileQueue = {};
}, 200);
/*@{{
@[ 加入批处理队列 ]{_unbroken_doc_da5379fc3_}
}}@*/
var processFile = function (path, extname) {
path = path.split('\\').join('/');
var logic = config.fileTypes[extname.substr(1)];
if (logic) {
fileQueue[path] = logic;
}
};
/*@{{
@[ 监视文件更改 ]{_unbroken_doc_d5b774c32_}
}}@*/
var watcher = createWatcher()
.on('add', function (path) {
// 获取所有文件类型
var extname = npath.extname(path);
allTypeMap[extname] = 1;
processFile(path, extname);
//console.log(path);
})
.on('change', function (path) {
var extname = npath.extname(path);
processFile(path, extname);
})
.on('ready', function () {
// 输出文件类型列表
var allTypes = _.keys(allTypeMap);
console.log('all types detected : %s', allTypes.map(function (type) {
return JSON.stringify(type);
}).join());
});
};
var validators = {
/*@{{
@[ 校对cache中的文件路径 ]{_unbroken_doc_236ad77f4_}
}}@*/
validateFiles: function (files, docIndex) {
var newFiles = {};
for (var path in files) {
if (!fs.existsSync(path)) {
console.log('path %s does not exist anymore, removed.', path);
} else {
newFiles[path] = files[path];
}
}
docIndex.files = newFiles;
debounceSaveDocIndex();
},
/*@{{
@[ 校对cache中的标记keys ]{_unbroken_doc_4fb26dc65_}
}}@*/
validateKeys: function (keys, docIndex) {
var tmpKeys = {};
var watcher = createWatcher()
.on('add', function (path) {
path = path.split('\\').join('/');
var content = fs.readFileSync(path).toString();
content.replace(rgxExistingMarker, function (match, rank, name, key) {
tmpKeys[key] = {
name: name,
path: path,
rank: rank
};
console.log('existing - ', name, key, rank);
});
})
.on('ready', function () {
var missingKeys = {}, keysNotAdded = {};
// 检测在index文件中定义, 但在项目内容中未找到的标记.
// 做警示提醒, 不做自动操作
_.each(tmpKeys, function (content, key) {
if (!keys[key]) {
keys[key] = content;
console.log('New key added %s (%s) from %s.', key, content.name, content.path);
debounceSaveDocIndex();
}
});
// 检测在项目内容中找到, 但没在index文件中定义的标记.
// 如果有, 则自动添加到index 文件
_.each(keys, function (content, key) {
if (!tmpKeys[key]) {
missingKeys[key] = content;
console.log('WARNING: %s (%s) from %s is missing.', key, content.name, content.path);
}
});
watcher.close();
});
}
};
/*@{{
@[ validate 校对任务 ]{_unbroken_doc_7f7ba06d6_}
}}@*/
taskDefs.validate = function () {
if (fs.existsSync(config.docIndexFilePath)) {
var docIndex = getDocIndex();
validators.validateFiles(docIndex.files, docIndex);
validators.validateKeys(docIndex.keys, docIndex);
// in future, validate backlinks? content? references?
} else {
console.log('Doc index文件还没有生成, 请先运行: gulp doc');
}
};
module.exports = {
/*@{{
@[ unbroken-doc 初始化 ]{_unbroken_doc_c067c8957_}
}}@*/
init: function (projectKey, configOrFunc) {
if (!projectKey) {
throw Error('You should specify a proper project key as it is the key element of your markers.' +
'\n on .init() method.');
}
config.projectKey = projectKey;
if (typeof configOrFunc == 'function') {
config = configOrFunc(config);
} else if (configOrFunc) {
_.extend(config, configOrFunc);
}
this.applyConfig();
},
applyConfig: function () {
config.docCacheFolderPath += '/';
config.projectKey = config.projectKey.replace(/\W+/g, '_');
config.ignores = config.ignores.concat(config.addIgnores);
config.docIndexFilePath = config.docCacheFolderPath + 'unbroken-doc-index.json';
ensurePath(config.docCacheFolderPath);
},
tasks: taskDefs
}
})();