JSDOC/CompressWhite.vala
[gnome.introspection-doc-generator] / 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 =  true;
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                 // list of files to compile...
103                 Gee.ArrayList<string> files;
104                 
105                 /**
106                 * @cfg debug -- pretty obvious.
107                 */
108                  
109                 public string activeFile = "";
110                 
111                 
112                 public  string outstr = ""; // if no target is specified - then this will contain the result
113     
114                 public Packer(string target, string targetDebug = "")
115                 {
116                         this.target = target;
117                         this.targetDebug  = targetDebug;
118                         this.files = new Gee.ArrayList<string>();
119                         
120                         new Lang_Class(); ///initilizaze lang..
121                          
122                 }
123                 
124                 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
125                 {
126                         foreach(var f in indexes) {
127                                 this.loadSourceIndex(f);
128                         }
129                 }
130                 
131                 public void loadFiles(string[] fs)
132                 {
133                         foreach(var f in fs) {
134                             GLib.debug("add File: %s", f);
135                                 this.files.add(f); //?? easier way?
136                         }
137                 }
138                 public void loadFile(string f)
139                 {
140                     GLib.debug("add File: %s", f);
141                         this.files.add(f); 
142                         GLib.debug("FILE LEN: %d", this.files.size);
143                 }
144                 
145                 public void pack()
146                 {
147                     if (this.files.size < 1) {
148                                 throw new PackerError.ArgumentError("No Files loaded before pack() called");
149                         }
150                         if (this.target.length > 0 ) {
151                                 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
152                         }
153                         if (this.targetDebug.length > 0 ) {
154                                 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
155                         }
156                         this.packAll();
157                 }
158                 
159   
160                 
161                 
162    
163                 
164  
165            
166                 /**
167                  * load a dependancy list -f option
168                  * @param {String} srcfile sourcefile to parse
169                  * 
170                  */
171                 
172                 public void loadSourceIndex(string srcfile)
173                 {
174                     string str;
175                     FileUtils.get_contents(srcfile,out str);
176                     
177                     var lines = str.split("\n");
178                     for(var i =0; i < lines.length;i++) {
179  
180                             var f = lines[i].strip();
181                         if (f.length < 1 ||
182                                 Regex.match_simple ("^/", f) ||
183                                 !Regex.match_simple ("[a-zA-Z]+", f) 
184                         ){
185                                 continue; // blank comment or not starting with a-z
186                         }
187                         
188                         if (Regex.match_simple ("\\.js$", f)) {
189                             this.files.add( f);
190                             // js file..
191                             continue;
192                         }
193                         
194                                 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
195                                 // should we prefix? =- or should this be done elsewhere?
196                                 
197                         var add = f.replace(".", "/") + ".js";
198                         if (this.files.contains(add)) {
199                             continue;
200                         }
201                         this.files.add( add );
202                         
203                     }
204                 }
205                 
206     
207                 private void packAll()  // do the packing (run from constructor)
208                 {
209                     
210                     //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
211                     //File.write(this.transfile, "");
212                     if (this.target.length > 0) {
213                         this.targetStream.write("".data);
214                     }
215                     
216                     if (this.targetDebugStream != null) {
217                             this.targetDebugStream.write("".data);
218                     }
219                     
220                     
221                     foreach(var file in this.files) {
222                         
223                         print("reading %s\n",file );
224                         
225                         if (!FileUtils.test (file, FileTest.EXISTS) || FileUtils.test (file, FileTest.IS_DIR)) {
226                             print("SKIP (is not a file) %s\n ", file);
227                             continue;
228                         }
229                        
230                                 var loaded_string = false;
231                                 string file_contents = "";
232                         // debug Target
233                         
234                         if (this.targetDebugStream !=null) {
235                                 
236                                 FileUtils.get_contents(file,out file_contents);
237                             this.targetDebugStream.write(file_contents.data);
238                             loaded_string = false;
239                         }
240                         // it's a good idea to check with 0 compression to see if the code can parse!!
241                         
242                         // debug file..
243                         //File.append(dout, str +"\n"); 
244                         
245                    
246                         
247                         var minfile = this.tmpDir + "/" + file.replace("/", ".");
248                         
249                         
250                         // let's see if we have a min file already?
251                         // this might happen if tmpDir is set .. 
252
253                         
254                         if (false && FileUtils.test (minfile, FileTest.EXISTS)) {
255                                 
256                                 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
257                                 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
258                                         
259                                         var ot = new Date();
260                                         ot.set_time_val(otv);
261                                         var mt = new Date();
262                                         mt.set_time_val(mtv);
263                             //print("compare : " + mt + "=>" + ot);
264                             if (mt.compare(ot) >= 0) {
265                                 continue; // file is newer or the same time..
266                                 
267                             }
268                             
269                         }
270                          
271                         print("COMPRESSING to %s\n", minfile);
272                         //var codeComp = pack(str, 10, 0, 0);
273                         if (FileUtils.test (minfile, FileTest.EXISTS)) {
274                             FileUtils.remove(minfile);
275                         }
276                         if (!loaded_string) {
277                                 FileUtils.get_contents(file,out file_contents);
278                         }
279
280                          this.packFile(file_contents, file, minfile);
281                          
282                       
283                     }
284                     
285                   
286                     print("MERGING SOURCE\n");
287                     
288                     for(var i=0; i < this.files.size; i++)  {
289                         var file = this.files[i];
290                         var minfile = this.tmpDir + "/" + file.replace("/", ".");
291                         
292                         
293                         if ( !FileUtils.test(minfile, FileTest.EXISTS)) {
294                                 print("skipping source %s - does not exist\n", minfile);
295                             continue;
296                         }
297                         string str;
298                         FileUtils.get_contents(minfile, out str);
299                         print("using MIN FILE  %s\n", minfile);
300                         if (str.length > 0) {
301                             if (this.targetStream != null) {
302                                         this.targetStream.write(("// " + file + "\n").data); 
303                                         this.targetStream.write((str + "\n").data); 
304
305                             } else {
306                                 this.outstr += "//" + file + "\n";
307                                 this.outstr += str + "\n";
308                             }
309                             
310                         }
311                         if (this.cleanup) {
312                             FileUtils.remove(minfile);
313                         }
314                         
315                     }
316                     if (this.target.length > 0 ) {
317                             print("Output file: " + this.target);
318                     }
319                     if (this.targetDebug.length > 0) {
320                                  print("Output debug file: %s\n" , this.targetDebug);
321                         }  
322                         
323                         if (this.outstr.length > 0 ) {
324                                 print(this.outstr);
325                         }
326                      
327                 
328                 
329                 }
330                 /**
331                  * Core packing routine  for a file
332                  * 
333                  * @param str - str source text..
334                  * @param fn - filename (for reference?)
335                  * @param minfile - min file location...
336                  * 
337                  */
338
339                 private string packFile  (string str,string fn, string minfile)
340                 {
341
342                         var tr = new  TokenReader();
343                         tr.keepDocs =true;
344                         tr.keepWhite = true;
345                         tr.keepComments = true;
346                         tr.sepIdents = true;
347                         tr.collapseWhite = false;
348                         tr.filename = fn;
349  
350                         // we can load translation map here...
351                 
352                         TokenArray toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
353                 
354                 
355                 
356                         this.activeFile = fn;
357                 
358                         // and replace if we are generating a different language..
359                 
360
361                         //var ts = new TokenStream(toks);
362                         //print(JSON.stringify(toks, null,4 )); Seed.quit();
363                         var ts = new Collapse(toks.tokens);
364                         
365                         //ts.dumpAll("");                       print("Done collaps"); Process.exit(1);
366                         
367                    // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
368                         //return;//
369                         var sp = new ScopeParser(ts);
370  
371                         //sp.packer = this;
372                         sp.buildSymbolTree();
373
374                         sp.mungeSymboltree();
375                         sp.printWarnings();
376                         //print(sp.warnings.join("\n"));
377
378                 
379                         var outf = CompressWhite(new TokenStream(toks.tokens), this, this.keepWhite); // do not kill whitespace..
380                 
381                         
382                         print("RESULT: \n %s\n", outf);
383                 
384                          if (outf.length > 0) {
385                                 FileUtils.set_contents(minfile, outf);
386                                  
387                         }  
388
389                 
390                         return outf;
391                 
392                 
393                          
394                 }
395                  
396
397                 public string md5(string str)
398                 {
399                 
400                         return GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str);
401                 
402                 }
403     
404          //stringHandler : function(tok) -- not used...
405     }
406     
407 }