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 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(file));
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 + '/' +file.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(file);
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(file);
176             var str = this.pack(str, file, minfile);
177             if (str.length) {
178                 File.write(minfile, str);
179             }
180             
181              
182           
183         }  
184         if (this.translateJSON) {
185             
186                
187             print("MERGING LANGUAGE");
188             var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
189             if (this.target) {
190                 File.write(this.target, out);
191             } else {
192                 this.out += out;
193             }
194             
195             
196             
197             File.write(this.translateJSON, "");
198             for(var i=0; i < this.files.length; i++)  {
199                 var file = this.files[i];
200                 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
201                 var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
202                 if (File.exists(transmd5)) {
203                     var str = File.read(transmd5);
204                     if (str.length) {
205                         if (this.target) {
206                             File.append(this.target, str + "\n");
207                         } else {
208                             this.out += str + "\n";
209                         }
210                         
211                     }
212                     if (this.cleanup) {
213                         File.remove(transmd5);
214                     }
215                 }
216                 if (File.exists(transfile)) {
217                     var str = File.read(transfile);
218                     if (str.length) {
219                         File.append(this.translateJSON, str);
220                     }
221                     if (this.cleanup) {
222                         File.remove(transfile);
223                     }
224                 }
225                 
226                
227             }
228         }
229         
230         print("MERGING SOURCE");
231         
232         for(var i=0; i < this.files.length; i++)  {
233             var file = this.files[i];
234             var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
235             
236             
237             if (!File.exists(minfile)) {
238                 continue;
239             }
240             var str = File.read(minfile);
241             print("using MIN FILE  "+ minfile);
242             if (str.length) {
243                 if (this.target) {
244                     File.append(this.target, str + "\n");   
245                 } else {
246                     this.out += str + "\n";
247                 }
248                 
249             }
250             if (this.cleanup) {
251                 File.remove(minfile);
252             }
253             
254         }
255         
256          
257     
258     
259     },
260     /**
261      * Core packing routine  for a file
262      * 
263      * @param str - str source text..
264      * @param fn - filename (for reference?)
265      * @param minfile - min file location...
266      * 
267      */
268     
269     pack : function (str,fn,minfile)
270     {
271     
272         var tr = new  TokenReader(  { keepDocs :true, keepWhite : true,  keepComments : true, sepIdents : true });
273         this.timerPrint("START" + fn);
274         
275         // we can load translation map here...
276         
277         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
278         
279         // at this point we can write a language file...
280         if (this.translateJSON) {
281             this.writeTranslateFile(fn, minfile, tr.translateMap);
282         }
283         
284         this.activeFile = fn;
285         
286         // and replace if we are generating a different language..
287         
288         this.timerPrint("Tokenized");
289         //return;//
290         var sp = new ScopeParser(new TokenStream(toks));
291         this.timerPrint("Converted to Parser");
292         sp.packer = this;
293         sp.buildSymbolTree();
294         this.timerPrint("Built Sym tree");
295         sp.mungeSymboltree();
296         this.timerPrint("Munged Sym tree");
297         print(sp.warnings.join("\n"));
298         var out = CompressWhite(sp.ts, this);
299         this.timerPrint("Compressed");
300         return out;
301         
302         
303          
304     },
305     
306     timerPrint: function (str) {
307         var ntime = new Date() * 1;
308         var tdif =  ntime -this.timer;
309         this.timer = ntime;
310         print('['+tdif+']'+str);
311     },
312     
313     /**
314      * 
315      * Translation concept...
316      * -> replace text strings with _T....
317      * -> this file will need inserting at the start of the application....
318      * -> we need to generate 2 files, 
319      * -> a reference used to do the translation, and the _T file..
320      * 
321      */
322     
323     writeTranslateFile : function(fn, minfile, map) 
324     {
325         var transfile = minfile + '.lang.trans';
326         var transmd5 = minfile + '.lang';
327         var i = 0;
328         var v = '';
329         if (File.exists(transfile)) {
330             File.remove(transfile);
331         }
332         if (File.exists(transmd5)) {
333             File.remove(transmd5);
334         }
335         for(v in map) { i++; break };
336         if (!i ) {
337             return; // no strings in file...
338         }
339         var ff = fn.split('/');
340         var ffn = ff[ff.length-1];
341          
342          
343         File.write(transfile, "\n" + ffn.toSource() + " : {");
344         var l = '';
345         var _tout = {}
346          
347         File.write(transmd5, '');
348         for(v in map) {
349             File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
350             l = ',';
351             // strings are raw... - as the where encoded to start with!!!
352             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
353         }
354         File.append(transfile, "\n},"); // always one trailing..
355         
356          
357     },
358     md5 : function (string)
359     {
360         
361         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
362         
363     },
364     stringHandler : function(tok)
365     {
366         //print("STRING HANDLER");
367        // callback when outputing compressed file, 
368         if (!this.translateJSON) {
369          //   print("TURNED OFF");
370             return tok.outData;
371         }
372         if (tok.name == SINGLE_QUOTE) {
373             return tok.outData;
374         }
375         var sval = tok.data.substring(1,tok.data.length-1);
376         // we do not clean up... quoting here!??!!?!?!?!?
377         
378         
379         // blank with tabs or spaces..
380         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
381        //     return tok.outData;
382        // }
383         
384         
385         
386         
387         var ff = this.activeFile.split('/');
388         var ffn = ff[ff.length-1];
389         return '_T["' + this.md5(ffn + '-' + sval) + '"]';
390         
391         
392     }
393     
394     
395 };