fix hasErrors - ignore warnings
[roojspacker] / roojspacker / 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                 // list of files to compile...
89                 public Gee.ArrayList<string> files;
90                 
91                 /**
92                 * @cfg activeFile ??? used???
93                 */
94                  
95                 public string activeFile = "";
96                         
97                 public  string outstr = ""; // if no target is specified - then this will contain the result
98                 
99                 public PackerRun config;
100                 
101                 public Packer(PackerRun config)
102                 {
103                         this.config = config;
104 //#if HAVE_JSON_GLIB
105                         this.result = new Json.Object();
106 //#else
107 //                      this.result_count = new  Gee.HashMap <string,int>();
108 //              
109 //                      this.result =  new Gee.HashMap<
110 //#                             string /* errtype*/ , Gee.HashMap<string /*fn*/,     Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>
111 //#                     >();
112 //#endif                        
113 //
114                         this.files = new Gee.ArrayList<string>();
115                         
116                         new Lang_Class(); ///initilizaze lang..
117                         
118                         //this.tmp = Glib.get_tmp_dir(); // do we have to delete this?
119                         
120                          
121                 }
122                 
123                 
124                 // this could be another class really..
125                 
126                 public enum ResultType { 
127                         err = 1 , 
128                         warn = 2;
129                         public string to_string() { 
130                                 switch(this) {
131                                         case err: return "ERR";
132                                         case warn: return "WARN";
133                                         default: assert_not_reached();
134                                 }
135                         
136                           }
137                   }
138                 /**
139                 *  result of complication - a JSON object containing warnings / errors etc..
140                 *  FORMAT:
141                 *     warn-TOTAL : X  (number of warnings.
142                 *     err-TOTAL: X  (number of errors) << this indicates failure...
143                 *     warn : {
144                 *            FILENAME : {
145                 *                  line : [ Errors,Errors,.... ]
146                 *     err : {
147                 *           .. sane format..
148                 *
149                 */
150                 
151 //#if HAVE_JSON_GLIB
152                 
153                 // loosely based on diagnostics in LSP
154                 // key/value  key = filename / value = LSP.Diagnostic
155                 
156                 public Json.Object result;   // output - what's the complication result
157                 
158
159                 public void  logError(ResultType type, string filename, int line, string message)
160                 {
161                         if (!this.result.has_member(type.to_string())) {
162                                 this.result.set_array_member(filename, new Json.Array());
163                         }
164                         var fa = this.result.get_array_member( filename);
165                         var diag = new Json.Object();
166                         diag.set_string_member( "message", message );
167                         diag.set_int_member( "severity", (int) type );
168                         diag.set_int_member( "line", line );
169                         fa.add_object_element(diag);
170                         
171                          
172                 }
173                  
174                 public bool hasErrors(string fn)
175                 {
176                           var ret = false;
177                           this.result.foreach_member((obj, filename, node) => {
178                                 if (ret) {
179                                         return;
180                                 }
181                                 var ar = this.result.get_array_member(filename.to_string());                            
182                                 if (fn == "") {
183                                         
184                                         for(var i = 0 ; i < ar.get_length(); i++) {
185                                                 if (ar.get_object_element(i).get_int_member("severity") != ResultType.warn) {
186                                 
187                                                         ret = true;
188                                                         return;
189                                                 }
190                                         }
191                                         
192                                         return; // next.
193                                 }
194                                 
195                                 if (fn != filename) {
196                                         return; // next;
197                                 }
198                                 for(var i = 0 ; i < ar.get_length(); i++) {
199                                         if (ar.get_object_element(i).get_int_member("severity") != ResultType.warn) {
200                         
201                                                 ret = true;
202                                                 return;
203                                         }
204                                 }
205                                 
206                          });
207                         
208                          return ret;
209                 }
210                  
211                 public void dumpErrors(ResultType type)
212                 {
213                          this.result.foreach_member((obj, filename, node) => {
214                                  
215                                 var ar = this.result.get_array_member(filename.to_string());
216                                 for(var i = 0; i < ar.get_length(); i++) {
217                                         var el = ar.get_object_element(i);
218                                         var ty = el.get_int_member("severity");
219                                         if ((int)ty != type) {
220                                                 continue;
221                                         }
222                                     print("%s: %s:%d %s\n", type.to_string(), filename, (int)el.get_int_member("line"),  el.get_string_member("message"));
223
224                                 }
225                         
226                         });
227                 }
228
229 /*#else
230                 public Gee.HashMap <string,int> result_count;   // output - what's the complication result
231                 
232                 public Gee.HashMap<
233                                 string // errtype
234                                 , Gee.HashMap<string //fn
235                                         ,Gee.HashMap<int //line 
236                                                 , Gee.ArrayList<string>>>
237                 > result;
238
239                 public void  logError(ResultType type, string filename, int line, string message) {
240                          
241                          
242                          if (!this.result_count.has_key(type.to_string()+"-TOTAL")) {
243                                  this.result_count.set(type.to_string()+"-TOTAL", 1);
244                          } else {
245                                 this.result_count.set(type.to_string()+"-TOTAL",                                 
246                                         this.result_count.get(type.to_string()+"-TOTAL") +1
247                                 );
248                          }
249                          
250                          
251                          
252                          if (!this.result.has_key(type.to_string())) {
253                                  this.result.set(type.to_string(),
254                                          new Gee.HashMap<string //fn 
255                                          ,     Gee.HashMap<int //line
256                                                         , Gee.ArrayList<string>>>()
257                                  );
258                          }
259                          var t = this.result.get(type.to_string());
260                          if (!t.has_key(filename)) {
261                                  t.set(filename, new  Gee.HashMap<int //line
262                                          , Gee.ArrayList<string>>());
263                          }
264                          var tt = t.get(filename);
265                          if (!tt.has_key(line)) {
266                                  tt.set(line, new Gee.ArrayList<string>());
267                          }
268                          var tl = tt.get(line);
269                          tl.add(message);
270                          
271                 }
272                 
273                 public bool hasErrors(string fn)
274                 {
275                          if (!this.result.has_key(ResultType.err.to_string())) {
276                                  return false;
277                          }
278                          
279                          if (fn.length < 1) {
280                                 return true;
281                          }
282                          var t = this.result.get(ResultType.err.to_string());
283                          
284                          if (t.has_key(fn)) {
285                                  return true;
286                          }
287                          return false;
288                 }
289                 public void dumpErrors(ResultType type)
290                 {
291                          if (!this.result.has_key(type.to_string())) {
292                                  return;
293                          }
294                         var t = this.result.get(type.to_string());
295                         foreach(string filename in t.keys) {
296                                 var node = t.get(filename);
297                                 foreach(int line in node.keys) {
298                                         var errors = node.get(line);
299                                         foreach(string errstr in errors) {
300                                                         print("%s: %s:%d %s\n", type.to_string(), filename, line, errstr);
301                                         }
302                                 }
303                         
304                         }
305                 }
306
307
308 #endif
309 */              
310                 
311                 
312                 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
313                 {
314                         foreach(var f in indexes) {
315                                 this.loadSourceIndex(f);
316                         }
317                 }
318                 
319                 public void loadFiles(string[] fs)
320                 {
321                         // fixme -- prefix baseDir?
322                         foreach(var f in fs) {
323                             GLib.debug("add File: %s", f);
324                                 this.files.add(f); //?? easier way?
325                         }
326                 }
327                 public void loadFile(string f)
328                 {
329                     // fixme -- prefix baseDir?
330                     GLib.debug("add File: %s", f);
331                         this.files.add(f); 
332                         GLib.debug("FILE LEN: %d", this.files.size);
333                 }
334                  
335                 
336                 public string pack(string target, string targetDebug = "") throws PackerError 
337                 {
338                     this.target = target;
339                         this.targetDebug  = targetDebug;
340                     
341                     if (this.files.size < 1) {
342                                 throw new PackerError.ArgumentError("No Files loaded before pack() called");
343                         }
344                         if (this.target.length > 0 ) {
345                                 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
346                         }
347                         if (this.targetDebug.length > 0 ) {
348                                 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
349                         }
350                         return this.packAll();
351                 }
352                 
353   
354                  
355  
356            
357                 /**
358                  * load a dependancy list -f option
359                  * @param {String} srcfile sourcefile to parse
360                  * 
361                  */
362                 
363                 public void loadSourceIndex(string in_srcfile)
364                 {
365                     
366                     var srcfile = in_srcfile;
367                     if (srcfile[0] != '/') {
368                                 srcfile = config.opt_real_basedir + in_srcfile;
369                         }
370                     string str;
371                     FileUtils.get_contents(srcfile,out str);
372                     
373                     var lines = str.split("\n");
374                     for(var i =0; i < lines.length;i++) {
375  
376                             var f = lines[i].strip();
377                         if (f.length < 1 ||
378                                 Regex.match_simple ("^/", f) ||
379                                 !Regex.match_simple ("[a-zA-Z]+", f) 
380                         ){
381                                 continue; // blank comment or not starting with a-z
382                         }
383                         
384                         if (Regex.match_simple ("\\.js$", f)) {
385                             this.files.add( f);
386                             // js file..
387                             continue;
388                         }
389                         
390                                 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
391                                 // should we prefix? =- or should this be done elsewhere?
392                                 
393                         var add = f.replace(".", "/") + ".js";
394                         
395                         if (add[0] != '/') {
396                                         add = config.opt_real_basedir + add;
397                                 }
398                         
399                         if (this.files.contains(add)) {
400                             continue;
401                         }
402                         
403                         
404                         
405                         this.files.add( add );
406                         
407                     }
408                 }
409                 
410     
411                 private string packAll()   // do the packing (run from constructor)
412                 {
413                     
414                     //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
415                     //File.write(this.transfile, "");
416                     if (this.target.length > 0) {
417                         this.targetStream.write("".data);
418                     }
419                     
420                     if (this.targetDebugStream != null) {
421                             this.targetDebugStream.write("".data);
422                     }
423                     
424                     
425                     var tmpDir = GLib.DirUtils.make_tmp("roojspacker_XXXXXX");
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 = 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 (config.opt_clean_cache && 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 (config.opt_dump_tokens || 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 = 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 > config.opt_real_basedir.length) ? file.substring(config.opt_real_basedir.length)  : file ) + 
519                                                 "\n").data); 
520
521                                         this.targetStream.write((str + "\n").data); 
522
523                             } else {
524                                 this.outstr += "//" + 
525                                         ( (file.length > config.opt_real_basedir.length) ? file.substring(config.opt_real_basedir.length)  : file ) +  "\n";
526                                 this.outstr += "//" +  file  +"\n";
527
528                                      this.outstr += str + "\n";
529                             }
530                             
531                         }
532                         if (config.opt_clean_cache) {
533                             FileUtils.remove(minfile);
534                         }
535                         
536                     }
537                     if (config.opt_clean_cache) {
538                                 FileUtils.remove(tmpDir);
539                         }
540                     
541                     if (this.target.length > 0 ) {
542                             print("Output file: " + this.target);
543                     }
544                     if (this.targetDebug.length > 0) {
545                                  print("Output debug file: %s\n" , this.targetDebug);
546                         }
547             
548
549             
550                         // OUTPUT should be handled by PackerRun (so that this can be used as a library...)
551                         if (this.outstr.length > 0 ) {
552                 return this.outstr;
553                         //      stdout.printf ("%s", this.outstr);
554                         }
555                     return "";
556                 
557                 
558                 }
559                 /**
560                  * Core packing routine  for a file
561                  * 
562                  * @param str - str source text..
563                  * @param fn - filename (for reference?)
564                  * @param minfile - min file location...
565                  * 
566                  */
567
568                 public  string packFile  (string str,string fn, string minfile)  
569                 {
570
571                         var tr = new  TokenReader(this);
572                         tr.keepDocs =true;
573                         tr.keepWhite = true;
574                         tr.keepComments = true;
575                         tr.sepIdents = true;
576                         tr.collapseWhite = false;
577                         tr.filename = fn;
578  
579                         // we can load translation map here...
580                 
581                         TokenArray toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
582                 
583                         if (config.opt_dump_tokens) {
584                                 toks.dump();
585                                 return "";
586                                 //GLib.Process.exit(0);
587                         }
588                 
589                         this.activeFile = fn;
590                 
591                         // and replace if we are generating a different language..
592                 
593
594                         //var ts = new TokenStream(toks);
595                         //print(JSON.stringify(toks, null,4 )); Seed.quit();
596                         var ts = new Collapse(toks.tokens, this, fn);
597                         
598                         //ts.dumpAll("");                       print("Done collaps"); Process.exit(1);
599                         
600                    // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
601                         //return;//
602                         if (!config.opt_skip_scope) {
603                                 var sp = new ScopeParser(ts, this, fn);
604  
605                                 //sp.packer = this;
606                                 sp.buildSymbolTree();
607                                 sp.mungeSymboltree();
608                         
609                         
610                                 sp.printWarnings();
611                         }
612                         
613                         
614                         //print(sp.warnings.join("\n"));
615                         //(new TokenStream(toks.tokens)).dumpAll(""); GLib.Process.exit(1);
616                         // compress works on the original array - in theory the replacements have already been done by now 
617                         var outf = CompressWhite(new TokenStream(toks.tokens), this, config.opt_keep_whitespace); // do not kill whitespace..
618                 
619                         
620         //              debug("RESULT: \n %s\n", outf);
621                         
622                         
623                         
624                         if (outf.length > 0 && minfile.length > 0 && !this.hasErrors(fn)) {
625                                 FileUtils.set_contents(minfile, outf);
626                                  
627                         }  
628
629                 
630                         return outf;
631                 
632                 
633                          
634                 }
635                  
636
637                 public string md5(string str)
638                 {
639                 
640                         return GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str);
641                 
642                 }
643     
644          //stringHandler : function(tok) -- not used...
645     }
646     
647 }