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