Update to sync with working copy
[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.Collapse.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     var _this = this;
75     if (this.srcfiles && this.srcfiles.length) {
76         this.srcfiles.forEach(function(f) {
77             _this.loadSourceFile(f);
78         });
79         
80     }
81     
82     if (!this.files) {
83         throw "No Files";
84     }
85     
86     var link = false;
87     if (cfg.autoBuild) {
88         
89         function dateString(d){
90             function pad(n){return n<10 ? '0'+n : n}
91             return d.getFullYear() +
92                  pad(d.getMonth()+1)+
93                  pad(d.getDate())+'_'+
94                  pad(d.getHours())+
95                  pad(d.getMinutes())+
96                  pad(d.getSeconds());
97         }
98
99         
100         
101         var version = 0;
102         this.files.forEach(function(f) {
103             version = Math.max(File.mtime(f), version);
104         });
105         var version  = dateString(new Date(version));
106         
107         var dirname = GLib.path_get_dirname(this.files[0]);
108         var outname = this.module ? this.module : GLib.path_get_basename(dirname);
109         this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
110          if (File.exists(this.target)) {
111             print("Target file already exists: " + this.target);
112             Seed.quit();
113         }
114         this.prefix = dirname +'/';
115         this.translateJSON  = dirname + '/compiled/_translation_.js';
116         
117     }
118      
119     print(this.translateJSON);
120     this.timer =  new Date() * 1;
121     this.packAll();
122     
123     
124     
125  
126 }
127 Packer.prototype = {
128     /**
129      * @prop srcfiles {String} file containing a list of files/or classes to use.
130      */
131     srcfile : false,
132     
133     /**
134      * @prop files {Array} list of files to compress (must be full path)
135      */
136     files : false,
137     /**
138      * @prop target {String} target to write files to - must be full path.
139      */
140     target : '',
141     /**
142      * @prop debugTarget {String} target to write files debug version to (uncompacted)- must be full path.
143      */
144     debugTarget : '', // merged file without compression.
145     /**
146      * @prop tmpDir {String} (optional) where to put the temporary files. 
147      *      if you set this, then files will not be cleaned up
148      */
149     tmpDir : '/tmp',
150     
151     translateJSON : '', // json based list of strings in all files.
152    
153     /**
154      * @prop cleanup {Boolean} (optional) clean up temp files after done - 
155      *    Defaults to false if you set tmpDir, otherwise true.
156      */
157     cleanup : true,  
158     
159     /**
160      * @prop prefix {String} (optional) prefix of directory to be stripped of when
161      *    Calculating md5 of filename 
162      */
163     prefix : '',  
164     out : '', // if no target is specified - then this will contain the result
165     
166     
167     loadSourceFile : function(srcfile)
168     {
169         var lines = File.read(srcfile).split("\n");
170         var _this = this;
171         lines.forEach(function(f) {
172             
173             if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
174                 return;
175             }
176             if (/\.js$/.test(f)) {
177                 _this.files.push( f);
178                 // js file..
179                 return;
180             }
181             
182             //println("ADD"+ f.replace(/\./g, '/'));
183             var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
184             if (_this.files.indexOf(f) > -1) {
185                 return;
186             }
187             _this.files.push( add );
188             
189         })
190     },
191     
192     
193     packAll : function()  // do the packing (run from constructor)
194     {
195         
196         //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
197         //File.write(this.transfile, "");
198         if (this.target) {
199             File.write(this.target, "");
200         }
201         
202         if (this.debugTarget) {
203             File.write(this.debugTarget, "");
204         }
205         
206         for(var i=0; i < this.files.length; i++)  {
207             var file = this.files[i];
208             
209             print("reading " +file );
210             if (!File.isFile(file)) {
211                 print("SKIP (is not a file) " + file);
212                 continue;
213             }
214            
215             if (this.debugTarget) {
216                 File.append(this.debugTarget, File.read(file));
217             }
218             // it's a good idea to check with 0 compression to see if the code can parse!!
219             
220             // debug file..
221             //File.append(dout, str +"\n"); 
222             
223        
224             
225             var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
226             
227             
228             // let's see if we have a min file already?
229             // this might happen if tmpDir is set .. 
230             if (true && File.exists(minfile)) {
231                 var mt = File.mtime(minfile);
232                 var ot = File.mtime(file);
233                 print("compare : " + mt + "=>" + ot);
234                 if (mt >= ot) {
235                     continue;
236                     /*
237                     // then the min'files time is > than original..
238                     var str = File.read(minfile);
239                     print("using MIN FILE  "+ minfile);
240                     if (str.length) {
241                         File.append(outpath, str + "\n");
242                     }
243                     
244                     continue;
245                     */
246                 }
247                 
248             }
249             
250             print("COMPRESSING ");
251             //var codeComp = pack(str, 10, 0, 0);
252             if (File.exists(minfile)) {
253                 File.remove(minfile);
254             }
255             var str = File.read(file);
256             var str = this.pack(str, file, minfile);
257             if (str.length) {
258                 File.write(minfile, str);
259             }
260             
261              
262           
263         }  
264         if (this.translateJSON) {
265             
266                
267             print("MERGING LANGUAGE");
268             var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
269             if (this.target) {
270                 File.write(this.target, out);
271             } else {
272                 this.out += out;
273             }
274             
275             
276             
277             File.write(this.translateJSON, "");
278             for(var i=0; i < this.files.length; i++)  {
279                 var file = this.files[i];
280                 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
281                 var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
282                 if (File.exists(transmd5)) {
283                     var str = File.read(transmd5);
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(transmd5);
294                     }
295                 }
296                 if (File.exists(transfile)) {
297                     var str = File.read(transfile);
298                     if (str.length) {
299                         File.append(this.translateJSON, str);
300                     }
301                     if (this.cleanup) {
302                         File.remove(transfile);
303                     }
304                 }
305                 
306                
307             }
308         }
309         
310         print("MERGING SOURCE");
311         
312         for(var i=0; i < this.files.length; i++)  {
313             var file = this.files[i];
314             var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
315             
316             
317             if (!File.exists(minfile)) {
318                 continue;
319             }
320             var str = File.read(minfile);
321             print("using MIN FILE  "+ minfile);
322             if (str.length) {
323                 if (this.target) {
324                     File.append(this.target, str + "\n");   
325                 } else {
326                     this.out += str + "\n";
327                 }
328                 
329             }
330             if (this.cleanup) {
331                 File.remove(minfile);
332             }
333             
334         }
335         
336          
337     
338     
339     },
340     /**
341      * Core packing routine  for a file
342      * 
343      * @param str - str source text..
344      * @param fn - filename (for reference?)
345      * @param minfile - min file location...
346      * 
347      */
348     
349     pack : function (str,fn,minfile)
350     {
351     
352         var tr = new  TokenReader(  { 
353             keepDocs :true, 
354             keepWhite : true,  
355             keepComments : true, 
356             sepIdents : true,
357             collapseWhite : false
358         });
359         this.timerPrint("START" + fn);
360         
361         // we can load translation map here...
362         
363         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
364         
365         // at this point we can write a language file...
366         if (this.translateJSON) {
367             
368             this.writeTranslateFile(fn, minfile, toks);
369         }
370         
371         this.activeFile = fn;
372         
373         // and replace if we are generating a different language..
374         
375         this.timerPrint("Tokenized");
376         //var ts = new TokenStream(toks);
377         //print(JSON.stringify(toks, null,4 )); Seed.quit();
378         var ts = new Collapse(toks);
379        // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
380         //return;//
381         var sp = new ScopeParser(ts);
382         this.timerPrint("Converted to Parser");
383         sp.packer = this;
384         sp.buildSymbolTree();
385         this.timerPrint("Built Sym tree");
386         sp.mungeSymboltree();
387         this.timerPrint("Munged Sym tree");
388         print(sp.warnings.join("\n"));
389         
390         
391         //var out = CompressWhite(new TokenStream(toks), this, true); // do not kill whitespace..
392         var out = CompressWhite(new TokenStream(toks), this, false);
393         this.timerPrint("Compressed");
394         return out;
395         
396         
397          
398     },
399     
400     timerPrint: function (str) {
401         var ntime = new Date() * 1;
402         var tdif =  ntime -this.timer;
403         this.timer = ntime;
404         print('['+tdif+']'+str);
405     },
406     
407     /**
408      * 
409      * Translation concept...
410      * -> replace text strings with _T....
411      * -> this file will need inserting at the start of the application....
412      * -> we need to generate 2 files, 
413      * -> a reference used to do the translation, and the _T file..
414      * 
415      */
416     
417     writeTranslateFile : function(fn, minfile, toks) 
418     {
419         
420         var map = {};
421         var _this = this;
422         toks.forEach(function (t) {
423             if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
424                 var sval = t.data.substring(1,t.data.length-1);
425                 var ffn = fn.substring(_this.prefix.length);
426                 map[sval] = _this.md5(ffn + '-' + sval);
427             }
428         })
429         
430         var transfile = minfile + '.lang.trans';
431         var transmd5 = minfile + '.lang';
432         print("writeTranslateFile "  + transfile);
433         var i = 0;
434         var v = '';
435         if (File.exists(transfile)) {
436             File.remove(transfile);
437         }
438         if (File.exists(transmd5)) {
439             File.remove(transmd5);
440         }
441         for(v in map) { i++; break };
442         if (!i ) {
443             return; // no strings in file...
444         }
445         var ffn = fn.substring(this.prefix.length);
446          
447          
448         File.write(transfile, "\n'" + ffn  + "' : {");
449         var l = '';
450         var _tout = {}
451          
452         File.write(transmd5, '');
453         for(v in map) {
454             File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
455             l = ',';
456             // strings are raw... - as the where encoded to start with!!!
457             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
458         }
459         File.append(transfile, "\n},"); // always one trailing..
460         
461          
462     },
463     md5 : function (string)
464     {
465         
466         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
467         
468     },
469     stringHandler : function(tok)
470     {
471         //print("STRING HANDLER");
472        // callback when outputing compressed file, 
473        var data = tok.data;
474         if (!this.translateJSON) {
475          //   print("TURNED OFF");
476             return data;
477         }
478         if (tok.name == 'SINGLE_QUOTE') {
479             return data;
480         }
481         
482         var sval = data.substring(1,data.length-1);
483         // we do not clean up... quoting here!??!!?!?!?!?
484         
485         
486         // blank with tabs or spaces..
487         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
488        //     return tok.outData;
489        // }
490         
491         var sval = tok.data.substring(1,data.length-1);
492         var fn = this.activeFile.substring(this.prefix.length);
493         
494         
495         return '_T["' + this.md5(fn + '-' + sval) + '"]';
496         
497         
498     }
499     
500     
501 };