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