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 Gio = imports.gi.Gio;
14 /**
15  * @namespace JSDOC
16  * @class  Packer
17  * Create a new packer
18  * 
19  * Use with pack.js 
20  * 
21  * 
22  * Usage:
23  * <code>
24  *
25 Packer = imports['JSDOC/Packer.js'].Packer;
26 var x = new  Packer({
27     
28     files : [ "/location/of/file1.js", "/location/of/file2.js", ... ],
29     target : "/tmp/output.js",
30     debugTarget : "/tmp/output.debug.js", // merged file without compression.
31     translateJSON: "/tmp/translate.json",
32     
33     
34 );
35 x.packFiles(
36     "/location/of/temp_batch_dir", 
37     "/location/of/output-compacted-file.js",
38     "/location/of/output-debug-merged-file.js"
39 );
40     
41  *</code> 
42  *
43  * Notes for improving compacting:
44  *  if you add a jsdoc comment 
45  * <code>
46  * /**
47  *   eval:var:avarname
48  *   eval:var:bvarname
49  *   ....
50  * </code>
51  * directly before an eval statement, it will compress all the code around the eval, 
52  * and not rename the variables 'avarname'
53  * 
54  * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
55  * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
56  * 
57  * 
58  * 
59  * Notes for translation
60  *  - translation relies on you using double quotes for strings if they need translating
61  *  - single quoted strings are ignored.
62  * 
63  * Generation of indexFiles
64  *   - translateIndex = the indexfile
65  * 
66  * 
67  * 
68  * 
69
70  */
71 Packer = function(cfg)
72 {
73     
74     XObject.extend(this, cfg);
75     var _this = this;
76     if (this.srcfiles && this.srcfiles.length) {
77         this.srcfiles.forEach(function(f) {
78             _this.loadSourceFile(f);
79         });
80         
81     }
82     
83     if (!this.files) {
84         throw "No Files";
85     }
86     
87     var link = false;
88     if (cfg.autoBuild) {
89         
90         function dateString(d){
91             function pad(n){return n<10 ? '0'+n : n}
92             return d.getUTCFullYear() +
93                  pad(d.getUTCMonth()+1)+
94                  pad(d.getUTCDate())+'_'+
95                  pad(d.getUTCHours())+
96                  pad(d.getUTCMinutes())+
97                  pad(d.getUTCSeconds());
98         }
99
100         
101         
102         var version = 0;
103         this.files.forEach(function(f) {
104             version = Math.max(File.mtime(f), version);
105         });
106         var version  = dateString(new Date(version));
107         
108         var dirname = GLib.path_get_dirname(this.files[0]);
109         var outname = this.module ? this.module : GLib.path_get_basename(dirname);
110         this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
111          if (File.exists(this.target)) {
112             print("Target file already exists: " + this.target);
113             Seed.quit();
114         }
115         this.prefix = dirname +'/';
116         this.translateJSON  = dirname + '/compiled/_translation_.js';
117         
118     }
119      
120     print(this.translateJSON);
121     this.timer =  new Date() * 1;
122     this.packAll();
123     
124     
125     
126  
127 }
128 Packer.prototype = {
129     /**
130      * @cfg {String} srcfiles file containing a list of files/or classes to use.
131      */
132     srcfile : false,
133     
134     /**
135      * @cfg {Array} files list of files to compress (must be full path)
136      */
137     files : false,
138     /**
139      * @cfg {String} target to write files to - must be full path.
140      */
141     target : '',
142     /**
143      * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
144      * and enables translation toolkit.
145      */
146     autoBuild : false,
147      /**
148      * @cfg {String} module used with autoBuild to force a file name
149      */
150     module: false,
151     /**
152      * @cfg {String} debugTargettarget to write files debug version to (uncompacted)- must be full path.
153      */
154     debugTarget : '', // merged file without compression.
155     /**
156      * @cfg {String} tmpDir  (optional) where to put the temporary files. 
157      *      if you set this, then files will not be cleaned up
158      */
159     tmpDir : '/tmp',
160     
161     translateJSON : '', // json based list of strings in all files.
162    
163     /**
164      * @cfg {Boolean} cleanup  (optional) clean up temp files after done - 
165      *    Defaults to false if you set tmpDir, otherwise true.
166      */
167     cleanup : true,  
168     /**
169      * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
170      *    usefull for debugging compressed files.
171      */
172     
173     keepWhite: true,
174     
175     /**
176      * @cfg {String} prefix (optional) prefix of directory to be stripped of when
177      *    Calculating md5 of filename 
178      */
179     prefix : '',  
180     out : '', // if no target is specified - then this will contain the result
181     
182     /**
183      * load a dependancy list -f option
184      * @param {String} srcfile sourcefile to parse
185      * 
186      */
187     
188     loadSourceFile : function(srcfile)
189     {
190         var lines = File.read(srcfile).split("\n");
191         var _this = this;
192         lines.forEach(function(f) {
193             
194             if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
195                 return;
196             }
197             if (/\.js$/.test(f)) {
198                 _this.files.push( f);
199                 // js file..
200                 return;
201             }
202             
203             //println("ADD"+ f.replace(/\./g, '/'));
204             var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
205             if (_this.files.indexOf(f) > -1) {
206                 return;
207             }
208             _this.files.push( add );
209             
210         })
211     },
212     
213     
214     packAll : function()  // do the packing (run from constructor)
215     {
216         
217         //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
218         //File.write(this.transfile, "");
219         if (this.target) {
220             File.write(this.target, "");
221         }
222         
223         if (this.debugTarget) {
224             File.write(this.debugTarget, "");
225         }
226         
227         for(var i=0; i < this.files.length; i++)  {
228             var file = this.files[i];
229             
230             print("reading " +file );
231             if (!File.isFile(file)) {
232                 print("SKIP (is not a file) " + file);
233                 continue;
234             }
235            
236             if (this.debugTarget) {
237                 File.append(this.debugTarget, File.read(file));
238             }
239             // it's a good idea to check with 0 compression to see if the code can parse!!
240             
241             // debug file..
242             //File.append(dout, str +"\n"); 
243             
244        
245             
246             var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
247             
248             
249             // let's see if we have a min file already?
250             // this might happen if tmpDir is set .. 
251             if (true && File.exists(minfile)) {
252                 var mt = File.mtime(minfile);
253                 var ot = File.mtime(file);
254                 print("compare : " + mt + "=>" + ot);
255                 if (mt >= ot) {
256                     continue;
257                     /*
258                     // then the min'files time is > than original..
259                     var str = File.read(minfile);
260                     print("using MIN FILE  "+ minfile);
261                     if (str.length) {
262                         File.append(outpath, str + "\n");
263                     }
264                     
265                     continue;
266                     */
267                 }
268                 
269             }
270             
271             print("COMPRESSING ");
272             //var codeComp = pack(str, 10, 0, 0);
273             if (File.exists(minfile)) {
274                 File.remove(minfile);
275             }
276             var str = File.read(file);
277             var str = this.pack(str, file, minfile);
278             if (str.length) {
279                 File.write(minfile, str);
280             }
281             
282              
283           
284         }  
285         if (this.translateJSON) {
286             
287                
288             print("MERGING LANGUAGE");
289             var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
290             if (this.target) {
291                 File.write(this.target, out);
292             } else {
293                 this.out += out;
294             }
295             
296             
297             
298             File.write(this.translateJSON, "");
299             for(var i=0; i < this.files.length; i++)  {
300                 var file = this.files[i];
301                 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
302                 var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
303                 if (File.exists(transmd5)) {
304                     var str = File.read(transmd5);
305                     if (str.length) {
306                         if (this.target) {
307                             File.append(this.target, str + "\n");
308                         } else {
309                             this.out += str + "\n";
310                         }
311                         
312                     }
313                     if (this.cleanup) {
314                         File.remove(transmd5);
315                     }
316                 }
317                 if (File.exists(transfile)) {
318                     var str = File.read(transfile);
319                     if (str.length) {
320                         File.append(this.translateJSON, str);
321                     }
322                     if (this.cleanup) {
323                         File.remove(transfile);
324                     }
325                 }
326                 
327                
328             }
329         }
330         
331         print("MERGING SOURCE");
332         
333         for(var i=0; i < this.files.length; i++)  {
334             var file = this.files[i];
335             var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
336             
337             
338             if (!File.exists(minfile)) {
339                 continue;
340             }
341             var str = File.read(minfile);
342             print("using MIN FILE  "+ minfile);
343             if (str.length) {
344                 if (this.target) {
345                     File.append(this.target, str + "\n");   
346                 } else {
347                     this.out += str + "\n";
348                 }
349                 
350             }
351             if (this.cleanup) {
352                 File.remove(minfile);
353             }
354             
355         }
356         print("Output file: " + this.target);
357         if (this.debugTarget) print("Output debug file: " + this.debugTarget);
358         
359          
360     
361     
362     },
363     /**
364      * Core packing routine  for a file
365      * 
366      * @param str - str source text..
367      * @param fn - filename (for reference?)
368      * @param minfile - min file location...
369      * 
370      */
371     
372     pack : function (str,fn,minfile)
373     {
374     
375         var tr = new  TokenReader(  { 
376             keepDocs :true, 
377             keepWhite : true,  
378             keepComments : true, 
379             sepIdents : true,
380             collapseWhite : false,
381             filename : fn
382         });
383         this.timerPrint("START" + fn);
384         
385         // we can load translation map here...
386         
387         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
388         
389         // at this point we can write a language file...
390         if (this.translateJSON) {
391             
392             this.writeTranslateFile(fn, minfile, toks);
393         }
394         
395         this.activeFile = fn;
396         
397         // and replace if we are generating a different language..
398         
399         this.timerPrint("Tokenized");
400         //var ts = new TokenStream(toks);
401         //print(JSON.stringify(toks, null,4 )); Seed.quit();
402         var ts = new Collapse(toks);
403        // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
404         //return;//
405         var sp = new ScopeParser(ts);
406         this.timerPrint("Converted to Parser");
407         sp.packer = this;
408         sp.buildSymbolTree();
409         this.timerPrint("Built Sym tree");
410         sp.mungeSymboltree();
411         this.timerPrint("Munged Sym tree");
412         print(sp.warnings.join("\n"));
413         
414         
415         var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
416         
417         
418         this.timerPrint("Compressed");
419         return out;
420         
421         
422          
423     },
424     
425     timerPrint: function (str) {
426         var ntime = new Date() * 1;
427         var tdif =  ntime -this.timer;
428         this.timer = ntime;
429         print('['+tdif+']'+str);
430     },
431     
432     /**
433      * 
434      * Translation concept...
435      * -> replace text strings with _T....
436      * -> this file will need inserting at the start of the application....
437      * -> we need to generate 2 files, 
438      * -> a reference used to do the translation, and the _T file..
439      * 
440      */
441     
442     writeTranslateFile : function(fn, minfile, toks) 
443     {
444         
445         var map = {};
446         var _this = this;
447         toks.forEach(function (t) {
448             if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
449                 var sval = t.data.substring(1,t.data.length-1);
450                 var ffn = fn.substring(_this.prefix.length);
451                 map[sval] = _this.md5(ffn + '-' + sval);
452             }
453         })
454         
455         var transfile = minfile + '.lang.trans';
456         var transmd5 = minfile + '.lang';
457         print("writeTranslateFile "  + transfile);
458         var i = 0;
459         var v = '';
460         if (File.exists(transfile)) {
461             File.remove(transfile);
462         }
463         if (File.exists(transmd5)) {
464             File.remove(transmd5);
465         }
466         for(v in map) { i++; break };
467         if (!i ) {
468             return; // no strings in file...
469         }
470         var ffn = fn.substring(this.prefix.length);
471          
472          
473         File.write(transfile, "\n'" + ffn  + "' : {");
474         var l = '';
475         var _tout = {}
476          
477         File.write(transmd5, '');
478         for(v in map) {
479             if (!v.length) {
480                 continue;
481             }
482             File.append(transfile, l + "\n\t" + JSON.stringify(v) + " : " + JSON.stringify(v));
483             l = ',';
484             // strings are raw... - as the where encoded to start with!!!
485             File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]='+JSON.stringify(v)+";\n");
486         }
487         File.append(transfile, "\n},"); // always one trailing..
488         
489          
490     },
491     md5 : function (string)
492     {
493         
494         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
495         
496     },
497     stringHandler : function(tok)
498     {
499         //print("STRING HANDLER");
500        // callback when outputing compressed file, 
501        var data = tok.data;
502         if (!this.translateJSON) {
503          //   print("TURNED OFF");
504             return data;
505         }
506         if (tok.name == 'SINGLE_QUOTE') {
507             return data;
508         }
509         
510         var sval = data.substring(1,data.length-1);
511         // we do not clean up... quoting here!??!!?!?!?!?
512         
513         
514         // blank with tabs or spaces..
515         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
516        //     return tok.outData;
517        // }
518         
519         var sval = tok.data.substring(1,data.length-1);
520         var fn = this.activeFile.substring(this.prefix.length);
521         
522         
523         return '_T["' + this.md5(fn + '-' + sval) + '"]';
524         
525         
526     }
527     
528     
529 };