99574f768f76ecc13909b5bbcf96c2814c373499
[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 x.debugTranslateTarget : "/tmp/output.translate.js" << this used to be the single vs double quotes.. we may not use it in future..
23 x.translateJSON: "/tmp/translate.json",
24     
25 x.packAll();  // writes files  etc..
26     
27  *</code> 
28  *
29  * Notes for improving compacting:
30  *  if you add a jsdoc comment 
31  * <code>
32  * /**
33  *   eval:var:avarname
34  *   eval:var:bvarname
35  *   ....
36  * </code>
37  * directly before an eval statement, it will compress all the code around the eval, 
38  * and not rename the variables 'avarname'
39  * 
40  * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
41  * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
42  * 
43  * 
44  * 
45  * Notes for translation
46  *  - translation relies on you using double quotes for strings if they need translating
47  *  - single quoted strings are ignored.
48  * 
49  * Generation of indexFiles
50  *   - translateIndex = the indexfile
51  * 
52  * 
53  * 
54  * 
55
56  */
57 namespace JSDOC 
58 {
59         public errordomain PackerError {
60             ArgumentError
61     }
62
63         public class Packer : Object 
64         {
65                 /**
66                 * @cfg {String} target to write files to - must be full path.
67                 */
68                 string target;
69                 GLib.FileOutputStream targetStream = null;
70                 /**
71                  * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
72                  */
73                 string targetDebug;
74                 
75
76                 GLib.FileOutputStream targetDebugStream  = null;
77                 /**
78                  * @cfg {String} tmpDir  (optional) where to put the temporary files. 
79                  *      if you set this, then files will not be cleaned up
80                  */
81                 public string tmpDir = "/tmp";  // FIXME??? in ctor?
82         
83         
84                   
85                 /**
86                  * @cfg {Boolean} cleanup  (optional) clean up temp files after done - 
87                  *    Defaults to false if you set tmpDir, otherwise true.
88                  */
89                 public bool cleanup =  true;
90                 
91                 
92                 /**
93                  * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
94                  *    usefull for debugging compressed files.
95                  */
96                 
97                 public bool keepWhite =  true;
98                 
99                 
100                 // list of files to compile...
101                 Gee.ArrayList<string> files;
102                 
103                 
104                 
105                 public string activeFile = "";
106                 
107                 
108                 public  string out = ""; // 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(Gee.ArrayList<string> fs)
125                 {
126                         foreach(var f in fs) {
127                                 this.files.add(f); //?? easier way?
128                         }
129                 }
130         
131                 
132                 public void pack()
133                 {
134                     if (this.files.size < 1) {
135                                 throw new PackerError.ArgumentError("No Files loaded before pack() called");
136                         }
137                         if (this.target.length > 0 ) {
138                                 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
139                         }
140                         if (this.targetDebug.length > 0 ) {
141                                 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
142                         }
143                         this.packAll();
144                 }
145                 
146   
147                 
148                 
149    
150                 
151  
152            
153                 /**
154                  * load a dependancy list -f option
155                  * @param {String} srcfile sourcefile to parse
156                  * 
157                  */
158                 
159                 public void loadSourceIndex(string srcfile)
160                 {
161                     string str;
162                     FileUtils.get_contents(srcfile,out str);
163                     
164                     var lines = str.split("\n");
165                     for(var i =0; i < lines.length;i++) {
166  
167                             var f = lines[i].strip();
168                         if (f.length < 1 ||
169                                 Regex.match_simple ("^/", f) ||
170                                 !Regex.match_simple ("[a-zA-Z]+", f) 
171                         ){
172                                 continue; // blank comment or not starting with a-z
173                         }
174                         
175                         if (Regex.match_simple ("\\.js$", f)) {
176                             this.files.add( f);
177                             // js file..
178                             continue;
179                         }
180                         
181                                 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
182                                 // should we prefix? =- or should this be done elsewhere?
183                                 
184                         var add = f.replace(".", "/") + ".js";
185                         if (this.files.contains(add)) {
186                             continue;
187                         }
188                         this.files.add( add );
189                         
190                     }
191                 }
192                 
193     
194                 private void packAll()  // do the packing (run from constructor)
195                 {
196                     
197                     //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
198                     //File.write(this.transfile, "");
199                     if (this.target.length > 0) {
200                         this.targetStream.write("".data);
201                     }
202                     
203                     if (this.targetDebugStream != null) {
204                             this.targetDebugStream.write("".data);
205                     }
206                     
207                     
208                     foreach(var file in this.files) {
209                         
210                         print("reading %s\n",file );
211                         
212                         if (FileUtils.test (file, FileTest.EXISTS) && ! FileUtils.test (file, FileTest.IS_DIR)) {
213                             print("SKIP (is not a file) %s\n ", file);
214                             continue;
215                         }
216                        
217                                 var loaded_string = false;
218                                 string file_contents;
219                         // debug Target
220                         
221                         if (this.targetDebugStream !=null) {
222                                 
223                                 FileUtils.get_contents(file,out file_contents);
224                             this.targetDebugStream.write(file_contents.data);
225                             loaded_string = false;
226                         }
227                         // it's a good idea to check with 0 compression to see if the code can parse!!
228                         
229                         // debug file..
230                         //File.append(dout, str +"\n"); 
231                         
232                    
233                         
234                         var minfile = this.tmpDir + "/" + file.replace("/", ".");
235                         
236                         
237                         // let's see if we have a min file already?
238                         // this might happen if tmpDir is set .. 
239
240                         
241                         if (true && FileUtils.test (minfile, FileTest.EXISTS)) {
242                                 
243                                 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
244                                 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
245                                         
246                                         var ot = new Date();
247                                         ot.set_time_val(otv);
248                                         var mt = new Date();
249                                         mt.set_time_val(mtv);
250                             //print("compare : " + mt + "=>" + ot);
251                             if (mt.compare(ot) >= 0) {
252                                 continue; // file is newer or the same time..
253                                 
254                             }
255                             
256                         }
257                          
258                         print("COMPRESSING ");
259                         //var codeComp = pack(str, 10, 0, 0);
260                         if (FileUtils.test (minfile, FileTest.EXISTS)) {
261                             FileUtils.remove(minfile);
262                         }
263                         if (!loaded_string) {
264                                 FileUtils.get_contents(file,out file_contents);
265                         }
266
267                         var str = this.packFile(file_contents, file, minfile);
268                          
269                       
270                     }
271                     
272                     
273                     
274                     // if we are translating, write the translations strings at the top
275                     // of the file..
276                     /*
277                     if (this.translateJSON) {
278                         
279                            
280                         print("MERGING LANGUAGE");
281                         var out = "if (typeof(_T) == 'undefined') { _T={};}\n";
282                         if (this.target) {
283                             File.write(this.target, out);
284                         } else {
285                             this.out += out;
286                         }
287                          
288                         File.write(this.translateJSON, "");
289                         for(var i=0; i < this.files.length; i++)  {
290                             var file = this.files[i];
291                             var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
292                             var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
293                             if (File.exists(transmd5)) {
294                                 var str = File.read(transmd5);
295                                 if (str.length) {
296                                     if (this.target) {
297                                         File.append(this.target, str + "\n");
298                                     } else {
299                                         this.out += str + "\n";
300                                     }
301                                     
302                                 }
303                                 if (this.cleanup) {
304                                     File.remove(transmd5);
305                                 }
306                             }
307                             if (File.exists(transfile)) {
308                                 var str = File.read(transfile);
309                                 if (str.length) {
310                                     File.append(this.translateJSON, str);
311                                 }
312                                 if (this.cleanup) {
313                                     File.remove(transfile);
314                                 }
315                             }
316                             
317                            
318                         }
319                     }
320                     */
321                     print("MERGING SOURCE");
322                     
323                     for(var i=0; i < this.files.size; i++)  {
324                         var file = this.files[i];
325                         var minfile = this.tmpDir + "/" + file.replace("/", ".");
326                         
327                         
328                         if ( FileUtils.test(minfile, FileTest.EXISTS)) {
329                             continue;
330                         }
331                         string str;
332                         FileUtils.get_contents(minfile, out str);
333                         print("using MIN FILE  %s\n", minfile);
334                         if (str.length > 0) {
335                             if (this.targetStream != null) {
336                                         this.targetStream.write(("//" + file + "\n").data); 
337                                         this.targetStream.write((str + "\n").data); 
338
339                             } else {
340                                 this.out += "//" + file + "\n";
341                                 this.out += str + "\n";
342                             }
343                             
344                         }
345                         if (this.cleanup) {
346                             FileUtils.remove(minfile);
347                         }
348                         
349                     }
350                     print("Output file: " + this.target);
351                     if (this.targetDebug.length > 0) {
352                                  print("Output debug file: " + this.targetDebug);
353                          }
354                     
355                      
356                 
357                 
358                 }
359                 /**
360                  * Core packing routine  for a file
361                  * 
362                  * @param str - str source text..
363                  * @param fn - filename (for reference?)
364                  * @param minfile - min file location...
365                  * 
366                  */
367
368                 private string packFile  (string str,string fn, string minfile)
369                 {
370
371                         var tr = new  TokenReader();
372                         tr.keepDocs =true;
373                         tr.keepWhite = true;
374                         tr.keepComments = true;
375                         tr.sepIdents = true;
376                         tr.collapseWhite = false;
377                         tr.filename = fn;
378  
379                         // we can load translation map here...
380                 
381                         TokenArray toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
382                 
383                 
384                 
385                         this.activeFile = fn;
386                 
387                         // and replace if we are generating a different language..
388                 
389
390                         //var ts = new TokenStream(toks);
391                         //print(JSON.stringify(toks, null,4 )); Seed.quit();
392                         var ts = new Collapse(toks.tokens);
393                    // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
394                         //return;//
395                         var sp = new ScopeParser(ts);
396  
397                         //sp.packer = this;
398                         sp.buildSymbolTree();
399
400                         sp.mungeSymboltree();
401                         sp.printWarnings();
402                         //print(sp.warnings.join("\n"));
403
404                 
405                         var outf = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
406                 
407                 
408                 
409                 
410                          if (outf.length > 0) {
411                                 FileUtils.set_contents(minfile, outf);
412                                  
413                         }
414                 
415                         return out;
416                 
417                 
418                          
419                 }
420                  
421
422                 public string md5(string str)
423                 {
424                 
425                         return GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str);
426                 
427                 }
428     
429          //stringHandler : function(tok) -- not used...
430     }
431     
432 }