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