1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | const chalk = require('chalk');
|
7 | const parseConfig = require('./helpers/parse-config');
|
8 | const getPathsSync = require('./helpers/get-paths-sync');
|
9 | const getPathsAsync = require('./helpers/get-paths-async');
|
10 | const replaceSync = require('./helpers/replace-sync');
|
11 | const replaceAsync = require('./helpers/replace-async');
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | function replaceInFile(config, cb) {
|
17 |
|
18 |
|
19 | try {
|
20 | config = parseConfig(config);
|
21 | }
|
22 | catch (error) {
|
23 | if (cb) {
|
24 | return cb(error, null);
|
25 | }
|
26 | return Promise.reject(error);
|
27 | }
|
28 |
|
29 |
|
30 | const {files, from, to, dry, verbose} = config;
|
31 |
|
32 |
|
33 |
|
34 | if (dry && verbose) {
|
35 | console.log(chalk.yellow('Dry run, not making actual changes'));
|
36 | }
|
37 |
|
38 |
|
39 | return getPathsAsync(files, config)
|
40 |
|
41 |
|
42 | .then(paths => Promise.all(
|
43 | paths.map(file => replaceAsync(file, from, to, config))
|
44 | ))
|
45 |
|
46 |
|
47 | .then(results => {
|
48 | if (cb) {
|
49 | cb(null, results);
|
50 | }
|
51 | return results;
|
52 | })
|
53 |
|
54 |
|
55 | .catch(error => {
|
56 | if (cb) {
|
57 | cb(error);
|
58 | }
|
59 | else {
|
60 | throw error;
|
61 | }
|
62 | });
|
63 | }
|
64 |
|
65 |
|
66 |
|
67 |
|
68 | replaceInFile.sync = function(config) {
|
69 |
|
70 |
|
71 | config = parseConfig(config);
|
72 |
|
73 |
|
74 | const {files, from, to, dry, verbose} = config;
|
75 | const paths = getPathsSync(files, config);
|
76 |
|
77 |
|
78 |
|
79 | if (dry && verbose) {
|
80 | console.log(chalk.yellow('Dry run, not making actual changes'));
|
81 | }
|
82 |
|
83 |
|
84 | return paths.map(path => replaceSync(path, from, to, config));
|
85 | };
|
86 |
|
87 |
|
88 | module.exports = replaceInFile;
|