check-imports.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* eslint-disable no-console */
  2. import fs from 'fs';
  3. import path from 'path';
  4. // eslint-disable-next-line @typescript-eslint/no-var-requires
  5. const find = require('find');
  6. /**
  7. * An array of regular expressions defining illegal import patterns to be checked in the
  8. * source files of the monorepo packages. This prevents bad imports (which work locally
  9. * and go undetected) from getting into published releases of Vendure.
  10. */
  11. const illegalImportPatterns: RegExp[] = [
  12. /@vendure\/common\/src/,
  13. /@vendure\/core\/src/,
  14. /@vendure\/admin-ui\/src/,
  15. ];
  16. const exclude: string[] = [
  17. path.join(__dirname, '../packages/dev-server'),
  18. ];
  19. findInFiles(illegalImportPatterns, path.join(__dirname, '../packages'), /\.ts$/, exclude);
  20. function findInFiles(patterns: RegExp[], directory: string, fileFilter: RegExp, excludePaths: string[]) {
  21. find.file(fileFilter, directory, async (files: string[]) => {
  22. const nonNodeModulesFiles = files.filter(f => !f.includes('node_modules'));
  23. console.log(`Checking imports in ${nonNodeModulesFiles.length} files...`);
  24. const matches = await getMatchedFiles(patterns, nonNodeModulesFiles, excludePaths);
  25. if (matches.length) {
  26. console.error(`Found illegal imports in the following files:`);
  27. console.error(matches.join('\n'));
  28. process.exitCode = 1;
  29. } else {
  30. console.log('Imports check ok!');
  31. }
  32. });
  33. }
  34. async function getMatchedFiles(patterns: RegExp[], files: string[], excludePaths: string[]) {
  35. const matchedFiles = [];
  36. outer:
  37. for (let i = files.length - 1; i >= 0; i--) {
  38. for (const excludedPath of excludePaths) {
  39. if (files[i].includes(excludedPath)) {
  40. continue outer;
  41. }
  42. }
  43. const content = await readFile(files[i]);
  44. for (const pattern of patterns) {
  45. if (pattern.test(content)) {
  46. matchedFiles.push(files[i]);
  47. continue;
  48. }
  49. }
  50. }
  51. return matchedFiles;
  52. }
  53. function readFile(filePath: string): Promise<string> {
  54. return new Promise((resolve, reject) => {
  55. fs.readFile(filePath, 'utf-8', (err, data) => {
  56. if (err) {
  57. reject(err);
  58. } else {
  59. resolve(data);
  60. }
  61. });
  62. });
  63. }