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