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