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