|
| 1 | +#!/usr/bin/env node |
| 2 | +// check all imports in ./src and filter out file extensions from the import paths for .ts and .tsx. |
| 3 | +import fs from 'fs'; |
| 4 | + |
| 5 | +const srcDir = './src'; |
| 6 | + |
| 7 | +// check if dry run |
| 8 | +if (process.argv.includes('--dry')) { |
| 9 | + console.log('Dry run enabled'); |
| 10 | + process.env.DRY_RUN = 'true'; |
| 11 | +} |
| 12 | + |
| 13 | +const dryRun = process.env.DRY_RUN === 'true'; |
| 14 | + |
| 15 | +const fixImports = path => { |
| 16 | + const content = fs.readFileSync(path, 'utf8'); |
| 17 | + const imports = content.match(/import (?:type )?{?(?:\s*[a-zA-Z0-9_]*,?\s)*}? ?from ['"]([^'"]*)['"];/gs) || []; |
| 18 | + |
| 19 | + const newImports = imports.map(imp => { |
| 20 | + const match = imp.match(/from ['"](.*)['"]/); |
| 21 | + const oldPath = match[1]; |
| 22 | + // remove .ts and .tsx |
| 23 | + const newPath = oldPath.replace(/\.tsx?/g, ''); |
| 24 | + |
| 25 | + return [imp, imp.replace(oldPath, newPath), oldPath === newPath]; |
| 26 | + }).filter(([oldPath, newImp, same]) => !same); |
| 27 | + |
| 28 | + if (!newImports.length) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + const newContent = content.replace( |
| 33 | + new RegExp(newImports.map(([oldPath]) => oldPath).join('|'), 'g'), |
| 34 | + match => { |
| 35 | + const newImport = newImports.find(([oldPath]) => oldPath === match); |
| 36 | + return newImport[1]; |
| 37 | + } |
| 38 | + ); |
| 39 | + |
| 40 | + const changesMade = content !== newContent; |
| 41 | + |
| 42 | + const newImportsStr = newImports.map(([oldPath, newPath]) => `Old: \n${oldPath} \nNew: \n${newPath}`).join('\n'); |
| 43 | + |
| 44 | + console.log(`\nChanges in ${path}:\n${newImportsStr}\n`); |
| 45 | + |
| 46 | + if (!changesMade) { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + if (dryRun) { |
| 51 | + console.log(`Dry run enabled, skipping writing to ${path}`); |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + if (content !== newContent) { |
| 56 | + fs.writeFileSync(path, newContent); |
| 57 | + console.log(`Fixed imports in ${path}`); |
| 58 | + } |
| 59 | +}; |
| 60 | + |
| 61 | +const walk = dir => { |
| 62 | + const files = fs.readdirSync(dir); |
| 63 | + files.forEach(file => { |
| 64 | + const path = `${dir}/${file}`; |
| 65 | + if (fs.statSync(path).isDirectory()) { |
| 66 | + walk(path); |
| 67 | + } else { |
| 68 | + if (path.endsWith('.ts') || path.endsWith('.tsx')) { |
| 69 | + fixImports(path); |
| 70 | + } |
| 71 | + } |
| 72 | + }); |
| 73 | + |
| 74 | + if (dir === srcDir) { |
| 75 | + console.log('All imports fixed'); |
| 76 | + } |
| 77 | +}; |
| 78 | + |
| 79 | +walk(srcDir); |
0 commit comments