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