-
Notifications
You must be signed in to change notification settings - Fork 65
/
replace-in-file.js
92 lines (76 loc) · 1.98 KB
/
replace-in-file.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';
/**
* Dependencies
*/
const chalk = require('chalk');
const parseConfig = require('./helpers/parse-config');
const getPathsSync = require('./helpers/get-paths-sync');
const getPathsAsync = require('./helpers/get-paths-async');
const replaceSync = require('./helpers/replace-sync');
const replaceAsync = require('./helpers/replace-async');
/**
* Replace in file helper
*/
function replaceInFile(config, cb) {
//Parse config
try {
config = parseConfig(config);
}
catch (error) {
if (cb) {
return cb(error, null);
}
return Promise.reject(error);
}
//Get config
const {files, from, to, dry, verbose} = config;
//Dry run?
//istanbul ignore if: No need to test console logs
if (dry && verbose) {
console.log(chalk.yellow('Dry run, not making actual changes'));
}
//Find paths
return getPathsAsync(files, config)
//Make replacements
.then(paths => Promise.all(
paths.map(file => replaceAsync(file, from, to, config))
))
//Success handler
.then(results => {
if (cb) {
cb(null, results);
}
return results;
})
//Error handler
.catch(error => {
if (cb) {
cb(error);
}
else {
throw error;
}
});
}
/**
* Sync API
*/
function replaceInFileSync(config) {
//Parse config
config = parseConfig(config);
//Get config, paths, and initialize changed files
const {files, from, to, dry, verbose} = config;
const paths = getPathsSync(files, config);
//Dry run?
//istanbul ignore if: No need to test console logs
if (dry && verbose) {
console.log(chalk.yellow('Dry run, not making actual changes'));
}
//Process synchronously and return results
return paths.map(path => replaceSync(path, from, to, config));
};
replaceInFile.replaceInFile = replaceInFile; // Self-reference to support named import
replaceInFile.replaceInFileSync = replaceInFileSync;
replaceInFile.sync = replaceInFileSync;
//Export
module.exports = replaceInFile;