npm-utils.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. /**
  2. * @fileoverview Utility for executing npm commands.
  3. * @author Ian VanSchooten
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const fs = require("fs"),
  10. spawn = require("cross-spawn"),
  11. path = require("path"),
  12. log = require("../shared/logging");
  13. //------------------------------------------------------------------------------
  14. // Helpers
  15. //------------------------------------------------------------------------------
  16. /**
  17. * Find the closest package.json file, starting at process.cwd (by default),
  18. * and working up to root.
  19. * @param {string} [startDir=process.cwd()] Starting directory
  20. * @returns {string} Absolute path to closest package.json file
  21. */
  22. function findPackageJson(startDir) {
  23. let dir = path.resolve(startDir || process.cwd());
  24. do {
  25. const pkgFile = path.join(dir, "package.json");
  26. if (!fs.existsSync(pkgFile) || !fs.statSync(pkgFile).isFile()) {
  27. dir = path.join(dir, "..");
  28. continue;
  29. }
  30. return pkgFile;
  31. } while (dir !== path.resolve(dir, ".."));
  32. return null;
  33. }
  34. //------------------------------------------------------------------------------
  35. // Private
  36. //------------------------------------------------------------------------------
  37. /**
  38. * Install node modules synchronously and save to devDependencies in package.json
  39. * @param {string|string[]} packages Node module or modules to install
  40. * @returns {void}
  41. */
  42. function installSyncSaveDev(packages) {
  43. const packageList = Array.isArray(packages) ? packages : [packages];
  44. const npmProcess = spawn.sync("npm", ["i", "--save-dev"].concat(packageList),
  45. { stdio: "inherit" });
  46. const error = npmProcess.error;
  47. if (error && error.code === "ENOENT") {
  48. const pluralS = packageList.length > 1 ? "s" : "";
  49. log.error(`Could not execute npm. Please install the following package${pluralS} with a package manager of your choice: ${packageList.join(", ")}`);
  50. }
  51. }
  52. /**
  53. * Fetch `peerDependencies` of the given package by `npm show` command.
  54. * @param {string} packageName The package name to fetch peerDependencies.
  55. * @returns {Object} Gotten peerDependencies. Returns null if npm was not found.
  56. */
  57. function fetchPeerDependencies(packageName) {
  58. const npmProcess = spawn.sync(
  59. "npm",
  60. ["show", "--json", packageName, "peerDependencies"],
  61. { encoding: "utf8" }
  62. );
  63. const error = npmProcess.error;
  64. if (error && error.code === "ENOENT") {
  65. return null;
  66. }
  67. const fetchedText = npmProcess.stdout.trim();
  68. return JSON.parse(fetchedText || "{}");
  69. }
  70. /**
  71. * Check whether node modules are include in a project's package.json.
  72. * @param {string[]} packages Array of node module names
  73. * @param {Object} opt Options Object
  74. * @param {boolean} opt.dependencies Set to true to check for direct dependencies
  75. * @param {boolean} opt.devDependencies Set to true to check for development dependencies
  76. * @param {boolean} opt.startdir Directory to begin searching from
  77. * @returns {Object} An object whose keys are the module names
  78. * and values are booleans indicating installation.
  79. */
  80. function check(packages, opt) {
  81. const deps = new Set();
  82. const pkgJson = (opt) ? findPackageJson(opt.startDir) : findPackageJson();
  83. let fileJson;
  84. if (!pkgJson) {
  85. throw new Error("Could not find a package.json file. Run 'npm init' to create one.");
  86. }
  87. try {
  88. fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
  89. } catch (e) {
  90. const error = new Error(e);
  91. error.messageTemplate = "failed-to-read-json";
  92. error.messageData = {
  93. path: pkgJson,
  94. message: e.message
  95. };
  96. throw error;
  97. }
  98. ["dependencies", "devDependencies"].forEach(key => {
  99. if (opt[key] && typeof fileJson[key] === "object") {
  100. Object.keys(fileJson[key]).forEach(dep => deps.add(dep));
  101. }
  102. });
  103. return packages.reduce((status, pkg) => {
  104. status[pkg] = deps.has(pkg);
  105. return status;
  106. }, {});
  107. }
  108. /**
  109. * Check whether node modules are included in the dependencies of a project's
  110. * package.json.
  111. *
  112. * Convenience wrapper around check().
  113. * @param {string[]} packages Array of node modules to check.
  114. * @param {string} rootDir The directory containing a package.json
  115. * @returns {Object} An object whose keys are the module names
  116. * and values are booleans indicating installation.
  117. */
  118. function checkDeps(packages, rootDir) {
  119. return check(packages, { dependencies: true, startDir: rootDir });
  120. }
  121. /**
  122. * Check whether node modules are included in the devDependencies of a project's
  123. * package.json.
  124. *
  125. * Convenience wrapper around check().
  126. * @param {string[]} packages Array of node modules to check.
  127. * @returns {Object} An object whose keys are the module names
  128. * and values are booleans indicating installation.
  129. */
  130. function checkDevDeps(packages) {
  131. return check(packages, { devDependencies: true });
  132. }
  133. /**
  134. * Check whether package.json is found in current path.
  135. * @param {string} [startDir] Starting directory
  136. * @returns {boolean} Whether a package.json is found in current path.
  137. */
  138. function checkPackageJson(startDir) {
  139. return !!findPackageJson(startDir);
  140. }
  141. //------------------------------------------------------------------------------
  142. // Public Interface
  143. //------------------------------------------------------------------------------
  144. module.exports = {
  145. installSyncSaveDev,
  146. fetchPeerDependencies,
  147. findPackageJson,
  148. checkDeps,
  149. checkDevDeps,
  150. checkPackageJson
  151. };