modify this extension by showing a popup with the list of files to be included in the codebase.md, each entry having a checkbox (all checked by default), so that the user an select which of the files to actually include.
extension.js
package.json
extension.js
js
Assistant
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.listCodeBaseFiles', function () {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders) {
vscode.window.showErrorMessage('No workspace folder open');
return;
}
const rootPath = workspaceFolders[0].uri.fsPath;
// const jsFiles = findJsFiles(rootPath);
try {
const { totalFiles, outputFileSizeInKB } = generateCodebaseMarkdown(rootPath);
if (totalFiles === 0) {
vscode.window.showInformationMessage('No matching files found in the workspace');
}
else {
vscode.window.showInformationMessage(`${totalFiles} files have been written to codebase.md (${outputFileSizeInKB.toFixed(2)} kb)`);
}
}
catch (error) {
vscode.window.showErrorMessage(`Error: ${error.message}`);
}
});
context.subscriptions.push(disposable);
}
function generateCodebaseMarkdown(rootPath) {
let listOfFiles = [];
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 allowedExtensions = ['.json', '.html', '.js', '.scss', '.css', '.ejs'];
const excludedFolders = [
'node_modules',
'.git',
'.vscode',
'bin',
'DB',
'img',
'font-awesome-4.7.0',
'convas-to-blob',
'javascript-load-image',
'flatpickr',
'summernote',
'qrcode-svg',
'sifter',
'tmpl',
'toastr'
];
const excludedFiles = ['code2prompt.js', '.gitignore', 'package-lock.json', 'nodemon.json'];
const excludedExtensions = ['.min.css', '.min.js'];
const MAX_FILE_SIZE = 200000; // bytes */
const outputFile = path.join(rootPath, 'codebase.md');
// Read .gitignore file and create ignore instance
const ig = ignore();
if (fs.existsSync(path.join(rootPath, '.gitignore'))) {
ig.add(fs.readFileSync(path.join(rootPath, '.gitignore')).toString());
}
let totalFiles = 0;
function traverseDirectory(dir, content = '') {
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, '/');
// Check if the file is ignored by .gitignore
if (ig.ignores(relativePath)) {
continue;
}
// Check if the current directory is in excludedFolders
if (stats.isDirectory() && excludedFolders.includes(item)) {
continue;
}
if (stats.isFile()) {
if (!excludedFiles.includes(item)) {
files.push(item);
}
} else if (stats.isDirectory()) {
directories.push(item);
}
}
// Sort files and directories alphabetically
files.sort((a, b) => a.localeCompare(b));
directories.sort((a, b) => a.localeCompare(b));
// Process files first
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;
// Check if the file is a .css file and if a .js file with the same name exists
if (ext === '.css') {
const jsFilePath = path.join(dir, `${path.basename(file, '.css')}.scss`);
if (fs.existsSync(jsFilePath)) {
continue; // Skip this .css file
}
}
if (allowedExtensions.includes(ext) &&
!excludedExtensions.some(excluded => file.endsWith(excluded)) &&
fileSizeInBytes <= MAX_FILE_SIZE) {
const relativePath = path.relative(rootPath, filePath).replace(/\\/g, '/');
const fileContent = fs.readFileSync(filePath, 'utf-8');
const extension = ext.slice(1);
content += `\n- ${relativePath}\n\`\`\`${extension}\n${fileContent}\n\`\`\`\n`;
listOfFiles.push(relativePath);
totalFiles++;
}
}
// Then process directories
for (const directory of directories) {
const dirPath = path.join(dir, directory);
content = traverseDirectory(dirPath, content);
}
return content;
}
let markdownContent = traverseDirectory(rootPath);
markdownContent = listOfFiles.join('\n') + '\n' + markdownContent;
if (markdownContent.length === 0) {
return { totalFiles: 0, outputFileSizeInKB: 0 };
}
fs.writeFileSync(outputFile, markdownContent);
let outputFileSizeInKB = fs.statSync(outputFile).size / 1024;
return { totalFiles, outputFileSizeInKB };
}
function deactivate() { }
module.exports = {
activate,
deactivate
}
package.json
json
{
"name": "andyp-code2prompt",
"displayName": "andyp-code2prompt",
"description": "Gather code files to codebase.md for LLM prompting",
"version": "0.0.5",
"engines": {
"vscode": "^1.60.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.code2prompt.listCodeBaseFiles"
],
"main": "./extension.js",
"contributes": {
"commands": [
{
"command": "extension.code2prompt.listCodeBaseFiles",
"title": "andyp-code2prompt: Create codebase.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"
],
"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"
}
}
To modify your extension to display a popup with a list of files, each with a checkbox, allowing users to select which files to include in codebase.md, you can utilize the vscode.window.showQuickPick method with canPickMany set to true. Below is the modified code that implements this functionality.
Updated extension.js
javascript
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.listCodeBaseFiles', 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, outputFileSizeInKB } = generateCodebaseMarkdown(rootPath, selectedFiles);
vscode.window.showInformationMessage(`${totalFiles} files have been written to codebase.md (${outputFileSizeInKB.toFixed(2)} kb)`);
});
}
}
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)) {
continue;
}
if (stats.isFile()) {
if (!excludedFiles.includes(item)) {
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 jsFilePath = path.join(dir, `${path.basename(file, '.css')}.scss`);
if (fs.existsSync(jsFilePath)) {
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 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++;
} catch (error) {
vscode.window.showErrorMessage(`Error reading file ${relativePath}: ${error.message}`);
}
}
if (markdownContent.length === 0) {
return { totalFiles: 0, outputFileSizeInKB: 0 };
}
const outputFile = path.join(rootPath, 'codebase.md');
fs.writeFileSync(outputFile, markdownContent);
let outputFileSizeInKB = fs.statSync(outputFile).size / 1024;
return { totalFiles, outputFileSizeInKB };
}
function deactivate() { }
module.exports = {
activate,
deactivate
}
Explanation:
Collecting Files:
The collectFiles function traverses the workspace and collects all files that meet your specified criteria (allowed extensions, excluded folders/files, etc.).
Each file is added to listOfFiles as an object with label, picked, and description. Setting picked: true ensures all checkboxes are checked by default.
Displaying QuickPick:
In the command handler, vscode.window.showQuickPick is called with listOfFiles and canPickMany: true.
This displays a popup with checkboxes for each file, allowing the user to select which files to include.
The selectedItems returned from the QuickPick are the files the user chose to include.
Generating Markdown:
The generateCodebaseMarkdown function now takes selectedFiles as an argument.
It reads the contents of each selected file and appends it to markdownContent in the desired markdown format.
Finally, it writes markdownContent to codebase.md in the workspace root.
Notes:
File Selection Order:
The files are displayed in the QuickPick in the order they're collected, sorted alphabetically.
Users can select or deselect files as needed.
Error Handling:
If an error occurs while reading a file, an error message is displayed, and the process continues with the next file.
Performance Considerations:
For larger projects, displaying a very long list of files might be less user-friendly.
Consider adding pagination or filtering if performance becomes an issue.
Dependencies:
Ensure all necessary modules (vscode, fs, path, ignore) are properly required.
This modification provides a user-friendly way for users to select which files to include in codebase.md, fulfilling the requested functionality.