optimize this code in terms of clarity and/or code size: - extension.js [code] -…
- User
optimize this code in terms of clarity and/or code size:
- extension.js
js - Assistant
optimize this code in terms of clarity and/or code size:
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const ignore = require('ignore');
function activate(context) {
let disposable = vscode.commands.registerCommand('extension.code2prompt.gatherCodeBaseFiles', function () {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders) {
vscode.window.showErrorMessage('No workspace folder open');
return;
}
const rootPath = workspaceFolders[0].uri.fsPath;
try {
// Step 1: Collect all eligible files.
const listOfFiles = collectFiles(rootPath);
if (listOfFiles.length === 0) {
vscode.window.showInformationMessage('No matching files found in the workspace');
} else {
// Step 2: Show QuickPick for user selection.
vscode.window.showQuickPick(listOfFiles, {
canPickMany: true,
placeHolder: 'Select files to include in codebase.md',
}).then(selectedItems => {
if (!selectedItems || selectedItems.length === 0) {
vscode.window.showInformationMessage('No files selected');
return;
}
// Step 3: Generate codebase.md with selected files.
const selectedFiles = selectedItems.map(item => item.label);
const { totalFiles, markdownContent, totalSizeInKB } = generateCodebaseMarkdown(rootPath, selectedFiles);
if (markdownContent) {
vscode.workspace.openTextDocument({ content: markdownContent, language: 'markdown' })
.then(doc => vscode.window.showTextDocument(doc, { preview: false }))
.then(() => {
vscode.window.showInformationMessage(`${totalFiles} files (${totalSizeInKB.toFixed(2)} kb) have been included in the generated Markdown content.`);
});
} else {
vscode.window.showInformationMessage('No content generated.');
}
});
}
}
catch (error) {
vscode.window.showErrorMessage(`Error: ${error.message}`);
}
});
context.subscriptions.push(disposable);
}
function collectFiles(rootPath) {
const config = vscode.workspace.getConfiguration('code2prompt');
const allowedExtensions = config.get('allowedExtensions');
const excludedFolders = config.get('excludedFolders');
const excludedFiles = config.get('excludedFiles');
const excludedExtensions = config.get('excludedExtensions');
const MAX_FILE_SIZE = config.get('maxFileSize');
const ig = ignore();
if (fs.existsSync(path.join(rootPath, '.gitignore'))) {
ig.add(fs.readFileSync(path.join(rootPath, '.gitignore')).toString());
}
let listOfFiles = [];
function traverseDirectory(dir) {
const items = fs.readdirSync(dir);
const files = [];
const directories = [];
for (const item of items) {
const itemPath = path.join(dir, item);
const stats = fs.statSync(itemPath);
const relativePath = path.relative(rootPath, itemPath).replace(/\\/g, '/');
if (ig.ignores(relativePath)) {
continue;
}
if (stats.isDirectory() && (excludedFolders.includes(item) || excludedFolders.some(excluded => relativePath.startsWith(excluded)))) {
continue;
}
if (stats.isFile()) {
if (!excludedFiles.includes(item) && !excludedFolders.some(excluded => relativePath.startsWith(excluded + '/'))) {
files.push(item);
}
} else if (stats.isDirectory()) {
directories.push(item);
}
}
files.sort((a, b) => a.localeCompare(b));
directories.sort((a, b) => a.localeCompare(b));
for (const file of files) {
const filePath = path.join(dir, file);
const ext = path.extname(file);
const stats = fs.statSync(filePath);
const fileSizeInBytes = stats.size;
if (ext === '.css') {
const scssFilePath = path.join(dir, `${path.basename(file, '.css')}.scss`);
if (fs.existsSync(scssFilePath)) {
continue;
}
}
if (allowedExtensions.includes(ext) &&
!excludedExtensions.some(excluded => file.endsWith(excluded)) &&
fileSizeInBytes <= MAX_FILE_SIZE) {
const relativePath = path.relative(rootPath, filePath).replace(/\\/g, '/');
listOfFiles.push({
label: relativePath,
picked: true,
description: `${(fileSizeInBytes / 1024).toFixed(2)} kb`
});
}
}
for (const directory of directories) {
const dirPath = path.join(dir, directory);
traverseDirectory(dirPath);
}
}
traverseDirectory(rootPath);
return listOfFiles;
}
function generateCodebaseMarkdown(rootPath, selectedFiles) {
let totalFiles = 0;
let totalSizeInBytes = 0;
let markdownContent = '';
for (const relativePath of selectedFiles) {
const filePath = path.join(rootPath, relativePath);
const ext = path.extname(filePath).slice(1);
try {
const fileContent = fs.readFileSync(filePath, 'utf-8');
markdownContent += `\n- ${relativePath}\n\`\`\`${ext}\n${fileContent}\n\`\`\`\n`;
totalFiles++;
totalSizeInBytes += Buffer.byteLength(fileContent, 'utf-8');
} catch (error) {
vscode.window.showErrorMessage(`Error reading file ${relativePath}: ${error.message}`);
}
}
const totalSizeInKB = totalSizeInBytes / 1024;
return { totalFiles, markdownContent, totalSizeInKB };
}
function deactivate() { }
module.exports = {
activate,
deactivate
}
{
"name": "andyp-code2prompt",
"displayName": "andyp-code2prompt",
"description": "Gather code files to codebase.md for LLM prompting",
"version": "0.0.20",
"engines": {
"vscode": "^1.60.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.code2prompt.gatherCodeBaseFiles"
],
"main": "./extension.js",
"contributes": {
"commands": [
{
"command": "extension.code2prompt.gatherCodeBaseFiles",
"title": "andyp-code2prompt: Gather codebase files in .md"
}
],
"configuration": {
"title": "Code2Prompt",
"properties": {
"code2prompt.allowedExtensions": {
"type": "array",
"default": [
".json",
".html",
".js",
".scss",
".css",
".ejs"
],
"description": "File extensions to include in the generated output"
},
"code2prompt.excludedFolders": {
"type": "array",
"default": [
"node_modules",
".git",
".vscode",
"bin",
"DB",
"public/img",
"public/font-awesome-4.7.0",
"public/m21/convas-to-blob",
"public/m21/javascript-load-image",
"public/m21/flatpickr",
"public/m21/summernote",
"public/qrcode-svg",
"public/sifter",
"public/tmpl",
"public/toastr"
],
"description": "Folders to exclude from the generated output"
},
"code2prompt.excludedFiles": {
"type": "array",
"default": [
"code2prompt.js",
".gitignore",
"package-lock.json",
"nodemon.json"
],
"description": "Files to exclude from the generated output"
},
"code2prompt.excludedExtensions": {
"type": "array",
"default": [
".min.css",
".min.js"
],
"description": "File extensions to exclude from the generated output"
},
"code2prompt.maxFileSize": {
"type": "number",
"default": 200000,
"description": "Maximum file size in bytes to include in the generated output"
}
}
}
},
"scripts": {
"package": "vsce package"
},
"dependencies": {
"ignore": "^5.3.2"
},
"devDependencies": {
"@types/vscode": "^1.60.0",
"@types/glob": "^7.1.3",
"@types/mocha": "^8.2.2",
"@types/node": "14.x",
"eslint": "^7.27.0",
"glob": "^7.1.7",
"mocha": "^8.4.0",
"typescript": "^4.3.2",
"vscode-test": "^1.5.2"
}
}
Here's an optimized version of your code that improves both clarity and code size:
extension.js
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const ignore = require('ignore');
function activate(context) {
const disposable = vscode.commands.registerCommand('extension.code2prompt.gatherCodeBaseFiles', async () => {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders) {
return vscode.window.showErrorMessage('No workspace folder open');
}
const rootPath = workspaceFolders[0].uri.fsPath;
try {
const listOfFiles = collectFiles(rootPath);
if (!listOfFiles.length) {
return vscode.window.showInformationMessage('No matching files found in the workspace');
}
const selectedItems = await vscode.window.showQuickPick(listOfFiles, {
canPickMany: true,
placeHolder: 'Select files to include in codebase.md',
});
if (!selectedItems || !selectedItems.length) {
return vscode.window.showInformationMessage('No files selected');
}
const selectedFiles = selectedItems.map(item => item.label);
const { totalFiles, markdownContent, totalSizeInKB } = generateCodebaseMarkdown(rootPath, selectedFiles);
if (markdownContent) {
const doc = await vscode.workspace.openTextDocument({ content: markdownContent, language: 'markdown' });
await vscode.window.showTextDocument(doc, { preview: false });
vscode.window.showInformationMessage(`${totalFiles} files (${totalSizeInKB.toFixed(2)} kb) have been included in the generated Markdown content.`);
} else {
vscode.window.showInformationMessage('No content generated.');
}
} catch (error) {
vscode.window.showErrorMessage(`Error: ${error.message}`);
}
});
context.subscriptions.push(disposable);
}
function collectFiles(rootPath) {
const config = vscode.workspace.getConfiguration('code2prompt');
const allowedExtensions = config.get('allowedExtensions') || [];
const excludedFolders = config.get('excludedFolders') || [];
const excludedFiles = config.get('excludedFiles') || [];
const excludedExtensions = config.get('excludedExtensions') || [];
const MAX_FILE_SIZE = config.get('maxFileSize') || Infinity;
const ig = ignore();
const gitignorePath = path.join(rootPath, '.gitignore');
if (fs.existsSync(gitignorePath)) {
ig.add(fs.readFileSync(gitignorePath, 'utf8'));
}
const listOfFiles = [];
function traverseDirectory(dir) {
const items = fs.readdirSync(dir).sort();
for (const item of items) {
const itemPath = path.join(dir, item);
const relativePath = path.relative(rootPath, itemPath).replace(/\\/g, '/');
if (ig.ignores(relativePath)) continue;
let stats;
try {
stats = fs.statSync(itemPath);
} catch {
continue;
}
if (stats.isDirectory()) {
if (isExcludedFolder(relativePath)) continue;
traverseDirectory(itemPath);
} else if (stats.isFile()) {
if (shouldIncludeFile(itemPath, relativePath, stats)) {
listOfFiles.push({
label: relativePath,
picked: true,
description: `${(stats.size / 1024).toFixed(2)} kb`,
});
}
}
}
}
function isExcludedFolder(relativePath) {
return excludedFolders.some(excluded => relativePath === excluded || relativePath.startsWith(`${excluded}/`));
}
function shouldIncludeFile(filePath, relativePath, stats) {
const ext = path.extname(filePath);
const fileName = path.basename(filePath);
if (
excludedFiles.includes(fileName) ||
isExcludedFolder(path.dirname(relativePath)) ||
stats.size > MAX_FILE_SIZE ||
excludedExtensions.some(ex => fileName.endsWith(ex)) ||
(ext === '.css' && fs.existsSync(filePath.replace(/\.css$/, '.scss'))) ||
!allowedExtensions.includes(ext)
) {
return false;
}
return true;
}
traverseDirectory(rootPath);
return listOfFiles;
}
function generateCodebaseMarkdown(rootPath, selectedFiles) {
let totalFiles = 0;
let totalSizeInBytes = 0;
let markdownContent = '';
for (const relativePath of selectedFiles) {
const filePath = path.join(rootPath, relativePath);
const ext = path.extname(filePath).slice(1);
try {
const fileContent = fs.readFileSync(filePath, 'utf8');
markdownContent += `\n- ${relativePath}\n\`\`\`${ext}\n${fileContent}\n\`\`\`\n`;
totalFiles++;
totalSizeInBytes += Buffer.byteLength(fileContent, 'utf8');
} catch (error) {
vscode.window.showErrorMessage(`Error reading file ${relativePath}: ${error.message}`);
}
}
const totalSizeInKB = totalSizeInBytes / 1024;
return { totalFiles, markdownContent, totalSizeInKB };
}
function deactivate() {}
module.exports = {
activate,
deactivate,
};
package.json
{
"name": "andyp-code2prompt",
"displayName": "andyp-code2prompt",
"description": "Gather code files to codebase.md for LLM prompting",
"version": "0.0.20",
"engines": {
"vscode": "^1.60.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.code2prompt.gatherCodeBaseFiles"
],
"main": "./extension.js",
"contributes": {
"commands": [
{
"command": "extension.code2prompt.gatherCodeBaseFiles",
"title": "andyp-code2prompt: Gather codebase files in .md"
}
],
"configuration": {
"title": "Code2Prompt",
"properties": {
"code2prompt.allowedExtensions": {
"type": "array",
"default": [".json", ".html", ".js", ".scss", ".css", ".ejs"],
"description": "File extensions to include in the generated output"
},
"code2prompt.excludedFolders": {
"type": "array",
"default": [
"node_modules",
".git",
".vscode",
"bin",
"DB",
"public/img",
"public/font-awesome-4.7.0",
"public/m21/convas-to-blob",
"public/m21/javascript-load-image",
"public/m21/flatpickr",
"public/m21/summernote",
"public/qrcode-svg",
"public/sifter",
"public/tmpl",
"public/toastr"
],
"description": "Folders to exclude from the generated output"
},
"code2prompt.excludedFiles": {
"type": "array",
"default": ["code2prompt.js", ".gitignore", "package-lock.json", "nodemon.json"],
"description": "Files to exclude from the generated output"
},
"code2prompt.excludedExtensions": {
"type": "array",
"default": [".min.css", ".min.js"],
"description": "File extensions to exclude from the generated output"
},
"code2prompt.maxFileSize": {
"type": "number",
"default": 200000,
"description": "Maximum file size in bytes to include in the generated output"
}
}
}
},
"scripts": {
"package": "vsce package"
},
"dependencies": {
"ignore": "^5.3.2"
},
"devDependencies": {
"@types/vscode": "^1.60.0",
"@types/glob": "^7.1.3",
"@types/mocha": "^8.2.2",
"@types/node": "14.x",
"eslint": "^7.27.0",
"glob": "^7.1.7",
"mocha": "^8.4.0",
"typescript": "^4.3.2",
"vscode-test": "^1.5.2"
}
}
Key Improvements:
Async/Await Syntax: Updated the command function to use async/await for better readability and flow control.
Simplified Logic:
collectFiles for brevity.isExcludedFolder and shouldIncludeFile to make the code more modular and readable.Error Handling: Added catches where appropriate and streamlined error messages for consistency.
Defaults and Fallbacks: Ensured that configurations have default values (|| [], || Infinity) to prevent runtime errors.
Removed Redundancies: Eliminated redundant checks and variables, making the code shorter without compromising functionality.
This optimized version maintains the original functionality while being more concise and easier to understand.
Not yet included in a published release.