-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
build.js
executable file
·303 lines (268 loc) · 8.77 KB
/
build.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
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
#!/usr/bin/env node
/**
* 根据爬取的景HTML文件生成docset
*/
const yargs = require('yargs/yargs')
const {hideBin} = require('yargs/helpers')
const argv = yargs(hideBin(process.argv)).argv;
const sqlite3 = require('sqlite3').verbose()
const fs = require('fs');
const path = require('path');
const cheerio = require('cheerio');
const childProcess = require('child_process');
const {XMLParser, XMLBuilder} = require("fast-xml-parser");
const options = {
sourceDir: path.join(__dirname, 'source-html', 'document'), // HTML源文件
docsetDir: path.join(__dirname, 'tcapi.docset'), // docset目标文件夹
contentsDir: path.join(__dirname, 'tcapi.docset', 'Contents'),
resourceDir: path.join(__dirname, 'tcapi.docset', 'Contents', 'Resources'),
DocumentsDir: path.join(__dirname, 'tcapi.docset', 'Contents', 'Resources', 'Documents')
};
const homePage = 'https://cloud.tencent.com/document';
let sqlFile = path.join(options.resourceDir, 'docSet.dsidx');
sqlite3.verbose();
let db;
async function parseDocumentationAndFillSearchIndex() {
const files = fs.readdirSync(options.sourceDir);
for (const file of files) {
await processDocumentationFile(path.join(options.sourceDir, file))
}
}
(async function main() {
console.log('Generate Docset start');
// console.time('Docset making');
// 初始化项目
if (argv.init) {
initDocsetFile();
copyConfigFiles();
if (fs.existsSync(sqlFile)) {
fs.unlinkSync(sqlFile);
}
connectDB();
await createDBTable();
}
// 拉取新站点
if (argv.crawl) {
crawlSite(argv.crawl);
}
// 添加新索引
if (argv.addIndex) {
connectDB();
await parseDocumentationAndFillSearchIndex();
}
if (argv.clearIndex) {
connectDB();
await clearSearchIndex();
}
if (argv.syncConfig) {
copyConfigFiles();
}
if (argv.create) {
createDocSet();
}
if (argv.updateVersion) {
updateVersion();
}
// console.timeEnd('Docset making');
// console.log('Generate Docset Successfully! ')
})();
function copyConfigFiles() {
fs.copyFileSync('Info.plist', path.join(options.contentsDir, 'Info.plist'));
fs.copyFileSync('icon.png', path.join(options.docsetDir, 'icon.png'));
}
function createInterfaceItems($, onlineUrl) {
const interfaceEls = $('#docArticleContent h2');
const items = [];
for (const interfaceEl of interfaceEls) {
let interfaceDesc = interfaceEl.next.children[0].data;
interfaceDesc = interfaceDesc || '';
// 考虑到美观,做些数据处理
interfaceDesc = interfaceDesc.replace(/。$/, '');
const interfaceName = interfaceEl.attribs.id;
items.push({
name: formatName(interfaceName, interfaceDesc), type: 'Interface', path: `${onlineUrl}#${interfaceName}`
})
}
return items;
}
/**
* 只处理HTML文件
*/
async function processDocumentationFile(file) {
if (fs.lstatSync(file).isDirectory()) {
for (const f of fs.readdirSync(file)) {
await processDocumentationFile(path.join(file, f));
}
return;
}
if (!file.match(/.html$/)) {
return;
}
let content = fs.readFileSync(file, 'utf-8');
const jquery = cheerio.load(content);
let relativeFilepath = file.replace(options.sourceDir + '/', '');
/**
* 函数名称
*/
let functionNameRegex = /(?<=Action=)[A-Za-z\d]+/;
let functionName = content.match(functionNameRegex)
let functionNameCN = jquery('.rno-title-module-title').text();
const items = [];
let onlineUrl = `${homePage}/${relativeFilepath.replace(/.html$/, '')}`;
const crumbs = jquery('.rno-header-crumbs-link-2'); // 文档中心 > API 中心 > 自动化助手 >
if (crumbs[2]) {
onlineUrl = `${onlineUrl}?product=${crumbs[2].attribs.title}`;
if (functionNameCN === 'API 概览') {
items.push({
name: `${formatName(crumbs[2].attribs.title, functionNameCN)}`, type: 'Module', path: onlineUrl
});
} else if (functionNameCN === '简介') {
items.push({
name: `${formatName(crumbs[2].attribs.title, functionNameCN)}`, type: 'Guide', path: onlineUrl
});
} else if (functionNameCN === '数据结构') {
items.push(...createInterfaceItems(jquery, onlineUrl));
} else if (functionName) {
items.push({
name: `${formatName(functionName[0], functionNameCN)}`, type: 'Method', path: onlineUrl
})
}
}
items.length > 0 && await fillSearchIndex(items);
}
function connectDB() {
db = new sqlite3.Database(sqlFile);
}
async function createDBTable() {
let query = ['CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT);', 'CREATE UNIQUE INDEX anchor ON searchIndex (name, type, path);'].join(' ');
try {
await new Promise((resolve, reject) => db.exec(query, (err) => {
err ? reject(err) : resolve();
}));
} catch (e) {
throw e;
}
console.log('Create DB Table Successfully!');
}
/**
* 入口名称比如查询一个类,这就是类名称
* Dash可以识别的类型,见
* @see https://kapeli.com/docsets#supportedentrytypes
* @param items
* @returns {Promise<void>}
*/
function fillSearchIndex(items) {
return new Promise(resolve => {
for (let i = 0; i < items.length; i++) {
const item = items[i];
db.run(`INSERT INTO searchIndex(name, type, path) VALUES ('${item.name}', '${item.type}', '${item.path}')`, (err) => {
if (!err) {
console.log(`${item.name}-${item.type} write to index success`);
}
if (i === items.length - 1) {
resolve();
}
});
}
})
}
function initDocsetFile() {
if (fs.existsSync(options.docsetDir)) {
console.log('Docset dir already exists, remove it first');
childProcess.execSync(`rm -rf '${options.docsetDir}'`);
}
childProcess.execSync('mkdir -p tcapi.docset/Contents/Resources/Documents/');
}
/**
* 抓取目标网页数据
* @param site
*/
function crawlSite(site) {
childProcess.execSync('WGET_CMD=$(which wget)\n' + '\n' + 'if [[ ! -z $WGET_CMD ]]; then\n' + ' brew install wget\n' + 'fi', {stdio: 'inherit'});
const command = `wget -np -r -l inf -nH -nc -R 'index.html*' --compression=gzip --domains=cloud.tencent.com -e robots=off -P ./source-html --adjust-extension '${site}' `;
console.log('执行爬取网页命令如下\n', command);
childProcess.execSync(command, {stdio: 'inherit'});
}
/**
* 清除搜索索引数据
* @returns {Promise<unknown>}
*/
function clearSearchIndex() {
return new Promise(resolve => {
const stmt = db.prepare('DELETE FROM searchIndex;');
stmt.all();
resolve();
})
}
function formatName(value1, value2) {
return `${value1} > ${value2}`;
}
/**
* 参考大小是347KB
*/
function tarDocset() {
let size;
if (fs.existsSync(path.join(__dirname, 'tcapi.tgz'))) {
size = fs.statSync(path.join(__dirname, 'tcapi.tgz')).size;
console.log('tar docset,之前大小是', size);
}
childProcess.execSync(`tar --exclude='.DS_Store' -cvzf tcapi.tgz tcapi.docset`);
// 获取文件大小
size = fs.statSync(path.join(__dirname, 'tcapi.tgz')).size;
console.log('tar docset 最新大小是', size);
}
function crawlSitesByProductNum() {
const productNums = fs.readFileSync(path.join(__dirname, 'products.txt'), {encoding: 'utf-8'}).split('\n').filter(item => item);
// 拉取目标产品HTML源文件
for (const productNumsKey of productNums) {
try {
crawlSite(`https://cloud.tencent.com/document/api/${productNumsKey}/`);
} catch (e) {
console.error(e);
}
}
// 处理非目标产品HTML源文件
const htmlPath = path.join(options.sourceDir, 'api');
for (const file of fs.readdirSync(htmlPath)) {
const b = productNums.some(productNumsKey => productNumsKey === file || productNumsKey === file.replace(/.html$/, ''));
console.log(b);
if (!b) {
childProcess.execSync(`rm -rf ${htmlPath}/${file}`);
}
}
}
/**
* 完整的docset创建流程
*/
async function createDocSet() {
childProcess.execSync(`rm -rf source-html`);
childProcess.execSync(`mkdir -p source-html`);
crawlSitesByProductNum();
// 初始化DB
initDocsetFile();
copyConfigFiles();
if (fs.existsSync(sqlFile)) {
fs.unlinkSync(sqlFile);
}
connectDB();
await createDBTable();
// // 生成搜索索引
await parseDocumentationAndFillSearchIndex();
// 打包
tarDocset();
// updateVersion
updateVersion();
}
function updateVersion() {
let xmlPath = path.join(__dirname, 'feed.xml');
const xmldata = fs.readFileSync(xmlPath, {encoding: 'utf-8'});
const parser = new XMLParser();
let jObj = parser.parse(xmldata);
console.log('updateVersion,之前版本是', jObj);
const builder = new XMLBuilder();
let now = new Date();
jObj.entry.version = [now.getFullYear(), now.getMonth() + 1, now.getTime(),].join('.');
console.log('updateVersion,新版本是', jObj);
const xmlContent = builder.build(jObj);
fs.writeFileSync(xmlPath, xmlContent, {encoding: 'utf-8'});
}