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 TextStream      = imports['JSDOC/TextStream.js'].TextStream;
6 TokenReader     = imports['JSDOC/TokenReader.js'].TokenReader;
7 ScopeParser     = imports['JSDOC/ScopeParser.js'].ScopeParser;
8 TokenStream     = imports['JSDOC/TokenStream.js'].TokenStream;
9 CompressWhite   = imports['JSDOC/CompressWhite.js'].CompressWhite;
10
11 GLib = imports.gi.GLib;
12 /**
13  * @namespace JSDOC
14  * @class  Packer
15  * Create a new packer
16  * 
17  * Use with pack.js 
18  * 
19  * 
20  * Usage:
21  * <code>
22  *
23 Packer = imports['JSDOC/Packer.js'].Packer;
24 var x = new  Packer({
25     
26     files : [ "/location/of/file1.js", "/location/of/file2.js", ... ],
27     target : "/tmp/output.js",
28     debugTarget : "/tmp/output.debug.js", // merged file without compression.
29     translateJSON: "/tmp/translate.json",
30     
31     
32 );
33 x.packFiles(
34     "/location/of/temp_batch_dir", 
35     "/location/of/output-compacted-file.js",
36     "/location/of/output-debug-merged-file.js"
37 );
38     
39  *</code> 
40  *
41  * Notes for improving compacting:
42  *  if you add a jsdoc comment 
43  * <code>
44  * /**
45  *   eval:var:avarname
46  *   eval:var:bvarname
47  *   ....
48  * </code>
49  * directly before an eval statement, it will compress all the code around the eval, 
50  * and not rename the variables 'avarname'
51  * 
52  * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
53  * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
54  * 
55  * 
56  * 
57  * Notes for translation
58  *  - translation relies on you using double quotes for strings if they need translating
59  *  - single quoted strings are ignored.
60  * 
61  * Generation of indexFiles
62  *   - translateIndex = the indexfile
63  * 
64  * 
65  * 
66  * 
67
68  */
69 Packer = function(cfg)
70 {
71     
72     XObject.extend(this, cfg);
73     if (!this.files) {
74         throw "No Files";
75     }
76     
77     
78     this.timer =  new Date() * 1;
79     this.packAll();
80     
81  
82 }
83 Packer.prototype = {
84     /**
85      * @prop files {Array} list of files to compress (must be full path)
86      */
87     files : false,
88     /**
89      * @prop target {String} target to write files to - must be full path.
90      */
91     target : '',
92     /**
93      * @prop debugTarget {String} target to write files debug version to (uncompacted)- must be full path.
94      */
95     debugTarget : '', // merged file without compression.
96     /**
97      * @prop tmpDir {String} (optional) where to put the temporary files. 
98      *      if you set this, then files will not be cleaned up
99      */
100     tmpDir : '/tmp',
101     
102     translateJSON : '', // json based list of strings in all files.
103    
104     /**
105      * @prop cleanup {Boolean} (optional) clean up temp files after done - 
106      *    Defaults to false if you set tmpDir, otherwise true.
107      */
108     cleanup : true,  
109     
110     /**
111      * @prop prefix {String} (optional) prefix of directory to be stripped of when
112      *    Calculating md5 of filename 
113      */
114     prefix : '',  
115     out : '', // if no target is specified - then this will contain the result
116     
117     packAll : function()  // do the packing (run from constructor)
118     {
119         
120         //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
121         //File.write(this.transfile, "");
122         if (this.target) {
123             File.write(this.target, "");
124         }
125         
126         if (this.debugTarget) {
127             File.write(this.debugTarget, "");
128         }
129         
130         for(var i=0; i < this.files.length; i++)  {
131             var file = this.files[i];
132             
133             print("reading " +file );
134             if (!File.isFile(file)) {
135                 print("SKIP (is not a file) " + file);
136                 continue;
137             }
138            
139             if (this.debugTarget) {
140                 File.append(this.debugTarget, File.read(file));
141             }
142             // it's a good idea to check with 0 compression to see if the code can parse!!
143             
144             // debug file..
145             //File.append(dout, str +"\n"); 
146             
147        
148             
149             var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
150             
151             
152             // let's see if we have a min file already?
153             // this might happen if tmpDir is set .. 
154             if (true && File.exists(minfile)) {
155                 var mt = File.mtime(minfile);
156                 var ot = File.mtime(file);
157                 print("compare : " + mt + "=>" + ot);
158                 if (mt >= ot) {
159                     continue;
160                     /*
161                     // then the min'files time is > than original..
162                     var str = File.read(minfile);
163                     print("using MIN FILE  "+ minfile);
164                     if (str.length) {
165                         File.append(outpath, str + "\n");
166                     }
167                     
168                     continue;
169                     */
170                 }
171                 
172             }
173             
174             print("COMPRESSING ");
175             //var codeComp = pack(str, 10, 0, 0);
176             if (File.exists(minfile)) {
177                 File.remove(minfile);
178             }
179             var str = File.read(file);
180             var str = this.pack(str, file, minfile);
181             if (str.length) {
182                 File.write(minfile, str);
183             }
184             
185              
186           
187         }  
188         if (this.translateJSON) {
189             
190                
191             print("MERGING LANGUAGE");
192             var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
193             if (this.target) {
194                 File.write(this.target, out);
195             } else {
196                 this.out += out;
197             }
198             
199             
200             
201             File.write(this.translateJSON, "");
202             for(var i=0; i < this.files.length; i++)  {
203                 var file = this.files[i];
204                 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
205                 var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
206                 if (File.exists(transmd5)) {
207                     var str = File.read(transmd5);
208                     if (str.length) {
209                         if (this.target) {
210                             File.append(this.target, str + "\n");
211                         } else {
212                             this.out += str + "\n";
213                         }
214                         
215                     }
216                     if (this.cleanup) {
217                         File.remove(transmd5);
218                     }
219                 }
220                 if (File.exists(transfile)) {
221                     var str = File.read(transfile);
222                     if (str.length) {
223                         File.append(this.translateJSON, str);
224                     }
225                     if (this.cleanup) {
226                         File.remove(transfile);
227                     }
228                 }
229                 
230                
231             }
232         }
233         
234         print("MERGING SOURCE");
235         
236         for(var i=0; i < this.files.length; i++)  {
237             var file = this.files[i];
238             var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
239             
240             
241             if (!File.exists(minfile)) {
242                 continue;
243             }
244             var str = File.read(minfile);
245             print("using MIN FILE  "+ minfile);
246             if (str.length) {
247                 if (this.target) {
248                     File.append(this.target, str + "\n");   
249                 } else {
250                     this.out += str + "\n";
251                 }
252                 
253             }
254             if (this.cleanup) {
255                 File.remove(minfile);
256             }
257             
258         }
259         
260          
261     
262     
263     },
264     /**
265      * Core packing routine  for a file
266      * 
267      * @param str - str source text..
268      * @param fn - filename (for reference?)
269      * @param minfile - min file location...
270      * 
271      */
272     
273     pack : function (str,fn,minfile)
274     {
275     
276         var tr = new  TokenReader(  { keepDocs :true, keepWhite : true,  keepComments : true, sepIdents : true });
277         this.timerPrint("START" + fn);
278         
279         // we can load translation map here...
280         
281         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
282         
283         // at this point we can write a language file...
284         if (this.translateJSON) {
285             
286             this.writeTranslateFile(fn, minfile, toks);
287         }
288         
289         this.activeFile = fn;
290         
291         // and replace if we are generating a different language..
292         
293         this.timerPrint("Tokenized");
294         //return;//
295         var sp = new ScopeParser(new TokenStream(toks));
296         this.timerPrint("Converted to Parser");
297         sp.packer = this;
298         sp.buildSymbolTree();
299         this.timerPrint("Built Sym tree");
300         sp.mungeSymboltree();
301         this.timerPrint("Munged Sym tree");
302         print(sp.warnings.join("\n"));
303         var out = CompressWhite(sp.ts, this);
304         this.timerPrint("Compressed");
305         return out;
306         
307         
308          
309     },
310     
311     timerPrint: function (str) {
312         var ntime = new Date() * 1;
313         var tdif =  ntime -this.timer;
314         this.timer = ntime;
315         print('['+tdif+']'+str);
316     },
317     
318     /**
319      * 
320      * Translation concept...
321      * -> replace text strings with _T....
322      * -> this file will need inserting at the start of the application....
323      * -> we need to generate 2 files, 
324      * -> a reference used to do the translation, and the _T file..
325      * 
326      */
327     
328     writeTranslateFile : function(fn, minfile, toks) 
329     {
330         
331         var map = {};
332         var _this = this;
333         toks.forEach(function (t) {
334             if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
335                 var sval = t.data.substring(1,t.data.length-1);
336                 var ffn = fn.substring(_this.prefix.length);
337                 map[] = _this.md5(ffn + '-' + sval);
338             }
339         })
340         
341         var transfile = minfile + '.lang.trans';
342         var transmd5 = minfile + '.lang';
343         print("writeTranslateFile "  + transfile);
344         var i = 0;
345         var v = '';
346         if (File.exists(transfile)) {
347             File.remove(transfile);
348         }
349         if (File.exists(transmd5)) {
350             File.remove(transmd5);
351         }
352         for(v in map) { i++; break };
353         if (!i ) {
354             return; // no strings in file...
355         }
356         var ffn = fn.substring(this.prefix.length);
357          
358          
359         File.write(transfile, "\n'" + ffn  + "' : {");
360         var l = '';
361         var _tout = {}
362          
363         File.write(transmd5, '');
364         for(v in map) {
365             File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
366             l = ',';
367             // strings are raw... - as the where encoded to start with!!!
368             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
369         }
370         File.append(transfile, "\n},"); // always one trailing..
371         
372          
373     },
374     md5 : function (string)
375     {
376         
377         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
378         
379     },
380     stringHandler : function(tok)
381     {
382         //print("STRING HANDLER");
383        // callback when outputing compressed file, 
384        var data = tok.data;
385         if (!this.translateJSON) {
386          //   print("TURNED OFF");
387             return data;
388         }
389         if (tok.name == 'SINGLE_QUOTE') {
390             return data;
391         }
392         
393         var sval = data.substring(1,data.length-1);
394         // we do not clean up... quoting here!??!!?!?!?!?
395         
396         
397         // blank with tabs or spaces..
398         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
399        //     return tok.outData;
400        // }
401         
402         var sval = tok.data.substring(1,data.length-1);
403         var fn = this.activeFile.substring(this.prefix.length);
404         
405         
406         return '_T["' + this.md5(fn + '-' + sval) + '"]';
407         
408         
409     }
410     
411     
412 };