JSDOC/CompressWhite.js
[gnome.introspection-doc-generator] / JSDOC / Packer.js
1 // <script type="text/javascript">
2 XObject = imports.XObject.XObject;
3 File = imports.File.File;
4
5 TokenReader = imports['JSDOC/TokenReader.js'].TokenReader;
6 ScopeParser = imports['JSDOC/ScopeParser.js'].ScopeParser;
7 TokenStream = imports['JSDOC/TokenStream.js'].TokenStream;
8 /**
9  * @namespace JSDOC
10  * @class  Packer
11  * Create a new packer
12  * 
13  * Usage:
14  * <code>
15  *
16 Packer = imports['JSDOC/Packer.js'].Packer;
17 var x = new  Packer(
18     [ "/location/of/file1.js", "/location/of/file2.js", ... ],
19     "/location/of"
20 );
21 x.packFiles(
22     "/location/of/temp_batch_dir", 
23     "/location/of/output-compacted-file.js",
24     "/location/of/output-debug-merged-file.js"
25 );
26     
27  *</code> 
28  *
29  * Notes for improving compacting:
30  *  if you add a jsdoc comment 
31  * <code>
32  * /**
33  *   eval:var:avarname
34  *   eval:var:bvarname
35  *   ....
36  * </code>
37  * directly before an eval statement, it will compress all the code around the eval, 
38  * and not rename the variables 'avarname'
39  * 
40  * Dont try running this on a merged uncompressed large file - it's horrifically slow.
41  * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
42  * 
43  * 
44  * 
45  * @param {Array} files List of Files - MUST BE WITH ABSOLUTE PATH eg. [ '/usr/src/xyz/abc.js', .... ]
46  * @param {String} source_path top level directory of source (used to work out the relative names for the minimized temp files)
47  */
48 Packer = function(files, spath)
49 {
50     this.files = files;
51     this.spath  = spath; // source path
52     this.aliasList = { }; // list of maps Roo.asdfasdfasf => Roo.A1
53     this.timer =  new Date() * 1;
54     this.translate = true;
55 }
56 Packer.prototype = {
57     
58     bpath : '',
59     
60     // set to false to stop translation happening..
61     
62     /**
63      * Pack the files.
64      * 
65      * @param {String} batch_path location of batched temporary min files.
66      * @param {String} compressed_file eg. roo-all.js
67      * @param {String} debug_file eg. roo-debug.js
68      * 
69      */
70     
71     packFiles : function(bpath, allfile, debugfile) {
72         var str;
73         var spath = this.spath;
74         var files = this.files;
75         this.bpath = bpath;
76         // old var names - fixme..
77         var dout = debugfile;
78         //File.write(dout, "");
79         
80         var outpath = allfile;
81       
82         var transfile = bpath + '/_translation_.js';
83         //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
84         //File.write(this.transfile, "");
85         File.write(dout, "");
86         File.write(allfile, "");
87         for(var i=0; i < files.length; i++)  {
88             
89             print("reading " +files[i] );
90             if (!File.exists(files[i])) {
91                 print("SKIP (does not exist) " + files[i]);
92                 continue;
93             }
94            
95             
96             File.append(dout, File.read(files[i]));
97             // it's a good idea to check with 0 compression to see if the code can parse!!
98             
99             // debug file..
100             //File.append(dout, str +"\n"); 
101             
102        
103             
104             var minfile = bpath + '/' +files[i].substr(spath.length+1).replace(/\//g, '.');
105             var transfile = bpath + '/' +files[i].substr(spath.length+1).replace(/\//g, '.') +'.lang';        
106             // let's see if we have a min file already?
107             if (true && File.exists(minfile)) {
108                 var mt = File.mtime(minfile);
109                 var ot = File.mtime(files[i]);
110                 print("compare : " + mt + "=>" + ot);
111                 if (mt >= ot) {
112                     continue;
113                     /*
114                     // then the min'files time is > than original..
115                     var str = File.read(minfile);
116                     print("using MIN FILE  "+ minfile);
117                     if (str.length) {
118                         File.append(outpath, str + "\n");
119                     }
120                     
121                     continue;
122                     */
123                 }
124                 
125             }
126             
127             print("COMPRESSING ");
128             //var codeComp = pack(str, 10, 0, 0);
129             var str = File.read(files[i]);
130             var str = this.pack(str, files[i], minfile);
131             if (str.length) {
132                 File.write(minfile, str);   
133             }
134             
135              
136             
137             //var str = File.read(minfile);
138             //print("using MIN FILE  "+ minfile);
139             //File.append(outpath, str + "\n");
140             //this.timerPrint("Wrote Files");
141             /*
142             if (codeComp.length) {
143                 //print(codeComp);
144                 
145                 File.append(outpath, codeComp+"\n");
146                 File.write(minfile, codeComp);
147             }
148             */
149             //print(codeComp);
150            // if (i > 10) return;
151         }  
152         if (this.translate) {
153             
154                
155             print("MERGING LANGUAGE");
156             File.write(outpath, "if (typeof(_T) == 'undefined') { _T={};}\n");
157             
158             var transfileAll =  bpath + '/_translation_.js';
159             File.write(transfileAll, "");
160             for(var i=0; i < files.length; i++)  {
161                 var transfile= bpath + '/' +files[i].substr(spath.length+1).replace(/\//g, '.') +'.lang.trans';
162                 var transmd5 = bpath + '/' +files[i].substr(spath.length+1).replace(/\//g, '.') +'.lang';
163                 if (File.exists(transmd5)) {
164                     var str = File.read(transmd5);
165                     if (str.length) {
166                         File.append(outpath, str + "\n");
167                     }
168                 }
169                 if (File.exists(transfile)) {
170                     var str = File.read(transfile);
171                     if (str.length) {
172                         File.append(transfileAll, str);
173                     }
174                 }
175                 
176                
177             }
178         }
179         print("MERGING SOURCE");
180         
181         for(var i=0; i < files.length; i++)  {
182          
183             var minfile = bpath + '/' +files[i].substr(spath.length+1).replace(/\//g, '.');
184             if (!File.exists(minfile)) {
185                 continue;
186             }
187             var str = File.read(minfile);
188             print("using MIN FILE  "+ minfile);
189             if (str.length) {
190                 File.append(outpath, str + "\n");
191             }
192         }
193         
194         
195         //File.append(dout, "\n");// end the function 
196         
197     
198     
199     },
200     /**
201      * Core packing routine  for a file
202      * 
203      * @param str - str source text..
204      * @param fn - filename (for reference?)
205      * @param minfile - min file location...
206      * 
207      */
208     
209     pack : function (str,fn,minfile)
210     {
211     
212         var tr = new  TokenReader();
213         this.timerPrint("START" + fn);
214         
215         // we can load translation map here...
216         
217         var toks = tr.tokenize(str,false); // dont merge xxx + . + yyyy etc.
218         
219         // at this point we can write a language file...
220         if (this.translate) {
221             this.writeTranslateFile(fn, minfile, tr.translateMap);
222         }
223         
224         this.activeFile = fn;
225         
226         // and replace if we are generating a different language..
227         
228         
229         
230         
231         this.timerPrint("Tokenized");
232         //return;//
233         var sp = new ScopeParser(new TokenStream(toks, str.length));
234         this.timerPrint("Converted to Parser");
235         sp.packer = this;
236         sp.buildSymbolTree();
237         this.timerPrint("Built Sym tree");
238         sp.mungeSymboltree();
239         this.timerPrint("Munged Sym tree");
240         print(sp.warnings.join("\n"));
241         var out = JSDOC.CompressWhite(sp.ts, this);
242         this.timerPrint("Compressed");
243         return out;
244         
245     },
246     
247     timerPrint: function (str) {
248         var ntime = new Date() * 1;
249         var tdif =  ntime -this.timer;
250         this.timer = ntime;
251         print('['+tdif+']'+str);
252     },
253     
254     /**
255      * 
256      * Translation concept...
257      * -> replace text strings with _T....
258      * -> this file will need inserting at the start of the application....
259      * -> we need to generate 2 files, 
260      * -> a reference used to do the translation, and the _T file..
261      * 
262      */
263     
264     writeTranslateFile : function(fn, minfile, map) 
265     {
266         var transfile = minfile + '.lang.trans';
267         var transmd5 = minfile + '.lang';
268         var i = 0;
269         var v = '';
270         if (File.exists(transfile)) {
271             File.remove(transfile);
272         }
273         if (File.exists(transmd5)) {
274             File.remove(transmd5);
275         }
276         for(v in map) { i++; break };
277         if (!i ) {
278             return; // no strings in file...
279         }
280         var ff = fn.split('/');
281         var ffn = ff[ff.length-1];
282          
283          
284         File.write(transfile, "\n" + ffn.toSource() + " : {");
285         var l = '';
286         var _tout = {}
287          
288         File.write(transmd5, '');
289         for(v in map) {
290             File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
291             l = ',';
292             // strings are raw... - as the where encoded to start with!!!
293             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
294         }
295         File.append(transfile, "\n},"); // always one trailing..
296         
297          
298     },
299     md5 : function (string)
300     {
301         
302         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
303         
304     }
305     stringHandler : function(tok)
306     {
307         //print("STRING HANDLER");
308        // callback when outputing compressed file, 
309         if (!this.translate) {
310          //   print("TURNED OFF");
311             return tok.outData;
312         }
313         if (tok.qc != '"') {
314             return tok.outData;
315         }
316         var sval = tok.data.substring(1,tok.data.length-1);
317         // blank with tabs or spaces..
318         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
319        //     return tok.outData;
320        // }
321         
322         
323         
324         
325         var ff = this.activeFile.split('/');
326         var ffn = ff[ff.length-1];
327         return '_T["' + this.md5(ffn + '-' + sval) + '"]';
328         
329         
330     }
331     
332     
333 });