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