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