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 tmpDir = "/tmp"; // FIXME??? in ctor?
78 Gee.ArrayList<string> files;
80 public Packer(string target, string debugTarget)
83 this.debugTarget = debugTarget;
87 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
89 foreach(var f in indexes) {
90 this.loadSourceIndex(f);
94 public void loadFiles(Gee.ArrayList<string> fs)
96 foreach(var f in fs) {
97 this.files.add(f); //?? easier way?
104 throw new Packer.ArgumentError("No Files loaded before pack() called");
113 translateJSON : '', // json based list of strings in all files.
116 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
117 * Defaults to false if you set tmpDir, otherwise true.
121 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
122 * usefull for debugging compressed files.
128 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
129 * Calculating md5 of filename
132 out : '', // if no target is specified - then this will contain the result
135 * load a dependancy list -f option
136 * @param {String} srcfile sourcefile to parse
140 loadSourceIndexes : function(srcfile)
142 var lines = File.read(srcfile).split("\n");
144 lines.forEach(function(f) {
146 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
149 if (/\.js$/.test(f)) {
150 _this.files.push( f);
155 //println("ADD"+ f.replace(/\./g, '/'));
156 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
157 if (_this.files.indexOf(f) > -1) {
160 _this.files.push( add );
166 packAll : function() // do the packing (run from constructor)
169 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
170 //File.write(this.transfile, "");
172 File.write(this.target, "");
175 if (this.debugTarget) {
176 File.write(this.debugTarget, "");
178 if (this.debugTranslateTarget) {
179 File.write(this.debugTarget, "");
182 for(var i=0; i < this.files.length; i++) {
183 var file = this.files[i];
185 print("reading " +file );
186 if (!File.isFile(file)) {
187 print("SKIP (is not a file) " + file);
193 if (this.debugTarget) {
194 File.append(this.debugTarget, File.read(file));
196 // it's a good idea to check with 0 compression to see if the code can parse!!
199 //File.append(dout, str +"\n");
203 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
206 // let's see if we have a min file already?
207 // this might happen if tmpDir is set ..
208 if (true && File.exists(minfile)) {
209 var mt = File.mtime(minfile);
210 var ot = File.mtime(file);
211 print("compare : " + mt + "=>" + ot);
219 print("COMPRESSING ");
220 //var codeComp = pack(str, 10, 0, 0);
221 if (File.exists(minfile)) {
222 File.remove(minfile);
224 var str = File.read(file);
225 var str = this.pack(str, file, minfile);
232 // if we are translating, write the translations strings at the top
235 if (this.translateJSON) {
238 print("MERGING LANGUAGE");
239 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
241 File.write(this.target, out);
246 File.write(this.translateJSON, "");
247 for(var i=0; i < this.files.length; i++) {
248 var file = this.files[i];
249 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
250 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
251 if (File.exists(transmd5)) {
252 var str = File.read(transmd5);
255 File.append(this.target, str + "\n");
257 this.out += str + "\n";
262 File.remove(transmd5);
265 if (File.exists(transfile)) {
266 var str = File.read(transfile);
268 File.append(this.translateJSON, str);
271 File.remove(transfile);
279 print("MERGING SOURCE");
281 for(var i=0; i < this.files.length; i++) {
282 var file = this.files[i];
283 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
286 if (!File.exists(minfile)) {
289 var str = File.read(minfile);
290 print("using MIN FILE "+ minfile);
293 File.append(this.target, '//' + file + "\n");
294 File.append(this.target, str + "\n");
296 this.out += '//' + file + "\n";
297 this.out += str + "\n";
302 File.remove(minfile);
306 print("Output file: " + this.target);
307 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
314 * Core packing routine for a file
316 * @param str - str source text..
317 * @param fn - filename (for reference?)
318 * @param minfile - min file location...
322 pack : function (str,fn,minfile)
325 var tr = new TokenReader( {
330 collapseWhite : false,
333 this.timerPrint("START" + fn);
335 // we can load translation map here...
337 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
339 // at this point we can write a language file...
340 if (this.translateJSON) {
342 this.writeTranslateFile(fn, minfile, toks);
345 this.activeFile = fn;
347 // and replace if we are generating a different language..
349 this.timerPrint("Tokenized");
350 //var ts = new TokenStream(toks);
351 //print(JSON.stringify(toks, null,4 )); Seed.quit();
352 var ts = new Collapse(toks);
353 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
355 var sp = new ScopeParser(ts);
356 this.timerPrint("Converted to Parser");
358 sp.buildSymbolTree();
359 this.timerPrint("Built Sym tree");
360 sp.mungeSymboltree();
361 this.timerPrint("Munged Sym tree");
362 print(sp.warnings.join("\n"));
363 this.timerPrint("Compressed");
365 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
368 this.timerPrint("Compressed");
371 File.write(minfile, out);
372 this.timerPrint("Write (" + out.length + "bytes) " + minfile);
381 timerPrint: function (str) {
382 var ntime = new Date() * 1;
383 var tdif = ntime -this.timer;
385 print('['+tdif+']'+str);
390 * Translation concept...
391 * -> replace text strings with _T....
392 * -> this file will need inserting at the start of the application....
393 * -> we need to generate 2 files,
394 * -> a reference used to do the translation, and the _T file..
397 * We store the trsum on the token...
401 writeTranslateFile : function(fn, minfile, toks)
404 var map = {}; // 'string=> md5sum'
409 var tokfind = function (j,dir) {
411 if ((dir < 0) && (j < 0)) {
414 if ((dir > 0) && (j >= toks.length)) {
418 if (toks[j].type != 'WHIT') {
427 for (var i=0;i<toks.length;i++) {
430 if (t.type != 'STRN') {
433 if (t.name != 'DOUBLE_QUOTE') {
437 last = tokfind(i,-1);
438 next = tokfind(i,+1);
440 // we have to ignore key values on objects
443 // last == '{' or ',' and
447 next.type == 'PUNC' &&
450 last.type == 'PUNC' &&
451 (last.data == ',' || last.data == '{')
453 continue; // found object key... - we can not translate these
456 var sval = t.data.substring(1,t.data.length-1);
457 var ffn = fn.substring(_this.prefix.length);
459 t.trsum = _this.md5(ffn + '-' + sval);
467 var transfile = minfile + '.lang.trans';
468 var transmd5 = minfile + '.lang';
469 print("writeTranslateFile " + transfile);
472 if (File.exists(transfile)) {
473 File.remove(transfile);
475 if (File.exists(transmd5)) {
476 File.remove(transmd5);
478 for(v in map) { i++; break };
480 return; // no strings in file...
482 var ffn = fn.substring(this.prefix.length);
485 File.write(transfile, "\n'" + ffn + "' : {");
489 File.write(transmd5, '');
494 File.append(transfile, l + "\n\t\"" + v + "\" : \"" + v +"\"");
496 // strings are raw... - as the where encoded to start with!!!
497 // so we should not need to encode them again.. - just wrap with "
498 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
500 File.append(transfile, "\n},"); // always one trailing..
504 md5 : function (string)
507 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
510 stringHandler : function(tok)
512 //print("STRING HANDLER");
513 // callback when outputing compressed file,
515 if (!this.translateJSON) {
516 // print("TURNED OFF");
519 if (tok.name == 'SINGLE_QUOTE') {
523 if (typeof(tok.trsum) == 'undefined') {
527 return '_T["' + tok.trsum + '"]';
529 var sval = data.substring(1,data.length-1);
530 // we do not clean up... quoting here!??!!?!?!?!?
533 // blank with tabs or spaces..
534 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
535 // return tok.outData;
538 var sval = tok.data.substring(1,data.length-1);
539 var fn = this.activeFile.substring(this.prefix.length);
542 return '_T["' + this.md5(fn + '-' + sval) + '"]';