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