index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. const childProcess = require("@lerna/child-process");
  3. const { Command } = require("@lerna/command");
  4. const { ValidationError } = require("@lerna/validation-error");
  5. const { getLastCommit } = require("./lib/get-last-commit");
  6. const { hasCommit } = require("./lib/has-commit");
  7. module.exports = factory;
  8. function factory(argv) {
  9. return new DiffCommand(argv);
  10. }
  11. class DiffCommand extends Command {
  12. initialize() {
  13. const packageName = this.options.pkgName;
  14. let targetPackage;
  15. if (packageName) {
  16. targetPackage = this.packageGraph.get(packageName);
  17. if (!targetPackage) {
  18. throw new ValidationError("ENOPKG", `Cannot diff, the package '${packageName}' does not exist.`);
  19. }
  20. }
  21. if (!hasCommit(this.execOpts)) {
  22. throw new ValidationError("ENOCOMMITS", "Cannot diff, there are no commits in this repository yet.");
  23. }
  24. const args = ["diff", getLastCommit(this.execOpts), "--color=auto"];
  25. if (targetPackage) {
  26. args.push("--", targetPackage.location);
  27. } else {
  28. args.push("--", ...this.project.packageParentDirs);
  29. }
  30. if (this.options.ignoreChanges) {
  31. this.options.ignoreChanges.forEach((ignorePattern) => {
  32. // https://stackoverflow.com/a/21079437
  33. args.push(`:(exclude,glob)${ignorePattern}`);
  34. });
  35. }
  36. this.args = args;
  37. }
  38. execute() {
  39. return childProcess.spawn("git", this.args, this.execOpts).catch((err) => {
  40. if (err.exitCode) {
  41. // quitting the diff viewer is not an error
  42. throw err;
  43. }
  44. });
  45. }
  46. }
  47. module.exports.DiffCommand = DiffCommand;