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