-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge-readmes.js
More file actions
71 lines (66 loc) · 2.01 KB
/
merge-readmes.js
File metadata and controls
71 lines (66 loc) · 2.01 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
const fs = require('fs')
const path = require('path')
const baseDir = __dirname
const readmes = ['README.md', 'README.zh-CN.md'].map((p) =>
path.join(baseDir, p)
)
const sources = [
{ file: 'tampermonkey.md', heading: /^###\s*Tampermonkey\b/ },
{ file: 'violentmonkey.md', heading: /^###\s*Violentmonkey\b/ },
{ file: 'scriptcat.md', heading: /^###\s*ScriptCat\b/ },
{ file: 'greasemonkey.md', heading: /^###\s*Greasemonkey\b/ },
{
file: 'quoid-userscripts.md',
heading: /^###\s*Userscripts\s*\(Safari\)/,
},
{ file: 'stay-safari.md', heading: /^###\s*Stay\s*\(Safari\)/ },
{ file: 'stay-chrome.md', heading: /^###\s*Stay\s*\(Chrome\)/ },
]
function readBody(filePath) {
const content = fs.readFileSync(filePath, 'utf8')
const lines = content.split(/\r?\n/)
if (lines.length && lines[0].trim().startsWith('#')) lines.shift()
return lines.join('\n').trim() + '\n'
}
function replaceSection(doc, headingRegex, newBody) {
const lines = doc.split(/\r?\n/)
let hIndex = -1
for (let i = 0; i < lines.length; i++) {
if (headingRegex.test(lines[i])) {
hIndex = i
break
}
}
if (hIndex === -1) return doc
let end = lines.length
for (let j = hIndex + 1; j < lines.length; j++) {
if (/^###\s/.test(lines[j])) {
end = j
break
}
}
const prefix = lines.slice(0, hIndex + 1).join('\n')
const suffix = lines.slice(end).join('\n')
const body = newBody.replace(/\r?\n$/, '') + '\n'
return prefix + '\n' + body + suffix
}
function run() {
const newBodies = {}
for (const { file, heading } of sources) {
const srcPath = path.join(baseDir, file)
if (fs.existsSync(srcPath)) {
newBodies[file] = { heading, body: readBody(srcPath) }
}
}
for (const readmePath of readmes) {
let doc = fs.readFileSync(readmePath, 'utf8')
for (const { file } of sources) {
const entry = newBodies[file]
if (entry) {
doc = replaceSection(doc, entry.heading, entry.body)
}
}
fs.writeFileSync(readmePath, doc, 'utf8')
}
}
run()