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