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