Skip to content

Instantly share code, notes, and snippets.

@mloureiro
Created November 13, 2024 17:56
Show Gist options
  • Save mloureiro/6a956dd6e3f157e4f9bc5e1c25e7ac9c to your computer and use it in GitHub Desktop.
Save mloureiro/6a956dd6e3f157e4f9bc5e1c25e7ac9c to your computer and use it in GitHub Desktop.
Find the circular dependencies
const fs = require("fs");
const path = require("path");
/**
* Recursively get all TypeScript files (.ts, .tsx) in a directory.
* @param {string} dirPath - Directory to search.
* @returns {string[]} - Array of file paths.
*/
function getTypeScriptFiles(dirPath) {
let files = [];
fs.readdirSync(dirPath).forEach((file) => {
const fullPath = path.join(dirPath, file);
if (fs.statSync(fullPath).isDirectory()) {
files = files.concat(getTypeScriptFiles(fullPath));
} else if (fullPath.endsWith(".ts") || fullPath.endsWith(".tsx")) {
files.push(fullPath);
}
});
return files;
}
/**
* Add console.log statements to the top and bottom of a file.
* @param {string} filePath - Path to the file.
*/
function addImportLogs(filePath) {
const relativePath = path.relative(process.cwd(), filePath);
const logStart = `console.group('>>> IMPORT: ${relativePath}');\n`;
const logEnd = `\nconsole.log('<<< DONE: ${relativePath}');\nconsole.groupEnd();\n`;
const fileContent = fs.readFileSync(filePath, "utf-8");
// Add logStart if not already present
let updatedContent = fileContent;
if (!fileContent.startsWith("console.log('>>> IMPORT:")) {
updatedContent = logStart + updatedContent;
console.log(`Added start log to: ${relativePath}`);
} else {
console.log(`Start log already exists in: ${relativePath}`);
}
// Add logEnd if not already present
if (!fileContent.endsWith(logEnd.trim())) {
updatedContent = updatedContent.trimEnd() + logEnd + "\n";
console.log(`Added end log to: ${relativePath}`);
} else {
console.log(`End log already exists in: ${relativePath}`);
}
// Write updated content back to the file
fs.writeFileSync(filePath, updatedContent, "utf-8");
}
/**
* Main function to process all files.
* @param {string} rootDir - Root directory to process.
*/
function main(rootDir) {
if (!fs.existsSync(rootDir)) {
console.error(`Error: Directory "${rootDir}" does not exist.`);
process.exit(1);
}
const tsFiles = getTypeScriptFiles(rootDir);
if (tsFiles.length === 0) {
console.log("No TypeScript files found.");
return;
}
tsFiles.forEach((file) => addImportLogs(file));
console.log("All files processed.");
}
// Entry point
const args = process.argv.slice(2);
if (args.length === 0) {
console.error("Usage: node addImportLog.js <ROOT_DIR>");
process.exit(1);
}
const ROOT_DIR = args[0];
main(ROOT_DIR);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment