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