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