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