Repository navigation
Expand file tree
/
Copy pathdownloadCSV.js
More file actions
225 lines (208 loc) · 8.36 KB
/
Copy pathdownloadCSV.js
File metadata and controls
225 lines (208 loc) · 8.36 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
const axios = require('axios')
const fs = require('fs')
const path = require('path')
const github = axios.create({})
// docs目录所在的位置
const FILE_PATH = "./docs"
const csvListRxp = /\[csv-(.*)]\((.*)\)/g
const csvNameAndUrlRxp = /\[csv-(.*)]\((.*)\)/
// 第3个参数 环境
let branch = process.argv[2] || "main"; // main v6.4
// 除了固定的分支以外,其余都尽量使用main分支
if(!/^v[0-9]+\.[0-9]+$/.test(branch)){
branch = 'main'
}
async function downloadCSV(url) {
return github.get(url).then(res => {
if (res.data.startsWith('#')) {
return res.data
} else {
console.log("res.code===", (res.code))
console.log("res.data===", JSON.stringify(res.data))
return ""
}
}) .catch((err) => {
throw new Error(`当前csv地址: ${url} 错误,请检查后重新提交`);
})
}
// 分析csv 只保证前面不除英文,注释可以出现
function analysis(string) {
if (!string) {
return {
tableHeader: [],
tableContent: []
}
}
string = string.slice(string.indexOf("#") + 1) // 去掉第一个#
const strings = string.split("\n").filter(s => !(s.startsWith("#") || s.trim() === "")).map(s => {
return s.split(",").map(s => s.trim())
})
const tableHeader = strings[0]
const tableContent = strings.slice(1)
return {
tableHeader,
tableContent
}
// const intervals = []
// let strings = string.split("\n")
// console.log(strings)
// let startIndex = -1
// while (true) {
// startIndex = strings[0].indexOf(',', startIndex + 1)
// if (startIndex === -1) {
// break
// }
// intervals.push(startIndex)
// }
// intervals.push(strings[0].length + 1)
// const newstrings = strings.map(s => {
// const arr = []
// let start = -1
// for (let i = 0; i < intervals.length; i++) {
// arr.push(s.slice(start + 1, intervals[i]))
// start = intervals[i]
// }
// return arr
// })
// console.log(newstrings)
}
function createTable(table, url) {
const { tableHeader, tableContent } = table
const headerLength = tableHeader.length
let tableString = "|"
let middleString = "|"
tableHeader.forEach(element => {
tableString += element
tableString += "|"
middleString += "-----------|"
});
middleString += "\n"
tableString += "\n"
tableString += middleString
tableContent.forEach((element) => {
let tr = "|"
element.forEach((e, index) => {
if (index < headerLength) {
tr += e
tr += "|"
} else {
console.log("csvUrl:" + url + ",extraData:" + e)
}
})
if (headerLength > element.length) {
console.log("This row is missing data,csvUrl:" + url + ",element:" + element.toString())
tr += "|".repeat(headerLength - element.length)
}
tr += "\n"
tableString += tr
})
return tableString
}
const mergeCHAndOrigin = (chTable, originTable, headers, {
key = 'Category',
value
}) => {
const { tableHeader: chTableHeader, tableContent: chTableContent } = chTable
const { tableHeader: originTableHeader, tableContent: originTableContent } = originTable
if (!originTableHeader.includes(key)) {
return {
tableHeader: [],
tableContent: []
}
}
const keyIndex = originTableHeader.indexOf(key)
const filteredOrigin = originTableContent.filter(content => content[keyIndex] === value) // 读取到列
const keys = filteredOrigin.map(item => item[0]) // 读取到keys
const filteredCh = chTableContent.filter(item => keys.includes(item[0]))
let newTableContent = new Array(keys.length).fill(1)
newTableContent = newTableContent.map(() => ([]))
headers.forEach((header, index) => {
if (originTableHeader.includes(header)) {
const hIndex = originTableHeader.indexOf(header)
filteredOrigin.forEach((f, i) => {
newTableContent[i][index] = f[hIndex]
})
} else if (chTableHeader.includes(header)) {
const chIndex = chTableHeader.indexOf(header)
filteredCh.forEach((f, i) => {
newTableContent[i][index] = f[chIndex]
})
}
})
return {
tableHeader: headers,
tableContent: newTableContent
}
}
const categoryHeaders = ['Field', 'DisplayName', 'Unit', 'Type', 'Description']
const cacheMap = {}
async function work(sourceDir) {
let files = fs.readdirSync(sourceDir);
files = files.filter(name => name !== ".vuepress")
for (let index = 0; index < files.length; index++) {
const filePath = path.join(sourceDir, files[index]);
const stat = fs.statSync(filePath);
if (!stat.isDirectory()) {
let fileContent = fs.readFileSync(filePath, "utf8");
const matchs = fileContent.match(csvListRxp)
console.log(`filePath:${filePath},matchs: ${matchs && matchs.toString()}`)
if (matchs) {
for (let a = 0; a < matchs.length; a++) {
let [, name, url] = matchs[a].match(csvNameAndUrlRxp)
url = url.replace(/main/, branch)
const isCategory = url.includes('Category=')
// 英文版使用 .en 中文版使用 .ch
url = filePath.includes('/zh/')? url: url.replace(/.ch$/, '.en')
const files = url.split("/")
let tableString
if (url in cacheMap) {
tableString = cacheMap[url]
} else if (isCategory) {
const Category = url.split("?Category=")[1]
const chURL = url.split("?")[0]
const originURL = chURL.slice(0, -3)
const chCSVContentString = await downloadCSV(chURL)
const originCSVContentString = await downloadCSV(originURL)
const chTable = analysis(chCSVContentString)
const originTable = analysis(originCSVContentString)
tableString = createTable(mergeCHAndOrigin(chTable, originTable, categoryHeaders, {
key: 'Category',
value: Category
}), chURL)
cacheMap[url] = tableString
} else {
const CSVContentString = await downloadCSV(url)
const table = analysis(CSVContentString)
tableString = createTable(table, url)
cacheMap[url] = tableString
}
const preIndex = fileContent.indexOf(matchs[a]) - 1
const nextIndex = fileContent.indexOf(matchs[a]) + matchs[a].length
let totalString = ""
if (fileContent[preIndex] !== "\n") {
totalString += "\n\n"
} else if (fileContent[preIndex - 1] !== "\n") {
totalString += "\n"
}
totalString += `<div class="csv-box">`
totalString += "\n\n"
// totalString += `**${name}**`
// totalString += "\n\n"
totalString += tableString
totalString += `<p class="csv-url">generate from csv file: <a title="${url}" href="${url}" target="_blank">${files[files.length - 1]}</a></p>\n`
totalString += `</div>`
if (fileContent[nextIndex] !== "\n") {
totalString += "\n\n"
} else if (fileContent[nextIndex + 1] !== "\n") {
totalString += "\n"
}
fileContent = fileContent.replace(matchs[a], totalString)
}
fs.writeFileSync(filePath, fileContent)
}
} else {
await work(filePath)
}
}
}
work(FILE_PATH)