utils.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import path = require('path');
  2. import glob = require('glob');
  3. import fs = require('fs-extra');
  4. import childProcess = require('child_process');
  5. import sortPackageJson = require('sort-package-json');
  6. /**
  7. * Get all of the lerna package paths.
  8. */
  9. export function getLernaPaths(): string[] {
  10. let basePath = path.resolve('.');
  11. let baseConfig = require(path.join(basePath, 'package.json'));
  12. let paths: string[] = [];
  13. for (let config of baseConfig.workspaces) {
  14. paths = paths.concat(glob.sync(path.join(basePath, config)));
  15. }
  16. return paths.filter(pkgPath => {
  17. return fs.existsSync(path.join(pkgPath, 'package.json'));
  18. });
  19. }
  20. /**
  21. * Get all of the core package paths.
  22. */
  23. export function getCorePaths(): string[] {
  24. let spec = path.resolve(path.join('.', 'packages', '*'));
  25. return glob.sync(spec);
  26. }
  27. /**
  28. * Write a package.json if necessary.
  29. *
  30. * @param data - The package data.
  31. *
  32. * @oaram pkgJsonPath - The path to the package.json file.
  33. *
  34. * @returns Whether the file has changed.
  35. */
  36. export function writePackageData(pkgJsonPath: string, data: any): boolean {
  37. let text = JSON.stringify(sortPackageJson(data), null, 2) + '\n';
  38. let orig = fs
  39. .readFileSync(pkgJsonPath, 'utf8')
  40. .split('\r\n')
  41. .join('\n');
  42. if (text !== orig) {
  43. fs.writeFileSync(pkgJsonPath, text, 'utf8');
  44. return true;
  45. }
  46. return false;
  47. }
  48. /**
  49. * Read a package.json file.
  50. */
  51. export function readJSONFile(filePath: string): any {
  52. return JSON.parse(fs.readFileSync(filePath, 'utf8'));
  53. }
  54. /**
  55. * Run a command with terminal output.
  56. *
  57. * @param cmd - The command to run.
  58. */
  59. export function run(
  60. cmd: string,
  61. options: childProcess.ExecSyncOptions = {},
  62. quiet?: boolean
  63. ): string {
  64. options = options || {};
  65. options['stdio'] = options.stdio || 'inherit';
  66. if (!quiet) {
  67. console.log('>', cmd);
  68. }
  69. return childProcess
  70. .execSync(cmd, options)
  71. .toString()
  72. .replace(/\n$/, '');
  73. }