Skip to content

Commit

Permalink
Move functionalities under lib
Browse files Browse the repository at this point in the history
  • Loading branch information
kmtusher97 committed Nov 20, 2024
1 parent bd82afd commit 3edf9f0
Show file tree
Hide file tree
Showing 5 changed files with 121 additions and 118 deletions.
117 changes: 2 additions & 115 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,116 +1,3 @@
const fs = require("fs");
const path = require("path");
const { generateTableOfContent } = require("./lib");

function getDefaultFileTitle(filePath) {
const fileSegments = filePath.split("/");
const fileName = fileSegments[fileSegments.length - 1];
const ext = path.extname(fileName);
return fileName.split(ext)[0];
}

function getMarkdownTitle(filePath) {
const content = fs.readFileSync(filePath, "utf8");

const titleMatch = content.match(/^#\s+(.*)/m);

if (titleMatch) {
return titleMatch[1].trim();
}
return getDefaultFileTitle(filePath);
}

function getFileTitle(filePath) {
if ([".MD", ".md"].includes(path.extname(filePath))) {
return getMarkdownTitle(filePath);
}
return getDefaultFileTitle(filePath);
}

function getTableOfContents({ dirPath = process.cwd(), extensions = [] }) {
try {
if (
!Array.isArray(extensions) ||
extensions.some((ext) => typeof ext !== "string")
) {
throw new Error("Extensions must be an array of strings.");
}

let toc = "";

function readDirectory({ directory, currentDir = ".", level = 0 }) {
const files = fs.readdirSync(directory);

for (const file of files) {
const fullPath = path.join(directory, file);
const stat = fs.statSync(fullPath);

if (stat.isDirectory()) {
toc += `${" ".repeat(level * 2)}* **${file}**\n`;
readDirectory({
directory: fullPath,
currentDir: currentDir + "/" + file,
level: level + 1,
});
} else if (
extensions.length === 0 ||
extensions.includes(path.extname(file))
) {
const filePath = currentDir + "/" + file;
toc += `${" ".repeat(level * 2)}* [${getFileTitle(
fullPath
)}](${filePath})\n`;
}
}
}

readDirectory({ directory: dirPath });
return toc;
} catch (error) {
throw error;
}
}

function updateTOC({ filePath = __dirname + "/README.md", contentToAdd }) {
try {
let fileContent = fs.existsSync(filePath)
? fs.readFileSync(filePath, "utf8")
: "";

const tocStart = "<!---TOC-START--->";
const tocEnd = "<!---TOC-END--->";

const tocStartIndex = fileContent.indexOf(tocStart);
const tocEndIndex = fileContent.indexOf(tocEnd);

if (tocStartIndex !== -1 && tocEndIndex !== -1) {
fileContent =
fileContent.substring(0, tocStartIndex + tocStart.length) +
`\n${contentToAdd}\n` +
fileContent.substring(tocEndIndex);
} else {
const tocSection = `${tocStart}\n${contentToAdd}\n${tocEnd}`;
fileContent = `${fileContent}\n\n${tocSection}`.trim();
}

fs.writeFileSync(filePath, fileContent, "utf8");
} catch (err) {
console.error("Error updating the TOC:", err.message);
}
}

function generateTableOfContent({
dirPath = process.cwd(),
extensions = [".md"],
filePath = __dirname + "/README.md",
}) {
updateTOC({
filePath,
contentToAdd: getTableOfContents({ dirPath, extensions }),
});
}

module.exports = {
getFileTitle,
getTableOfContents,
generateTableOfContent,
};
module.exports = { generateTableOfContent };
116 changes: 116 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
const fs = require("fs");
const path = require("path");

function getDefaultFileTitle(filePath) {
const fileSegments = filePath.split("/");
const fileName = fileSegments[fileSegments.length - 1];
const ext = path.extname(fileName);
return fileName.split(ext)[0];
}

function getMarkdownTitle(filePath) {
const content = fs.readFileSync(filePath, "utf8");

const titleMatch = content.match(/^#\s+(.*)/m);

if (titleMatch) {
return titleMatch[1].trim();
}
return getDefaultFileTitle(filePath);
}

function getFileTitle(filePath) {
if ([".MD", ".md"].includes(path.extname(filePath))) {
return getMarkdownTitle(filePath);
}
return getDefaultFileTitle(filePath);
}

function getTableOfContents({ dirPath = process.cwd(), extensions = [] }) {
try {
if (
!Array.isArray(extensions) ||
extensions.some((ext) => typeof ext !== "string")
) {
throw new Error("Extensions must be an array of strings.");
}

let toc = "";

function readDirectory({ directory, currentDir = ".", level = 0 }) {
const files = fs.readdirSync(directory);

for (const file of files) {
const fullPath = path.join(directory, file);
const stat = fs.statSync(fullPath);

if (stat.isDirectory()) {
toc += `${" ".repeat(level * 2)}* **${file}**\n`;
readDirectory({
directory: fullPath,
currentDir: currentDir + "/" + file,
level: level + 1,
});
} else if (
extensions.length === 0 ||
extensions.includes(path.extname(file))
) {
const filePath = currentDir + "/" + file;
toc += `${" ".repeat(level * 2)}* [${getFileTitle(
fullPath
)}](${filePath})\n`;
}
}
}

readDirectory({ directory: dirPath });
return toc;
} catch (error) {
throw error;
}
}

function updateTOC({ filePath = __dirname + "/README.md", contentToAdd }) {
try {
let fileContent = fs.existsSync(filePath)
? fs.readFileSync(filePath, "utf8")
: "";

const tocStart = "<!---TOC-START--->";
const tocEnd = "<!---TOC-END--->";

const tocStartIndex = fileContent.indexOf(tocStart);
const tocEndIndex = fileContent.indexOf(tocEnd);

if (tocStartIndex !== -1 && tocEndIndex !== -1) {
fileContent =
fileContent.substring(0, tocStartIndex + tocStart.length) +
`\n${contentToAdd}\n` +
fileContent.substring(tocEndIndex);
} else {
const tocSection = `${tocStart}\n${contentToAdd}\n${tocEnd}`;
fileContent = `${fileContent}\n\n${tocSection}`.trim();
}

fs.writeFileSync(filePath, fileContent, "utf8");
} catch (err) {
console.error("Error updating the TOC:", err.message);
}
}

function generateTableOfContent({
dirPath = process.cwd(),
extensions = [".md"],
filePath = __dirname + "/README.md",
}) {
updateTOC({
filePath,
contentToAdd: getTableOfContents({ dirPath, extensions }),
});
}

module.exports = {
getFileTitle,
getTableOfContents,
generateTableOfContent,
};
2 changes: 1 addition & 1 deletion tests/generateTableOfContents.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const fs = require("fs");
const { generateTableOfContent } = require("..");
const { generateTableOfContent } = require("../lib");

describe("generateTableOfContents", () => {
test("should generate TOC on marker less markdown file", () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/getFileTitle.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { getFileTitle } = require("..");
const { getFileTitle } = require("../lib");

describe("getFileTitle", () => {
test("should return markdown file title", () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/getTableOfContents.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { getTableOfContents } = require("..");
const { getTableOfContents } = require("../lib");

describe("getFilesByExtension", () => {
test("should return files with specified extensions", () => {
Expand Down

0 comments on commit 3edf9f0

Please sign in to comment.