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