parse-config.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. /**
  3. * Defaults
  4. */
  5. const defaults = {
  6. ignore: [],
  7. encoding: 'utf-8',
  8. disableGlobs: false,
  9. allowEmptyPaths: false,
  10. countMatches: false,
  11. isRegex: false,
  12. verbose: false,
  13. quiet: false,
  14. dry: false,
  15. glob: {},
  16. cwd: null,
  17. };
  18. /**
  19. * Parse config
  20. */
  21. module.exports = function parseConfig(config) {
  22. //Validate config
  23. if (typeof config !== 'object' || config === null) {
  24. throw new Error('Must specify configuration object');
  25. }
  26. //Fix glob
  27. config.glob = config.glob || {};
  28. //Extract data
  29. const {files, from, to, processor, ignore, encoding} = config;
  30. if (typeof processor !== 'undefined') {
  31. if (typeof processor !== 'function' && !Array.isArray(processor)) {
  32. throw new Error('Processor should be either a function or an array of functions');
  33. }
  34. } else {
  35. //Validate values
  36. if (typeof files === 'undefined') {
  37. throw new Error('Must specify file or files');
  38. }
  39. if (typeof from === 'undefined') {
  40. throw new Error('Must specify string or regex to replace');
  41. }
  42. if (typeof to === 'undefined') {
  43. throw new Error('Must specify a replacement (can be blank string)');
  44. }
  45. }
  46. //Ensure arrays
  47. if (!Array.isArray(files)) {
  48. config.files = [files];
  49. }
  50. if (!Array.isArray(ignore)) {
  51. if (typeof ignore === 'undefined') {
  52. config.ignore = [];
  53. }
  54. else {
  55. config.ignore = [ignore];
  56. }
  57. }
  58. //Use default encoding if invalid
  59. if (typeof encoding !== 'string' || encoding === '') {
  60. config.encoding = 'utf-8';
  61. }
  62. //Merge config with defaults
  63. return Object.assign({}, defaults, config);
  64. };