process-file.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 processSync = require('./helpers/process-sync');
  10. const processAsync = require('./helpers/process-async');
  11. function processFile(config, cb) {
  12. try {
  13. config = parseConfig(config);
  14. }
  15. catch (error) {
  16. if (typeof cb === 'function') {
  17. return cb(error, null);
  18. }
  19. return Promise.reject(error);
  20. }
  21. const {files, processor, dry, verbose} = config;
  22. //Dry run?
  23. //istanbul ignore if: No need to test console logs
  24. if (dry && verbose) {
  25. console.log(chalk.yellow('Dry run, not making actual changes'));
  26. }
  27. //Find paths
  28. return getPathsAsync(files, config)
  29. .then(paths => Promise.all(
  30. paths.map(file => processAsync(file, processor, config))
  31. ))
  32. .then(results => {
  33. if (typeof cb === 'function') {
  34. cb(null, results);
  35. }
  36. return results;
  37. })
  38. .catch(error => {
  39. if (typeof cb === 'function') {
  40. cb(error);
  41. }
  42. else {
  43. throw error;
  44. }
  45. });
  46. }
  47. /**
  48. * Sync API
  49. */
  50. function processFileSync(config) {
  51. //Parse config
  52. config = parseConfig(config);
  53. //Get config, paths, and initialize changed files
  54. const {files, processor, dry, verbose} = config;
  55. const paths = getPathsSync(files, config);
  56. //Dry run?
  57. //istanbul ignore if: No need to test console logs
  58. if (dry && verbose) {
  59. console.log(chalk.yellow('Dry run, not making actual changes'));
  60. }
  61. //Process synchronously and return results
  62. return paths.map(path => processSync(path, processor, config));
  63. }
  64. // Self-reference to support named import
  65. processFile.processFile = processFile;
  66. processFile.processFileSync = processFileSync;
  67. processFile.sync = processFileSync;
  68. //Export
  69. module.exports = processFile;