fix-src-imports.js 1.3 KB

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