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