Skip to content

Instantly share code, notes, and snippets.

@cfigueiroa
Created June 15, 2023 00:43
Show Gist options
  • Save cfigueiroa/957e5a6e14a6201be69f2d977e06e42c to your computer and use it in GitHub Desktop.
Save cfigueiroa/957e5a6e14a6201be69f2d977e06e42c to your computer and use it in GitHub Desktop.
tree.js
import fs from 'fs';
import path from 'path';
const outputFileName = 'directory_structure.md';
function parseGitIgnore(gitignorePath) {
const excludedItems = ['.git'];
const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');
const lines = gitignoreContent.split('\n');
lines.forEach((line) => {
line = line.trim();
if (line && !line.startsWith('#')) {
excludedItems.push(line);
}
});
return excludedItems;
}
function getDirectoryStructure(dir, excludedItems, level = 0, parentIsLast = []) {
let structure = '';
const files = fs.readdirSync(dir).filter((file) => !excludedItems.includes(file));
files.forEach((file, index) => {
const fullPath = path.join(dir, file);
const stats = fs.statSync(fullPath);
const isLastItem = index === files.length - 1;
const prefix = parentIsLast.map((isLast) => (isLast ? ' ' : '│ ')).join('');
const line = isLastItem ? '└── ' : '├── ';
if (stats.isDirectory()) {
structure += `${prefix}${line}${file}\n`;
structure += getDirectoryStructure(fullPath, excludedItems, level + 1, [...parentIsLast, isLastItem]);
} else {
structure += `${prefix}${line}${file}\n`;
}
});
return structure;
}
function writeDirectoryStructureToFile() {
const currentDir = process.cwd();
const gitignorePath = path.join(currentDir, '.gitignore');
const excludedItems = parseGitIgnore(gitignorePath);
const structure = getDirectoryStructure(currentDir, excludedItems);
fs.writeFileSync(outputFileName, "```\n" + structure + "```\n");
console.log(`Directory structure written to ${outputFileName}`);
}
writeDirectoryStructureToFile();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment