-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·306 lines (273 loc) · 9.48 KB
/
index.js
File metadata and controls
executable file
·306 lines (273 loc) · 9.48 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#!/usr/bin/env node
const { program } = require("commander");
const fs = require("fs");
const yaml = require("js-yaml");
const glob = require("glob");
const acorn = require("acorn");
const doctrine = require("doctrine");
const path = require("path");
const prompts = require("prompts");
const safeReadFile = (filePath, encoding) => {
try {
return fs.readFileSync(filePath, encoding);
} catch (err) {
console.error(`Error reading file ${filePath}: ${err.message}`);
return null;
}
};
const safeParseJson = (jsonString) => {
try {
return JSON.parse(jsonString);
} catch (err) {
console.error(`Error parsing JSON: ${err.message}`);
return null;
}
};
const safeGlobSync = (pattern, options) => {
try {
return glob.sync(pattern, options);
} catch (err) {
console.error(`Error in glob.sync with pattern ${pattern}: ${err.message}`);
return [];
}
};
program
.command("generate")
.description("Generate README documentation")
.action(() => {
console.log("Generating README...");
generateReadme();
});
program
.command("init")
.description("Initialize AutoDoc configuration file")
.action(async () => {
console.log(
"Initializing AutoDoc configuration and sample Markdown files...",
);
const questions = [
{
type: "text",
name: "projectName",
message: "Project name:",
initial: path.basename(process.cwd()),
},
{
type: "text",
name: "projectDescription",
message: "Project description:",
initial: "A project generated by AutoDoc",
},
{
type: "confirm",
name: "generateInstall",
message: "Generate INSTALL.md?",
initial: true,
},
{
type: "confirm",
name: "generateContributing",
message: "Generate CONTRIBUTING.md?",
initial: true,
},
{
type: "confirm",
name: "generateUsage",
message: "Generate USAGE.md?",
initial: true,
},
];
let answers;
try {
answers = await prompts(questions);
if (!answers) {
console.log("Prompt cancelled. Initialization aborted.");
return;
}
} catch (error) {
console.error("Error during prompts:", error);
return;
}
const defaultConfig = {
projectName: answers.projectName,
projectDescription: answers.projectDescription,
files: ["src/**/*.js"],
exclude: ["src/test/**/*.js"],
output: "README.md",
sections: [
{
title: "Installation",
files: answers.generateInstall ? ["./INSTALL.md"] : [],
},
{ title: "API Documentation", files: ["src/index.js", "src/utils.js"] },
{
title: "Contributing",
files: answers.generateContributing ? ["./CONTRIBUTING.md"] : [],
},
{ title: "Dependencies", files: ["./DEPENDENCIES.md"] }, // Include DEPENDENCIES.md
{ title: "Usage", files: answers.generateUsage ? ["./USAGE.md"] : [] },
].filter((section) => section.files.length > 0),
};
try {
const configPath = path.join(process.cwd(), "AutoDoc.yaml");
fs.writeFileSync(configPath, yaml.dump(defaultConfig));
console.log(`AutoDoc.yaml created successfully at ${configPath}`);
if (answers.generateInstall) {
const installPath = path.join(process.cwd(), "INSTALL.md");
fs.writeFileSync(
installPath,
generateInstallMarkdown(answers.projectName),
);
console.log(`INSTALL.md created successfully at ${installPath}`);
}
if (answers.generateContributing) {
const contributingPath = path.join(process.cwd(), "CONTRIBUTING.md");
fs.writeFileSync(
contributingPath,
generateContributingMarkdown(answers.projectName),
);
console.log(
`CONTRIBUTING.md created successfully at ${contributingPath}`,
);
}
if (answers.generateUsage) {
const usagePath = path.join(process.cwd(), "USAGE.md");
fs.writeFileSync(usagePath, generateUsageMarkdown(answers.projectName));
console.log(`USAGE.md created successfully at ${usagePath}`);
}
const dependenciesPath = path.join(process.cwd(), "DEPENDENCIES.md");
fs.writeFileSync(dependenciesPath, generateDependenciesMarkdown());
console.log(
`DEPENDENCIES.md created successfully at ${dependenciesPath}`,
);
console.log("Initialization completed.");
} catch (err) {
console.error("Error during initialization:", err);
}
});
function generateInstallMarkdown(projectName) {
return `To install ${projectName}, run:\n\n\`\`\`bash\nnpm install\n\`\`\`\n\nFor further installation instructions, please refer to the project's documentation.\n`;
}
function generateContributingMarkdown(projectName) {
return `We welcome contributions to ${projectName}! Please follow these guidelines:\n\n1. Fork the repository on GitHub.\n2. Create a new branch for your feature or bug fix: \`git checkout -b feature/your-feature-name\` or \`git checkout -b fix/your-fix-name\`.\n3. Make your changes and commit them: \`git commit -m 'Add some feature'\`.\n4. Push to the branch: \`git push origin feature/your-feature-name\`.\n5. Submit a pull request to the \`main\` branch of the original repository.\n\nFor more detailed contribution guidelines, please refer to the project's [CONTRIBUTING.md](CONTRIBUTING.md) file (if available) or the project's documentation.\n`;
}
function generateUsageMarkdown(projectName) {
return `Here's a basic example of how to use ${projectName}:\n\n\`\`\`javascript\n// Example usage for ${projectName}\n// ...\n\`\`\`\n\nFor detailed usage instructions, please refer to the project's [USAGE.md](USAGE.md) file (if available) or the project's documentation.\n\nIf you have any specific usage examples you'd like to add, please contribute them to the USAGE.md file.\n`;
}
function generateDependenciesMarkdown() {
const packageJsonContent = safeReadFile("./package.json", "utf8");
if (!packageJsonContent) {
return "# Dependencies\n\nCould not find package.json to list dependencies.";
}
const packageJson = safeParseJson(packageJsonContent);
if (!packageJson) {
return "# Dependencies\n\nError parsing package.json.";
}
let dependencyString = "";
if (packageJson.dependencies) {
for (const dependency in packageJson.dependencies) {
dependencyString += `- ${dependency}: ${packageJson.dependencies[dependency]}\n`;
}
}
if (packageJson.devDependencies) {
for (const dependency in packageJson.devDependencies) {
dependencyString += `- ${dependency}: ${packageJson.devDependencies[dependency]}\n`;
}
}
return dependencyString;
}
function generateReadme() {
try {
const configPath = path.join(process.cwd(), "AutoDoc.yaml");
const configContent = safeReadFile(configPath, "utf8");
if (!configContent) {
console.error(
`Error: Could not read configuration file at ${configPath}.`,
);
return;
}
const config = yaml.load(configContent);
console.log("Configuration loaded:", config);
let readme = "";
if (config.projectDescription) {
readme += `\n## ${config.projectName}\n\n`;
readme += `${config.projectDescription}\n\n`;
}
config.sections.forEach((section) => {
if (section.files && section.files.length > 0) {
readme += `\n## ${section.title}\n\n`;
section.files.forEach((filePattern) => {
const files = safeGlobSync(filePattern, { ignore: config.exclude });
files.forEach((file) => {
readme += readFileContent(file);
});
});
}
});
const outputPath = path.join(process.cwd(), config.output);
fs.writeFileSync(outputPath, readme);
console.log(`Readme written to ${outputPath}`);
} catch (err) {
console.error("Error generating README:", err);
}
}
function processFile(filePath) {
const fileContent = safeReadFile(filePath, "utf8");
if (!fileContent) {
return "";
}
try {
const ast = acorn.parse(fileContent, {
ecmaVersion: 2020,
sourceType: "module",
onComment: [],
ranges: true,
});
return extractDocumentation(ast, fileContent);
} catch (err) {
console.error(`Error processing file ${filePath}: ${err.message}`);
return "";
}
}
function extractDocumentation(ast, fileContent) {
let documentation = "";
if (!ast || !ast.body) {
return documentation;
}
ast.body.forEach((node) => {
if (node.leadingComments) {
node.leadingComments.forEach((comment) => {
if (comment.type === "Block" && comment.value.startsWith("*")) {
try {
const jsdoc = doctrine.parse(comment.value, { unwrap: true });
documentation += formatJSDoc(jsdoc);
} catch (err) {
console.error(`Error parsing JSDoc comment: ${err.message}`);
}
}
});
}
});
return documentation;
}
function formatJSDoc(jsdoc) {
let formatted = "";
if (jsdoc.description) {
formatted += jsdoc.description + "\n\n";
}
if (jsdoc.tags) {
jsdoc.tags.forEach((tag) => {
formatted += `**${tag.title}**: `;
if (tag.type) formatted += `{${tag.type.name}} `;
if (tag.name) formatted += tag.name + " ";
if (tag.description) formatted += tag.description;
formatted += "\n";
});
}
return formatted + "\n";
}
function readFileContent(filePath) {
const content = safeReadFile(filePath, "utf8");
return content || "";
}
program.parse(process.argv);