source: Dev/branches/rest-dojo-ui/client/util/buildscripts/jslib/fileUtil.js @ 256

Last change on this file since 256 was 256, checked in by hendrikvanantwerpen, 13 years ago

Reworked project structure based on REST interaction and Dojo library. As
soon as this is stable, the old jQueryUI branch can be removed (it's
kept for reference).

File size: 8.8 KB
Line 
1//Helper functions to deal with file I/O.
2
3var fileUtil = {};
4
5fileUtil.getLineSeparator = function(){
6        //summary: Gives the line separator for the platform.
7        //For web builds override this function.
8        return java.lang.System.getProperty("line.separator"); //Java String
9}
10
11fileUtil.getFilteredFileList = function(/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject, /*boolean?*/dontRecurse){
12        //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
13        //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
14        //and it will be treated as the "include" case.
15        //Ignores files/directories that start with a period (.).
16        var files = [];
17
18        var topDir = startDir;
19        if(!startDirIsJavaObject){
20                topDir = new java.io.File(startDir);
21        }
22
23        var regExpInclude = regExpFilters.include || regExpFilters;
24        var regExpExclude = regExpFilters.exclude || null;
25
26        if(topDir.exists()){
27                var dirFileArray = topDir.listFiles();
28                for (var i = 0; i < dirFileArray.length; i++){
29                        var file = dirFileArray[i];
30                        if(file.isFile()){
31                                var filePath = file.getPath();
32                                if(makeUnixPaths){
33                                        //Make sure we have a JS string.
34                                        filePath = new String(filePath);
35                                        if(filePath.indexOf("/") == -1){
36                                                filePath = filePath.replace(/\\/g, "/");
37                                        }
38                                }
39                               
40                                var ok = true;
41                                if(regExpInclude){
42                                        ok = filePath.match(regExpInclude);
43                                }
44                                if(ok && regExpExclude){
45                                        ok = !filePath.match(regExpExclude);
46                                }
47
48                                if(ok && !file.getName().match(/^\./)){
49                                        files.push(filePath);
50                                }
51                        }else if(file.isDirectory() && !file.getName().match(/^\./) && !dontRecurse){
52                                var dirFiles = this.getFilteredFileList(file, regExpFilters, makeUnixPaths, true);
53                                files.push.apply(files, dirFiles);
54                        }
55                }
56        }
57
58        return files; //Array
59}
60
61
62fileUtil.copyDir = function(/*String*/srcDir, /*String*/destDir, /*RegExp*/regExpFilter, /*boolean?*/onlyCopyNew){
63        //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
64        //file should be copied. Returns a list file name strings of the destinations that were copied.
65        var fileNames = fileUtil.getFilteredFileList(srcDir, regExpFilter, true);
66        var copiedFiles = [];
67       
68        for(var i = 0; i < fileNames.length; i++){
69                var srcFileName = fileNames[i];
70                var destFileName = srcFileName.replace(srcDir, destDir);
71
72                if(fileUtil.copyFile(srcFileName, destFileName, onlyCopyNew)){
73                        copiedFiles.push(destFileName);
74                }
75        }
76
77        return copiedFiles.length ? copiedFiles : null; //Array or null
78}
79
80fileUtil.asyncFixEOLRe= new RegExp(fileUtil.getLineSeparator(), "g");
81
82fileUtil.transformAsyncModule= function(filename, contents) {
83        var match,
84                bundleMatch,
85                moduleId,
86                requireArgs = [],
87                lineSeparator = fileUtil.getLineSeparator(),
88                dojo = { isBrowser:true },
89                getAsyncArgs = function(moduleId_, deps){
90                        if(!deps){
91                                //no moduleId given
92                                deps= moduleId_;
93                        } else {
94                                moduleId= moduleId_;
95                        }
96                        for (var i = 0; i < deps.length; i++) {
97                                if (deps[i]!="require") {
98                                        requireArgs.push(deps[i].replace(/\//g, "."));
99                                }
100                        }
101                }
102        ;
103
104        // the v1.x content in the i18n bundles is bracketed by "//begin v1.x content" and "//end v1.x content"
105        match = contents.match(/(\/\/begin\sv1\.x\scontent)([\s\S]+)(\/\/end\sv1\.x\scontent)/);
106        if(match){
107                return match[2];
108        }
109        // must not be an i18n bundle
110
111        match = contents.match(/\/\/\s*AMD\-ID\s*"([^\n"]+)"/i);
112        moduleId = (match && match[1]) || "";
113        if(moduleId || contents.substring(0, 8) == "define(\""){
114                if((match = contents.match(/^define\(([^\]]+)\]\s*\,[\s\n]*function.+$/m))){
115                        eval("getAsyncArgs(" + match[1] + "])");
116                        if(!moduleId){
117                                logger.info("warning: the module " + filename + " looked like an AMD module, but didn't provide a module id");
118                                return contents;
119                        }
120                        var prefix = "dojo.provide(\"" + moduleId.replace(/\//g, ".") + "\");" + lineSeparator;
121                        for(var req, reqs = requireArgs, i = 0; i<reqs.length; i++){
122                                req = reqs[i];
123                                if(req.substring(0, 5) == "text!"){
124                                        // do nothing
125                                }else if(req.substring(0, 5) == "i18n!"){
126                                        bundleMatch = req.match(/i18n\!(.+)\.nls\.(\w+)/);
127                                        prefix += "dojo.requireLocalization(\"" + bundleMatch[1].replace(/\//g, ".") + "\", \"" +        bundleMatch[2] +        "\");" + lineSeparator;
128                                }else if(req != "dojo" && req != "dijit" && req != "dojox" && !/^dojo\.lib/.test(req)){
129                                        prefix += "dojo.require(\"" + req +     "\");" + lineSeparator;
130                                }
131                        }
132
133                        // strip all module return values that end with the comment "// AMD-result"
134                        contents = contents.replace( /^\s*return\s+.+\/\/\s*AMD-return((\s.+)|(\s*))$/img , "");
135                        var matchLength = match.index + match[0].length + 1;
136                        var contentsLength = contents.search(/\s*return\s+[_a-zA-Z\.0-9]+\s*;\s*(\/\/.+)?\s*\}\);\s*$/);
137                        if(contentsLength == -1){
138                                //logger.info("warning: no return for: " + fileUtil.asyncProvideArg);
139                                contentsLength= contents.search(/\}\);\s*$/);
140                        }
141                        return prefix + lineSeparator + contents.substring(matchLength, contentsLength);
142                } else {
143                        return contents;
144                }
145        } else {
146                return contents;
147        }
148};
149
150fileUtil.copyFile = function(/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew){
151        //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
152        //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
153        var destFile = new java.io.File(destFileName);
154
155        //logger.trace("Src filename: " + srcFileName);
156        //logger.trace("Dest filename: " + destFileName);
157
158        //If onlyCopyNew is true, then compare dates and only copy if the src is newer
159        //than dest.
160        if(onlyCopyNew){
161                var srcFile = new java.io.File(srcFileName);
162                if(destFile.exists() && destFile.lastModified() >= srcFile.lastModified()){
163                        return false; //Boolean
164                }
165        }
166
167        //Make sure destination dir exists.
168        var parentDir = destFile.getParentFile();
169        if(!parentDir.exists()){
170                if(!parentDir.mkdirs()){
171                        throw "Could not create directory: " + parentDir.getAbsolutePath();
172                }
173        }
174
175        if (/.+\.js$/.test(srcFileName)) {
176                fileUtil.saveUtf8File(destFileName, fileUtil.transformAsyncModule(srcFileName, fileUtil.readFile(srcFileName)).replace(fileUtil.asyncFixEOLRe, "\n"));
177        } else {
178                //Java's version of copy file.
179                var srcChannel = new java.io.FileInputStream(srcFileName).getChannel();
180                var destChannel = new java.io.FileOutputStream(destFileName).getChannel();
181                destChannel.transferFrom(srcChannel, 0, srcChannel.size());
182                srcChannel.close();
183                destChannel.close();
184        }
185       
186        return true; //Boolean
187}
188
189fileUtil.readFile = function(/*String*/path, /*String?*/encoding){
190        //summary: reads a file and returns a string
191        encoding = encoding || "utf-8";
192        var file = new java.io.File(path);
193        var lineSeparator = fileUtil.getLineSeparator();
194        var input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding));
195        try{
196                var stringBuffer = new java.lang.StringBuffer();
197                var line = input.readLine();
198
199                // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
200                // http://www.unicode.org/faq/utf_bom.html
201               
202                // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
203                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
204                if(line && line.length() && line.charAt(0) === 0xfeff){
205                        // Eat the BOM, since we've already found the encoding on this file,
206                        // and we plan to concatenating this buffer with others; the BOM should
207                        // only appear at the top of a file.
208                        line = line.substring(1);
209                }
210                while(line !== null){
211                        stringBuffer.append(line);
212                        stringBuffer.append(lineSeparator);
213                        line = input.readLine();
214                }
215                //Make sure we return a JavaScript string and not a Java string.
216                return new String(stringBuffer.toString()); //String
217        }finally{
218                input.close();
219        }
220}
221
222fileUtil.saveUtf8File = function(/*String*/fileName, /*String*/fileContents){
223        //summary: saves a file using UTF-8 encoding.
224        fileUtil.saveFile(fileName, fileContents, "utf-8");
225}
226
227fileUtil.saveFile = function(/*String*/fileName, /*String*/fileContents, /*String?*/encoding){
228        //summary: saves a file.
229        var outFile = new java.io.File(fileName);
230        var outWriter;
231       
232        var parentDir = outFile.getParentFile();
233        if(!parentDir.exists()){
234                if(!parentDir.mkdirs()){
235                        throw "Could not create directory: " + parentDir.getAbsolutePath();
236                }
237        }
238       
239        if(encoding){
240                outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
241        }else{
242                outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
243        }
244
245        var os = new java.io.BufferedWriter(outWriter);
246        try{
247                os.write(fileContents);
248        }finally{
249                os.close();
250        }
251}
252
253fileUtil.deleteFile = function(/*String*/fileName){
254        //summary: deletes a file or directory if it exists.
255        var file = new java.io.File(fileName);
256        if(file.exists()){
257                if(file.isDirectory()){
258                        var files = file.listFiles();
259                        for(var i = 0; i < files.length; i++){
260                                this.deleteFile(files[i]);
261                        }
262                }
263                file["delete"]();
264        }
265}
Note: See TracBrowser for help on using the repository browser.