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 Packer(string target, string debugTarget)
100 this.target = target;
101 this.debugTarget = debugTarget;
105 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
107 foreach(var f in indexes) {
108 this.loadSourceIndex(f);
112 public void loadFiles(Gee.ArrayList<string> fs)
114 foreach(var f in fs) {
115 this.files.add(f); //?? easier way?
122 throw new Packer.ArgumentError("No Files loaded before pack() called");
134 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
135 * Calculating md5 of filename
138 out : '', // if no target is specified - then this will contain the result
141 * load a dependancy list -f option
142 * @param {String} srcfile sourcefile to parse
146 loadSourceIndexes : function(srcfile)
148 var lines = File.read(srcfile).split("\n");
150 lines.forEach(function(f) {
152 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
155 if (/\.js$/.test(f)) {
156 _this.files.push( f);
161 //println("ADD"+ f.replace(/\./g, '/'));
162 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
163 if (_this.files.indexOf(f) > -1) {
166 _this.files.push( add );
172 packAll : function() // do the packing (run from constructor)
175 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
176 //File.write(this.transfile, "");
178 File.write(this.target, "");
181 if (this.debugTarget) {
182 File.write(this.debugTarget, "");
184 if (this.debugTranslateTarget) {
185 File.write(this.debugTarget, "");
188 for(var i=0; i < this.files.length; i++) {
189 var file = this.files[i];
191 print("reading " +file );
192 if (!File.isFile(file)) {
193 print("SKIP (is not a file) " + file);
199 if (this.debugTarget) {
200 File.append(this.debugTarget, File.read(file));
202 // it's a good idea to check with 0 compression to see if the code can parse!!
205 //File.append(dout, str +"\n");
209 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
212 // let's see if we have a min file already?
213 // this might happen if tmpDir is set ..
214 if (true && File.exists(minfile)) {
215 var mt = File.mtime(minfile);
216 var ot = File.mtime(file);
217 print("compare : " + mt + "=>" + ot);
225 print("COMPRESSING ");
226 //var codeComp = pack(str, 10, 0, 0);
227 if (File.exists(minfile)) {
228 File.remove(minfile);
230 var str = File.read(file);
231 var str = this.pack(str, file, minfile);
238 // if we are translating, write the translations strings at the top
241 if (this.translateJSON) {
244 print("MERGING LANGUAGE");
245 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
247 File.write(this.target, out);
252 File.write(this.translateJSON, "");
253 for(var i=0; i < this.files.length; i++) {
254 var file = this.files[i];
255 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
256 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
257 if (File.exists(transmd5)) {
258 var str = File.read(transmd5);
261 File.append(this.target, str + "\n");
263 this.out += str + "\n";
268 File.remove(transmd5);
271 if (File.exists(transfile)) {
272 var str = File.read(transfile);
274 File.append(this.translateJSON, str);
277 File.remove(transfile);
285 print("MERGING SOURCE");
287 for(var i=0; i < this.files.length; i++) {
288 var file = this.files[i];
289 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
292 if (!File.exists(minfile)) {
295 var str = File.read(minfile);
296 print("using MIN FILE "+ minfile);
299 File.append(this.target, '//' + file + "\n");
300 File.append(this.target, str + "\n");
302 this.out += '//' + file + "\n";
303 this.out += str + "\n";
308 File.remove(minfile);
312 print("Output file: " + this.target);
313 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
320 * Core packing routine for a file
322 * @param str - str source text..
323 * @param fn - filename (for reference?)
324 * @param minfile - min file location...
328 pack : function (str,fn,minfile)
331 var tr = new TokenReader( {
336 collapseWhite : false,
339 this.timerPrint("START" + fn);
341 // we can load translation map here...
343 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
345 // at this point we can write a language file...
346 if (this.translateJSON) {
348 this.writeTranslateFile(fn, minfile, toks);
351 this.activeFile = fn;
353 // and replace if we are generating a different language..
355 this.timerPrint("Tokenized");
356 //var ts = new TokenStream(toks);
357 //print(JSON.stringify(toks, null,4 )); Seed.quit();
358 var ts = new Collapse(toks);
359 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
361 var sp = new ScopeParser(ts);
362 this.timerPrint("Converted to Parser");
364 sp.buildSymbolTree();
365 this.timerPrint("Built Sym tree");
366 sp.mungeSymboltree();
367 this.timerPrint("Munged Sym tree");
368 print(sp.warnings.join("\n"));
369 this.timerPrint("Compressed");
371 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
374 this.timerPrint("Compressed");
377 File.write(minfile, out);
378 this.timerPrint("Write (" + out.length + "bytes) " + minfile);
387 timerPrint: function (str) {
388 var ntime = new Date() * 1;
389 var tdif = ntime -this.timer;
391 print('['+tdif+']'+str);
396 * Translation concept...
397 * -> replace text strings with _T....
398 * -> this file will need inserting at the start of the application....
399 * -> we need to generate 2 files,
400 * -> a reference used to do the translation, and the _T file..
403 * We store the trsum on the token...
407 writeTranslateFile : function(fn, minfile, toks)
410 var map = {}; // 'string=> md5sum'
415 var tokfind = function (j,dir) {
417 if ((dir < 0) && (j < 0)) {
420 if ((dir > 0) && (j >= toks.length)) {
424 if (toks[j].type != 'WHIT') {
433 for (var i=0;i<toks.length;i++) {
436 if (t.type != 'STRN') {
439 if (t.name != 'DOUBLE_QUOTE') {
443 last = tokfind(i,-1);
444 next = tokfind(i,+1);
446 // we have to ignore key values on objects
449 // last == '{' or ',' and
453 next.type == 'PUNC' &&
456 last.type == 'PUNC' &&
457 (last.data == ',' || last.data == '{')
459 continue; // found object key... - we can not translate these
462 var sval = t.data.substring(1,t.data.length-1);
463 var ffn = fn.substring(_this.prefix.length);
465 t.trsum = _this.md5(ffn + '-' + sval);
473 var transfile = minfile + '.lang.trans';
474 var transmd5 = minfile + '.lang';
475 print("writeTranslateFile " + transfile);
478 if (File.exists(transfile)) {
479 File.remove(transfile);
481 if (File.exists(transmd5)) {
482 File.remove(transmd5);
484 for(v in map) { i++; break };
486 return; // no strings in file...
488 var ffn = fn.substring(this.prefix.length);
491 File.write(transfile, "\n'" + ffn + "' : {");
495 File.write(transmd5, '');
500 File.append(transfile, l + "\n\t\"" + v + "\" : \"" + v +"\"");
502 // strings are raw... - as the where encoded to start with!!!
503 // so we should not need to encode them again.. - just wrap with "
504 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
506 File.append(transfile, "\n},"); // always one trailing..
510 md5 : function (string)
513 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
516 stringHandler : function(tok)
518 //print("STRING HANDLER");
519 // callback when outputing compressed file,
521 if (!this.translateJSON) {
522 // print("TURNED OFF");
525 if (tok.name == 'SINGLE_QUOTE') {
529 if (typeof(tok.trsum) == 'undefined') {
533 return '_T["' + tok.trsum + '"]';
535 var sval = data.substring(1,data.length-1);
536 // we do not clean up... quoting here!??!!?!?!?!?
539 // blank with tabs or spaces..
540 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
541 // return tok.outData;
544 var sval = tok.data.substring(1,data.length-1);
545 var fn = this.activeFile.substring(this.prefix.length);
548 return '_T["' + this.md5(fn + '-' + sval) + '"]';