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