cli.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/usr/bin/env node
  2. 'use strict';
  3. /**
  4. * Dependencies
  5. */
  6. const {argv} = require('yargs');
  7. const replace = require('../lib/replace-in-file');
  8. const loadConfig = require('../lib/helpers/load-config');
  9. const combineConfig = require('../lib/helpers/combine-config');
  10. const errorHandler = require('../lib/helpers/error-handler');
  11. const successHandler = require('../lib/helpers/success-handler');
  12. /**
  13. * Main routine
  14. */
  15. async function main() {
  16. //Extract parameters
  17. const {configFile} = argv;
  18. //Verify arguments
  19. if (argv._.length < 3 && !configFile) {
  20. throw new Error('Replace in file needs at least 3 arguments');
  21. }
  22. //Load config and combine with passed arguments
  23. const config = await loadConfig(configFile);
  24. const options = combineConfig(config, argv);
  25. //Extract settings
  26. const {from, to, files, isRegex, verbose, quiet} = options;
  27. //Single star globs already get expanded in the command line
  28. options.files = files.reduce((files, file) => {
  29. return files.concat(file.split(','));
  30. }, []);
  31. //If the isRegex flag is passed, convert the from parameter to a RegExp object
  32. if (isRegex) {
  33. const flags = from.replace(/.*\/([gimyus]*)$/, '$1');
  34. const pattern = from.replace(new RegExp(`^/(.*?)/${flags}$`), '$1');
  35. options.from = new RegExp(pattern, flags);
  36. }
  37. //Log
  38. if (!quiet) {
  39. console.log(`Replacing '${from}' with '${to}'`);
  40. }
  41. //Replace
  42. const results = replace.sync(options);
  43. if (!quiet) {
  44. successHandler(results, verbose);
  45. }
  46. }
  47. //Call main routine
  48. main().catch(error => errorHandler(error));