-
Notifications
You must be signed in to change notification settings - Fork 315
/
Copy pathbuild-file-tree.mjs
77 lines (70 loc) · 1.9 KB
/
build-file-tree.mjs
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
import path from "path";
import matter from "gray-matter";
import fs from "fs/promises";
import { getDirData } from "./utils/get-dir-data.mjs";
import { COLLECTIONS_ROOT } from "./index.mjs";
/**
*
* @param {string} entry
* @returns
*/
export async function buildFileTree(entry = COLLECTIONS_ROOT) {
const entryPath = path.resolve(process.cwd(), entry);
const parentSegment = path.parse(entryPath).dir;
try {
const stats = await fs.stat(entryPath);
if (stats.isDirectory()) {
const info = await getDirData(entryPath);
const nested = await Promise.all(
info.pages.map(async (file) => {
return buildFileTree(path.join(entryPath, file));
})
);
const children = entryPath.includes("/reference/")
? nested
.filter(Boolean)
.sort((firstChild, secondChild) =>
firstChild.title
.toLowerCase()
.localeCompare(secondChild.title.toLowerCase())
)
: nested.filter(Boolean);
return {
type: "section",
title: info.title,
pages: info.pages,
children,
};
} else if (!entryPath.includes("data.json")) {
const file = await fs.readFile(entryPath, "utf-8");
const parentSection = await getDirData(path.resolve(parentSegment));
const { title, mainNavExclude, isDeprecated } = matter(file).data;
/**
* @todo
* parse frontmatter with Zod
*/
return {
type: "markdown",
file: path.basename(entryPath),
path:
"/" +
path
.relative(path.join(process.cwd(), COLLECTIONS_ROOT), entryPath)
.replace(/\index\.mdx?/, "")
.replace(/\.mdx?/, ""),
slug: path.basename(entryPath, path.extname(entryPath)),
parent: parentSection.title,
title,
mainNavExclude,
isDeprecated,
isTranslated: true,
};
} else {
console.error(`WARNING: \n ${entry} was not found.\n Please fix it!\n`);
return;
}
} catch (e) {
console.error("Failed creating tree", e);
return;
}
}