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.
68 * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
73 * @cfg {String} tmpDir (optional) where to put the temporary files.
74 * if you set this, then files will not be cleaned up
76 public string tmpDir = "/tmp"; // FIXME??? in ctor?
81 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
82 * Defaults to false if you set tmpDir, otherwise true.
84 public bool cleanup = true;
88 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
89 * usefull for debugging compressed files.
92 public bool keepWhite = true;
95 // list of files to compile...
96 Gee.ArrayList<string> files;
98 public string out = ""; // if no target is specified - then this will contain the result
100 public Packer(string target, string targetDebug = "")
102 this.target = target;
103 this.targetDebug = targetDebug;
107 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
109 foreach(var f in indexes) {
110 this.loadSourceIndex(f);
114 public void loadFiles(Gee.ArrayList<string> fs)
116 foreach(var f in fs) {
117 this.files.add(f); //?? easier way?
120 FileOutputStream targetStream = null;
121 FileOutputStream targetDebugStream = null;
126 throw new Packer.ArgumentError("No Files loaded before pack() called");
128 if (this.target.length > 0 ) {
129 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
131 if (this.targetDebug.length > 0 ) {
132 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
145 * load a dependancy list -f option
146 * @param {String} srcfile sourcefile to parse
150 public void loadSourceIndex(string srcfile)
153 FileUtils.get_contents(srcfile,out str);
155 var lines = str.split("\n");
156 for(var i =0; i < lines.length;i++) {
158 var f = lines[i].strip();
160 Regex.match_simple ("^\/", f) ||
161 !Regex.match_simple ("[a-zA-Z]+", f)
163 continue; // blank comment or not starting with a-z
166 if (Regex.match_simple ("\.js$", f)) {
172 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
173 // should we prefix? =- or should this be done elsewhere?
175 var add = f.replace(".", "/") + ".js";
176 if (_this.files.contains(add)) {
179 _this.files.add( add );
185 private void packAll() // do the packing (run from constructor)
188 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
189 //File.write(this.transfile, "");
190 if (this.target.length > 0) {
191 this.targetStream.write("");
194 if (this.debugTarget > 0) {
195 this.targetDebugStream.write("");
197 foreach(var file in this.files) {
199 print("reading %s\n",file );
201 if (FileUtils.test (file, FileTest.EXISTS) && ! FileUtils.test (file, FileTest.IS_DIR)) {
202 print("SKIP (is not a file) %s\n ", file);
208 if (this.debugTargetStream !=null) {
210 FileUtils.get_contents(file,out str);
211 this.debugTarget.write(str);
213 // it's a good idea to check with 0 compression to see if the code can parse!!
216 //File.append(dout, str +"\n");
220 var minfile = this.tmpDir + '/' + file.replace("/", '.');
223 // let's see if we have a min file already?
224 // this might happen if tmpDir is set ..
225 var use_minfile = false;
227 if (true && FileUtils.test (minfile, FileTest.EXISTS)) {
229 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
230 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
233 ot.set_time_val(otv);
235 mt.set_time_val(mtv);
236 //print("compare : " + mt + "=>" + ot);
237 if (mt.compare(ot) >= 0) {
238 continue; // file is newer or the same time..
244 print("COMPRESSING ");
245 //var codeComp = pack(str, 10, 0, 0);
246 if (File.exists(minfile)) {
247 File.remove(minfile);
249 var str = File.read(file);
250 var str = this.packFile(str, file, minfile);
257 // if we are translating, write the translations strings at the top
260 if (this.translateJSON) {
263 print("MERGING LANGUAGE");
264 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
266 File.write(this.target, out);
271 File.write(this.translateJSON, "");
272 for(var i=0; i < this.files.length; i++) {
273 var file = this.files[i];
274 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
275 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
276 if (File.exists(transmd5)) {
277 var str = File.read(transmd5);
280 File.append(this.target, str + "\n");
282 this.out += str + "\n";
287 File.remove(transmd5);
290 if (File.exists(transfile)) {
291 var str = File.read(transfile);
293 File.append(this.translateJSON, str);
296 File.remove(transfile);
304 print("MERGING SOURCE");
306 for(var i=0; i < this.files.length; i++) {
307 var file = this.files[i];
308 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
311 if (!File.exists(minfile)) {
314 var str = File.read(minfile);
315 print("using MIN FILE "+ minfile);
318 File.append(this.target, '//' + file + "\n");
319 File.append(this.target, str + "\n");
321 this.out += '//' + file + "\n";
322 this.out += str + "\n";
327 File.remove(minfile);
331 print("Output file: " + this.target);
332 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
339 * Core packing routine for a file
341 * @param str - str source text..
342 * @param fn - filename (for reference?)
343 * @param minfile - min file location...
347 packFile : function (str,fn,minfile)
350 var tr = new TokenReader( {
355 collapseWhite : false,
358 this.timerPrint("START" + fn);
360 // we can load translation map here...
362 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
364 // at this point we can write a language file...
365 if (this.translateJSON) {
367 this.writeTranslateFile(fn, minfile, toks);
370 this.activeFile = fn;
372 // and replace if we are generating a different language..
374 this.timerPrint("Tokenized");
375 //var ts = new TokenStream(toks);
376 //print(JSON.stringify(toks, null,4 )); Seed.quit();
377 var ts = new Collapse(toks);
378 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
380 var sp = new ScopeParser(ts);
381 this.timerPrint("Converted to Parser");
383 sp.buildSymbolTree();
384 this.timerPrint("Built Sym tree");
385 sp.mungeSymboltree();
386 this.timerPrint("Munged Sym tree");
387 print(sp.warnings.join("\n"));
388 this.timerPrint("Compressed");
390 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
393 this.timerPrint("Compressed");
396 File.write(minfile, out);
397 this.timerPrint("Write (" + out.length + "bytes) " + minfile);
406 timerPrint: function (str) {
407 var ntime = new Date() * 1;
408 var tdif = ntime -this.timer;
410 print('['+tdif+']'+str);
415 * Translation concept...
416 * -> replace text strings with _T....
417 * -> this file will need inserting at the start of the application....
418 * -> we need to generate 2 files,
419 * -> a reference used to do the translation, and the _T file..
422 * We store the trsum on the token...
426 writeTranslateFile : function(fn, minfile, toks)
429 var map = {}; // 'string=> md5sum'
434 var tokfind = function (j,dir) {
436 if ((dir < 0) && (j < 0)) {
439 if ((dir > 0) && (j >= toks.length)) {
443 if (toks[j].type != 'WHIT') {
452 for (var i=0;i<toks.length;i++) {
455 if (t.type != 'STRN') {
458 if (t.name != 'DOUBLE_QUOTE') {
462 last = tokfind(i,-1);
463 next = tokfind(i,+1);
465 // we have to ignore key values on objects
468 // last == '{' or ',' and
472 next.type == 'PUNC' &&
475 last.type == 'PUNC' &&
476 (last.data == ',' || last.data == '{')
478 continue; // found object key... - we can not translate these
481 var sval = t.data.substring(1,t.data.length-1);
482 var ffn = fn.substring(_this.prefix.length);
484 t.trsum = _this.md5(ffn + '-' + sval);
492 var transfile = minfile + '.lang.trans';
493 var transmd5 = minfile + '.lang';
494 print("writeTranslateFile " + transfile);
497 if (File.exists(transfile)) {
498 File.remove(transfile);
500 if (File.exists(transmd5)) {
501 File.remove(transmd5);
503 for(v in map) { i++; break };
505 return; // no strings in file...
507 var ffn = fn.substring(this.prefix.length);
510 File.write(transfile, "\n'" + ffn + "' : {");
514 File.write(transmd5, '');
519 File.append(transfile, l + "\n\t\"" + v + "\" : \"" + v +"\"");
521 // strings are raw... - as the where encoded to start with!!!
522 // so we should not need to encode them again.. - just wrap with "
523 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
525 File.append(transfile, "\n},"); // always one trailing..
529 md5 : function (string)
532 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
535 stringHandler : function(tok)
537 //print("STRING HANDLER");
538 // callback when outputing compressed file,
540 if (!this.translateJSON) {
541 // print("TURNED OFF");
544 if (tok.name == 'SINGLE_QUOTE') {
548 if (typeof(tok.trsum) == 'undefined') {
552 return '_T["' + tok.trsum + '"]';
554 var sval = data.substring(1,data.length-1);
555 // we do not clean up... quoting here!??!!?!?!?!?
558 // blank with tabs or spaces..
559 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
560 // return tok.outData;
563 var sval = tok.data.substring(1,data.length-1);
564 var fn = this.activeFile.substring(this.prefix.length);
567 return '_T["' + this.md5(fn + '-' + sval) + '"]';