fix-src-imports.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env node
  2. const fs = require( 'fs' );
  3. const path = require( 'path' );
  4. const glob = require( 'glob' );
  5. const srcDir = path.join( process.cwd(), 'src' );
  6. const srcPath = path.join( srcDir , '**', '*.js' );
  7. for ( const filePath of glob.sync( srcPath ) ) {
  8. const fileDepth = countOcurrences( filePath.replace( srcDir + '/', '' ), path.sep );
  9. const fix = ( wholeImport, pathStart ) => fixImport( wholeImport, pathStart, fileDepth );
  10. const fileContent = fs.readFileSync( filePath, 'utf-8' )
  11. .replace( /\nimport[^']+?'((\.\.\/)+[\w-]+)\/[^']+?'/gm, fix );
  12. fs.writeFileSync( filePath, fileContent , 'utf-8' );
  13. }
  14. function fixImport( wholeImport, pathStart, fileDepth ) {
  15. const indexOfPathStart = wholeImport.indexOf( '../' );
  16. const packageShortName = pathStart.split( '/' ).slice( -1 )[0];
  17. const importDepth = countOcurrences( pathStart, '../' );
  18. if ( importDepth <= fileDepth ) {
  19. return wholeImport;
  20. }
  21. return (
  22. wholeImport.slice( 0, indexOfPathStart ) +
  23. 'ckeditor5-' + packageShortName +
  24. '/src' +
  25. wholeImport.slice( indexOfPathStart + pathStart.length )
  26. );
  27. }
  28. function countOcurrences( str, pattern ) {
  29. return str.split( pattern ).length - 1;
  30. }