Created
June 15, 2023 00:43
-
-
Save cfigueiroa/957e5a6e14a6201be69f2d977e06e42c to your computer and use it in GitHub Desktop.
tree.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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