docswriter
Version:
Automated documentation generator using AI and Gemini API
90 lines (75 loc) • 2.33 kB
JavaScript
/**
* Formats the generated documentation using a template
* @param {string} content - Raw generated documentation content
* @param {Object} analysis - Project analysis data
* @returns {string} Formatted documentation
*/
function formatDocumentation(content, analysis) {
// Add header with generation info
const header = `
<!--
Generated by DocsWriter
Date: ${new Date().toLocaleString()}
Project: ${analysis.projectName}
-->
`;
// Add table of contents if not already present
if (!content.includes("## Table of Contents")) {
const toc = generateTableOfContents(content);
// Find the first heading and insert ToC after it
const firstHeadingMatch = content.match(/^# .+$/m);
if (firstHeadingMatch) {
const firstHeadingIndex =
content.indexOf(firstHeadingMatch[0]) + firstHeadingMatch[0].length;
content =
content.substring(0, firstHeadingIndex) +
"\n\n" +
toc +
content.substring(firstHeadingIndex);
} else {
content = toc + content;
}
}
// Add footer
const footer = `
---
* Documentation generated by https://github.com/Ashish-suman-sharma *
`;
return header + content + footer;
}
/**
* Generates a table of contents from markdown content
* @param {string} content - Markdown content
* @returns {string} Table of contents in markdown format
*/
function generateTableOfContents(content) {
const headings = [];
const lines = content.split("\n");
// Extract all headings
for (const line of lines) {
const match = line.match(/^(#{2,4}) (.+)$/);
if (match) {
const level = match[1].length - 1; // Subtract 1 to convert ## (h2) to level 1
const text = match[2].trim();
const anchor = text
.toLowerCase()
.replace(/[^\w\s-]/g, "")
.replace(/\s+/g, "-");
headings.push({ level, text, anchor });
}
}
if (headings.length === 0) {
return "";
}
// Generate ToC
let toc = "## Table of Contents\n\n";
for (const heading of headings) {
const indent = " ".repeat(heading.level - 1);
toc += `${indent}- [${heading.text}](#${heading.anchor})\n`;
}
return toc + "\n";
}
module.exports = {
formatDocumentation,
generateTableOfContents,
};