Skip to content

Commit

Permalink
fixed nested mdx and files named index
Browse files Browse the repository at this point in the history
  • Loading branch information
Neobii committed Apr 17, 2021
1 parent 1e4417c commit 533db1d
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/mdx/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./listMdxFiles";
export * from "./mdx";
63 changes: 63 additions & 0 deletions packages/mdx/mdx.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { promises as fsPromises } from "fs";
import path from "path";

type MdxPath = {
params: {
fileName: Array<String>
}
}

export async function getMdxPaths(docsDir) {
// relative to the project root
const fullPath = path.resolve(docsDir);
let paths: MdxPath[] = [];
for await (const f of getFiles(fullPath)) {
//process paths
const fParsed = path.parse(f);
if(fParsed.ext.match(/.mdx?$/)) {
const relativePath = f.replace(fullPath, "");
let pathArgs: Array<String> = relativePath.split(path.sep);
pathArgs.shift();
if(fParsed.name === "index") {
pathArgs.pop();
} else {
pathArgs[pathArgs.length - 1] = fParsed.name;
}
paths.push({params: {fileName: pathArgs}})
}
}
return paths;
}

export async function* getFiles(dir) {
const dirents = await fsPromises.readdir(dir, { withFileTypes: true });
for (const dirent of dirents) {
const res = path.resolve(dir, dirent.name);
if (dirent.isDirectory()) {
yield* getFiles(res);
} else {
//do something to get the path link
yield res
}
}
}



export function getFirstHeader(mdText) {
return mdText.match(/^<.+?>(.+?)<.+?>/)?.[1];
}

export async function getSource(docFolder, fileNames) {
const fullPath = path.resolve(docFolder, ...fileNames)
let isFolder;
try {
await fsPromises.access(fullPath);
isFolder = true;
} catch {
isFolder = false;
}
const filePath = (isFolder)?path.resolve(fullPath, "index.md"): fullPath + ".md";
const source = await fsPromises.readFile(filePath, { encoding: "utf8" });
return { filePath, source }
}

0 comments on commit 533db1d

Please sign in to comment.