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