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",
26 "/location/of/temp_batch_dir",
27 "/location/of/output-compacted-file.js",
28 "/location/of/output-debug-merged-file.js"
33 * Notes for improving compacting:
34 * if you add a jsdoc comment
41 * directly before an eval statement, it will compress all the code around the eval,
42 * and not rename the variables 'avarname'
44 * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
45 * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
49 * Notes for translation
50 * - translation relies on you using double quotes for strings if they need translating
51 * - single quoted strings are ignored.
53 * Generation of indexFiles
54 * - translateIndex = the indexfile
61 const Packer = function(cfg)
64 XObject.extend(this, cfg);
66 if (this.srcfiles && this.srcfiles.length) {
67 this.srcfiles.forEach(function(f) {
68 _this.loadSourceFile(f);
80 function dateString(d){
81 function pad(n){return n<10 ? '0'+n : n}
82 return d.getFullYear() +
93 this.files.forEach(function(f) {
94 version = Math.max(File.mtime(f), version);
96 var version = dateString(new Date(version));
98 var dirname = GLib.path_get_dirname(this.files[0]);
99 var outname = this.module ? this.module : GLib.path_get_basename(dirname);
100 this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
101 if (File.exists(this.target)) {
102 print("Target file already exists: " + this.target);
105 this.prefix = dirname +'/';
106 this.translateJSON = dirname + '/compiled/_translation_.js';
110 print(this.translateJSON);
111 this.timer = new Date() * 1;
120 * @cfg {String} srcfiles file containing a list of files/or classes to use.
125 * @cfg {Array} files list of files to compress (must be full path)
129 * @cfg {String} target to write files to - must be full path.
133 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
134 * and enables translation toolkit.
138 * @cfg {String} module used with autoBuild to force a file name
142 * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
144 debugTarget : '', // merged file without compression.
146 * @cfg {String} debugTranslateTarget target to write files debug version
147 * to (uncompacted) but with translation- must be full path.
150 debugTranslateTarget : '',
153 * @cfg {String} tmpDir (optional) where to put the temporary files.
154 * if you set this, then files will not be cleaned up
158 translateJSON : '', // json based list of strings in all files.
161 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
162 * Defaults to false if you set tmpDir, otherwise true.
166 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
167 * usefull for debugging compressed files.
173 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
174 * Calculating md5 of filename
177 out : '', // if no target is specified - then this will contain the result
180 * load a dependancy list -f option
181 * @param {String} srcfile sourcefile to parse
185 loadSourceFile : function(srcfile)
187 var lines = File.read(srcfile).split("\n");
189 lines.forEach(function(f) {
191 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
194 if (/\.js$/.test(f)) {
195 _this.files.push( f);
200 //println("ADD"+ f.replace(/\./g, '/'));
201 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
202 if (_this.files.indexOf(f) > -1) {
205 _this.files.push( add );
211 packAll : function() // do the packing (run from constructor)
214 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
215 //File.write(this.transfile, "");
217 File.write(this.target, "");
220 if (this.debugTarget) {
221 File.write(this.debugTarget, "");
223 if (this.debugTranslateTarget) {
224 File.write(this.debugTarget, "");
227 for(var i=0; i < this.files.length; i++) {
228 var file = this.files[i];
230 print("reading " +file );
231 if (!File.isFile(file)) {
232 print("SKIP (is not a file) " + file);
238 if (this.debugTarget) {
239 File.append(this.debugTarget, File.read(file));
241 // it's a good idea to check with 0 compression to see if the code can parse!!
244 //File.append(dout, str +"\n");
248 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
251 // let's see if we have a min file already?
252 // this might happen if tmpDir is set ..
253 if (true && File.exists(minfile)) {
254 var mt = File.mtime(minfile);
255 var ot = File.mtime(file);
256 print("compare : " + mt + "=>" + ot);
264 print("COMPRESSING ");
265 //var codeComp = pack(str, 10, 0, 0);
266 if (File.exists(minfile)) {
267 File.remove(minfile);
269 var str = File.read(file);
270 var str = this.pack(str, file, minfile);
277 // if we are translating, write the translations strings at the top
280 if (this.translateJSON) {
283 print("MERGING LANGUAGE");
284 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
286 File.write(this.target, out);
291 File.write(this.translateJSON, "");
292 for(var i=0; i < this.files.length; i++) {
293 var file = this.files[i];
294 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
295 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
296 if (File.exists(transmd5)) {
297 var str = File.read(transmd5);
300 File.append(this.target, str + "\n");
302 this.out += str + "\n";
307 File.remove(transmd5);
310 if (File.exists(transfile)) {
311 var str = File.read(transfile);
313 File.append(this.translateJSON, str);
316 File.remove(transfile);
324 print("MERGING SOURCE");
326 for(var i=0; i < this.files.length; i++) {
327 var file = this.files[i];
328 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
331 if (!File.exists(minfile)) {
334 var str = File.read(minfile);
335 print("using MIN FILE "+ minfile);
338 File.append(this.target, '//' + file + "\n");
339 File.append(this.target, str + "\n");
341 this.out += '//' + file + "\n";
342 this.out += str + "\n";
347 File.remove(minfile);
351 print("Output file: " + this.target);
352 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
359 * Core packing routine for a file
361 * @param str - str source text..
362 * @param fn - filename (for reference?)
363 * @param minfile - min file location...
367 pack : function (str,fn,minfile)
370 var tr = new TokenReader( {
375 collapseWhite : false,
378 this.timerPrint("START" + fn);
380 // we can load translation map here...
382 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
384 // at this point we can write a language file...
385 if (this.translateJSON) {
387 this.writeTranslateFile(fn, minfile, toks);
390 this.activeFile = fn;
392 // and replace if we are generating a different language..
394 this.timerPrint("Tokenized");
395 //var ts = new TokenStream(toks);
396 //print(JSON.stringify(toks, null,4 )); Seed.quit();
397 var ts = new Collapse(toks);
398 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
400 var sp = new ScopeParser(ts);
401 this.timerPrint("Converted to Parser");
403 sp.buildSymbolTree();
404 this.timerPrint("Built Sym tree");
405 sp.mungeSymboltree();
406 this.timerPrint("Munged Sym tree");
407 print(sp.warnings.join("\n"));
408 this.timerPrint("Compressed");
410 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
413 this.timerPrint("Compressed");
416 File.write(minfile, out);
417 this.timerPrint("Write (" + out.length + "bytes) " + minfile);
426 timerPrint: function (str) {
427 var ntime = new Date() * 1;
428 var tdif = ntime -this.timer;
430 print('['+tdif+']'+str);
435 * Translation concept...
436 * -> replace text strings with _T....
437 * -> this file will need inserting at the start of the application....
438 * -> we need to generate 2 files,
439 * -> a reference used to do the translation, and the _T file..
442 * We store the trsum on the token...
446 writeTranslateFile : function(fn, minfile, toks)
449 var map = {}; // 'string=> md5sum'
454 var tokfind = function (j,dir) {
456 if ((dir < 0) && (j < 0)) {
459 if ((dir > 0) && (j >= toks.length)) {
463 if (toks[j].type != 'WHIT') {
472 for (var i=0;i<toks.length;i++) {
475 if (t.type != 'STRN') {
478 if (t.name != 'DOUBLE_QUOTE') {
482 last = tokfind(i,-1);
483 next = tokfind(i,+1);
485 // we have to ignore key values on objects
488 // last == '{' or ',' and
492 next.type == 'PUNC' &&
495 last.type == 'PUNC' &&
496 (last.data == ',' || last.data == '{')
498 continue; // found object key... - we can not translate these
501 var sval = t.data.substring(1,t.data.length-1);
502 var ffn = fn.substring(_this.prefix.length);
504 t.trsum = _this.md5(ffn + '-' + sval);
512 var transfile = minfile + '.lang.trans';
513 var transmd5 = minfile + '.lang';
514 print("writeTranslateFile " + transfile);
517 if (File.exists(transfile)) {
518 File.remove(transfile);
520 if (File.exists(transmd5)) {
521 File.remove(transmd5);
523 for(v in map) { i++; break };
525 return; // no strings in file...
527 var ffn = fn.substring(this.prefix.length);
530 File.write(transfile, "\n'" + ffn + "' : {");
534 File.write(transmd5, '');
539 File.append(transfile, l + "\n\t\"" + v + "\" : \"" + v +"\"");
541 // strings are raw... - as the where encoded to start with!!!
542 // so we should not need to encode them again.. - just wrap with "
543 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
545 File.append(transfile, "\n},"); // always one trailing..
549 md5 : function (string)
552 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
555 stringHandler : function(tok)
557 //print("STRING HANDLER");
558 // callback when outputing compressed file,
560 if (!this.translateJSON) {
561 // print("TURNED OFF");
564 if (tok.name == 'SINGLE_QUOTE') {
568 if (typeof(tok.trsum) == 'undefined') {
572 return '_T["' + tok.trsum + '"]';
574 var sval = data.substring(1,data.length-1);
575 // we do not clean up... quoting here!??!!?!?!?!?
578 // blank with tabs or spaces..
579 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
580 // return tok.outData;
583 var sval = tok.data.substring(1,data.length-1);
584 var fn = this.activeFile.substring(this.prefix.length);
587 return '_T["' + this.md5(fn + '-' + sval) + '"]';