Skip to content

Commit 80bdffe

Browse files
authored
restructure map topics (#18042)
1 parent 5022cc6 commit 80bdffe

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#!/usr/bin/env node
2+
3+
const fs = require('fs')
4+
const path = require('path')
5+
const walk = require('walk-sync')
6+
7+
const relativeRefRegex = /\/[a-zA-Z0-9-]+/g
8+
const linkString = /{% [^}]*?link.*? \/(.*?) ?%}/m
9+
const linksArray = new RegExp(linkString.source, 'gm')
10+
11+
const fullDirectoryPath = path.join(process.cwd(), '/content')
12+
const files = walk(fullDirectoryPath, {
13+
includeBasePath: true,
14+
directories: false
15+
})
16+
17+
files.forEach(file => {
18+
if (path.basename(file) !== 'index.md') return
19+
20+
let fileContent = fs.readFileSync(file, 'utf-8')
21+
// find array of TOC link strings
22+
const rawItems = fileContent.match(linksArray)
23+
if (!rawItems || !rawItems[0].includes('topic_link_in_list')) return
24+
25+
const pageToc = {}
26+
let currentTopic = ''
27+
28+
// Create an object of topics and articles
29+
rawItems.forEach(tocItem => {
30+
const relativePath = tocItem.match(relativeRefRegex).pop().replace('/', '')
31+
if (tocItem.includes('topic_link_in_list')) {
32+
currentTopic = relativePath
33+
pageToc[relativePath] = []
34+
} else {
35+
const tmpArray = pageToc[currentTopic]
36+
tmpArray.push(relativePath)
37+
pageToc[currentTopic] = tmpArray
38+
}
39+
})
40+
for (const topic in pageToc) {
41+
const oldTopicDirectory = path.dirname(file)
42+
const newTopicDirectory = path.join(oldTopicDirectory, topic)
43+
const topicFile = path.join(oldTopicDirectory, `${topic}.md`)
44+
45+
if (!fs.existsSync(newTopicDirectory)) fs.mkdirSync(newTopicDirectory)
46+
47+
let topicContent = fs.readFileSync(topicFile, 'utf-8')
48+
topicContent = topicContent.replace('mapTopic: true\n', '')
49+
50+
const articles = pageToc[topic]
51+
52+
articles.forEach(article => {
53+
fs.renameSync(`${oldTopicDirectory}/${article}.md`, `${newTopicDirectory}/${article}.md`)
54+
topicContent = topicContent + `{% link_with_intro /${article} %}\n`
55+
fileContent = fileContent.replace(`/{% link_in_list /${article}`, `/{% link_in_list /${newTopicDirectory}/${article}`)
56+
})
57+
fs.writeFileSync(`${newTopicDirectory}/index.md`, topicContent)
58+
fs.unlinkSync(topicFile)
59+
}
60+
})

0 commit comments

Comments
 (0)