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