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