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