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