forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate-tree.js
62 lines (54 loc) · 1.96 KB
/
create-tree.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
const fs = require('fs').promises
const path = require('path')
const Page = require('./page')
const { sortBy } = require('lodash')
const basePath = path.posix.join(__dirname, '..', 'content')
module.exports = async function createTree (originalPath, langObj) {
// On recursive runs, this is processing page.children items in `/<link>` format.
// If the path exists as is, assume this is a directory with a child index.md.
// Otherwise, assume it's a child .md file and add `.md` to the path.
let filepath
try {
await fs.access(originalPath)
filepath = `${originalPath}/index.md`
} catch {
filepath = `${originalPath}.md`
}
const relativePath = filepath.replace(`${basePath}/`, '')
const localizedBasePath = path.posix.join(__dirname, '..', langObj.dir, 'content')
// Initialize the Page! This is where the file reads happen.
let page = await Page.init({
basePath: localizedBasePath,
relativePath,
languageCode: langObj.code
})
if (!page) {
// Do not throw an error if Early Access is not available.
if (relativePath.startsWith('early-access')) return
// If a translated path doesn't exist, fall back to the English so there is parity between
// the English tree and the translated trees.
if (langObj.code !== 'en') {
page = await Page.init({
basePath: basePath,
relativePath,
languageCode: langObj.code
})
}
if (!page) throw Error(`Cannot initialize page for ${filepath}`)
}
// Create the root tree object on the first run, and create children recursively.
const item = {
page
}
// Process frontmatter children recursively.
if (item.page.children) {
item.childPages = sortBy(
(await Promise.all(item.page.children
.map(async (child) => await createTree(path.posix.join(originalPath, child), langObj))))
.filter(Boolean),
// Sort by the ordered array of `children` in the frontmatter.
item.page.children
)
}
return item
}