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