Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

npm-utils.js 5.9KB

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