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