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