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
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     
128     loadSourceFile : function()
129     {
130         var lines = File.read(this.srcfile).split("\n");
131         var _this = this;
132         lines.forEach(function(f) {
133             
134             if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
135                 return;
136             }
137             if (/\.js$/.test(f)) {
138                 _this.files.push( f);
139                 // js file..
140                 return;
141             }
142             
143             //println("ADD"+ f.replace(/\./g, '/'));
144             var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
145             if (_this.files.indexOf(f) > -1) {
146                 return;
147             }
148             _this.files.push( add );
149             
150         })
151     },
152     
153     
154     packAll : function()  // do the packing (run from constructor)
155     {
156         
157         //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
158         //File.write(this.transfile, "");
159         if (this.target) {
160             File.write(this.target, "");
161         }
162         
163         if (this.debugTarget) {
164             File.write(this.debugTarget, "");
165         }
166         
167         for(var i=0; i < this.files.length; i++)  {
168             var file = this.files[i];
169             
170             print("reading " +file );
171             if (!File.isFile(file)) {
172                 print("SKIP (is not a file) " + file);
173                 continue;
174             }
175            
176             if (this.debugTarget) {
177                 File.append(this.debugTarget, File.read(file));
178             }
179             // it's a good idea to check with 0 compression to see if the code can parse!!
180             
181             // debug file..
182             //File.append(dout, str +"\n"); 
183             
184        
185             
186             var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
187             
188             
189             // let's see if we have a min file already?
190             // this might happen if tmpDir is set .. 
191             if (true && File.exists(minfile)) {
192                 var mt = File.mtime(minfile);
193                 var ot = File.mtime(file);
194                 print("compare : " + mt + "=>" + ot);
195                 if (mt >= ot) {
196                     continue;
197                     /*
198                     // then the min'files time is > than original..
199                     var str = File.read(minfile);
200                     print("using MIN FILE  "+ minfile);
201                     if (str.length) {
202                         File.append(outpath, str + "\n");
203                     }
204                     
205                     continue;
206                     */
207                 }
208                 
209             }
210             
211             print("COMPRESSING ");
212             //var codeComp = pack(str, 10, 0, 0);
213             if (File.exists(minfile)) {
214                 File.remove(minfile);
215             }
216             var str = File.read(file);
217             var str = this.pack(str, file, minfile);
218             if (str.length) {
219                 File.write(minfile, str);
220             }
221             
222              
223           
224         }  
225         if (this.translateJSON) {
226             
227                
228             print("MERGING LANGUAGE");
229             var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
230             if (this.target) {
231                 File.write(this.target, out);
232             } else {
233                 this.out += out;
234             }
235             
236             
237             
238             File.write(this.translateJSON, "");
239             for(var i=0; i < this.files.length; i++)  {
240                 var file = this.files[i];
241                 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
242                 var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
243                 if (File.exists(transmd5)) {
244                     var str = File.read(transmd5);
245                     if (str.length) {
246                         if (this.target) {
247                             File.append(this.target, str + "\n");
248                         } else {
249                             this.out += str + "\n";
250                         }
251                         
252                     }
253                     if (this.cleanup) {
254                         File.remove(transmd5);
255                     }
256                 }
257                 if (File.exists(transfile)) {
258                     var str = File.read(transfile);
259                     if (str.length) {
260                         File.append(this.translateJSON, str);
261                     }
262                     if (this.cleanup) {
263                         File.remove(transfile);
264                     }
265                 }
266                 
267                
268             }
269         }
270         
271         print("MERGING SOURCE");
272         
273         for(var i=0; i < this.files.length; i++)  {
274             var file = this.files[i];
275             var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
276             
277             
278             if (!File.exists(minfile)) {
279                 continue;
280             }
281             var str = File.read(minfile);
282             print("using MIN FILE  "+ minfile);
283             if (str.length) {
284                 if (this.target) {
285                     File.append(this.target, str + "\n");   
286                 } else {
287                     this.out += str + "\n";
288                 }
289                 
290             }
291             if (this.cleanup) {
292                 File.remove(minfile);
293             }
294             
295         }
296         
297          
298     
299     
300     },
301     /**
302      * Core packing routine  for a file
303      * 
304      * @param str - str source text..
305      * @param fn - filename (for reference?)
306      * @param minfile - min file location...
307      * 
308      */
309     
310     pack : function (str,fn,minfile)
311     {
312     
313         var tr = new  TokenReader(  { 
314             keepDocs :true, 
315             keepWhite : true,  
316             keepComments : true, 
317             sepIdents : true 
318         });
319         this.timerPrint("START" + fn);
320         
321         // we can load translation map here...
322         
323         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
324         
325         // at this point we can write a language file...
326         if (this.translateJSON) {
327             
328             this.writeTranslateFile(fn, minfile, toks);
329         }
330         
331         this.activeFile = fn;
332         
333         // and replace if we are generating a different language..
334         
335         this.timerPrint("Tokenized");
336         var ts = new TokenStream(toks);
337         //ts.dump();
338         //return;//
339         var sp = new ScopeParser(ts);
340         this.timerPrint("Converted to Parser");
341         sp.packer = this;
342         sp.buildSymbolTree();
343         this.timerPrint("Built Sym tree");
344         sp.mungeSymboltree();
345         this.timerPrint("Munged Sym tree");
346         print(sp.warnings.join("\n"));
347         var out = CompressWhite(sp.ts, this);
348         this.timerPrint("Compressed");
349         return out;
350         
351         
352          
353     },
354     
355     timerPrint: function (str) {
356         var ntime = new Date() * 1;
357         var tdif =  ntime -this.timer;
358         this.timer = ntime;
359         print('['+tdif+']'+str);
360     },
361     
362     /**
363      * 
364      * Translation concept...
365      * -> replace text strings with _T....
366      * -> this file will need inserting at the start of the application....
367      * -> we need to generate 2 files, 
368      * -> a reference used to do the translation, and the _T file..
369      * 
370      */
371     
372     writeTranslateFile : function(fn, minfile, toks) 
373     {
374         
375         var map = {};
376         var _this = this;
377         toks.forEach(function (t) {
378             if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
379                 var sval = t.data.substring(1,t.data.length-1);
380                 var ffn = fn.substring(_this.prefix.length);
381                 map[sval] = _this.md5(ffn + '-' + sval);
382             }
383         })
384         
385         var transfile = minfile + '.lang.trans';
386         var transmd5 = minfile + '.lang';
387         print("writeTranslateFile "  + transfile);
388         var i = 0;
389         var v = '';
390         if (File.exists(transfile)) {
391             File.remove(transfile);
392         }
393         if (File.exists(transmd5)) {
394             File.remove(transmd5);
395         }
396         for(v in map) { i++; break };
397         if (!i ) {
398             return; // no strings in file...
399         }
400         var ffn = fn.substring(this.prefix.length);
401          
402          
403         File.write(transfile, "\n'" + ffn  + "' : {");
404         var l = '';
405         var _tout = {}
406          
407         File.write(transmd5, '');
408         for(v in map) {
409             File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
410             l = ',';
411             // strings are raw... - as the where encoded to start with!!!
412             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
413         }
414         File.append(transfile, "\n},"); // always one trailing..
415         
416          
417     },
418     md5 : function (string)
419     {
420         
421         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
422         
423     },
424     stringHandler : function(tok)
425     {
426         //print("STRING HANDLER");
427        // callback when outputing compressed file, 
428        var data = tok.data;
429         if (!this.translateJSON) {
430          //   print("TURNED OFF");
431             return data;
432         }
433         if (tok.name == 'SINGLE_QUOTE') {
434             return data;
435         }
436         
437         var sval = data.substring(1,data.length-1);
438         // we do not clean up... quoting here!??!!?!?!?!?
439         
440         
441         // blank with tabs or spaces..
442         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
443        //     return tok.outData;
444        // }
445         
446         var sval = tok.data.substring(1,data.length-1);
447         var fn = this.activeFile.substring(this.prefix.length);
448         
449         
450         return '_T["' + this.md5(fn + '-' + sval) + '"]';
451         
452         
453     }
454     
455     
456 };