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