UNPKG

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