/** * @fileoverview File tree generation utility. * Recursively builds a JSON representation of a directory structure. * @module utils/fileTree */ import fs from 'fs-extra'; import path from 'path'; /** * Generates a file tree structure from a directory. * * @async * @param {string} dirPath - Absolute path to the directory * @param {string} [relativePath=''] - Relative path from root (used for recursion) * @returns {Promise} Tree structure object * * @example * // Returns: * // { * // name: "root", * // type: "folder", * // path: "/", * // children: [ * // { name: "file.txt", type: "file", size: 1024, path: "/file.txt", extension: ".txt" } * // ] * // } */ export const generateFileTree = async (dirPath, relativePath = '') => { const stats = await fs.stat(dirPath); const name = path.basename(dirPath) || 'root'; const currentPath = relativePath || '/'; if (stats.isFile()) { return { name, type: 'file', size: stats.size, path: currentPath, extension: path.extname(name).toLowerCase(), }; } // It's a directory const children = []; const entries = await fs.readdir(dirPath); // Sort entries: folders first, then files, alphabetically const sortedEntries = entries.sort((a, b) => { return a.toLowerCase().localeCompare(b.toLowerCase()); }); for (const entry of sortedEntries) { const entryPath = path.join(dirPath, entry); const entryRelativePath = path.posix.join(currentPath, entry); try { const entryStats = await fs.stat(entryPath); if (entryStats.isDirectory()) { // Recursively get directory contents const subtree = await generateFileTree(entryPath, entryRelativePath); children.push(subtree); } else if (entryStats.isFile()) { children.push({ name: entry, type: 'file', size: entryStats.size, path: entryRelativePath, extension: path.extname(entry).toLowerCase(), }); } } catch (error) { // Skip entries we can't read (permission issues, etc.) console.warn(`Could not read entry: ${entryPath}`, error.message); } } // Sort children: folders first, then files children.sort((a, b) => { if (a.type === 'folder' && b.type !== 'folder') return -1; if (a.type !== 'folder' && b.type === 'folder') return 1; return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); }); return { name: relativePath ? name : 'root', type: 'folder', path: currentPath, children, }; }; /** * Calculates total size of a directory recursively. * * @async * @param {string} dirPath - Path to the directory * @returns {Promise} Total size in bytes */ export const getDirectorySize = async (dirPath) => { let totalSize = 0; const calculateSize = async (currentPath) => { const stats = await fs.stat(currentPath); if (stats.isFile()) { totalSize += stats.size; } else if (stats.isDirectory()) { const entries = await fs.readdir(currentPath); for (const entry of entries) { await calculateSize(path.join(currentPath, entry)); } } }; await calculateSize(dirPath); return totalSize; }; /** * Counts files and folders in a directory. * * @async * @param {string} dirPath - Path to the directory * @returns {Promise<{files: number, folders: number}>} Count object */ export const countItems = async (dirPath) => { let files = 0; let folders = 0; const count = async (currentPath) => { const stats = await fs.stat(currentPath); if (stats.isFile()) { files++; } else if (stats.isDirectory()) { folders++; const entries = await fs.readdir(currentPath); for (const entry of entries) { await count(path.join(currentPath, entry)); } } }; await count(dirPath); // Subtract 1 from folders to not count the root return { files, folders: Math.max(0, folders - 1) }; };