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"
23 x.pack(); // writes files etc..
27 * Notes for improving compacting:
28 * if you add a jsdoc comment
35 * directly before an eval statement, it will compress all the code around the eval,
36 * and not rename the variables 'avarname'
38 * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
39 * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
43 * Notes for translation
44 * - translation relies on you using double quotes for strings if they need translating
45 * - single quoted strings are ignored.
47 * Generation of indexFiles
48 * - translateIndex = the indexfile
57 public errordomain PackerError {
62 public class Packer : Object
65 * @cfg {String} target to write files to - must be full path.
68 GLib.FileOutputStream targetStream = null;
70 * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
72 string targetDebug = "";
75 GLib.FileOutputStream targetDebugStream = null;
77 * @cfg {String} tmpDir (optional) where to put the temporary files.
78 * if you set this, then files will not be cleaned up
80 * at present we need tmpfiles - as we compile multiple files into one.
81 * we could do this in memory now, as I suspect vala will not be as bad as javascript for leakage...
84 public string tmpDir = "/tmp"; // FIXME??? in ctor?
89 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
90 * Defaults to false if you set tmpDir, otherwise true.
92 public bool cleanup = false;
96 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
97 * usefull for debugging compressed files.
100 public bool keepWhite = false;
103 * @cfg {Boolean} skipScope (optional) skip Scope parsing and replacement.
104 * usefull for debugging...
107 public bool skipScope = false;
111 * @cfg {Boolean} dumpTokens (optional) read the first file and dump the tokens.
112 * usefull for debugging...
115 public bool dumpTokens = false;
117 // list of files to compile...
118 Gee.ArrayList<string> files;
121 * @cfg activeFile ??? used???
124 public string activeFile = "";
128 * @cfg baseDir -- prefix the files listed in indexfiles with this.
131 public string baseDir = "";
134 public string outstr = ""; // if no target is specified - then this will contain the result
141 this.result = new Json.Object();
142 this.files = new Gee.ArrayList<string>();
144 new Lang_Class(); ///initilizaze lang..
149 // this could be another class really..
151 public enum ResultType {
154 public string to_string() {
156 case err: return "ERR";
157 case warn: return "WARN";
158 default: assert_not_reached();
164 * result of complication - a JSON object containing warnings / errors etc..
166 * warn-TOTAL : X (number of warnings.
167 * err-TOTAL: X (number of errors) << this indicates failure...
170 * line : [ Errors,Errors,.... ]
177 public Json.Object result; // output - what's the complication result
179 public void logError(ResultType type, string filename, int line, string message) {
181 if (!this.result.has_member(type.to_string()+"-TOTAL")) {
182 this.result.set_int_member(type.to_string()+"-TOTAL", 1);
184 this.result.set_int_member(type.to_string()+"-TOTAL",
185 this.result.get_int_member(type.to_string()+"-TOTAL") +1
190 if (!this.result.has_member(type.to_string())) {
191 this.result.set_object_member(type.to_string(), new Json.Object());
193 var t = this.result.get_object_member(type.to_string());
194 if (!t.has_member(filename)) {
195 t.set_object_member(filename, new Json.Object());
197 var tt = t.get_object_member(filename);
198 if (!tt.has_member(line.to_string())) {
199 tt.set_array_member(line.to_string(), new Json.Array());
201 var tl = tt.get_array_member(line.to_string());
202 tl.add_string_element(message);
206 public bool hasErrors(string fn)
208 if (!this.result.has_member(ResultType.err.to_string())) {
215 var t = this.result.get_object_member(ResultType.err.to_string());
217 if (t.has_member(fn)) {
222 public void dumpErrors(ResultType type)
224 if (!this.result.has_member(type.to_string())) {
227 var t = this.result.get_object_member(type.to_string());
228 t.foreach_member((obj, filename, node) => {
229 var linelist = node.dup_object();
230 linelist.foreach_member((linelistobj, linestr, nodear) => {
231 var errors= nodear.dup_array();
232 errors.foreach_element((errorar, ignore, nodestr) => {
233 print("%s: %s:%s %s\n", type.to_string(), filename, linestr, nodestr.get_string());
244 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
246 foreach(var f in indexes) {
247 this.loadSourceIndex(f);
251 public void loadFiles(string[] fs)
253 // fixme -- prefix baseDir?
254 foreach(var f in fs) {
255 GLib.debug("add File: %s", f);
256 this.files.add(f); //?? easier way?
259 public void loadFile(string f)
261 // fixme -- prefix baseDir?
262 GLib.debug("add File: %s", f);
264 GLib.debug("FILE LEN: %d", this.files.size);
268 public string pack(string target, string targetDebug = "") throws PackerError
270 this.target = target;
271 this.targetDebug = targetDebug;
273 if (this.files.size < 1) {
274 throw new PackerError.ArgumentError("No Files loaded before pack() called");
276 if (this.target.length > 0 ) {
277 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
279 if (this.targetDebug.length > 0 ) {
280 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
282 return this.packAll();
290 * load a dependancy list -f option
291 * @param {String} srcfile sourcefile to parse
295 public void loadSourceIndex(string in_srcfile)
298 var srcfile = in_srcfile;
299 if (srcfile[0] != '/') {
300 srcfile = this.baseDir + in_srcfile;
303 FileUtils.get_contents(srcfile,out str);
305 var lines = str.split("\n");
306 for(var i =0; i < lines.length;i++) {
308 var f = lines[i].strip();
310 Regex.match_simple ("^/", f) ||
311 !Regex.match_simple ("[a-zA-Z]+", f)
313 continue; // blank comment or not starting with a-z
316 if (Regex.match_simple ("\\.js$", f)) {
322 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
323 // should we prefix? =- or should this be done elsewhere?
325 var add = f.replace(".", "/") + ".js";
328 add = this.baseDir + add;
331 if (this.files.contains(add)) {
337 this.files.add( add );
343 private string packAll() // do the packing (run from constructor)
346 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
347 //File.write(this.transfile, "");
348 if (this.target.length > 0) {
349 this.targetStream.write("".data);
352 if (this.targetDebugStream != null) {
353 this.targetDebugStream.write("".data);
357 foreach(var file in this.files) {
359 print("reading %s\n",file );
361 if (!FileUtils.test (file, FileTest.EXISTS) || FileUtils.test (file, FileTest.IS_DIR)) {
362 print("SKIP (is not a file) %s\n ", file);
366 var loaded_string = false;
367 string file_contents = "";
370 if (this.targetDebugStream !=null) {
372 FileUtils.get_contents(file,out file_contents);
373 this.targetDebugStream.write(file_contents.data);
374 loaded_string = false;
376 // it's a good idea to check with 0 compression to see if the code can parse!!
379 //File.append(dout, str +"\n");
383 var minfile = this.tmpDir + "/" + file.replace("/", ".");
386 // let's see if we have a min file already?
387 // this might happen if tmpDir is set ..
390 if ( FileUtils.test (minfile, FileTest.EXISTS)) {
392 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
393 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
396 // print("%s : compare : Cache file %s to Orignal Time %s\n", file, mtv.to_iso8601(), otv.to_iso8601());
397 if (mtv.tv_usec > otv.tv_usec) {
398 continue; // file is newer or the same time..
404 print("COMPRESSING to %s\n", minfile);
405 //var codeComp = pack(str, 10, 0, 0);
406 if (this.cleanup && FileUtils.test (minfile, FileTest.EXISTS)) {
407 FileUtils.remove(minfile);
409 if (!loaded_string) {
410 FileUtils.get_contents(file,out file_contents);
413 this.packFile(file_contents, file, minfile);
418 // at this point if we have errors, we should stop..
421 this.dumpErrors(ResultType.warn);
422 this.dumpErrors(ResultType.err); // since they are fatal - display them last...
427 if (this.dumpTokens || this.hasErrors("")) {
429 GLib.Process.exit(0);
431 print("MERGING SOURCE\n");
433 for(var i=0; i < this.files.size; i++) {
434 var file = this.files[i];
435 var minfile = this.tmpDir + "/" + file.replace("/", ".");
438 if ( !FileUtils.test(minfile, FileTest.EXISTS)) {
439 print("skipping source %s - does not exist\n", minfile);
443 FileUtils.get_contents(minfile, out str);
444 print("using MIN FILE %s\n", minfile);
445 if (str.length > 0) {
446 if (this.targetStream != null) {
447 this.targetStream.write(("// " +
448 ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length) : file ) +
450 this.targetStream.write((str + "\n").data);
453 this.outstr += "//" +
454 ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length) : file ) + "\n";
455 this.outstr += str + "\n";
460 FileUtils.remove(minfile);
467 if (this.target.length > 0 ) {
468 print("Output file: " + this.target);
470 if (this.targetDebug.length > 0) {
471 print("Output debug file: %s\n" , this.targetDebug);
476 // OUTPUT should be handled by PackerRun (so that this can be used as a library...)
477 if (this.outstr.length > 0 ) {
479 // stdout.printf ("%s", this.outstr);
486 * Core packing routine for a file
488 * @param str - str source text..
489 * @param fn - filename (for reference?)
490 * @param minfile - min file location...
494 public string packFile (string str,string fn, string minfile)
497 var tr = new TokenReader(this);
500 tr.keepComments = true;
502 tr.collapseWhite = false;
505 // we can load translation map here...
507 TokenArray toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
509 if (this.dumpTokens) {
512 //GLib.Process.exit(0);
515 this.activeFile = fn;
517 // and replace if we are generating a different language..
520 //var ts = new TokenStream(toks);
521 //print(JSON.stringify(toks, null,4 )); Seed.quit();
522 var ts = new Collapse(toks.tokens, this, fn);
524 //ts.dumpAll(""); print("Done collaps"); Process.exit(1);
526 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
528 if (!this.skipScope) {
529 var sp = new ScopeParser(ts, this, fn);
532 sp.buildSymbolTree();
533 sp.mungeSymboltree();
540 //print(sp.warnings.join("\n"));
541 //(new TokenStream(toks.tokens)).dumpAll(""); GLib.Process.exit(1);
542 // compress works on the original array - in theory the replacements have already been done by now
543 var outf = CompressWhite(new TokenStream(toks.tokens), this, this.keepWhite); // do not kill whitespace..
546 debug("RESULT: \n %s\n", outf);
550 if (outf.length > 0 && minfile.length > 0 && !this.hasErrors(fn)) {
551 FileUtils.set_contents(minfile, outf);
563 public string md5(string str)
566 return GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str);
570 //stringHandler : function(tok) -- not used...