add support for recursive selection and deselection of files in the tree view

This commit is contained in:
2025-03-12 07:25:26 +00:00
parent 65bf168e1f
commit 2d28f71e9b
5 changed files with 473 additions and 39 deletions

251
src/test/fileTreeTest.ts Normal file
View File

@@ -0,0 +1,251 @@
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
// Using require for the ignore package due to its module export style
const ignoreLib = require('ignore');
// A simplified version of our tree structure for testing
interface TreeNode {
name: string;
isDirectory: boolean;
children: Map<string, TreeNode>;
}
// Test implementation of the file tree generation logic
function generateFileTree(files: string[], rootPath: string): string {
// Create a tree representation
const treeLines: string[] = [];
// Create root node
const root: TreeNode = {
name: path.basename(rootPath),
isDirectory: true,
children: new Map<string, TreeNode>()
};
// Initialize the ignore instance
const ig = ignoreLib();
// Read .gitignore patterns if available
try {
const gitignorePath = path.join(rootPath, '.gitignore');
if (fs.existsSync(gitignorePath)) {
const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');
console.log('Using .gitignore content:');
console.log(gitignoreContent);
// Add patterns from .gitignore
ig.add(gitignoreContent);
// Always include .gitignore itself
ig.add('!.gitignore');
// Debug what's being ignored
console.log('\nIgnore patterns loaded. Testing patterns:');
['file1.txt', 'file2.log', 'node_modules/package.json', 'src/index.ts', 'temp/temp.txt'].forEach(testPath => {
console.log(`${testPath}: ${ig.ignores(testPath) ? 'IGNORED' : 'included'}`);
});
console.log();
}
} catch (error) {
console.error('Error reading .gitignore:', error);
}
// Build the tree structure
for (const filePath of files) {
const relativePath = getRelativePath(filePath, rootPath);
// Skip ignored files using the ignore package
// Use forward slashes for paths to ensure consistent matching
const normalizedPath = relativePath.split(path.sep).join('/');
if (ig.ignores(normalizedPath)) {
console.log(`Ignoring: ${normalizedPath}`);
continue;
}
// Split the path into parts
const parts = relativePath.split('/');
// Start from the root
let currentNode = root;
// Build the path in the tree
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (!part) { continue; } // Skip empty parts
const isDirectory = i < parts.length - 1;
if (!currentNode.children.has(part)) {
currentNode.children.set(part, {
name: part,
isDirectory,
children: new Map<string, TreeNode>()
});
} else if (isDirectory) {
// Ensure it's marked as a directory if we encounter it again
currentNode.children.get(part)!.isDirectory = true;
}
currentNode = currentNode.children.get(part)!;
}
}
// Function to recursively build the tree lines
const buildTreeLines = (node: TreeNode, prefix: string = '', isLast: boolean = true, parentPrefix: string = ''): void => {
// Skip the root node in the output
if (node !== root) {
const linePrefix = parentPrefix + (isLast ? '└── ' : '├── ');
treeLines.push(`${linePrefix}${node.name}${node.isDirectory ? '' : ''}`);
}
// Sort children: directories first, then files, both alphabetically
const sortedChildren = Array.from(node.children.values())
.sort((a, b) => {
if (a.isDirectory === b.isDirectory) {
return a.name.localeCompare(b.name);
}
return a.isDirectory ? -1 : 1;
});
// Process children
sortedChildren.forEach((child, index) => {
const isChildLast = index === sortedChildren.length - 1;
const childParentPrefix = node === root ? '' : parentPrefix + (isLast ? ' ' : '│ ');
buildTreeLines(child, prefix, isChildLast, childParentPrefix);
});
};
// Build the tree lines
buildTreeLines(root);
return treeLines.join('\n');
}
// Helper function to get relative path
function getRelativePath(filePath: string, rootPath: string): string {
if (filePath.startsWith(rootPath)) {
const relativePath = filePath.substring(rootPath.length);
return relativePath.startsWith('/') ? relativePath.substring(1) : relativePath;
}
return filePath;
}
// Run tests
function runTests() {
console.log('Running file tree generation tests...');
// Create a temporary directory for our tests
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'prompter-test-'));
console.log(`Created temp directory: ${tempDir}`);
try {
// Test 1: Basic file structure
console.log('\nTest 1: Basic file structure');
const files = [
path.join(tempDir, 'file1.txt'),
path.join(tempDir, 'folder1/file2.txt'),
path.join(tempDir, 'folder1/subfolder/file3.txt'),
path.join(tempDir, 'folder2/file4.txt')
];
// Create the directories and files
files.forEach(file => {
const dir = path.dirname(file);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(file, 'test content');
});
const result1 = generateFileTree(files, tempDir);
console.log(result1);
// Test 2: With .gitignore
console.log('\nTest 2: With .gitignore');
// Create a .gitignore file with more explicit patterns
const gitignorePath = path.join(tempDir, '.gitignore');
fs.writeFileSync(gitignorePath, '# Ignore log files\n*.log\n\n# Ignore node_modules directory\nnode_modules/\n\n# Ignore temp directory\ntemp/\n');
console.log('Created .gitignore with content:');
console.log(fs.readFileSync(gitignorePath, 'utf8'));
// Create test files for .gitignore testing
const files2 = [
path.join(tempDir, '.gitignore'),
path.join(tempDir, 'file1.txt'),
path.join(tempDir, 'file2.log'), // Should be ignored
path.join(tempDir, 'node_modules/package.json'), // Should be ignored
path.join(tempDir, 'src/index.ts'),
path.join(tempDir, 'temp/temp.txt') // Should be ignored
];
console.log('Test files created:');
files2.forEach(f => console.log(` - ${getRelativePath(f, tempDir)}`));
// Create the directories and files
files2.forEach(file => {
const dir = path.dirname(file);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Don't overwrite the .gitignore file
if (path.basename(file) !== '.gitignore') {
fs.writeFileSync(file, 'test content');
}
});
const result2 = generateFileTree(files2, tempDir);
console.log(result2);
// Test 3: Empty directories
console.log('\nTest 3: Empty directories');
const emptyDir = path.join(tempDir, 'emptyDir');
if (!fs.existsSync(emptyDir)) {
fs.mkdirSync(emptyDir, { recursive: true });
}
const files3 = [
path.join(tempDir, 'file1.txt'),
path.join(tempDir, 'emptyDir') // Empty directory
];
const result3 = generateFileTree(files3, tempDir);
console.log(result3);
// Test 4: Sorting
console.log('\nTest 4: Sorting (directories first, then files)');
const files4 = [
path.join(tempDir, 'z_file.txt'),
path.join(tempDir, 'a_file.txt'),
path.join(tempDir, 'z_folder/file.txt'),
path.join(tempDir, 'a_folder/file.txt')
];
// Create the directories and files
files4.forEach(file => {
const dir = path.dirname(file);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(file, 'test content');
});
const result4 = generateFileTree(files4, tempDir);
console.log(result4);
} catch (error) {
console.error('Test error:', error);
} finally {
// Clean up
console.log('\nCleaning up...');
try {
fs.rmSync(tempDir, { recursive: true, force: true });
console.log(`Removed temp directory: ${tempDir}`);
} catch (cleanupError) {
console.error('Error during cleanup:', cleanupError);
}
}
}
// Run the tests
runTests();