Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Table of content generation functionalities #1

Merged
merged 4 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/workflows/unit-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: CI

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: "18"

- name: Install dependencies
run: npm install

- name: Run tests
run: npm test
71 changes: 2 additions & 69 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,70 +1,3 @@
const fs = require("fs");
const path = require("path");
const { generateTableOfContent } = require("./lib");

function getDefaultFileTitle(fileName) {
const ext = path.extname(fileName);
return fileName.split(ext)[0];
}

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

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

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

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

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

let fileList = [];

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

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

if (stat.isDirectory()) {
readDirectory({
directory: fullPath,
currentDir: currentDir + "/" + file,
});
} else if (
extensions.length === 0 ||
extensions.includes(path.extname(file))
) {
fileList.push(currentDir + "/" + file);
}
}
}

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

module.exports = {
getFileNames,
getFileTitle,
};
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,
};
49 changes: 49 additions & 0 deletions tests/generateTableOfContents.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const fs = require("fs");
const { generateTableOfContent } = require("../lib");

describe("generateTableOfContents", () => {
test("should generate TOC on marker less markdown file", () => {
const dirPath = __dirname + "/mocks";
const fileName = "markdownWithoutMarker.md";
const filePath = __dirname + "/" + fileName;

fs.writeFileSync(filePath, "## Table of contents");
generateTableOfContent({ dirPath, filePath });

const fileContent = fs.readFileSync(filePath, "utf8");

expect(fileContent).toContain(
`* [TestFile3](./TestFile3.md)\n* **test-files**\n * [Test File 1 Title](./test-files/TestFile1.md)\n`
);

fs.unlink(filePath, (err) => {
if (err) {
throw err;
}
});
});

test("should generate TOC on marker less markdown file", () => {
const dirPath = __dirname + "/mocks";
const fileName = "markdownWithMarker.md";
const filePath = __dirname + "/" + fileName;

fs.writeFileSync(
filePath,
"## Table of contents\n\n\n<!---TOC-START--->\n<!---TOC-END--->\n\n"
);
generateTableOfContent({ dirPath, filePath });

const fileContent = fs.readFileSync(filePath, "utf8");

expect(fileContent).toContain(
`* [TestFile3](./TestFile3.md)\n* **test-files**\n * [Test File 1 Title](./test-files/TestFile1.md)\n`
);

fs.unlink(filePath, (err) => {
if (err) {
throw err;
}
});
});
});
8 changes: 4 additions & 4 deletions tests/getFileTitle.spec.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
const { getFileTitle } = require("..");
const { getFileTitle } = require("../lib");

describe("getFileTitle", () => {
test("should return markdown file title", () => {
const fileName = "TestFile1.md";
const filePath = __dirname + `/mocks/test-files/${fileName}`;

const title = getFileTitle({ filePath, fileName });
const title = getFileTitle(filePath);
expect(title).toEqual("Test File 1 Title");
});

test("should return file title for markdown files without title", () => {
const fileName = "TestFile3.md";
const filePath = __dirname + `/mocks//${fileName}`;

const title = getFileTitle({ filePath, fileName });
const title = getFileTitle(filePath);
expect(title).toEqual("TestFile3");
});

test("should return file title for non markdown files", () => {
const fileName = "TextFile.txt";
const filePath = __dirname + `/mocks/test-files/${fileName}`;

const title = getFileTitle({ filePath, fileName });
const title = getFileTitle(filePath);
expect(title).toEqual("TextFile");
});
});
24 changes: 12 additions & 12 deletions tests/getFileNames.spec.js → tests/getTableOfContents.spec.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
const { getFileNames } = require("..");
const { getTableOfContents } = require("../lib");

describe("getFilesByExtension", () => {
test("should return files with specified extensions", () => {
const dirPath = __dirname + "/mocks";
const extensions = [".md"];

const result = getFileNames({ dirPath, extensions });
expect(result).toEqual(["./TestFile3.md", "./test-files/TestFile1.md"]);
const result = getTableOfContents({ dirPath, extensions });
expect(result).toEqual(
`* [TestFile3](./TestFile3.md)\n* **test-files**\n * [Test File 1 Title](./test-files/TestFile1.md)\n`
);
});

test("should return all files no extensions", () => {
const dirPath = __dirname + "/mocks";
const extensions = [];

const result = getFileNames({ dirPath, extensions });
const result = getTableOfContents({ dirPath, extensions });

expect(result).toEqual([
"./TestFile3.md",
"./test-files/TestFile1.md",
"./test-files/TextFile.txt",
]);
expect(result).toEqual(
`* [TestFile3](./TestFile3.md)\n* **test-files**\n * [Test File 1 Title](./test-files/TestFile1.md)\n * [TextFile](./test-files/TextFile.txt)\n`
);
});

test("should throw error for non-existent directory", () => {
const invalidPath = "/invalid/path";
const extensions = [".txt"];

expect(() =>
getFileNames({ dirPath: invalidPath, extensions })
getTableOfContents({ dirPath: invalidPath, extensions })
).toThrowError(/no such file or directory/);
});

Expand All @@ -36,15 +36,15 @@ describe("getFilesByExtension", () => {
const extensions = [5];

expect(() =>
getFileNames({ dirPath: invalidPath, extensions })
getTableOfContents({ dirPath: invalidPath, extensions })
).toThrowError(/Extensions must be an array of strings/);
});

test("should include files with multiple matching extensions", () => {
const dirPath = __dirname + "/mocks";
const extensions = [".md", ".txt"];

const result = getFileNames({ dirPath, extensions });
const result = getTableOfContents({ dirPath, extensions });
expect(result).toContain("./test-files/TextFile.txt");
expect(result).toContain("./TestFile3.md");
});
Expand Down
Loading