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 TokenReader     = imports['JSDOC/TokenReader.js'].TokenReader;
6 ScopeParser     = imports['JSDOC/ScopeParser.js'].ScopeParser;
7 TokenStream     = imports['JSDOC/TokenStream.js'].TokenStream;
8 CompressWhite   = imports['JSDOC/CompressWhite.js'].CompressWhite;
9
10 GLib = imports.gi.GLib;
11 /**
12  * @namespace JSDOC
13  * @class  Packer
14  * Create a new packer
15  * 
16  * Use with pack.js 
17  * 
18  * 
19  * Usage:
20  * <code>
21  *
22 Packer = imports['JSDOC/Packer.js'].Packer;
23 var x = new  Packer({
24     
25     files : [ "/location/of/file1.js", "/location/of/file2.js", ... ],
26     target : "/tmp/output.js",
27     debugTarget : "/tmp/output.debug.js", // merged file without compression.
28     translateJson : "/tmp/translate.json",
29     
30     
31 );
32 x.packFiles(
33     "/location/of/temp_batch_dir", 
34     "/location/of/output-compacted-file.js",
35     "/location/of/output-debug-merged-file.js"
36 );
37     
38  *</code> 
39  *
40  * Notes for improving compacting:
41  *  if you add a jsdoc comment 
42  * <code>
43  * /**
44  *   eval:var:avarname
45  *   eval:var:bvarname
46  *   ....
47  * </code>
48  * directly before an eval statement, it will compress all the code around the eval, 
49  * and not rename the variables 'avarname'
50  * 
51  * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
52  * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
53  * 
54  * 
55  * 
56  * Notes for translation
57  *  - translation relies on you using double quotes for strings if they need translating
58  *  - single quoted strings are ignored.
59  * 
60  * Generation of indexFiles
61  *   - translateIndex = the indexfile
62  * 
63  * 
64  * 
65  * 
66
67  */
68 Packer = function(cfg)
69 {
70     
71     XObject.extend(this, cfg);
72     if (!this.files) {
73         throw "No Files";
74     }
75     if (!this.target) {
76         throw "No Target";
77     }
78      
79     this.timer =  new Date() * 1;
80  
81 }
82 Packer.prototype = {
83     /**
84      * @prop files {Array} list of files to compress (must be full path)
85      */
86     files : false,
87     /**
88      * @prop target {String} target to write files to - must be full path.
89      */
90     target : '',
91     /**
92      * @prop debugTarget {String} target to write files debug version to (uncompacted)- must be full path.
93      */
94     debugTarget : '', // merged file without compression.
95     
96     workingDir : '/tmp',
97     
98     translateJson : '', // json based list of strings in all files.
99    
100     // set to false to stop translation happening..
101     
102     /**
103      * Pack the files.
104      * 
105      * @param {String} batch_path location of batched temporary min files.
106      * @param {String} compressed_file eg. roo-all.js
107      * @param {String} debug_file eg. roo-debug.js
108      * 
109      */
110     
111     packFiles : function() {
112         
113         //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
114         //File.write(this.transfile, "");
115         File.write(this.target, "");
116         if (this.debugTarget) {
117             File.write(this.debugTarget, "");
118         }
119         
120         for(var i=0; i < this.files.length; i++)  {
121             var file = this.files[i];
122             
123             print("reading " +file );
124             if (!File.exists(file)) {
125                 print("SKIP (does not exist) " + file);
126                 continue;
127             }
128            
129             if (this.debugTarget) {
130                 File.append(this.debugTarget, File.read(files[i]));
131             }
132             // it's a good idea to check with 0 compression to see if the code can parse!!
133             
134             // debug file..
135             //File.append(dout, str +"\n"); 
136             
137        
138             
139             var minfile = bpath + '/' +files[i].substr(spath.length+1).replace(/\//g, '.');
140             var transfile = bpath + '/' +files[i].substr(spath.length+1).replace(/\//g, '.') +'.lang';        
141             // let's see if we have a min file already?
142             if (true && File.exists(minfile)) {
143                 var mt = File.mtime(minfile);
144                 var ot = File.mtime(files[i]);
145                 print("compare : " + mt + "=>" + ot);
146                 if (mt >= ot) {
147                     continue;
148                     /*
149                     // then the min'files time is > than original..
150                     var str = File.read(minfile);
151                     print("using MIN FILE  "+ minfile);
152                     if (str.length) {
153                         File.append(outpath, str + "\n");
154                     }
155                     
156                     continue;
157                     */
158                 }
159                 
160             }
161             
162             print("COMPRESSING ");
163             //var codeComp = pack(str, 10, 0, 0);
164             var str = File.read(files[i]);
165             var str = this.pack(str, files[i], minfile);
166             if (str.length) {
167                 File.write(minfile, str);   
168             }
169             
170              
171             
172             //var str = File.read(minfile);
173             //print("using MIN FILE  "+ minfile);
174             //File.append(outpath, str + "\n");
175             //this.timerPrint("Wrote Files");
176             /*
177             if (codeComp.length) {
178                 //print(codeComp);
179                 
180                 File.append(outpath, codeComp+"\n");
181                 File.write(minfile, codeComp);
182             }
183             */
184             //print(codeComp);
185            // if (i > 10) return;
186         }  
187         if (this.translate) {
188             
189                
190             print("MERGING LANGUAGE");
191             File.write(outpath, "if (typeof(_T) == 'undefined') { _T={};}\n");
192             
193             var transfileAll =  bpath + '/_translation_.js';
194             File.write(transfileAll, "");
195             for(var i=0; i < files.length; i++)  {
196                 var transfile= bpath + '/' +files[i].substr(spath.length+1).replace(/\//g, '.') +'.lang.trans';
197                 var transmd5 = bpath + '/' +files[i].substr(spath.length+1).replace(/\//g, '.') +'.lang';
198                 if (File.exists(transmd5)) {
199                     var str = File.read(transmd5);
200                     if (str.length) {
201                         File.append(outpath, str + "\n");
202                     }
203                 }
204                 if (File.exists(transfile)) {
205                     var str = File.read(transfile);
206                     if (str.length) {
207                         File.append(transfileAll, str);
208                     }
209                 }
210                 
211                
212             }
213         }
214         print("MERGING SOURCE");
215         
216         for(var i=0; i < files.length; i++)  {
217          
218             var minfile = bpath + '/' +files[i].substr(spath.length+1).replace(/\//g, '.');
219             if (!File.exists(minfile)) {
220                 continue;
221             }
222             var str = File.read(minfile);
223             print("using MIN FILE  "+ minfile);
224             if (str.length) {
225                 File.append(outpath, str + "\n");
226             }
227         }
228         
229         
230         //File.append(dout, "\n");// end the function 
231         
232     
233     
234     },
235     /**
236      * Core packing routine  for a file
237      * 
238      * @param str - str source text..
239      * @param fn - filename (for reference?)
240      * @param minfile - min file location...
241      * 
242      */
243     
244     pack : function (str,fn,minfile)
245     {
246     
247         var tr = new  TokenReader();
248         this.timerPrint("START" + fn);
249         
250         // we can load translation map here...
251         
252         var toks = tr.tokenize(str,false); // dont merge xxx + . + yyyy etc.
253         
254         // at this point we can write a language file...
255         if (this.translate) {
256             this.writeTranslateFile(fn, minfile, tr.translateMap);
257         }
258         
259         this.activeFile = fn;
260         
261         // and replace if we are generating a different language..
262         
263         
264         
265         
266         this.timerPrint("Tokenized");
267         //return;//
268         var sp = new ScopeParser(new TokenStream(toks, str.length));
269         this.timerPrint("Converted to Parser");
270         sp.packer = this;
271         sp.buildSymbolTree();
272         this.timerPrint("Built Sym tree");
273         sp.mungeSymboltree();
274         this.timerPrint("Munged Sym tree");
275         print(sp.warnings.join("\n"));
276         var out = JSDOC.CompressWhite(sp.ts, this);
277         this.timerPrint("Compressed");
278         return out;
279         
280     },
281     
282     timerPrint: function (str) {
283         var ntime = new Date() * 1;
284         var tdif =  ntime -this.timer;
285         this.timer = ntime;
286         print('['+tdif+']'+str);
287     },
288     
289     /**
290      * 
291      * Translation concept...
292      * -> replace text strings with _T....
293      * -> this file will need inserting at the start of the application....
294      * -> we need to generate 2 files, 
295      * -> a reference used to do the translation, and the _T file..
296      * 
297      */
298     
299     writeTranslateFile : function(fn, minfile, map) 
300     {
301         var transfile = minfile + '.lang.trans';
302         var transmd5 = minfile + '.lang';
303         var i = 0;
304         var v = '';
305         if (File.exists(transfile)) {
306             File.remove(transfile);
307         }
308         if (File.exists(transmd5)) {
309             File.remove(transmd5);
310         }
311         for(v in map) { i++; break };
312         if (!i ) {
313             return; // no strings in file...
314         }
315         var ff = fn.split('/');
316         var ffn = ff[ff.length-1];
317          
318          
319         File.write(transfile, "\n" + ffn.toSource() + " : {");
320         var l = '';
321         var _tout = {}
322          
323         File.write(transmd5, '');
324         for(v in map) {
325             File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
326             l = ',';
327             // strings are raw... - as the where encoded to start with!!!
328             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
329         }
330         File.append(transfile, "\n},"); // always one trailing..
331         
332          
333     },
334     md5 : function (string)
335     {
336         
337         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
338         
339     },
340     stringHandler : function(tok)
341     {
342         //print("STRING HANDLER");
343        // callback when outputing compressed file, 
344         if (!this.translate) {
345          //   print("TURNED OFF");
346             return tok.outData;
347         }
348         if (tok.qc != '"') {
349             return tok.outData;
350         }
351         var sval = tok.data.substring(1,tok.data.length-1);
352         // blank with tabs or spaces..
353         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
354        //     return tok.outData;
355        // }
356         
357         
358         
359         
360         var ff = this.activeFile.split('/');
361         var ffn = ff[ff.length-1];
362         return '_T["' + this.md5(ffn + '-' + sval) + '"]';
363         
364         
365     }
366     
367     
368 };