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