14 var x = new JSON.Packer(target, debugTarget);
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"
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",
25 x.packAll(); // writes files etc..
29 * Notes for improving compacting:
30 * if you add a jsdoc comment
37 * directly before an eval statement, it will compress all the code around the eval,
38 * and not rename the variables 'avarname'
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
45 * Notes for translation
46 * - translation relies on you using double quotes for strings if they need translating
47 * - single quoted strings are ignored.
49 * Generation of indexFiles
50 * - translateIndex = the indexfile
61 public class Packer : Object
64 * @cfg {String} target to write files to - must be full path.
67 FileOutputStream targetStream = null;
69 * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
74 FileOutputStream targetDebugStream = null;
76 * @cfg {String} tmpDir (optional) where to put the temporary files.
77 * if you set this, then files will not be cleaned up
79 public string tmpDir = "/tmp"; // FIXME??? in ctor?
84 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
85 * Defaults to false if you set tmpDir, otherwise true.
87 public bool cleanup = true;
91 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
92 * usefull for debugging compressed files.
95 public bool keepWhite = true;
98 // list of files to compile...
99 Gee.ArrayList<string> files;
101 public string out = ""; // if no target is specified - then this will contain the result
103 public Packer(string target, string targetDebug = "")
105 this.target = target;
106 this.targetDebug = targetDebug;
110 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
112 foreach(var f in indexes) {
113 this.loadSourceIndex(f);
117 public void loadFiles(Gee.ArrayList<string> fs)
119 foreach(var f in fs) {
120 this.files.add(f); //?? easier way?
128 throw new Packer.ArgumentError("No Files loaded before pack() called");
130 if (this.target.length > 0 ) {
131 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
133 if (this.targetDebug.length > 0 ) {
134 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
147 * load a dependancy list -f option
148 * @param {String} srcfile sourcefile to parse
152 public void loadSourceIndex(string srcfile)
155 FileUtils.get_contents(srcfile,out str);
157 var lines = str.split("\n");
158 for(var i =0; i < lines.length;i++) {
160 var f = lines[i].strip();
162 Regex.match_simple ("^/", f) ||
163 !Regex.match_simple ("[a-zA-Z]+", f)
165 continue; // blank comment or not starting with a-z
168 if (Regex.match_simple ("\\.js$", f)) {
174 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
175 // should we prefix? =- or should this be done elsewhere?
177 var add = f.replace(".", "/") + ".js";
178 if (_this.files.contains(add)) {
181 _this.files.add( add );
187 private void packAll() // do the packing (run from constructor)
190 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
191 //File.write(this.transfile, "");
192 if (this.target.length > 0) {
193 this.targetStream.write("");
196 if (this.debugTarget > 0) {
197 this.targetDebugStream.write("");
199 foreach(var file in this.files) {
201 print("reading %s\n",file );
203 if (FileUtils.test (file, FileTest.EXISTS) && ! FileUtils.test (file, FileTest.IS_DIR)) {
204 print("SKIP (is not a file) %s\n ", file);
208 var loaded_string = false;
209 string file_contents;
212 if (this.targetDebugStream !=null) {
214 FileUtils.get_contents(file,out file_contents);
215 this.targetDebugStream.write(file_contents);
216 loaded_string = false;
218 // it's a good idea to check with 0 compression to see if the code can parse!!
221 //File.append(dout, str +"\n");
225 var minfile = this.tmpDir + '/' + file.replace("/", '.');
228 // let's see if we have a min file already?
229 // this might happen if tmpDir is set ..
232 if (true && FileUtils.test (minfile, FileTest.EXISTS)) {
234 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
235 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
238 ot.set_time_val(otv);
240 mt.set_time_val(mtv);
241 //print("compare : " + mt + "=>" + ot);
242 if (mt.compare(ot) >= 0) {
243 continue; // file is newer or the same time..
249 print("COMPRESSING ");
250 //var codeComp = pack(str, 10, 0, 0);
251 if (FileUtils.test (minfile, FileTest.EXISTS)) {
252 FileUtils.remove(minfile);
254 if (!loaded_string) {
255 FileUtils.get_contents(file,out file_contents);
258 var str = this.packFile(file_contents, file, minfile);
265 // if we are translating, write the translations strings at the top
268 if (this.translateJSON) {
271 print("MERGING LANGUAGE");
272 var out = "if (typeof(_T) == 'undefined') { _T={};}\n";
274 File.write(this.target, out);
279 File.write(this.translateJSON, "");
280 for(var i=0; i < this.files.length; i++) {
281 var file = this.files[i];
282 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
283 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
284 if (File.exists(transmd5)) {
285 var str = File.read(transmd5);
288 File.append(this.target, str + "\n");
290 this.out += str + "\n";
295 File.remove(transmd5);
298 if (File.exists(transfile)) {
299 var str = File.read(transfile);
301 File.append(this.translateJSON, str);
304 File.remove(transfile);
312 print("MERGING SOURCE");
314 for(var i=0; i < this.files.length; i++) {
315 var file = this.files[i];
316 var minfile = this.tmpDir + '/' + file.replace('/', '.');
319 if (!File.exists(minfile)) {
322 var str = File.read(minfile);
323 print("using MIN FILE "+ minfile);
325 if (this.targetStream != null) {
326 this.targetStream.write("//" + file + "\n");
327 this.targetStream.write(str + "\n");
330 this.out += "//" + file + "\n";
331 this.out += str + "\n";
336 FileUtils.remove(minfile);
340 print("Output file: " + this.target);
341 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
348 * Core packing routine for a file
350 * @param str - str source text..
351 * @param fn - filename (for reference?)
352 * @param minfile - min file location...
356 packFile : function (str,fn,minfile)
359 var tr = new TokenReader( {
364 collapseWhite : false,
367 this.timerPrint("START" + fn);
369 // we can load translation map here...
371 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
373 // at this point we can write a language file...
374 if (this.translateJSON) {
376 this.writeTranslateFile(fn, minfile, toks);
379 this.activeFile = fn;
381 // and replace if we are generating a different language..
383 this.timerPrint("Tokenized");
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();
389 var sp = new ScopeParser(ts);
390 this.timerPrint("Converted to Parser");
392 sp.buildSymbolTree();
393 this.timerPrint("Built Sym tree");
394 sp.mungeSymboltree();
395 this.timerPrint("Munged Sym tree");
396 print(sp.warnings.join("\n"));
397 this.timerPrint("Compressed");
399 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
402 this.timerPrint("Compressed");
405 File.write(minfile, out);
406 this.timerPrint("Write (" + out.length + "bytes) " + minfile);
416 md5 : function (string)
419 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
422 stringHandler : function(tok)
424 //print("STRING HANDLER");
425 // callback when outputing compressed file,
427 if (!this.translateJSON) {
428 // print("TURNED OFF");
431 if (tok.name == 'SINGLE_QUOTE') {
435 if (typeof(tok.trsum) == 'undefined') {
439 return '_T["' + tok.trsum + '"]';
441 var sval = data.substring(1,data.length-1);
442 // we do not clean up... quoting here!??!!?!?!?!?
445 // blank with tabs or spaces..
446 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
447 // return tok.outData;
450 var sval = tok.data.substring(1,data.length-1);
451 var fn = this.activeFile.substring(this.prefix.length);
454 return '_T["' + this.md5(fn + '-' + sval) + '"]';