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