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