-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (76 loc) · 2.56 KB
/
index.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
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const globby = require('globby');
const wasRequired = require.main !== module;
const f = (content, ...changes) => {
const format = {
bold: '\x1b[1m',
red: '\x1b[31m',
green: '\x1b[32m',
};
return changes.reduce((string, change) => {
if (format[change]) {
return `${format[change]}${string}\x1b[0m`;
}
return string;
}, content);
};
const find = (arr, str) => {
return arr.indexOf(str) !== -1;
};
const replace = (path, string, pattern, replacement, callback) => {
const logs = [];
if (string.match(pattern)) {
logs.push(f(path, 'bold'));
string = string.replace(pattern, (match) => {
const newValue = match.replace(pattern, replacement);
logs.push([' ', f(match, 'bold', 'red'), '→', f(newValue, 'bold', 'green')]);
return newValue;
});
logs.push('');
}
callback(logs);
return string;
};
const handler = (glob, pattern, replacement, isPreview, isSilent) => {
console.log('');
globby.sync(glob).forEach((path) => {
const contents = fs.readFileSync(path, 'utf-8');
const newContents = replace(path, contents, pattern, replacement, (logs) => {
if (!isSilent) {
logs.forEach((line) => {
console.log([].concat(line).join(' '));
});
}
});
if (!isPreview) {
fs.writeFileSync(path, newContents);
}
});
};
const cli = (args) => {
if (args.length < 3) {
console.log(f('\n usage: emn <glob> <pattern> <replacement> [--preview] [--silent]\n', 'bold', 'red'));
return;
}
const [glob, pattern, replacement, ...options] = args;
const regexPattern = pattern.match(/^\/([^]*)\/(\w+)?$/);
if (regexPattern === null) {
console.log(f(`\n Invalid regex expression: ${pattern}\n`, 'bold', 'red'));
return;
}
const [, body, flags] = regexPattern;
const formattedReplacement = replacement.replace(/\\(\d+)/g, '$$1');
const isPreview = find(options, '--preview') || find(options, '-p');
const isSilent = find(options, '--silent') || find(options, '-s');
handler(glob, new RegExp(body, flags), formattedReplacement, isPreview, isSilent);
};
if (wasRequired) {
module.exports = (glob, pattern, replacement, options = {}) => {
const {isPreview, isSilent} = options;
handler(glob, pattern, replacement, isPreview, isSilent);
};
} else {
cli(process.argv.slice(2));
};