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