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     
103     print(this);
104     Seed.quit();
105     
106     this.timer =  new Date() * 1;
107     this.packAll();
108     
109  
110 }
111 Packer.prototype = {
112     /**
113      * @cfg {String} srcfiles file containing a list of files/or classes to use.
114      */
115     srcfile : false,
116     
117     /**
118      * @cfg {Array} files list of files to compress (must be full path)
119      */
120     files : false,
121     /**
122      * @cfg {String} target to write files to - must be full path.
123      */
124     target : '',
125     /**
126      * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
127      * and enables translation toolkit.
128      */
129     autoBuild : false,
130      /**
131      * @cfg {String} module used with autoBuild to force a file name
132      */
133     module: false,
134     /**
135      * @cfg {String} debugTargettarget to write files debug version to (uncompacted)- must be full path.
136      */
137     debugTarget : '', // merged file without compression.
138     /**
139      * @cfg {String} tmpDir  (optional) where to put the temporary files. 
140      *      if you set this, then files will not be cleaned up
141      */
142     tmpDir : '/tmp',
143     
144     translateJSON : '', // json based list of strings in all files.
145    
146     /**
147      * @cfg {Boolean} cleanup  (optional) clean up temp files after done - 
148      *    Defaults to false if you set tmpDir, otherwise true.
149      */
150     cleanup : true,  
151     
152     /**
153      * @cfg {String} prefix (optional) prefix of directory to be stripped of when
154      *    Calculating md5 of filename 
155      */
156     prefix : '',  
157     out : '', // if no target is specified - then this will contain the result
158     
159     /**
160      * load a dependancy list -f option
161      * @param {String} srcfile sourcefile to parse
162      * 
163      */
164     
165     loadSourceFile : function(srcfile)
166     {
167         var lines = File.read(srcfile).split("\n");
168         var _this = this;
169         lines.forEach(function(f) {
170             
171             if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
172                 return;
173             }
174             if (/\.js$/.test(f)) {
175                 _this.files.push( f);
176                 // js file..
177                 return;
178             }
179             
180             //println("ADD"+ f.replace(/\./g, '/'));
181             var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
182             if (_this.files.indexOf(f) > -1) {
183                 return;
184             }
185             _this.files.push( add );
186             
187         })
188     },
189     
190     
191     packAll : function()  // do the packing (run from constructor)
192     {
193         
194         //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
195         //File.write(this.transfile, "");
196         if (this.target) {
197             File.write(this.target, "");
198         }
199         
200         if (this.debugTarget) {
201             File.write(this.debugTarget, "");
202         }
203         
204         for(var i=0; i < this.files.length; i++)  {
205             var file = this.files[i];
206             
207             print("reading " +file );
208             if (!File.isFile(file)) {
209                 print("SKIP (is not a file) " + file);
210                 continue;
211             }
212            
213             if (this.debugTarget) {
214                 File.append(this.debugTarget, File.read(file));
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(/\//g, '.');
224             
225             
226             // let's see if we have a min file already?
227             // this might happen if tmpDir is set .. 
228             if (true && File.exists(minfile)) {
229                 var mt = File.mtime(minfile);
230                 var ot = File.mtime(file);
231                 print("compare : " + mt + "=>" + ot);
232                 if (mt >= ot) {
233                     continue;
234                     /*
235                     // then the min'files time is > than original..
236                     var str = File.read(minfile);
237                     print("using MIN FILE  "+ minfile);
238                     if (str.length) {
239                         File.append(outpath, str + "\n");
240                     }
241                     
242                     continue;
243                     */
244                 }
245                 
246             }
247             
248             print("COMPRESSING ");
249             //var codeComp = pack(str, 10, 0, 0);
250             if (File.exists(minfile)) {
251                 File.remove(minfile);
252             }
253             var str = File.read(file);
254             var str = this.pack(str, file, minfile);
255             if (str.length) {
256                 File.write(minfile, str);
257             }
258             
259              
260           
261         }  
262         if (this.translateJSON) {
263             
264                
265             print("MERGING LANGUAGE");
266             var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
267             if (this.target) {
268                 File.write(this.target, out);
269             } else {
270                 this.out += out;
271             }
272             
273             
274             
275             File.write(this.translateJSON, "");
276             for(var i=0; i < this.files.length; i++)  {
277                 var file = this.files[i];
278                 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
279                 var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
280                 if (File.exists(transmd5)) {
281                     var str = File.read(transmd5);
282                     if (str.length) {
283                         if (this.target) {
284                             File.append(this.target, str + "\n");
285                         } else {
286                             this.out += str + "\n";
287                         }
288                         
289                     }
290                     if (this.cleanup) {
291                         File.remove(transmd5);
292                     }
293                 }
294                 if (File.exists(transfile)) {
295                     var str = File.read(transfile);
296                     if (str.length) {
297                         File.append(this.translateJSON, str);
298                     }
299                     if (this.cleanup) {
300                         File.remove(transfile);
301                     }
302                 }
303                 
304                
305             }
306         }
307         
308         print("MERGING SOURCE");
309         
310         for(var i=0; i < this.files.length; i++)  {
311             var file = this.files[i];
312             var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
313             
314             
315             if (!File.exists(minfile)) {
316                 continue;
317             }
318             var str = File.read(minfile);
319             print("using MIN FILE  "+ minfile);
320             if (str.length) {
321                 if (this.target) {
322                     File.append(this.target, str + "\n");   
323                 } else {
324                     this.out += str + "\n";
325                 }
326                 
327             }
328             if (this.cleanup) {
329                 File.remove(minfile);
330             }
331             
332         }
333         
334          
335     
336     
337     },
338     /**
339      * Core packing routine  for a file
340      * 
341      * @param str - str source text..
342      * @param fn - filename (for reference?)
343      * @param minfile - min file location...
344      * 
345      */
346     
347     pack : function (str,fn,minfile)
348     {
349     
350         var tr = new  TokenReader(  { 
351             keepDocs :true, 
352             keepWhite : true,  
353             keepComments : true, 
354             sepIdents : true,
355             collapseWhite : false
356         });
357         this.timerPrint("START" + fn);
358         
359         // we can load translation map here...
360         
361         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
362         
363         // at this point we can write a language file...
364         if (this.translateJSON) {
365             
366             this.writeTranslateFile(fn, minfile, toks);
367         }
368         
369         this.activeFile = fn;
370         
371         // and replace if we are generating a different language..
372         
373         this.timerPrint("Tokenized");
374         //var ts = new TokenStream(toks);
375         //print(JSON.stringify(toks, null,4 )); Seed.quit();
376         var ts = new Collapse(toks);
377        // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
378         //return;//
379         var sp = new ScopeParser(ts);
380         this.timerPrint("Converted to Parser");
381         sp.packer = this;
382         sp.buildSymbolTree();
383         this.timerPrint("Built Sym tree");
384         sp.mungeSymboltree();
385         this.timerPrint("Munged Sym tree");
386         print(sp.warnings.join("\n"));
387         
388         
389         //var out = CompressWhite(new TokenStream(toks), this, true); // do not kill whitespace..
390         var out = CompressWhite(new TokenStream(toks), this, false);
391         this.timerPrint("Compressed");
392         return out;
393         
394         
395          
396     },
397     
398     timerPrint: function (str) {
399         var ntime = new Date() * 1;
400         var tdif =  ntime -this.timer;
401         this.timer = ntime;
402         print('['+tdif+']'+str);
403     },
404     
405     /**
406      * 
407      * Translation concept...
408      * -> replace text strings with _T....
409      * -> this file will need inserting at the start of the application....
410      * -> we need to generate 2 files, 
411      * -> a reference used to do the translation, and the _T file..
412      * 
413      */
414     
415     writeTranslateFile : function(fn, minfile, toks) 
416     {
417         
418         var map = {};
419         var _this = this;
420         toks.forEach(function (t) {
421             if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
422                 var sval = t.data.substring(1,t.data.length-1);
423                 var ffn = fn.substring(_this.prefix.length);
424                 map[sval] = _this.md5(ffn + '-' + sval);
425             }
426         })
427         
428         var transfile = minfile + '.lang.trans';
429         var transmd5 = minfile + '.lang';
430         print("writeTranslateFile "  + transfile);
431         var i = 0;
432         var v = '';
433         if (File.exists(transfile)) {
434             File.remove(transfile);
435         }
436         if (File.exists(transmd5)) {
437             File.remove(transmd5);
438         }
439         for(v in map) { i++; break };
440         if (!i ) {
441             return; // no strings in file...
442         }
443         var ffn = fn.substring(this.prefix.length);
444          
445          
446         File.write(transfile, "\n'" + ffn  + "' : {");
447         var l = '';
448         var _tout = {}
449          
450         File.write(transmd5, '');
451         for(v in map) {
452             if (!v.length) {
453                 continue;
454             }
455             File.append(transfile, l + "\n\t" + JSON.stringify(v) + " : " + JSON.stringify(v));
456             l = ',';
457             // strings are raw... - as the where encoded to start with!!!
458             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]='+JSON.stringify(v)+";\n");
459         }
460         File.append(transfile, "\n},"); // always one trailing..
461         
462          
463     },
464     md5 : function (string)
465     {
466         
467         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
468         
469     },
470     stringHandler : function(tok)
471     {
472         //print("STRING HANDLER");
473        // callback when outputing compressed file, 
474        var data = tok.data;
475         if (!this.translateJSON) {
476          //   print("TURNED OFF");
477             return data;
478         }
479         if (tok.name == 'SINGLE_QUOTE') {
480             return data;
481         }
482         
483         var sval = data.substring(1,data.length-1);
484         // we do not clean up... quoting here!??!!?!?!?!?
485         
486         
487         // blank with tabs or spaces..
488         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
489        //     return tok.outData;
490        // }
491         
492         var sval = tok.data.substring(1,data.length-1);
493         var fn = this.activeFile.substring(this.prefix.length);
494         
495         
496         return '_T["' + this.md5(fn + '-' + sval) + '"]';
497         
498         
499     }
500     
501     
502 };