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