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