check-imports.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* tslint:disable:no-console */
  2. import fs from 'fs';
  3. import path from 'path';
  4. // tslint:disable-next-line: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 illegalImportPatters: RegExp[] = [
  12. /@vendure\/common\/src/,
  13. ];
  14. findInFiles(illegalImportPatters, path.join(__dirname, '../packages'), /\.ts$/);
  15. function findInFiles(patterns: RegExp[], directory: string, fileFilter: RegExp) {
  16. find.file(fileFilter, directory, async (files: string[]) => {
  17. const matches = await getMatchedFiles(patterns, files);
  18. if (matches.length) {
  19. console.error(`Found illegal imports in the following files:`);
  20. console.error(matches.join('\n'));
  21. process.exitCode = 1;
  22. } else {
  23. console.log('Imports check ok!');
  24. }
  25. });
  26. }
  27. async function getMatchedFiles(patterns: RegExp[], files: string[]) {
  28. const matchedFiles = [];
  29. for (let i = files.length - 1; i >= 0; i--) {
  30. const content = await readFile(files[i]);
  31. for (const pattern of patterns) {
  32. if (pattern.test(content)) {
  33. matchedFiles.push(files[i]);
  34. continue;
  35. }
  36. }
  37. }
  38. return matchedFiles;
  39. }
  40. function readFile(filePath: string): Promise<string> {
  41. return new Promise((resolve, reject) => {
  42. fs.readFile(filePath, 'utf-8', (err, data) => {
  43. if (err) {
  44. reject(err);
  45. } else {
  46. resolve(data);
  47. }
  48. });
  49. });
  50. }