src/jsdoc/Packer.vala
[roojspacker] / src / 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     
23 x.pack();  // writes files  etc..
24     
25  *</code> 
26  *
27  * Notes for improving compacting:
28  *  if you add a jsdoc comment 
29  * <code>
30  * /**
31  *   eval:var:avarname
32  *   eval:var:bvarname
33  *   ....
34  * </code>
35  * directly before an eval statement, it will compress all the code around the eval, 
36  * and not rename the variables 'avarname'
37  * 
38  * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
39  * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
40  * 
41  * 
42  * 
43  * Notes for translation
44  *  - translation relies on you using double quotes for strings if they need translating
45  *  - single quoted strings are ignored.
46  * 
47  * Generation of indexFiles
48  *   - translateIndex = the indexfile
49  * 
50  * 
51  * 
52  * 
53
54  */
55 namespace JSDOC 
56 {
57         public errordomain PackerError {
58             ArgumentError
59     }
60     
61     
62         public class Packer : Object 
63         {
64                 /**
65                 * @cfg {String} target to write files to - must be full path.
66                 */
67                 string target = "";
68                 GLib.FileOutputStream targetStream = null;
69                 /**
70                  * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
71                  */
72                 string targetDebug = "";
73                 
74
75                 GLib.FileOutputStream targetDebugStream  = null;
76                 /**
77                  * @cfg {String} tmpDir  (optional) where to put the temporary files. 
78                  *      if you set this, then files will not be cleaned up
79                  *  
80                  *  at present we need tmpfiles - as we compile multiple files into one.
81                  *  we could do this in memory now, as I suspect vala will not be as bad as javascript for leakage...
82                  *
83                  */
84                 public string tmpDir = "/tmp";  // FIXME??? in ctor?
85         
86         
87                   
88                 /**
89                  * @cfg {Boolean} cleanup  (optional) clean up temp files after done - 
90                  *    Defaults to false if you set tmpDir, otherwise true.
91                  */
92                 public bool cleanup =  false;
93                 
94                 
95                 /**
96                  * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
97                  *    usefull for debugging compressed files.
98                  */
99                 
100                 public bool keepWhite =  false;
101                         
102                 /**
103                  * @cfg {Boolean} skipScope (optional) skip Scope parsing and replacement.
104                  *    usefull for debugging...
105                  */
106                 
107                 public bool skipScope = false;
108                 
109                 
110                 /**
111                  * @cfg {Boolean} dumpTokens (optional) read the first file and dump the tokens.
112                  *    usefull for debugging...
113                  */
114                 
115                 public bool dumpTokens = false;
116                 
117                 // list of files to compile...
118                 Gee.ArrayList<string> files;
119                 
120                 /**
121                 * @cfg activeFile ??? used???
122                 */
123                  
124                 public string activeFile = "";
125                 
126                         
127                 /**
128                 * @cfg baseDir -- prefix the files listed in indexfiles with this.
129                 */
130                  
131                 public string baseDir = "";
132                 
133                 
134                 public  string outstr = ""; // if no target is specified - then this will contain the result
135                 
136                 
137                 
138                 
139                 public Packer()
140                 {
141                         this.result = new Json.Object();
142                         this.files = new Gee.ArrayList<string>();
143                         
144                         new Lang_Class(); ///initilizaze lang..
145                          
146                 }
147                 
148                 
149                 // this could be another class really..
150                 
151                 public enum ResultType { 
152                         err , 
153                         warn;
154                         public string to_string() { 
155                                 switch(this) {
156                                         case err: return "ERR";
157                                         case warn: return "WARN";
158                                         default: assert_not_reached();
159                                 }
160                         
161                           }
162                   }
163                 /**
164                 *  result of complication - a JSON object containing warnings / errors etc..
165                 *  FORMAT:
166                 *     warn-TOTAL : X  (number of warnings.
167                 *     err-TOTAL: X  (number of errors) << this indicates failure...
168                 *     warn : {
169                 *            FILENAME : {
170                 *                  line : [ Errors,Errors,.... ]
171                 *     err : {
172                 *           .. sane format..
173                 *
174                 */
175                 
176 #ifdef HAVE_JSON_GLIB
177                 
178                 public Json.Object result;   // output - what's the complication result
179
180                 public void  logError(ResultType type, string filename, int line, string message) {
181                          
182                          if (!this.result.has_member(type.to_string()+"-TOTAL")) {
183                                  this.result.set_int_member(type.to_string()+"-TOTAL", 1);
184                          } else {
185                                 this.result.set_int_member(type.to_string()+"-TOTAL", 
186                                         this.result.get_int_member(type.to_string()+"-TOTAL") +1 
187                                 );
188                          }
189                          
190                          
191                          if (!this.result.has_member(type.to_string())) {
192                                  this.result.set_object_member(type.to_string(), new Json.Object());
193                          }
194                          var t = this.result.get_object_member(type.to_string());
195                          if (!t.has_member(filename)) {
196                                  t.set_object_member(filename, new Json.Object());
197                          }
198                          var tt = t.get_object_member(filename);
199                          if (!tt.has_member(line.to_string())) {
200                                  tt.set_array_member(line.to_string(), new Json.Array());
201                          }
202                          var tl = tt.get_array_member(line.to_string());
203                          tl.add_string_element(message);
204                          
205                 }
206                 
207                 public bool hasErrors(string fn)
208                 {
209                          if (!this.result.has_member(ResultType.err.to_string())) {
210                                  return false;
211                          }
212                          
213                          if (fn.length < 1) {
214                                 return true;
215                          }
216                          var t = this.result.get_object_member(ResultType.err.to_string());
217                          
218                          if (t.has_member(fn)) {
219                                  return true;
220                          }
221                          return false;
222                 }
223                 public void dumpErrors(ResultType type)
224                 {
225                          if (!this.result.has_member(type.to_string())) {
226                                  return;
227                          }
228                         var t = this.result.get_object_member(type.to_string());
229                         t.foreach_member((obj, filename, node) => {
230                                         var linelist = node.dup_object();
231                                         linelist.foreach_member((linelistobj, linestr, nodear) => {
232                                                 var errors=  nodear.dup_array();
233                                                 errors.foreach_element((errorar, ignore, nodestr) => {
234                                                         print("%s: %s:%s %s\n", type.to_string(), filename, linestr, nodestr.get_string());
235                                                 });
236                                         });
237                         
238                         });
239                 }
240 #else
241                 public Gee.HashMap result_count<string,int>;   // output - what's the complication result
242                 
243                 public Gee.HashMap result_count<
244                                 string, Gee.HashMap<int, Gee.ArrayList<string>>
245                 >;
246
247                 public void  logError(ResultType type, string filename, int line, string message) {
248                          
249                          
250                          if (!this.result_count.has_key(type.to_string()+"-TOTAL")) {
251                                  this.result_count.set(type.to_string()+"-TOTAL", 1);
252                          } else {
253                                 this.result_count.set(type.to_string()+"-TOTAL",                                 
254                                         this.result_count.get(type.to_string()+"-TOTAL") +1
255                                 );
256                          }
257                          
258                          
259                          
260                          if (!this.result.has_key(type.to_string())) {
261                                  this.result.set(type.to_string(), new Gee.HashMap<int, Gee.ArrayList<string>>);
262                          }
263                          var t = this.result.get(type.to_string());
264                          if (!t.has_key(filename)) {
265                                  t.set(filename, new Json.Object());
266                          }
267                          var tt = t.get_object_member(filename);
268                          if (!tt.has_member(line)) {
269                                  tt.set_array_member(line, Gee.ArrayList<string));
270                          }
271                          var tl = tt.get(line);
272                          tl.line(message);
273                          
274                 }
275                 
276                 public bool hasErrors(string fn)
277                 {
278                          if (!this.result.has_key(ResultType.err.to_string())) {
279                                  return false;
280                          }
281                          
282                          if (fn.length < 1) {
283                                 return true;
284                          }
285                          var t = this.result.get(ResultType.err.to_string());
286                          
287                          if (t.has_key(fn)) {
288                                  return true;
289                          }
290                          return false;
291                 }
292                 public void dumpErrors(ResultType type)
293                 {
294                          if (!this.result.has_key(type.to_string())) {
295                                  return;
296                          }
297                         var t = this.result.get(type.to_string());
298                         t.map_iterator().foreach((filename, node) => {
299                                         node.map_iterator().foreach(line, errors) => {
300
301                                                 errors.foreach((errstr) => {
302                                                         print("%s: %s:%d %s\n", type.to_string(), filename, line, errstr);
303                                                 });
304                                         });
305                         
306                         });
307                 }
308
309
310 #endif
311                 
312                 
313                 
314                 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
315                 {
316                         foreach(var f in indexes) {
317                                 this.loadSourceIndex(f);
318                         }
319                 }
320                 
321                 public void loadFiles(string[] fs)
322                 {
323                         // fixme -- prefix baseDir?
324                         foreach(var f in fs) {
325                             GLib.debug("add File: %s", f);
326                                 this.files.add(f); //?? easier way?
327                         }
328                 }
329                 public void loadFile(string f)
330                 {
331                     // fixme -- prefix baseDir?
332                     GLib.debug("add File: %s", f);
333                         this.files.add(f); 
334                         GLib.debug("FILE LEN: %d", this.files.size);
335                 }
336                  
337                 
338                 public string pack(string target, string targetDebug = "") throws PackerError 
339                 {
340                     this.target = target;
341                         this.targetDebug  = targetDebug;
342                     
343                     if (this.files.size < 1) {
344                                 throw new PackerError.ArgumentError("No Files loaded before pack() called");
345                         }
346                         if (this.target.length > 0 ) {
347                                 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
348                         }
349                         if (this.targetDebug.length > 0 ) {
350                                 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
351                         }
352                         return this.packAll();
353                 }
354                 
355   
356                  
357  
358            
359                 /**
360                  * load a dependancy list -f option
361                  * @param {String} srcfile sourcefile to parse
362                  * 
363                  */
364                 
365                 public void loadSourceIndex(string in_srcfile)
366                 {
367                     
368                     var srcfile = in_srcfile;
369                     if (srcfile[0] != '/') {
370                                 srcfile = this.baseDir + in_srcfile;
371                         }
372                     string str;
373                     FileUtils.get_contents(srcfile,out str);
374                     
375                     var lines = str.split("\n");
376                     for(var i =0; i < lines.length;i++) {
377  
378                             var f = lines[i].strip();
379                         if (f.length < 1 ||
380                                 Regex.match_simple ("^/", f) ||
381                                 !Regex.match_simple ("[a-zA-Z]+", f) 
382                         ){
383                                 continue; // blank comment or not starting with a-z
384                         }
385                         
386                         if (Regex.match_simple ("\\.js$", f)) {
387                             this.files.add( f);
388                             // js file..
389                             continue;
390                         }
391                         
392                                 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
393                                 // should we prefix? =- or should this be done elsewhere?
394                                 
395                         var add = f.replace(".", "/") + ".js";
396                         
397                         if (add[0] != '/') {
398                                         add = this.baseDir + add;
399                                 }
400                         
401                         if (this.files.contains(add)) {
402                             continue;
403                         }
404                         
405                         
406                         
407                         this.files.add( add );
408                         
409                     }
410                 }
411                 
412     
413                 private string packAll()   // do the packing (run from constructor)
414                 {
415                     
416                     //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
417                     //File.write(this.transfile, "");
418                     if (this.target.length > 0) {
419                         this.targetStream.write("".data);
420                     }
421                     
422                     if (this.targetDebugStream != null) {
423                             this.targetDebugStream.write("".data);
424                     }
425                     
426                     
427                     foreach(var file in this.files) {
428                         
429                         print("reading %s\n",file );
430                         
431                         if (!FileUtils.test (file, FileTest.EXISTS) || FileUtils.test (file, FileTest.IS_DIR)) {
432                             print("SKIP (is not a file) %s\n ", file);
433                             continue;
434                         }
435                        
436                                 var loaded_string = false;
437                                 string file_contents = "";
438                         // debug Target
439                         
440                         if (this.targetDebugStream !=null) {
441                                 
442                                 FileUtils.get_contents(file,out file_contents);
443                             this.targetDebugStream.write(file_contents.data);
444                             loaded_string = false;
445                         }
446                         // it's a good idea to check with 0 compression to see if the code can parse!!
447                         
448                         // debug file..
449                         //File.append(dout, str +"\n"); 
450                         
451                    
452                         
453                         var minfile = this.tmpDir + "/" + file.replace("/", ".");
454                         
455                         
456                         // let's see if we have a min file already?
457                         // this might happen if tmpDir is set .. 
458
459                         
460                         if ( FileUtils.test (minfile, FileTest.EXISTS)) {
461                                  
462                                 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
463                                 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
464                                         
465                                          
466                            // print("%s : compare : Cache file  %s to Orignal Time %s\n", file, mtv.to_iso8601(), otv.to_iso8601());
467                             if (mtv.tv_usec > otv.tv_usec) {
468                                 continue; // file is newer or the same time..
469                                 
470                             }
471                             
472                         }
473                          
474                         print("COMPRESSING to %s\n", minfile);
475                         //var codeComp = pack(str, 10, 0, 0);
476                         if (this.cleanup && FileUtils.test (minfile, FileTest.EXISTS)) {
477                             FileUtils.remove(minfile);
478                         }
479                         if (!loaded_string) {
480                                 FileUtils.get_contents(file,out file_contents);
481                         }
482
483                          this.packFile(file_contents, file, minfile);
484                          
485                       
486                     }
487                     
488                     // at this point if we have errors, we should stop..
489
490                                             
491                         this.dumpErrors(ResultType.warn);
492                         this.dumpErrors(ResultType.err); // since they are fatal - display them last...
493                         
494                         
495                         
496                         
497                         if (this.dumpTokens || this.hasErrors("")) {
498                                  
499                                 GLib.Process.exit(0);
500                         }
501                     print("MERGING SOURCE\n");
502                     
503                     for(var i=0; i < this.files.size; i++)  {
504                         var file = this.files[i];
505                         var minfile = this.tmpDir + "/" + file.replace("/", ".");
506                         
507                         
508                         if ( !FileUtils.test(minfile, FileTest.EXISTS)) {
509                                 print("skipping source %s - does not exist\n", minfile);
510                             continue;
511                         }
512                         string str;
513                         FileUtils.get_contents(minfile, out str);
514                         print("using MIN FILE  %s\n", minfile);
515                         if (str.length > 0) {
516                             if (this.targetStream != null) {
517                                         this.targetStream.write(("// " + 
518                                                 ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length)  : file ) + 
519                                                 "\n").data); 
520                                         this.targetStream.write((str + "\n").data); 
521
522                             } else {
523                                 this.outstr += "//" + 
524                                         ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length)  : file ) +  "\n";
525                                 this.outstr += str + "\n";
526                             }
527                             
528                         }
529                         if (this.cleanup) {
530                             FileUtils.remove(minfile);
531                         }
532                         
533                     }
534                     
535                     
536                     
537                     if (this.target.length > 0 ) {
538                             print("Output file: " + this.target);
539                     }
540                     if (this.targetDebug.length > 0) {
541                                  print("Output debug file: %s\n" , this.targetDebug);
542                         }
543             
544
545             
546                         // OUTPUT should be handled by PackerRun (so that this can be used as a library...)
547                         if (this.outstr.length > 0 ) {
548                 return this.outstr;
549                         //      stdout.printf ("%s", this.outstr);
550                         }
551                     return "";
552                 
553                 
554                 }
555                 /**
556                  * Core packing routine  for a file
557                  * 
558                  * @param str - str source text..
559                  * @param fn - filename (for reference?)
560                  * @param minfile - min file location...
561                  * 
562                  */
563
564                 public  string packFile  (string str,string fn, string minfile)  
565                 {
566
567                         var tr = new  TokenReader(this);
568                         tr.keepDocs =true;
569                         tr.keepWhite = true;
570                         tr.keepComments = true;
571                         tr.sepIdents = true;
572                         tr.collapseWhite = false;
573                         tr.filename = fn;
574  
575                         // we can load translation map here...
576                 
577                         TokenArray toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
578                 
579                         if (this.dumpTokens) {
580                                 toks.dump();
581                                 return "";
582                                 //GLib.Process.exit(0);
583                         }
584                 
585                         this.activeFile = fn;
586                 
587                         // and replace if we are generating a different language..
588                 
589
590                         //var ts = new TokenStream(toks);
591                         //print(JSON.stringify(toks, null,4 )); Seed.quit();
592                         var ts = new Collapse(toks.tokens, this, fn);
593                         
594                         //ts.dumpAll("");                       print("Done collaps"); Process.exit(1);
595                         
596                    // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
597                         //return;//
598                         if (!this.skipScope) {
599                                 var sp = new ScopeParser(ts, this, fn);
600  
601                                 //sp.packer = this;
602                                 sp.buildSymbolTree();
603                                 sp.mungeSymboltree();
604                         
605                         
606                                 sp.printWarnings();
607                         }
608                         
609                         
610                         //print(sp.warnings.join("\n"));
611                         //(new TokenStream(toks.tokens)).dumpAll(""); GLib.Process.exit(1);
612                         // compress works on the original array - in theory the replacements have already been done by now 
613                         var outf = CompressWhite(new TokenStream(toks.tokens), this, this.keepWhite); // do not kill whitespace..
614                 
615                         
616                         debug("RESULT: \n %s\n", outf);
617                         
618                         
619                         
620                         if (outf.length > 0 && minfile.length > 0 && !this.hasErrors(fn)) {
621                                 FileUtils.set_contents(minfile, outf);
622                                  
623                         }  
624
625                 
626                         return outf;
627                 
628                 
629                          
630                 }
631                  
632
633                 public string md5(string str)
634                 {
635                 
636                         return GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str);
637                 
638                 }
639     
640          //stringHandler : function(tok) -- not used...
641     }
642     
643 }