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['JSDOC/TextStream.js'].TextStream;
6 TokenReader     = imports['JSDOC/TokenReader.js'].TokenReader;
7 ScopeParser     = imports['JSDOC/ScopeParser.js'].ScopeParser;
8 TokenStream     = imports['JSDOC/TokenStream.js'].TokenStream;
9 CompressWhite   = imports['JSDOC/CompressWhite.js'].CompressWhite;
10
11 GLib = imports.gi.GLib;
12 /**
13  * @namespace JSDOC
14  * @class  Packer
15  * Create a new packer
16  * 
17  * Use with pack.js 
18  * 
19  * 
20  * Usage:
21  * <code>
22  *
23 Packer = imports['JSDOC/Packer.js'].Packer;
24 var x = new  Packer({
25     
26     files : [ "/location/of/file1.js", "/location/of/file2.js", ... ],
27     target : "/tmp/output.js",
28     debugTarget : "/tmp/output.debug.js", // merged file without compression.
29     translateJSON: "/tmp/translate.json",
30     
31     
32 );
33 x.packFiles(
34     "/location/of/temp_batch_dir", 
35     "/location/of/output-compacted-file.js",
36     "/location/of/output-debug-merged-file.js"
37 );
38     
39  *</code> 
40  *
41  * Notes for improving compacting:
42  *  if you add a jsdoc comment 
43  * <code>
44  * /**
45  *   eval:var:avarname
46  *   eval:var:bvarname
47  *   ....
48  * </code>
49  * directly before an eval statement, it will compress all the code around the eval, 
50  * and not rename the variables 'avarname'
51  * 
52  * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
53  * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
54  * 
55  * 
56  * 
57  * Notes for translation
58  *  - translation relies on you using double quotes for strings if they need translating
59  *  - single quoted strings are ignored.
60  * 
61  * Generation of indexFiles
62  *   - translateIndex = the indexfile
63  * 
64  * 
65  * 
66  * 
67
68  */
69 Packer = function(cfg)
70 {
71     
72     XObject.extend(this, cfg);
73     if (!this.files) {
74         throw "No Files";
75     }
76     
77     
78     this.timer =  new Date() * 1;
79     this.packAll();
80     
81  
82 }
83 Packer.prototype = {
84     /**
85      * @prop srcfiles {String} file containing a list of files/or classes to use.
86      */
87     srcfiles : false,
88     
89     /**
90      * @prop files {Array} list of files to compress (must be full path)
91      */
92     files : false,
93     /**
94      * @prop target {String} target to write files to - must be full path.
95      */
96     target : '',
97     /**
98      * @prop debugTarget {String} target to write files debug version to (uncompacted)- must be full path.
99      */
100     debugTarget : '', // merged file without compression.
101     /**
102      * @prop tmpDir {String} (optional) where to put the temporary files. 
103      *      if you set this, then files will not be cleaned up
104      */
105     tmpDir : '/tmp',
106     
107     translateJSON : '', // json based list of strings in all files.
108    
109     /**
110      * @prop cleanup {Boolean} (optional) clean up temp files after done - 
111      *    Defaults to false if you set tmpDir, otherwise true.
112      */
113     cleanup : true,  
114     
115     /**
116      * @prop prefix {String} (optional) prefix of directory to be stripped of when
117      *    Calculating md5 of filename 
118      */
119     prefix : '',  
120     out : '', // if no target is specified - then this will contain the result
121     
122     packAll : function()  // do the packing (run from constructor)
123     {
124         
125         //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
126         //File.write(this.transfile, "");
127         if (this.target) {
128             File.write(this.target, "");
129         }
130         
131         if (this.debugTarget) {
132             File.write(this.debugTarget, "");
133         }
134         
135         for(var i=0; i < this.files.length; i++)  {
136             var file = this.files[i];
137             
138             print("reading " +file );
139             if (!File.isFile(file)) {
140                 print("SKIP (is not a file) " + file);
141                 continue;
142             }
143            
144             if (this.debugTarget) {
145                 File.append(this.debugTarget, File.read(file));
146             }
147             // it's a good idea to check with 0 compression to see if the code can parse!!
148             
149             // debug file..
150             //File.append(dout, str +"\n"); 
151             
152        
153             
154             var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
155             
156             
157             // let's see if we have a min file already?
158             // this might happen if tmpDir is set .. 
159             if (true && File.exists(minfile)) {
160                 var mt = File.mtime(minfile);
161                 var ot = File.mtime(file);
162                 print("compare : " + mt + "=>" + ot);
163                 if (mt >= ot) {
164                     continue;
165                     /*
166                     // then the min'files time is > than original..
167                     var str = File.read(minfile);
168                     print("using MIN FILE  "+ minfile);
169                     if (str.length) {
170                         File.append(outpath, str + "\n");
171                     }
172                     
173                     continue;
174                     */
175                 }
176                 
177             }
178             
179             print("COMPRESSING ");
180             //var codeComp = pack(str, 10, 0, 0);
181             if (File.exists(minfile)) {
182                 File.remove(minfile);
183             }
184             var str = File.read(file);
185             var str = this.pack(str, file, minfile);
186             if (str.length) {
187                 File.write(minfile, str);
188             }
189             
190              
191           
192         }  
193         if (this.translateJSON) {
194             
195                
196             print("MERGING LANGUAGE");
197             var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
198             if (this.target) {
199                 File.write(this.target, out);
200             } else {
201                 this.out += out;
202             }
203             
204             
205             
206             File.write(this.translateJSON, "");
207             for(var i=0; i < this.files.length; i++)  {
208                 var file = this.files[i];
209                 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
210                 var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
211                 if (File.exists(transmd5)) {
212                     var str = File.read(transmd5);
213                     if (str.length) {
214                         if (this.target) {
215                             File.append(this.target, str + "\n");
216                         } else {
217                             this.out += str + "\n";
218                         }
219                         
220                     }
221                     if (this.cleanup) {
222                         File.remove(transmd5);
223                     }
224                 }
225                 if (File.exists(transfile)) {
226                     var str = File.read(transfile);
227                     if (str.length) {
228                         File.append(this.translateJSON, str);
229                     }
230                     if (this.cleanup) {
231                         File.remove(transfile);
232                     }
233                 }
234                 
235                
236             }
237         }
238         
239         print("MERGING SOURCE");
240         
241         for(var i=0; i < this.files.length; i++)  {
242             var file = this.files[i];
243             var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
244             
245             
246             if (!File.exists(minfile)) {
247                 continue;
248             }
249             var str = File.read(minfile);
250             print("using MIN FILE  "+ minfile);
251             if (str.length) {
252                 if (this.target) {
253                     File.append(this.target, str + "\n");   
254                 } else {
255                     this.out += str + "\n";
256                 }
257                 
258             }
259             if (this.cleanup) {
260                 File.remove(minfile);
261             }
262             
263         }
264         
265          
266     
267     
268     },
269     /**
270      * Core packing routine  for a file
271      * 
272      * @param str - str source text..
273      * @param fn - filename (for reference?)
274      * @param minfile - min file location...
275      * 
276      */
277     
278     pack : function (str,fn,minfile)
279     {
280     
281         var tr = new  TokenReader(  { keepDocs :true, keepWhite : true,  keepComments : true, sepIdents : true });
282         this.timerPrint("START" + fn);
283         
284         // we can load translation map here...
285         
286         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
287         
288         // at this point we can write a language file...
289         if (this.translateJSON) {
290             
291             this.writeTranslateFile(fn, minfile, toks);
292         }
293         
294         this.activeFile = fn;
295         
296         // and replace if we are generating a different language..
297         
298         this.timerPrint("Tokenized");
299         //return;//
300         var sp = new ScopeParser(new TokenStream(toks));
301         this.timerPrint("Converted to Parser");
302         sp.packer = this;
303         sp.buildSymbolTree();
304         this.timerPrint("Built Sym tree");
305         sp.mungeSymboltree();
306         this.timerPrint("Munged Sym tree");
307         print(sp.warnings.join("\n"));
308         var out = CompressWhite(sp.ts, this);
309         this.timerPrint("Compressed");
310         return out;
311         
312         
313          
314     },
315     
316     timerPrint: function (str) {
317         var ntime = new Date() * 1;
318         var tdif =  ntime -this.timer;
319         this.timer = ntime;
320         print('['+tdif+']'+str);
321     },
322     
323     /**
324      * 
325      * Translation concept...
326      * -> replace text strings with _T....
327      * -> this file will need inserting at the start of the application....
328      * -> we need to generate 2 files, 
329      * -> a reference used to do the translation, and the _T file..
330      * 
331      */
332     
333     writeTranslateFile : function(fn, minfile, toks) 
334     {
335         
336         var map = {};
337         var _this = this;
338         toks.forEach(function (t) {
339             if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
340                 var sval = t.data.substring(1,t.data.length-1);
341                 var ffn = fn.substring(_this.prefix.length);
342                 map[sval] = _this.md5(ffn + '-' + sval);
343             }
344         })
345         
346         var transfile = minfile + '.lang.trans';
347         var transmd5 = minfile + '.lang';
348         print("writeTranslateFile "  + transfile);
349         var i = 0;
350         var v = '';
351         if (File.exists(transfile)) {
352             File.remove(transfile);
353         }
354         if (File.exists(transmd5)) {
355             File.remove(transmd5);
356         }
357         for(v in map) { i++; break };
358         if (!i ) {
359             return; // no strings in file...
360         }
361         var ffn = fn.substring(this.prefix.length);
362          
363          
364         File.write(transfile, "\n'" + ffn  + "' : {");
365         var l = '';
366         var _tout = {}
367          
368         File.write(transmd5, '');
369         for(v in map) {
370             File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
371             l = ',';
372             // strings are raw... - as the where encoded to start with!!!
373             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
374         }
375         File.append(transfile, "\n},"); // always one trailing..
376         
377          
378     },
379     md5 : function (string)
380     {
381         
382         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
383         
384     },
385     stringHandler : function(tok)
386     {
387         //print("STRING HANDLER");
388        // callback when outputing compressed file, 
389        var data = tok.data;
390         if (!this.translateJSON) {
391          //   print("TURNED OFF");
392             return data;
393         }
394         if (tok.name == 'SINGLE_QUOTE') {
395             return data;
396         }
397         
398         var sval = data.substring(1,data.length-1);
399         // we do not clean up... quoting here!??!!?!?!?!?
400         
401         
402         // blank with tabs or spaces..
403         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
404        //     return tok.outData;
405        // }
406         
407         var sval = tok.data.substring(1,data.length-1);
408         var fn = this.activeFile.substring(this.prefix.length);
409         
410         
411         return '_T["' + this.md5(fn + '-' + sval) + '"]';
412         
413         
414     }
415     
416     
417 };