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