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