1 |
|
2 | var normalize, replacer, tmpdir;
|
3 |
|
4 | tmpdir = require('os').tmpdir;
|
5 |
|
6 | normalize = require('path').normalize;
|
7 |
|
8 | replacer = {
|
9 | patterns: {
|
10 | tmpdir: {
|
11 | find: '%tmpdir%',
|
12 | replace: tmpdir,
|
13 | after: normalize
|
14 | },
|
15 | env: {
|
16 | find: /%env:(\w+)%/gi,
|
17 | replace: function(m, g1) {
|
18 | return process.env[g1];
|
19 | }
|
20 | }
|
21 | },
|
22 | createRegex: function(str) {
|
23 | if (typeof str === 'string') {
|
24 | return new RegExp(str, 'gi');
|
25 | } else if (str instanceof RegExp) {
|
26 | return str;
|
27 | } else {
|
28 | throw new Error('This is not a string nor RegExp');
|
29 | }
|
30 | },
|
31 | replace: function(str) {
|
32 | var find, item, key, oldStr, ref;
|
33 | oldStr = str;
|
34 | ref = replacer.patterns;
|
35 | for (key in ref) {
|
36 | item = ref[key];
|
37 | find = replacer.createRegex(item.find);
|
38 | if (find.test(str)) {
|
39 | str = str.replace(find, item.replace);
|
40 | [].concat(item.after).filter(function(i) {
|
41 | return typeof i === 'function';
|
42 | }).forEach(function(fix) {
|
43 | return str = fix(str);
|
44 | });
|
45 | }
|
46 | }
|
47 | return str;
|
48 | }
|
49 | };
|
50 |
|
51 | module.exports = replacer;
|