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 debugTarget)
102 this.target = target;
103 this.debugTarget = debugTarget;
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?
124 throw new Packer.ArgumentError("No Files loaded before pack() called");
137 * load a dependancy list -f option
138 * @param {String} srcfile sourcefile to parse
142 public void loadSourceIndex(string srcfile)
145 FileUtils.get_contents(srcfile,out str);
147 var lines = str.split("\n");
148 for(var i =0; i < lines.length;i++) {
151 if (Regex.match_simple ("^\s*\/", f) ||
152 !Regex.match_simple ("[a-zA-Z]+", f)
154 continue; // blank or not starting with a-z
156 if (/\.js$/.test(f)) {
157 _this.files.push( f);
162 //println("ADD"+ f.replace(/\./g, '/'));
163 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
164 if (_this.files.indexOf(f) > -1) {
167 _this.files.push( add );
173 packAll : function() // do the packing (run from constructor)
176 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
177 //File.write(this.transfile, "");
179 File.write(this.target, "");
182 if (this.debugTarget) {
183 File.write(this.debugTarget, "");
185 if (this.debugTranslateTarget) {
186 File.write(this.debugTarget, "");
189 for(var i=0; i < this.files.length; i++) {
190 var file = this.files[i];
192 print("reading " +file );
193 if (!File.isFile(file)) {
194 print("SKIP (is not a file) " + file);
200 if (this.debugTarget) {
201 File.append(this.debugTarget, File.read(file));
203 // it's a good idea to check with 0 compression to see if the code can parse!!
206 //File.append(dout, str +"\n");
210 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
213 // let's see if we have a min file already?
214 // this might happen if tmpDir is set ..
215 if (true && File.exists(minfile)) {
216 var mt = File.mtime(minfile);
217 var ot = File.mtime(file);
218 print("compare : " + mt + "=>" + ot);
226 print("COMPRESSING ");
227 //var codeComp = pack(str, 10, 0, 0);
228 if (File.exists(minfile)) {
229 File.remove(minfile);
231 var str = File.read(file);
232 var str = this.pack(str, file, minfile);
239 // if we are translating, write the translations strings at the top
242 if (this.translateJSON) {
245 print("MERGING LANGUAGE");
246 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
248 File.write(this.target, out);
253 File.write(this.translateJSON, "");
254 for(var i=0; i < this.files.length; i++) {
255 var file = this.files[i];
256 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
257 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
258 if (File.exists(transmd5)) {
259 var str = File.read(transmd5);
262 File.append(this.target, str + "\n");
264 this.out += str + "\n";
269 File.remove(transmd5);
272 if (File.exists(transfile)) {
273 var str = File.read(transfile);
275 File.append(this.translateJSON, str);
278 File.remove(transfile);
286 print("MERGING SOURCE");
288 for(var i=0; i < this.files.length; i++) {
289 var file = this.files[i];
290 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
293 if (!File.exists(minfile)) {
296 var str = File.read(minfile);
297 print("using MIN FILE "+ minfile);
300 File.append(this.target, '//' + file + "\n");
301 File.append(this.target, str + "\n");
303 this.out += '//' + file + "\n";
304 this.out += str + "\n";
309 File.remove(minfile);
313 print("Output file: " + this.target);
314 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
321 * Core packing routine for a file
323 * @param str - str source text..
324 * @param fn - filename (for reference?)
325 * @param minfile - min file location...
329 pack : function (str,fn,minfile)
332 var tr = new TokenReader( {
337 collapseWhite : false,
340 this.timerPrint("START" + fn);
342 // we can load translation map here...
344 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
346 // at this point we can write a language file...
347 if (this.translateJSON) {
349 this.writeTranslateFile(fn, minfile, toks);
352 this.activeFile = fn;
354 // and replace if we are generating a different language..
356 this.timerPrint("Tokenized");
357 //var ts = new TokenStream(toks);
358 //print(JSON.stringify(toks, null,4 )); Seed.quit();
359 var ts = new Collapse(toks);
360 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
362 var sp = new ScopeParser(ts);
363 this.timerPrint("Converted to Parser");
365 sp.buildSymbolTree();
366 this.timerPrint("Built Sym tree");
367 sp.mungeSymboltree();
368 this.timerPrint("Munged Sym tree");
369 print(sp.warnings.join("\n"));
370 this.timerPrint("Compressed");
372 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
375 this.timerPrint("Compressed");
378 File.write(minfile, out);
379 this.timerPrint("Write (" + out.length + "bytes) " + minfile);
388 timerPrint: function (str) {
389 var ntime = new Date() * 1;
390 var tdif = ntime -this.timer;
392 print('['+tdif+']'+str);
397 * Translation concept...
398 * -> replace text strings with _T....
399 * -> this file will need inserting at the start of the application....
400 * -> we need to generate 2 files,
401 * -> a reference used to do the translation, and the _T file..
404 * We store the trsum on the token...
408 writeTranslateFile : function(fn, minfile, toks)
411 var map = {}; // 'string=> md5sum'
416 var tokfind = function (j,dir) {
418 if ((dir < 0) && (j < 0)) {
421 if ((dir > 0) && (j >= toks.length)) {
425 if (toks[j].type != 'WHIT') {
434 for (var i=0;i<toks.length;i++) {
437 if (t.type != 'STRN') {
440 if (t.name != 'DOUBLE_QUOTE') {
444 last = tokfind(i,-1);
445 next = tokfind(i,+1);
447 // we have to ignore key values on objects
450 // last == '{' or ',' and
454 next.type == 'PUNC' &&
457 last.type == 'PUNC' &&
458 (last.data == ',' || last.data == '{')
460 continue; // found object key... - we can not translate these
463 var sval = t.data.substring(1,t.data.length-1);
464 var ffn = fn.substring(_this.prefix.length);
466 t.trsum = _this.md5(ffn + '-' + sval);
474 var transfile = minfile + '.lang.trans';
475 var transmd5 = minfile + '.lang';
476 print("writeTranslateFile " + transfile);
479 if (File.exists(transfile)) {
480 File.remove(transfile);
482 if (File.exists(transmd5)) {
483 File.remove(transmd5);
485 for(v in map) { i++; break };
487 return; // no strings in file...
489 var ffn = fn.substring(this.prefix.length);
492 File.write(transfile, "\n'" + ffn + "' : {");
496 File.write(transmd5, '');
501 File.append(transfile, l + "\n\t\"" + v + "\" : \"" + v +"\"");
503 // strings are raw... - as the where encoded to start with!!!
504 // so we should not need to encode them again.. - just wrap with "
505 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
507 File.append(transfile, "\n},"); // always one trailing..
511 md5 : function (string)
514 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
517 stringHandler : function(tok)
519 //print("STRING HANDLER");
520 // callback when outputing compressed file,
522 if (!this.translateJSON) {
523 // print("TURNED OFF");
526 if (tok.name == 'SINGLE_QUOTE') {
530 if (typeof(tok.trsum) == 'undefined') {
534 return '_T["' + tok.trsum + '"]';
536 var sval = data.substring(1,data.length-1);
537 // we do not clean up... quoting here!??!!?!?!?!?
540 // blank with tabs or spaces..
541 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
542 // return tok.outData;
545 var sval = tok.data.substring(1,data.length-1);
546 var fn = this.activeFile.substring(this.prefix.length);
549 return '_T["' + this.md5(fn + '-' + sval) + '"]';