replace-in-file.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. 'use strict';
  2. /**
  3. * Dependencies
  4. */
  5. const chalk = require('chalk');
  6. const parseConfig = require('./helpers/parse-config');
  7. const getPathsSync = require('./helpers/get-paths-sync');
  8. const getPathsAsync = require('./helpers/get-paths-async');
  9. const replaceSync = require('./helpers/replace-sync');
  10. const replaceAsync = require('./helpers/replace-async');
  11. const processFile = require('./process-file');
  12. /**
  13. * Replace in file helper
  14. */
  15. function replaceInFile(config, cb) {
  16. // If custom processor is provided use it instead
  17. if (config && config.processor) {
  18. return processFile(config, cb);
  19. }
  20. //Parse config
  21. try {
  22. config = parseConfig(config);
  23. }
  24. catch (error) {
  25. if (typeof cb === 'function') {
  26. return cb(error, null);
  27. }
  28. return Promise.reject(error);
  29. }
  30. //Get config
  31. const {files, from, to, dry, verbose} = config;
  32. //Dry run?
  33. //istanbul ignore if: No need to test console logs
  34. if (dry && verbose) {
  35. console.log(chalk.yellow('Dry run, not making actual changes'));
  36. }
  37. //Find paths
  38. return getPathsAsync(files, config)
  39. //Make replacements
  40. .then(paths => Promise.all(
  41. paths.map(file => replaceAsync(file, from, to, config))
  42. ))
  43. //Success handler
  44. .then(results => {
  45. if (typeof cb === 'function') {
  46. cb(null, results);
  47. }
  48. return results;
  49. })
  50. //Error handler
  51. .catch(error => {
  52. if (typeof cb === 'function') {
  53. cb(error);
  54. }
  55. else {
  56. throw error;
  57. }
  58. });
  59. }
  60. /**
  61. * Sync API
  62. */
  63. function replaceInFileSync(config) {
  64. // If custom processor is provided use it instead
  65. if (config && config.processor) {
  66. return processFile.processFileSync(config);
  67. }
  68. //Parse config
  69. config = parseConfig(config);
  70. //Get config, paths, and initialize changed files
  71. const {files, from, to, dry, verbose} = config;
  72. const paths = getPathsSync(files, config);
  73. //Dry run?
  74. //istanbul ignore if: No need to test console logs
  75. if (dry && verbose) {
  76. console.log(chalk.yellow('Dry run, not making actual changes'));
  77. }
  78. //Process synchronously and return results
  79. return paths.map(path => replaceSync(path, from, to, config));
  80. }
  81. // Self-reference to support named import
  82. replaceInFile.replaceInFile = replaceInFile;
  83. replaceInFile.replaceInFileSync = replaceInFileSync;
  84. replaceInFile.sync = replaceInFileSync;
  85. //Export
  86. module.exports = replaceInFile;