Spaces:
Running
Running
File size: 4,016 Bytes
ef747c9 | 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 | /**
* @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<Object>} 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<number>} 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) };
};
|