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