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