14 var x = new JSON.Packer();
15 x.files = an array of files
16 x.srcfiles = array of files (that list other files...) << not supported?
17 x.target = "output.pathname.js"
18 x.debugTarget = "output.pathname.debug.js"
21 x.debugTranslateTarget : "/tmp/output.translate.js" << this used to be the single vs double quotes.. we may not use it in future..
22 x.translateJSON: "/tmp/translate.json",
24 x.packAll(); // writes files etc..
28 * Notes for improving compacting:
29 * if you add a jsdoc comment
36 * directly before an eval statement, it will compress all the code around the eval,
37 * and not rename the variables 'avarname'
39 * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
40 * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
44 * Notes for translation
45 * - translation relies on you using double quotes for strings if they need translating
46 * - single quoted strings are ignored.
48 * Generation of indexFiles
49 * - translateIndex = the indexfile
56 const Packer = function(cfg)
59 XObject.extend(this, cfg);
61 if (this.srcfiles && this.srcfiles.length) {
62 this.srcfiles.forEach(function(f) {
63 _this.loadSourceFile(f);
75 function dateString(d){
76 function pad(n){return n<10 ? '0'+n : n}
77 return d.getFullYear() +
88 this.files.forEach(function(f) {
89 version = Math.max(File.mtime(f), version);
91 var version = dateString(new Date(version));
93 var dirname = GLib.path_get_dirname(this.files[0]);
94 var outname = this.module ? this.module : GLib.path_get_basename(dirname);
95 this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
96 if (File.exists(this.target)) {
97 print("Target file already exists: " + this.target);
100 this.prefix = dirname +'/';
101 this.translateJSON = dirname + '/compiled/_translation_.js';
105 print(this.translateJSON);
106 this.timer = new Date() * 1;
115 * @cfg {String} srcfiles file containing a list of files/or classes to use.
120 * @cfg {Array} files list of files to compress (must be full path)
124 * @cfg {String} target to write files to - must be full path.
128 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
129 * and enables translation toolkit.
133 * @cfg {String} module used with autoBuild to force a file name
137 * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
139 debugTarget : '', // merged file without compression.
141 * @cfg {String} debugTranslateTarget target to write files debug version
142 * to (uncompacted) but with translation- must be full path.
145 debugTranslateTarget : '',
148 * @cfg {String} tmpDir (optional) where to put the temporary files.
149 * if you set this, then files will not be cleaned up
153 translateJSON : '', // json based list of strings in all files.
156 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
157 * Defaults to false if you set tmpDir, otherwise true.
161 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
162 * usefull for debugging compressed files.
168 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
169 * Calculating md5 of filename
172 out : '', // if no target is specified - then this will contain the result
175 * load a dependancy list -f option
176 * @param {String} srcfile sourcefile to parse
180 loadSourceFile : function(srcfile)
182 var lines = File.read(srcfile).split("\n");
184 lines.forEach(function(f) {
186 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
189 if (/\.js$/.test(f)) {
190 _this.files.push( f);
195 //println("ADD"+ f.replace(/\./g, '/'));
196 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
197 if (_this.files.indexOf(f) > -1) {
200 _this.files.push( add );
206 packAll : function() // do the packing (run from constructor)
209 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
210 //File.write(this.transfile, "");
212 File.write(this.target, "");
215 if (this.debugTarget) {
216 File.write(this.debugTarget, "");
218 if (this.debugTranslateTarget) {
219 File.write(this.debugTarget, "");
222 for(var i=0; i < this.files.length; i++) {
223 var file = this.files[i];
225 print("reading " +file );
226 if (!File.isFile(file)) {
227 print("SKIP (is not a file) " + file);
233 if (this.debugTarget) {
234 File.append(this.debugTarget, File.read(file));
236 // it's a good idea to check with 0 compression to see if the code can parse!!
239 //File.append(dout, str +"\n");
243 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
246 // let's see if we have a min file already?
247 // this might happen if tmpDir is set ..
248 if (true && File.exists(minfile)) {
249 var mt = File.mtime(minfile);
250 var ot = File.mtime(file);
251 print("compare : " + mt + "=>" + ot);
259 print("COMPRESSING ");
260 //var codeComp = pack(str, 10, 0, 0);
261 if (File.exists(minfile)) {
262 File.remove(minfile);
264 var str = File.read(file);
265 var str = this.pack(str, file, minfile);
272 // if we are translating, write the translations strings at the top
275 if (this.translateJSON) {
278 print("MERGING LANGUAGE");
279 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
281 File.write(this.target, out);
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);
295 File.append(this.target, str + "\n");
297 this.out += str + "\n";
302 File.remove(transmd5);
305 if (File.exists(transfile)) {
306 var str = File.read(transfile);
308 File.append(this.translateJSON, str);
311 File.remove(transfile);
319 print("MERGING SOURCE");
321 for(var i=0; i < this.files.length; i++) {
322 var file = this.files[i];
323 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
326 if (!File.exists(minfile)) {
329 var str = File.read(minfile);
330 print("using MIN FILE "+ minfile);
333 File.append(this.target, '//' + file + "\n");
334 File.append(this.target, str + "\n");
336 this.out += '//' + file + "\n";
337 this.out += str + "\n";
342 File.remove(minfile);
346 print("Output file: " + this.target);
347 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
354 * Core packing routine for a file
356 * @param str - str source text..
357 * @param fn - filename (for reference?)
358 * @param minfile - min file location...
362 pack : function (str,fn,minfile)
365 var tr = new TokenReader( {
370 collapseWhite : false,
373 this.timerPrint("START" + fn);
375 // we can load translation map here...
377 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
379 // at this point we can write a language file...
380 if (this.translateJSON) {
382 this.writeTranslateFile(fn, minfile, toks);
385 this.activeFile = fn;
387 // and replace if we are generating a different language..
389 this.timerPrint("Tokenized");
390 //var ts = new TokenStream(toks);
391 //print(JSON.stringify(toks, null,4 )); Seed.quit();
392 var ts = new Collapse(toks);
393 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
395 var sp = new ScopeParser(ts);
396 this.timerPrint("Converted to Parser");
398 sp.buildSymbolTree();
399 this.timerPrint("Built Sym tree");
400 sp.mungeSymboltree();
401 this.timerPrint("Munged Sym tree");
402 print(sp.warnings.join("\n"));
403 this.timerPrint("Compressed");
405 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
408 this.timerPrint("Compressed");
411 File.write(minfile, out);
412 this.timerPrint("Write (" + out.length + "bytes) " + minfile);
421 timerPrint: function (str) {
422 var ntime = new Date() * 1;
423 var tdif = ntime -this.timer;
425 print('['+tdif+']'+str);
430 * Translation concept...
431 * -> replace text strings with _T....
432 * -> this file will need inserting at the start of the application....
433 * -> we need to generate 2 files,
434 * -> a reference used to do the translation, and the _T file..
437 * We store the trsum on the token...
441 writeTranslateFile : function(fn, minfile, toks)
444 var map = {}; // 'string=> md5sum'
449 var tokfind = function (j,dir) {
451 if ((dir < 0) && (j < 0)) {
454 if ((dir > 0) && (j >= toks.length)) {
458 if (toks[j].type != 'WHIT') {
467 for (var i=0;i<toks.length;i++) {
470 if (t.type != 'STRN') {
473 if (t.name != 'DOUBLE_QUOTE') {
477 last = tokfind(i,-1);
478 next = tokfind(i,+1);
480 // we have to ignore key values on objects
483 // last == '{' or ',' and
487 next.type == 'PUNC' &&
490 last.type == 'PUNC' &&
491 (last.data == ',' || last.data == '{')
493 continue; // found object key... - we can not translate these
496 var sval = t.data.substring(1,t.data.length-1);
497 var ffn = fn.substring(_this.prefix.length);
499 t.trsum = _this.md5(ffn + '-' + sval);
507 var transfile = minfile + '.lang.trans';
508 var transmd5 = minfile + '.lang';
509 print("writeTranslateFile " + transfile);
512 if (File.exists(transfile)) {
513 File.remove(transfile);
515 if (File.exists(transmd5)) {
516 File.remove(transmd5);
518 for(v in map) { i++; break };
520 return; // no strings in file...
522 var ffn = fn.substring(this.prefix.length);
525 File.write(transfile, "\n'" + ffn + "' : {");
529 File.write(transmd5, '');
534 File.append(transfile, l + "\n\t\"" + v + "\" : \"" + v +"\"");
536 // strings are raw... - as the where encoded to start with!!!
537 // so we should not need to encode them again.. - just wrap with "
538 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
540 File.append(transfile, "\n},"); // always one trailing..
544 md5 : function (string)
547 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
550 stringHandler : function(tok)
552 //print("STRING HANDLER");
553 // callback when outputing compressed file,
555 if (!this.translateJSON) {
556 // print("TURNED OFF");
559 if (tok.name == 'SINGLE_QUOTE') {
563 if (typeof(tok.trsum) == 'undefined') {
567 return '_T["' + tok.trsum + '"]';
569 var sval = data.substring(1,data.length-1);
570 // we do not clean up... quoting here!??!!?!?!?!?
573 // blank with tabs or spaces..
574 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
575 // return tok.outData;
578 var sval = tok.data.substring(1,data.length-1);
579 var fn = this.activeFile.substring(this.prefix.length);
582 return '_T["' + this.md5(fn + '-' + sval) + '"]';