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