UNPKG

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