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