printDiffs.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.diffStringsUnified = exports.diffStringsRaw = void 0;
  6. var _cleanupSemantic = require('./cleanupSemantic');
  7. var _diffLines = require('./diffLines');
  8. var _diffStrings = _interopRequireDefault(require('./diffStrings'));
  9. var _getAlignedDiffs = _interopRequireDefault(require('./getAlignedDiffs'));
  10. var _normalizeDiffOptions = require('./normalizeDiffOptions');
  11. function _interopRequireDefault(obj) {
  12. return obj && obj.__esModule ? obj : {default: obj};
  13. }
  14. /**
  15. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  16. *
  17. * This source code is licensed under the MIT license found in the
  18. * LICENSE file in the root directory of this source tree.
  19. */
  20. const hasCommonDiff = (diffs, isMultiline) => {
  21. if (isMultiline) {
  22. // Important: Ignore common newline that was appended to multiline strings!
  23. const iLast = diffs.length - 1;
  24. return diffs.some(
  25. (diff, i) =>
  26. diff[0] === _cleanupSemantic.DIFF_EQUAL &&
  27. (i !== iLast || diff[1] !== '\n')
  28. );
  29. }
  30. return diffs.some(diff => diff[0] === _cleanupSemantic.DIFF_EQUAL);
  31. }; // Compare two strings character-by-character.
  32. // Format as comparison lines in which changed substrings have inverse colors.
  33. const diffStringsUnified = (a, b, options) => {
  34. if (a !== b && a.length !== 0 && b.length !== 0) {
  35. const isMultiline = a.includes('\n') || b.includes('\n'); // getAlignedDiffs assumes that a newline was appended to the strings.
  36. const diffs = diffStringsRaw(
  37. isMultiline ? a + '\n' : a,
  38. isMultiline ? b + '\n' : b,
  39. true // cleanupSemantic
  40. );
  41. if (hasCommonDiff(diffs, isMultiline)) {
  42. const optionsNormalized = (0, _normalizeDiffOptions.normalizeDiffOptions)(
  43. options
  44. );
  45. const lines = (0, _getAlignedDiffs.default)(
  46. diffs,
  47. optionsNormalized.changeColor
  48. );
  49. return (0, _diffLines.printDiffLines)(lines, optionsNormalized);
  50. }
  51. } // Fall back to line-by-line diff.
  52. return (0, _diffLines.diffLinesUnified)(
  53. a.split('\n'),
  54. b.split('\n'),
  55. options
  56. );
  57. }; // Compare two strings character-by-character.
  58. // Optionally clean up small common substrings, also known as chaff.
  59. exports.diffStringsUnified = diffStringsUnified;
  60. const diffStringsRaw = (a, b, cleanup) => {
  61. const diffs = (0, _diffStrings.default)(a, b);
  62. if (cleanup) {
  63. (0, _cleanupSemantic.cleanupSemantic)(diffs); // impure function
  64. }
  65. return diffs;
  66. };
  67. exports.diffStringsRaw = diffStringsRaw;