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