项目原始demo,不改动
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 

178 lines
5.8 KiB

  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. log.info("Could not read package.json file. Please check that the file contains valid JSON.");
  93. throw new Error(e);
  94. }
  95. if (opt.devDependencies && typeof fileJson.devDependencies === "object") {
  96. deps = deps.concat(Object.keys(fileJson.devDependencies));
  97. }
  98. if (opt.dependencies && typeof fileJson.dependencies === "object") {
  99. deps = deps.concat(Object.keys(fileJson.dependencies));
  100. }
  101. return packages.reduce((status, pkg) => {
  102. status[pkg] = deps.indexOf(pkg) !== -1;
  103. return status;
  104. }, {});
  105. }
  106. /**
  107. * Check whether node modules are included in the dependencies of a project's
  108. * package.json.
  109. *
  110. * Convienience wrapper around check().
  111. *
  112. * @param {string[]} packages Array of node modules to check.
  113. * @param {string} rootDir The directory contianing a package.json
  114. * @returns {Object} An object whose keys are the module names
  115. * and values are booleans indicating installation.
  116. */
  117. function checkDeps(packages, rootDir) {
  118. return check(packages, { dependencies: true, startDir: rootDir });
  119. }
  120. /**
  121. * Check whether node modules are included in the devDependencies of a project's
  122. * package.json.
  123. *
  124. * Convienience wrapper around check().
  125. *
  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. *
  136. * @param {string=} startDir Starting directory
  137. * @returns {boolean} Whether a package.json is found in current path.
  138. */
  139. function checkPackageJson(startDir) {
  140. return !!findPackageJson(startDir);
  141. }
  142. //------------------------------------------------------------------------------
  143. // Public Interface
  144. //------------------------------------------------------------------------------
  145. module.exports = {
  146. installSyncSaveDev,
  147. fetchPeerDependencies,
  148. checkDeps,
  149. checkDevDeps,
  150. checkPackageJson
  151. };