1 | define(["./fs"], function(fs) { |
---|
2 | var cached= {}; |
---|
3 | |
---|
4 | return function(contents, replacement) { |
---|
5 | var encoding= "utf8"; |
---|
6 | if (replacement instanceof Array) { |
---|
7 | // replacement is a vector of replacement instructions; maybe the first item is an encoding |
---|
8 | if (typeof replacement[0]=="string") { |
---|
9 | encoding= replacement[0]; |
---|
10 | replacement= replacement.slice(1); |
---|
11 | } |
---|
12 | } else { |
---|
13 | // replacement is a single replacement [search, replacement, type] triple |
---|
14 | replacement= [replacement]; |
---|
15 | } |
---|
16 | // at this point, encoding has been determined and replacement is a vector of [search, replacement, type] triples |
---|
17 | |
---|
18 | replacement.forEach(function(item) { |
---|
19 | var |
---|
20 | searchText= item[0], |
---|
21 | replacementText= item[1], |
---|
22 | type= item[2]; |
---|
23 | if (type=="file") { |
---|
24 | // replacementText gives a filename that holds the replacement text |
---|
25 | // TODO add type AMD module |
---|
26 | replacementText= (cached[filename]= cached[filename] || fs.readFileSynch(replacementText, encoding)); |
---|
27 | } |
---|
28 | if (searchText instanceof RegExp) { |
---|
29 | contents= contents.replace(searchText, replacementText); |
---|
30 | } else if (typeof searchText=="function") { |
---|
31 | contents= searchText(contents); |
---|
32 | } else { |
---|
33 | // replace all occurences of searchText with replacementText |
---|
34 | var |
---|
35 | searchTextLength= searchText.length, |
---|
36 | replacementTextLength= replacementText.length, |
---|
37 | start= contents.indexOf(searchText); |
---|
38 | while (start!=-1) { |
---|
39 | contents= contents.substring(0, start) + replacementText + contents.substring(start + searchTextLength); |
---|
40 | start= contents.indexOf(searchText, start + replacementTextLength); |
---|
41 | } |
---|
42 | } |
---|
43 | }); |
---|
44 | return contents; |
---|
45 | }; |
---|
46 | }); |
---|
47 | |
---|