JSDOC/Packer.vala
[gnome.introspection-doc-generator] / JSDOC / Packer.vala
1  
2 /**
3  * @namespace JSDOC
4  * @class  Packer
5  * Create a new packer
6  * 
7  * Use with pack.js 
8  * 
9  * 
10  * Usage:
11  * <code>
12  *
13  
14 var x = new  JSON.Packer(target, debugTarget);
15
16 x.files = an array of files
17 x.srcfiles = array of files (that list other files...) << not supported?
18 x.target = "output.pathname.js"
19 x.debugTarget = "output.pathname.debug.js"
20
21
22 x.debugTranslateTarget : "/tmp/output.translate.js" << this used to be the single vs double quotes.. we may not use it in future..
23 x.translateJSON: "/tmp/translate.json",
24     
25 x.packAll();  // writes files  etc..
26     
27  *</code> 
28  *
29  * Notes for improving compacting:
30  *  if you add a jsdoc comment 
31  * <code>
32  * /**
33  *   eval:var:avarname
34  *   eval:var:bvarname
35  *   ....
36  * </code>
37  * directly before an eval statement, it will compress all the code around the eval, 
38  * and not rename the variables 'avarname'
39  * 
40  * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
41  * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
42  * 
43  * 
44  * 
45  * Notes for translation
46  *  - translation relies on you using double quotes for strings if they need translating
47  *  - single quoted strings are ignored.
48  * 
49  * Generation of indexFiles
50  *   - translateIndex = the indexfile
51  * 
52  * 
53  * 
54  * 
55
56  */
57 namespace JSDOC 
58 {
59
60
61         public class Packer : Object 
62         {
63                 /**
64                 * @cfg {String} target to write files to - must be full path.
65                 */
66                 string target;
67                 FileOutputStream targetStream = null;
68                 /**
69                  * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
70                  */
71                 string targetDebug;
72                 
73
74                 FileOutputStream targetDebugStream  = null;
75                 /**
76                  * @cfg {String} tmpDir  (optional) where to put the temporary files. 
77                  *      if you set this, then files will not be cleaned up
78                  */
79                 public string tmpDir = "/tmp";  // FIXME??? in ctor?
80         
81         
82                   
83                 /**
84                  * @cfg {Boolean} cleanup  (optional) clean up temp files after done - 
85                  *    Defaults to false if you set tmpDir, otherwise true.
86                  */
87                 public bool cleanup =  true;
88                 
89                 
90                 /**
91                  * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
92                  *    usefull for debugging compressed files.
93                  */
94                 
95                 public bool keepWhite =  true;
96                 
97                 
98                 // list of files to compile...
99                 Gee.ArrayList<string> files;
100                 
101                 public  string out = ""; // if no target is specified - then this will contain the result
102     
103                 public Packer(string target, string targetDebug = "")
104                 {
105                         this.target = target;
106                         this.targetDebug  = targetDebug;
107                 
108                 }
109                 
110                 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
111                 {
112                         foreach(var f in indexes) {
113                                 this.loadSourceIndex(f);
114                         }
115                 }
116                 
117                 public void loadFiles(Gee.ArrayList<string> fs)
118                 {
119                         foreach(var f in fs) {
120                                 this.files.add(f); //?? easier way?
121                         }
122                 }
123         
124                 
125                 public void pack()
126                 {
127                     if (!this.files) {
128                                 throw new Packer.ArgumentError("No Files loaded before pack() called");
129                         }
130                         if (this.target.length > 0 ) {
131                                 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
132                         }
133                         if (this.targetDebug.length > 0 ) {
134                                 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
135                         }
136                         this.packAll();
137                 }
138                 
139   
140                 
141                 
142    
143                 
144  
145            
146                 /**
147                  * load a dependancy list -f option
148                  * @param {String} srcfile sourcefile to parse
149                  * 
150                  */
151                 
152                 public void loadSourceIndex(string srcfile)
153                 {
154                     string str;
155                     FileUtils.get_contents(srcfile,out str);
156                     
157                     var lines = str.split("\n");
158                     for(var i =0; i < lines.length;i++) {
159  
160                             var f = lines[i].strip();
161                         if (f.length < 1 ||
162                                 Regex.match_simple ("^/", f) ||
163                                 !Regex.match_simple ("[a-zA-Z]+", f) 
164                         ){
165                                 continue; // blank comment or not starting with a-z
166                         }
167                         
168                         if (Regex.match_simple ("\\.js$", f)) {
169                             this.files.add( f);
170                             // js file..
171                             continue;
172                         }
173                         
174                                 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
175                                 // should we prefix? =- or should this be done elsewhere?
176                                 
177                         var add = f.replace(".", "/") + ".js";
178                         if (_this.files.contains(add)) {
179                             continue;
180                         }
181                         _this.files.add( add );
182                         
183                     }
184                 }
185                 
186     
187                 private void packAll()  // do the packing (run from constructor)
188                 {
189                     
190                     //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
191                     //File.write(this.transfile, "");
192                     if (this.target.length > 0) {
193                         this.targetStream.write("");
194                     }
195                     
196                     if (this.debugTarget > 0) {
197                             this.targetDebugStream.write("");
198                     }
199                     foreach(var file in this.files) {
200                         
201                         print("reading %s\n",file );
202                         
203                         if (FileUtils.test (file, FileTest.EXISTS) && ! FileUtils.test (file, FileTest.IS_DIR)) {
204                             print("SKIP (is not a file) %s\n ", file);
205                             continue;
206                         }
207                        
208                                 var loaded_string = false;
209                                 string file_contents;
210                         // debug Target
211                         
212                         if (this.targetDebugStream !=null) {
213                                 
214                                 FileUtils.get_contents(file,out file_contents);
215                             this.targetDebugStream.write(file_contents);
216                             loaded_string = false;
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("/", '.');
226                         
227                         
228                         // let's see if we have a min file already?
229                         // this might happen if tmpDir is set .. 
230
231                         
232                         if (true && FileUtils.test (minfile, FileTest.EXISTS)) {
233                                 
234                                 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
235                                 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
236                                         
237                                         var ot = new Date();
238                                         ot.set_time_val(otv);
239                                         var mt = new Date();
240                                         mt.set_time_val(mtv);
241                             //print("compare : " + mt + "=>" + ot);
242                             if (mt.compare(ot) >= 0) {
243                                 continue; // file is newer or the same time..
244                                 
245                             }
246                             
247                         }
248                          
249                         print("COMPRESSING ");
250                         //var codeComp = pack(str, 10, 0, 0);
251                         if (FileUtils.test (minfile, FileTest.EXISTS)) {
252                             FileUtils.remove(minfile);
253                         }
254                         if (!loaded_string) {
255                                 FileUtils.get_contents(file,out file_contents);
256                         }
257
258                         var str = this.packFile(file_contents, file, minfile);
259                          
260                       
261                     }
262                     
263                     
264                     
265                     // if we are translating, write the translations strings at the top
266                     // of the file..
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                         File.write(this.translateJSON, "");
280                         for(var i=0; i < this.files.length; i++)  {
281                             var file = this.files[i];
282                             var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
283                             var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
284                             if (File.exists(transmd5)) {
285                                 var str = File.read(transmd5);
286                                 if (str.length) {
287                                     if (this.target) {
288                                         File.append(this.target, str + "\n");
289                                     } else {
290                                         this.out += str + "\n";
291                                     }
292                                     
293                                 }
294                                 if (this.cleanup) {
295                                     File.remove(transmd5);
296                                 }
297                             }
298                             if (File.exists(transfile)) {
299                                 var str = File.read(transfile);
300                                 if (str.length) {
301                                     File.append(this.translateJSON, str);
302                                 }
303                                 if (this.cleanup) {
304                                     File.remove(transfile);
305                                 }
306                             }
307                             
308                            
309                         }
310                     }
311                     */
312                     print("MERGING SOURCE");
313                     
314                     for(var i=0; i < this.files.length; i++)  {
315                         var file = this.files[i];
316                         var minfile = this.tmpDir + '/' + file.replace('/', '.');
317                         
318                         
319                         if (!File.exists(minfile)) {
320                             continue;
321                         }
322                         var str = File.read(minfile);
323                         print("using MIN FILE  "+ minfile);
324                         if (str.length) {
325                             if (this.targetStream != null) {
326                                         this.targetStream.write("//" + file + "\n"); 
327                                         this.targetStream.write(str + "\n"); 
328
329                             } else {
330                                 this.out += "//" + file + "\n";
331                                 this.out += str + "\n";
332                             }
333                             
334                         }
335                         if (this.cleanup) {
336                             FileUtils.remove(minfile);
337                         }
338                         
339                     }
340                     print("Output file: " + this.target);
341                     if (this.debugTarget) print("Output debug file: " + this.debugTarget);
342                     
343                      
344                 
345                 
346                 }
347     /**
348      * Core packing routine  for a file
349      * 
350      * @param str - str source text..
351      * @param fn - filename (for reference?)
352      * @param minfile - min file location...
353      * 
354      */
355     
356     packFile : function (str,fn,minfile)
357     {
358     
359         var tr = new  TokenReader(  { 
360             keepDocs :true, 
361             keepWhite : true,  
362             keepComments : true, 
363             sepIdents : true,
364             collapseWhite : false,
365             filename : fn
366         });
367         this.timerPrint("START" + fn);
368         
369         // we can load translation map here...
370         
371         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
372         
373         // at this point we can write a language file...
374         if (this.translateJSON) {
375             
376             this.writeTranslateFile(fn, minfile, toks);
377         }
378         
379         this.activeFile = fn;
380         
381         // and replace if we are generating a different language..
382         
383         this.timerPrint("Tokenized");
384         //var ts = new TokenStream(toks);
385         //print(JSON.stringify(toks, null,4 )); Seed.quit();
386         var ts = new Collapse(toks);
387        // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
388         //return;//
389         var sp = new ScopeParser(ts);
390         this.timerPrint("Converted to Parser");
391         sp.packer = this;
392         sp.buildSymbolTree();
393         this.timerPrint("Built Sym tree");
394         sp.mungeSymboltree();
395         this.timerPrint("Munged Sym tree");
396         print(sp.warnings.join("\n"));
397         this.timerPrint("Compressed");
398         
399         var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
400         
401         
402         this.timerPrint("Compressed");
403         
404          if (out.length) {
405             File.write(minfile, out);
406             this.timerPrint("Write (" + out.length + "bytes) " + minfile);
407         }
408         
409         return out;
410         
411         
412          
413     },
414      
415     
416     md5 : function (string)
417     {
418         
419         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
420         
421     },
422     stringHandler : function(tok)
423     {
424         //print("STRING HANDLER");
425        // callback when outputing compressed file, 
426        var data = tok.data;
427         if (!this.translateJSON) {
428          //   print("TURNED OFF");
429             return data;
430         }
431         if (tok.name == 'SINGLE_QUOTE') {
432             return data;
433         }
434         
435         if (typeof(tok.trsum) == 'undefined') {
436             return data;
437         }
438         
439         return '_T["' + tok.trsum + '"]';
440         
441         var sval = data.substring(1,data.length-1);
442         // we do not clean up... quoting here!??!!?!?!?!?
443         
444         
445         // blank with tabs or spaces..
446         //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
447        //     return tok.outData;
448        // }
449         
450         var sval = tok.data.substring(1,data.length-1);
451         var fn = this.activeFile.substring(this.prefix.length);
452         
453         
454         return '_T["' + this.md5(fn + '-' + sval) + '"]';
455         
456         
457     }
458     
459     
460 };