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