1 |
|
2 | 'use strict';
|
3 | var through = require('through2');
|
4 | var path = require('path');
|
5 | var colors = require('ansi-colors');
|
6 |
|
7 | var log = require('../log/logger');
|
8 | var TITLE = 'replace:'
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | function logReplace(n, key, value, file) {
|
18 | log.info(
|
19 | colors.gray(TITLE),
|
20 | colors.dim('√'.repeat(n)),
|
21 | colors.gray.italic(key.toString()),
|
22 | colors.dim.gray('→'),
|
23 | typeof value === 'function' ? colors.cyan(colors.italic('Function:') + (value.name || '')) : colors.underline(value),
|
24 | colors.gray('(' + colors.underline(
|
25 | path.relative(file.base, file.path)
|
26 | ) + ')')
|
27 | )
|
28 | }
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | function multiReplace(opts, replacement, prefix, suffix) {
|
38 | function replace(file, encoding, callback) {
|
39 | var str = file.contents.toString();
|
40 | prefix = prefix || '';
|
41 | suffix = suffix || '';
|
42 | if (file.isBuffer()) {
|
43 | if (replacement === undefined) {
|
44 | console.assert(typeof opts === 'object', 'replace opts should object')
|
45 | for (var key in opts) {
|
46 | var search_key = prefix + key + suffix;
|
47 | var sp = str.split(search_key);
|
48 | if (sp.length > 1) {
|
49 | str = sp.join(opts[key]);
|
50 | logReplace(sp.length - 1, search_key, opts[key], file);
|
51 | }
|
52 | }
|
53 | } else if (opts instanceof RegExp) {
|
54 |
|
55 | |
56 |
|
57 |
|
58 | var n = (str.match(opts) || []).length;
|
59 | if (n > 0) {
|
60 | str = str.replace(opts, replacement);
|
61 | logReplace(n, opts, replacement, file);
|
62 | }
|
63 | } else {
|
64 |
|
65 | var search_key = prefix + opts + suffix;
|
66 | var n = str.split(search_key).length - 1;
|
67 | if (n > 0) {
|
68 |
|
69 | str = str.replace(new RegExp(search_key, 'mg'), replacement);
|
70 | logReplace(n, search_key, replacement, file);
|
71 | }
|
72 |
|
73 | }
|
74 | file.contents = Buffer.from(str);
|
75 | } else if (file.isStream()) {
|
76 | console.error('Streaming not supported')
|
77 | this.emit('error', 'replace:Streaming not supported');
|
78 | return callback('Streaming not supported', file);
|
79 | }
|
80 | callback(null, file);
|
81 | }
|
82 |
|
83 | return through.obj(replace);
|
84 | };
|
85 | module.exports = multiReplace; |
\ | No newline at end of file |