-
Notifications
You must be signed in to change notification settings - Fork 12
/
doc.js
127 lines (104 loc) · 2.92 KB
/
doc.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
const path = require('path')
const fs = require('fs-extra')
const readline = require('linebyline')
const _ = require('underscore')
const moment = require('moment')
const TEMPLATE = path.join(__dirname, 'TEMPLATE.md')
const README = path.join(__dirname, 'README.md')
const NORMALAPI_FILE = path.join(__dirname, 'src/api/normalApi.js')
const INSTANCEAPI_FILE = path.join(__dirname, 'src/api/instanceApi.js')
const POLYFILLS_FILE = path.join(__dirname, 'src/polyfills/index.js')
let NORMALAPI_DATA = []
let INSTANCEAPI_DATA = []
let POLYFILLS_DATA = []
async function init(){
await handlerNormalApi()
await handlerInstanceApi()
await handlerPolyfills()
writeMarkdown()
}
// 开始任务
init()
// normalApi.js 转换成数组数据
function handlerNormalApi(){
return handler(NORMALAPI_FILE, NORMALAPI_DATA, {
hasItems: true
})
}
// instanceApi.js 转换成数组数据
function handlerInstanceApi(){
return handler(INSTANCEAPI_FILE, INSTANCEAPI_DATA, {
hasItems: false
})
}
// polyfills/index.js 转换成数组数据
function handlerPolyfills(){
return handler(POLYFILLS_FILE, POLYFILLS_DATA, {
hasItems: true,
itemReg: /(\w+):/
})
}
/**
* 文件注释转数组数据
* @param file 文件路径
* @param arr 保存的数据
* @param opts 配置参数
* @param [opts.hasItems] 是否有子级
* @param [opts.itemReg] 子级匹配的正则
*/
function handler(file, arr, opts){
let rl = readline(file, { retainBuffer: true })
let ready = false
return new Promise((resolve) => {
rl.on('line', (data) => {
let content = data.toString()
if(/module\.exports/.test(content)){
ready = true
}
if(ready){
// 匹配一级中文开头的标题
let matchs = content.match(/\/\/\s([\u4e00-\u9fa5]+.*)/)
if(matchs && matchs[1]){
arr.push({
title: matchs[1],
items: []
})
}
// 匹配 API 上的注释
let item = null
let matchApi = content.match(opts.itemReg || /'(\w+)',(\s+\/\/\s+([\w\s]+))?/)
if(matchApi && matchApi[1]){
let labels = []
if(matchApi[3]){
labels = matchApi[3].split(/\s/)
}
item = {
title: matchApi[1],
labels: labels
}
}
if(item){
if(opts.hasItems){
let last = arr[arr.length - 1]
last && last.items.push(item)
}else{
arr.push(item)
}
}
}
});
rl.on('end', resolve)
})
}
// 生成文档,TEMPLATE.md => README.md
function writeMarkdown(){
let tplContent = fs.readFileSync(TEMPLATE).toString()
let compiled = _.template(tplContent);
tplContent = compiled({
updateDate: moment().format('YYYY-MM-DD'),
instanceApi: INSTANCEAPI_DATA,
normalApi: NORMALAPI_DATA,
polyfills: POLYFILLS_DATA
});
fs.writeFileSync(README, tplContent, 'utf-8');
}