make-replacements.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. /**
  3. * Get replacement helper
  4. */
  5. function getReplacement(replace, isArray, i) {
  6. if (isArray && typeof replace[i] === 'undefined') {
  7. return null;
  8. }
  9. if (isArray) {
  10. return replace[i];
  11. }
  12. return replace;
  13. }
  14. /**
  15. * Helper to make replacements
  16. */
  17. module.exports = function makeReplacements(contents, from, to, file, count) {
  18. //Turn into array
  19. if (!Array.isArray(from)) {
  20. from = [from];
  21. }
  22. //Check if replace value is an array and prepare result
  23. const isArray = Array.isArray(to);
  24. const result = {file};
  25. //Counting? Initialize number of matches
  26. if (count) {
  27. result.numMatches = 0;
  28. result.numReplacements = 0;
  29. }
  30. //Make replacements
  31. const newContents = from.reduce((contents, item, i) => {
  32. //Call function if given, passing in the filename
  33. if (typeof item === 'function') {
  34. item = item(file);
  35. }
  36. //Get replacement value
  37. let replacement = getReplacement(to, isArray, i);
  38. if (replacement === null) {
  39. return contents;
  40. }
  41. //Call function if given, appending the filename
  42. if (typeof replacement === 'function') {
  43. const original = replacement;
  44. replacement = (...args) => original(...args, file);
  45. }
  46. //Count matches
  47. if (count) {
  48. const matches = contents.match(item);
  49. if (matches) {
  50. const replacements = matches.filter(match => match !== replacement);
  51. result.numMatches += matches.length;
  52. result.numReplacements += replacements.length;
  53. }
  54. }
  55. //Make replacement
  56. return contents.replace(item, replacement);
  57. }, contents);
  58. //Check if changed
  59. result.hasChanged = (newContents !== contents);
  60. //Return result and new contents
  61. return [result, newContents];
  62. };