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