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