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