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