UNPKG

2.82 kBJavaScriptView Raw
1//@ts-check
2'use strict';
3var through = require('through2');
4var path = require('path');
5var colors = require('ansi-colors');
6
7var log = require('../log/logger');
8var TITLE = 'replace:'
9
10/**
11 *
12 * @param {number} n
13 * @param {string|RegExp} key
14 * @param {*} value
15 * @param {object} file
16 */
17function 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 * @param {object|string|RegExp} opts
33 * @param {string|Function} [replacement]
34 * @param {string} [prefix]
35 * @param {string} [suffix]
36 */
37function 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 * @type {number}
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 //@ts-ignore
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};
85module.exports = multiReplace;
\No newline at end of file