From 6380a015430f78749a8c7afa1a3983d3bc581249 Mon Sep 17 00:00:00 2001 From: Jack Westbrook Date: Thu, 9 May 2024 10:49:47 +0200 Subject: [PATCH] Frontend: Improve barrel file detection in codemod (#87389) --- scripts/codemods/explicit-barrel-imports.cjs | 50 ++++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/scripts/codemods/explicit-barrel-imports.cjs b/scripts/codemods/explicit-barrel-imports.cjs index c87c26cc5d6..e4f3d8b9a67 100644 --- a/scripts/codemods/explicit-barrel-imports.cjs +++ b/scripts/codemods/explicit-barrel-imports.cjs @@ -1,39 +1,39 @@ -const fs = require('fs'); const path = require('path'); +const isBareSpecifier = (importPath) => !importPath.startsWith('app/') && /^[^./]/.test(importPath); +const barrelFileNames = ['index.ts', 'index.tsx', 'index.js', 'index.jsx']; + +const resolvePath = (fileDir, importPath) => + importPath.startsWith('app/') + ? require.resolve(path.join(__dirname, '..', '..', 'public', importPath)) + : require.resolve(path.resolve(fileDir, importPath)); + module.exports = function (fileInfo, api) { const j = api.jscodeshift; const root = j.withParser('tsx')(fileInfo.source); const fileDir = path.dirname(fileInfo.path); - - // Function to check if the path potentially points to a barrel file - const mightBeBarrelFileImport = (importPath) => { - const fullPath = path.join(fileDir, importPath); - if (fs.existsSync(fullPath) && fs.lstatSync(fullPath).isDirectory()) { - if (fs.existsSync(path.join(fullPath, 'index.ts')) || fs.existsSync(path.join(fullPath, 'index.js'))) { - return true; - } - } - return false; - }; - - // Udpate import declarations that import from barrel files + // Update import declarations that import from barrel files root .find(j.ImportDeclaration) - .filter((path) => mightBeBarrelFileImport(path.node.source.value)) + .filter((path) => !isBareSpecifier(path.node.source.value)) .forEach((path) => { - // Create a comment node - const comment = j.commentLine(' @todo: replace barrel import path'); + const resolvedPath = resolvePath(fileDir, path.node.source.value); + if (barrelFileNames.some((barrelFileName) => resolvedPath.endsWith(barrelFileName))) { + // Create a comment node + const comment = j.commentLine(' @todo: replace barrel import path'); - // Attach the comment as a leading comment to the import declaration - if (!path.node.comments) { - path.node.comments = []; + // Attach the comment as a leading comment to the import declaration + if (!path.node.comments) { + path.node.comments = []; + } + path.node.comments.push(comment); + + // Update the import path appending '/index' + path.node.source.value = path.node.source.value + '/index'; } - path.node.comments.push(comment); - - // Update the import path appending '/index' - path.node.source.value = path.node.source.value + '/index'; }); - return root.toSource(); + return root.toSource({ + quote: 'single', + }); };