fix-src-imports.js 1.2 KB

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