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 #if HAVE_JSON_GLIB
142                         this.result = new Json.Object();
143 #else
144                         this.result_count = new  Gee.HashMap <string,int>();
145                 
146                         this.result =  new Gee.HashMap<
147                                 string /* errtype*/ , Gee.HashMap<string /*fn*/,     Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>
148                         >();
149         
150 #endif                  
151                         this.files = new Gee.ArrayList<string>();
152                         
153                         new Lang_Class(); ///initilizaze lang..
154                          
155                 }
156                 
157                 
158                 // this could be another class really..
159                 
160                 public enum ResultType { 
161                         err , 
162                         warn;
163                         public string to_string() { 
164                                 switch(this) {
165                                         case err: return "ERR";
166                                         case warn: return "WARN";
167                                         default: assert_not_reached();
168                                 }
169                         
170                           }
171                   }
172                 /**
173                 *  result of complication - a JSON object containing warnings / errors etc..
174                 *  FORMAT:
175                 *     warn-TOTAL : X  (number of warnings.
176                 *     err-TOTAL: X  (number of errors) << this indicates failure...
177                 *     warn : {
178                 *            FILENAME : {
179                 *                  line : [ Errors,Errors,.... ]
180                 *     err : {
181                 *           .. sane format..
182                 *
183                 */
184                 
185 #if HAVE_JSON_GLIB
186                 
187                 public Json.Object result;   // output - what's the complication result
188
189                 public void  logError(ResultType type, string filename, int line, string message) {
190                          
191                          if (!this.result.has_member(type.to_string()+"-TOTAL")) {
192                                  this.result.set_int_member(type.to_string()+"-TOTAL", 1);
193                          } else {
194                                 this.result.set_int_member(type.to_string()+"-TOTAL", 
195                                         this.result.get_int_member(type.to_string()+"-TOTAL") +1 
196                                 );
197                          }
198                          
199                          
200                          if (!this.result.has_member(type.to_string())) {
201                                  this.result.set_object_member(type.to_string(), new Json.Object());
202                          }
203                          var t = this.result.get_object_member(type.to_string());
204                          if (!t.has_member(filename)) {
205                                  t.set_object_member(filename, new Json.Object());
206                          }
207                          var tt = t.get_object_member(filename);
208                          if (!tt.has_member(line.to_string())) {
209                                  tt.set_array_member(line.to_string(), new Json.Array());
210                          }
211                          var tl = tt.get_array_member(line.to_string());
212                          tl.add_string_element(message);
213                          
214                 }
215                 
216                 public bool hasErrors(string fn)
217                 {
218                          if (!this.result.has_member(ResultType.err.to_string())) {
219                                  return false;
220                          }
221                          
222                          if (fn.length < 1) {
223                                 return true;
224                          }
225                          var t = this.result.get_object_member(ResultType.err.to_string());
226                          
227                          if (t.has_member(fn)) {
228                                  return true;
229                          }
230                          return false;
231                 }
232                 public void dumpErrors(ResultType type)
233                 {
234                          if (!this.result.has_member(type.to_string())) {
235                                  return;
236                          }
237                         var t = this.result.get_object_member(type.to_string());
238                         t.foreach_member((obj, filename, node) => {
239                                         var linelist = node.dup_object();
240                                         linelist.foreach_member((linelistobj, linestr, nodear) => {
241                                                 var errors=  nodear.dup_array();
242                                                 errors.foreach_element((errorar, ignore, nodestr) => {
243                                                         print("%s: %s:%s %s\n", type.to_string(), filename, linestr, nodestr.get_string());
244                                                 });
245                                         });
246                         
247                         });
248                 }
249 #else
250                 public Gee.HashMap <string,int> result_count;   // output - what's the complication result
251                 
252                 public Gee.HashMap<
253                                 string /* errtype*/ , Gee.HashMap<string /*fn*/,     Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>
254                 > result;
255
256                 public void  logError(ResultType type, string filename, int line, string message) {
257                          
258                          
259                          if (!this.result_count.has_key(type.to_string()+"-TOTAL")) {
260                                  this.result_count.set(type.to_string()+"-TOTAL", 1);
261                          } else {
262                                 this.result_count.set(type.to_string()+"-TOTAL",                                 
263                                         this.result_count.get(type.to_string()+"-TOTAL") +1
264                                 );
265                          }
266                          
267                          
268                          
269                          if (!this.result.has_key(type.to_string())) {
270                                  this.result.set(type.to_string(),
271                                          new Gee.HashMap<string /*fn*/,     Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>()
272                                  );
273                          }
274                          var t = this.result.get(type.to_string());
275                          if (!t.has_key(filename)) {
276                                  t.set(filename, new  Gee.HashMap<int /*line*/, Gee.ArrayList<string>>());
277                          }
278                          var tt = t.get(filename);
279                          if (!tt.has_key(line)) {
280                                  tt.set(line, new Gee.ArrayList<string>());
281                          }
282                          var tl = tt.get(line);
283                          tl.line(message);
284                          
285                 }
286                 
287                 public bool hasErrors(string fn)
288                 {
289                          if (!this.result.has_key(ResultType.err.to_string())) {
290                                  return false;
291                          }
292                          
293                          if (fn.length < 1) {
294                                 return true;
295                          }
296                          var t = this.result.get(ResultType.err.to_string());
297                          
298                          if (t.has_key(fn)) {
299                                  return true;
300                          }
301                          return false;
302                 }
303                 public void dumpErrors(ResultType type)
304                 {
305                          if (!this.result.has_key(type.to_string())) {
306                                  return;
307                          }
308                         var t = this.result.get(type.to_string());
309                         foreach(string filename in t.keys) {
310                                 var node = t.get(filename);
311                                 foreach(int line in node.keys) {
312                                         var errors = node.get(line);
313                                         foreach(string errstr in errors) {
314                                                         print("%s: %s:%d %s\n", type.to_string(), filename, line, errstr);
315                                         }
316                                 }
317                         
318                         }
319                 }
320
321
322 #endif
323                 
324                 
325                 
326                 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
327                 {
328                         foreach(var f in indexes) {
329                                 this.loadSourceIndex(f);
330                         }
331                 }
332                 
333                 public void loadFiles(string[] fs)
334                 {
335                         // fixme -- prefix baseDir?
336                         foreach(var f in fs) {
337                             GLib.debug("add File: %s", f);
338                                 this.files.add(f); //?? easier way?
339                         }
340                 }
341                 public void loadFile(string f)
342                 {
343                     // fixme -- prefix baseDir?
344                     GLib.debug("add File: %s", f);
345                         this.files.add(f); 
346                         GLib.debug("FILE LEN: %d", this.files.size);
347                 }
348                  
349                 
350                 public string pack(string target, string targetDebug = "") throws PackerError 
351                 {
352                     this.target = target;
353                         this.targetDebug  = targetDebug;
354                     
355                     if (this.files.size < 1) {
356                                 throw new PackerError.ArgumentError("No Files loaded before pack() called");
357                         }
358                         if (this.target.length > 0 ) {
359                                 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
360                         }
361                         if (this.targetDebug.length > 0 ) {
362                                 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
363                         }
364                         return this.packAll();
365                 }
366                 
367   
368                  
369  
370            
371                 /**
372                  * load a dependancy list -f option
373                  * @param {String} srcfile sourcefile to parse
374                  * 
375                  */
376                 
377                 public void loadSourceIndex(string in_srcfile)
378                 {
379                     
380                     var srcfile = in_srcfile;
381                     if (srcfile[0] != '/') {
382                                 srcfile = this.baseDir + in_srcfile;
383                         }
384                     string str;
385                     FileUtils.get_contents(srcfile,out str);
386                     
387                     var lines = str.split("\n");
388                     for(var i =0; i < lines.length;i++) {
389  
390                             var f = lines[i].strip();
391                         if (f.length < 1 ||
392                                 Regex.match_simple ("^/", f) ||
393                                 !Regex.match_simple ("[a-zA-Z]+", f) 
394                         ){
395                                 continue; // blank comment or not starting with a-z
396                         }
397                         
398                         if (Regex.match_simple ("\\.js$", f)) {
399                             this.files.add( f);
400                             // js file..
401                             continue;
402                         }
403                         
404                                 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
405                                 // should we prefix? =- or should this be done elsewhere?
406                                 
407                         var add = f.replace(".", "/") + ".js";
408                         
409                         if (add[0] != '/') {
410                                         add = this.baseDir + add;
411                                 }
412                         
413                         if (this.files.contains(add)) {
414                             continue;
415                         }
416                         
417                         
418                         
419                         this.files.add( add );
420                         
421                     }
422                 }
423                 
424     
425                 private string packAll()   // do the packing (run from constructor)
426                 {
427                     
428                     //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
429                     //File.write(this.transfile, "");
430                     if (this.target.length > 0) {
431                         this.targetStream.write("".data);
432                     }
433                     
434                     if (this.targetDebugStream != null) {
435                             this.targetDebugStream.write("".data);
436                     }
437                     
438                     
439                     foreach(var file in this.files) {
440                         
441                         print("reading %s\n",file );
442                         
443                         if (!FileUtils.test (file, FileTest.EXISTS) || FileUtils.test (file, FileTest.IS_DIR)) {
444                             print("SKIP (is not a file) %s\n ", file);
445                             continue;
446                         }
447                        
448                                 var loaded_string = false;
449                                 string file_contents = "";
450                         // debug Target
451                         
452                         if (this.targetDebugStream !=null) {
453                                 
454                                 FileUtils.get_contents(file,out file_contents);
455                             this.targetDebugStream.write(file_contents.data);
456                             loaded_string = false;
457                         }
458                         // it's a good idea to check with 0 compression to see if the code can parse!!
459                         
460                         // debug file..
461                         //File.append(dout, str +"\n"); 
462                         
463                    
464                         
465                         var minfile = this.tmpDir + "/" + file.replace("/", ".");
466                         
467                         
468                         // let's see if we have a min file already?
469                         // this might happen if tmpDir is set .. 
470
471                         
472                         if ( FileUtils.test (minfile, FileTest.EXISTS)) {
473                                  
474                                 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
475                                 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
476                                         
477                                          
478                            // print("%s : compare : Cache file  %s to Orignal Time %s\n", file, mtv.to_iso8601(), otv.to_iso8601());
479                             if (mtv.tv_usec > otv.tv_usec) {
480                                 continue; // file is newer or the same time..
481                                 
482                             }
483                             
484                         }
485                          
486                         print("COMPRESSING to %s\n", minfile);
487                         //var codeComp = pack(str, 10, 0, 0);
488                         if (this.cleanup && FileUtils.test (minfile, FileTest.EXISTS)) {
489                             FileUtils.remove(minfile);
490                         }
491                         if (!loaded_string) {
492                                 FileUtils.get_contents(file,out file_contents);
493                         }
494
495                          this.packFile(file_contents, file, minfile);
496                          
497                       
498                     }
499                     
500                     // at this point if we have errors, we should stop..
501
502                                             
503                         this.dumpErrors(ResultType.warn);
504                         this.dumpErrors(ResultType.err); // since they are fatal - display them last...
505                         
506                         
507                         
508                         
509                         if (this.dumpTokens || this.hasErrors("")) {
510                                  
511                                 GLib.Process.exit(0);
512                         }
513                     print("MERGING SOURCE\n");
514                     
515                     for(var i=0; i < this.files.size; i++)  {
516                         var file = this.files[i];
517                         var minfile = this.tmpDir + "/" + file.replace("/", ".");
518                         
519                         
520                         if ( !FileUtils.test(minfile, FileTest.EXISTS)) {
521                                 print("skipping source %s - does not exist\n", minfile);
522                             continue;
523                         }
524                         string str;
525                         FileUtils.get_contents(minfile, out str);
526                         print("using MIN FILE  %s\n", minfile);
527                         if (str.length > 0) {
528                             if (this.targetStream != null) {
529                                         this.targetStream.write(("// " + 
530                                                 ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length)  : file ) + 
531                                                 "\n").data); 
532                                         this.targetStream.write((str + "\n").data); 
533
534                             } else {
535                                 this.outstr += "//" + 
536                                         ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length)  : file ) +  "\n";
537                                 this.outstr += str + "\n";
538                             }
539                             
540                         }
541                         if (this.cleanup) {
542                             FileUtils.remove(minfile);
543                         }
544                         
545                     }
546                     
547                     
548                     
549                     if (this.target.length > 0 ) {
550                             print("Output file: " + this.target);
551                     }
552                     if (this.targetDebug.length > 0) {
553                                  print("Output debug file: %s\n" , this.targetDebug);
554                         }
555             
556
557             
558                         // OUTPUT should be handled by PackerRun (so that this can be used as a library...)
559                         if (this.outstr.length > 0 ) {
560                 return this.outstr;
561                         //      stdout.printf ("%s", this.outstr);
562                         }
563                     return "";
564                 
565                 
566                 }
567                 /**
568                  * Core packing routine  for a file
569                  * 
570                  * @param str - str source text..
571                  * @param fn - filename (for reference?)
572                  * @param minfile - min file location...
573                  * 
574                  */
575
576                 public  string packFile  (string str,string fn, string minfile)  
577                 {
578
579                         var tr = new  TokenReader(this);
580                         tr.keepDocs =true;
581                         tr.keepWhite = true;
582                         tr.keepComments = true;
583                         tr.sepIdents = true;
584                         tr.collapseWhite = false;
585                         tr.filename = fn;
586  
587                         // we can load translation map here...
588                 
589                         TokenArray toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
590                 
591                         if (this.dumpTokens) {
592                                 toks.dump();
593                                 return "";
594                                 //GLib.Process.exit(0);
595                         }
596                 
597                         this.activeFile = fn;
598                 
599                         // and replace if we are generating a different language..
600                 
601
602                         //var ts = new TokenStream(toks);
603                         //print(JSON.stringify(toks, null,4 )); Seed.quit();
604                         var ts = new Collapse(toks.tokens, this, fn);
605                         
606                         //ts.dumpAll("");                       print("Done collaps"); Process.exit(1);
607                         
608                    // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
609                         //return;//
610                         if (!this.skipScope) {
611                                 var sp = new ScopeParser(ts, this, fn);
612  
613                                 //sp.packer = this;
614                                 sp.buildSymbolTree();
615                                 sp.mungeSymboltree();
616                         
617                         
618                                 sp.printWarnings();
619                         }
620                         
621                         
622                         //print(sp.warnings.join("\n"));
623                         //(new TokenStream(toks.tokens)).dumpAll(""); GLib.Process.exit(1);
624                         // compress works on the original array - in theory the replacements have already been done by now 
625                         var outf = CompressWhite(new TokenStream(toks.tokens), this, this.keepWhite); // do not kill whitespace..
626                 
627                         
628                         debug("RESULT: \n %s\n", outf);
629                         
630                         
631                         
632                         if (outf.length > 0 && minfile.length > 0 && !this.hasErrors(fn)) {
633                                 FileUtils.set_contents(minfile, outf);
634                                  
635                         }  
636
637                 
638                         return outf;
639                 
640                 
641                          
642                 }
643                  
644
645                 public string md5(string str)
646                 {
647                 
648                         return GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str);
649                 
650                 }
651     
652          //stringHandler : function(tok) -- not used...
653     }
654     
655 }