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 PackerError.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("".data);
196                     }
197                     
198                     if (this.targetDebugStream != null) {
199                             this.targetDebugStream.write("".data);
200                     }
201                     
202                     
203                     foreach(var file in this.files) {
204                         
205                         print("reading %s\n",file );
206                         
207                         if (FileUtils.test (file, FileTest.EXISTS) && ! FileUtils.test (file, FileTest.IS_DIR)) {
208                             print("SKIP (is not a file) %s\n ", file);
209                             continue;
210                         }
211                        
212                                 var loaded_string = false;
213                                 string file_contents;
214                         // debug Target
215                         
216                         if (this.targetDebugStream !=null) {
217                                 
218                                 FileUtils.get_contents(file,out file_contents);
219                             this.targetDebugStream.write(file_contents.data);
220                             loaded_string = false;
221                         }
222                         // it's a good idea to check with 0 compression to see if the code can parse!!
223                         
224                         // debug file..
225                         //File.append(dout, str +"\n"); 
226                         
227                    
228                         
229                         var minfile = this.tmpDir + '/' + file.replace("/", '.');
230                         
231                         
232                         // let's see if we have a min file already?
233                         // this might happen if tmpDir is set .. 
234
235                         
236                         if (true && FileUtils.test (minfile, FileTest.EXISTS)) {
237                                 
238                                 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
239                                 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
240                                         
241                                         var ot = new Date();
242                                         ot.set_time_val(otv);
243                                         var mt = new Date();
244                                         mt.set_time_val(mtv);
245                             //print("compare : " + mt + "=>" + ot);
246                             if (mt.compare(ot) >= 0) {
247                                 continue; // file is newer or the same time..
248                                 
249                             }
250                             
251                         }
252                          
253                         print("COMPRESSING ");
254                         //var codeComp = pack(str, 10, 0, 0);
255                         if (FileUtils.test (minfile, FileTest.EXISTS)) {
256                             FileUtils.remove(minfile);
257                         }
258                         if (!loaded_string) {
259                                 FileUtils.get_contents(file,out file_contents);
260                         }
261
262                         var str = this.packFile(file_contents, file, minfile);
263                          
264                       
265                     }
266                     
267                     
268                     
269                     // if we are translating, write the translations strings at the top
270                     // of the file..
271                     /*
272                     if (this.translateJSON) {
273                         
274                            
275                         print("MERGING LANGUAGE");
276                         var out = "if (typeof(_T) == 'undefined') { _T={};}\n";
277                         if (this.target) {
278                             File.write(this.target, out);
279                         } else {
280                             this.out += out;
281                         }
282                          
283                         File.write(this.translateJSON, "");
284                         for(var i=0; i < this.files.length; i++)  {
285                             var file = this.files[i];
286                             var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
287                             var transmd5 = this.tmpDir  + '/' +file.replace(/\//g, '.') +'.lang';
288                             if (File.exists(transmd5)) {
289                                 var str = File.read(transmd5);
290                                 if (str.length) {
291                                     if (this.target) {
292                                         File.append(this.target, str + "\n");
293                                     } else {
294                                         this.out += str + "\n";
295                                     }
296                                     
297                                 }
298                                 if (this.cleanup) {
299                                     File.remove(transmd5);
300                                 }
301                             }
302                             if (File.exists(transfile)) {
303                                 var str = File.read(transfile);
304                                 if (str.length) {
305                                     File.append(this.translateJSON, str);
306                                 }
307                                 if (this.cleanup) {
308                                     File.remove(transfile);
309                                 }
310                             }
311                             
312                            
313                         }
314                     }
315                     */
316                     print("MERGING SOURCE");
317                     
318                     for(var i=0; i < this.files.length; i++)  {
319                         var file = this.files[i];
320                         var minfile = this.tmpDir + '/' + file.replace('/', '.');
321                         
322                         
323                         if (!File.exists(minfile)) {
324                             continue;
325                         }
326                         var str = File.read(minfile);
327                         print("using MIN FILE  "+ minfile);
328                         if (str.length) {
329                             if (this.targetStream != null) {
330                                         this.targetStream.write("//" + file + "\n"); 
331                                         this.targetStream.write(str + "\n"); 
332
333                             } else {
334                                 this.out += "//" + file + "\n";
335                                 this.out += str + "\n";
336                             }
337                             
338                         }
339                         if (this.cleanup) {
340                             FileUtils.remove(minfile);
341                         }
342                         
343                     }
344                     print("Output file: " + this.target);
345                     if (this.debugTarget) print("Output debug file: " + this.debugTarget);
346                     
347                      
348                 
349                 
350                 }
351                 /**
352                  * Core packing routine  for a file
353                  * 
354                  * @param str - str source text..
355                  * @param fn - filename (for reference?)
356                  * @param minfile - min file location...
357                  * 
358                  */
359
360                 private string packFile  (string str,string fn, string minfile)
361                 {
362
363                         var tr = new  TokenReader();
364                         tr.keepDocs =true;
365                         tr.keepWhite = true;
366                         tr.keepComments = true;
367                         tr.sepIdents = true;
368                         tr.collapseWhite = false;
369                         tr.filename = fn;
370
371                         this.timerPrint("START" + fn);
372                 
373                         // we can load translation map here...
374                 
375                         var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
376                 
377                 
378                 
379                         this.activeFile = fn;
380                 
381                         // and replace if we are generating a different language..
382                 
383
384                         //var ts = new TokenStream(toks);
385                         //print(JSON.stringify(toks, null,4 )); Seed.quit();
386                         var ts = new Collapse(toks);
387                    // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
388                         //return;//
389                         var sp = new ScopeParser(ts);
390
391                         sp.packer = this;
392                         sp.buildSymbolTree();
393
394                         sp.mungeSymboltree();
395
396                         print(sp.warnings.join("\n"));
397
398                 
399                         var outf = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
400                 
401                 
402                 
403                 
404                          if (out.length > 0) {
405                                 FileUtils.put_contents(minfile, outf);
406                                  
407                         }
408                 
409                         return out;
410                 
411                 
412                          
413                 }
414                  
415
416                 public string md5(string str)
417                 {
418                 
419                         return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, str);
420                 
421                 }
422     
423          //stringHandler : function(tok) -- not used...
424     }
425     
426 }