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