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