選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.js 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const fs = require('fs');
  2. const path = require('path');
  3. const crossSpawn = require('cross-spawn');
  4. const pkgDir = require('pkg-dir');
  5. let cachedHasYarn;
  6. let cachedHasNPM;
  7. let cachedClient;
  8. function clearCache() {
  9. cachedHasYarn = undefined;
  10. cachedHasNPM = undefined;
  11. cachedClient = undefined;
  12. }
  13. function hasYarn() {
  14. if (cachedHasYarn !== undefined) return cachedHasYarn;
  15. try {
  16. const cmd = crossSpawn.sync('yarn', ['--version']);
  17. const version = cmd.stdout && cmd.stdout.toString().trim();
  18. cachedHasYarn = !!version;
  19. } catch (e) {
  20. cachedHasYarn = false;
  21. }
  22. return cachedHasYarn;
  23. }
  24. function hasNpm() {
  25. if (cachedHasNPM !== undefined) return cachedHasNPM;
  26. try {
  27. const cmd = crossSpawn.sync('npm', ['--version']);
  28. const version = cmd.stdout && cmd.stdout.toString().trim();
  29. cachedHasNPM = !!version;
  30. } catch (e) {
  31. cachedHasNPM = false;
  32. }
  33. return cachedHasNPM;
  34. }
  35. function yarnOrNpm() {
  36. if (cachedClient !== undefined) return cachedClient;
  37. const pkgRoot = pkgDir.sync();
  38. if (pkgRoot) {
  39. const pkgLockPath = path.join(pkgRoot, 'package-lock.json');
  40. const yarnLockPath = path.join(pkgRoot, 'yarn.lock');
  41. try {
  42. fs.statSync(yarnLockPath);
  43. cachedClient = 'yarn';
  44. return cachedClient;
  45. } catch (e) {}
  46. try {
  47. fs.statSync(pkgLockPath);
  48. cachedClient = 'npm';
  49. return cachedClient;
  50. } catch (e) {}
  51. }
  52. return hasYarn() ? 'yarn' : 'npm';
  53. }
  54. function spawn(...args) {
  55. args.unshift(yarnOrNpm());
  56. return crossSpawn(...args);
  57. }
  58. function spawnSync(...args) {
  59. args.unshift(yarnOrNpm());
  60. return crossSpawn.sync(...args);
  61. }
  62. yarnOrNpm.hasYarn = hasYarn;
  63. yarnOrNpm.hasNpm = hasNpm;
  64. yarnOrNpm.spawn = spawn;
  65. yarnOrNpm.spawn.sync = spawnSync;
  66. yarnOrNpm.clearCache = clearCache;
  67. module.exports = yarnOrNpm;