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