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