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