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