Skip to content

Instantly share code, notes, and snippets.

@vamshi9666
Created May 17, 2022 02:23
Show Gist options
  • Save vamshi9666/e789a54cf998ff6b97bc65dfc2fbf2f1 to your computer and use it in GitHub Desktop.
Save vamshi9666/e789a54cf998ff6b97bc65dfc2fbf2f1 to your computer and use it in GitHub Desktop.
get components summary
const sourceCodeDir = "./pages";
const fs = require("fs");
const path = require("path");
const getAllFiles = function (dirPath, arrayOfFiles) {
files = fs.readdirSync(dirPath);
arrayOfFiles = arrayOfFiles || [];
files.forEach(function (file) {
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles);
} else {
arrayOfFiles.push(path.join(dirPath, "/", file));
}
});
const onlyTsxFiles = arrayOfFiles
.filter((file) => {
return file.endsWith(".tsx");
})
// .filter((file) => {
// //filter out directories
// // return !file.endsWith("/");
// })
.map((file) => {
return file.replace("/scripts", "");
});
return onlyTsxFiles;
};
function getChakraComponentsUsed(fileContent) {
const regex =
/import\s*{[\s\S]*?}\s*from\s*["'](chakra-ui|@chakra-ui\/[\s\S]*?)["']/gm;
const importStatement = fileContent.match(regex)[0] || "";
console.log("importStatement", importStatement);
const components = importStatement.split("{")[1].split("}")[0].split(",");
return components;
}
async function walkAndGetResults(sourcePath) {
const allFiles = await getAllFiles(sourcePath);
console.log("staring with ", allFiles);
// return;
const results = allFiles.flatMap((file) => {
try {
//path from root
// console.log("file", file);
const fileContent = fs.readFileSync(file, "utf8");
const chakraComponentsImported = getChakraComponentsUsed(fileContent);
// results = results.concat(chakraComponentsImported)
console.log("file content first line", file, chakraComponentsImported);
return chakraComponentsImported;
// results = results.concat(chakraComponentsImported);
} catch (error) {
console.log("error>>>", error);
}
});
const componentCounts = {};
// console.log("results", results);
results.forEach((component) => {
console.log("component", component);
const cName = component && component?.trim();
if (componentCounts[cName]) {
componentCounts[cName]++;
} else {
componentCounts[cName] = 1;
}
});
return { sourcePath, counts: componentCounts };
}
async function main() {
const pageRes = await walkAndGetResults("./pages");
const cRes = await walkAndGetResults("./components");
const counts = {
pageRes,
cRes,
};
console.log("counts", counts);
// save to json file
const json = JSON.stringify(counts);
fs.writeFileSync("./components-counts.json", json);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment