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?
88 // list of files to compile...
89 Gee.ArrayList<string> files;
92 * @cfg activeFile ??? used???
95 public string activeFile = "";
99 * @cfg baseDir -- prefix the files listed in indexfiles with this.
102 public string baseDir = "";
105 public string outstr = ""; // if no target is specified - then this will contain the result
113 this.result = new Json.Object();
115 this.result_count = new Gee.HashMap <string,int>();
117 this.result = new Gee.HashMap<
118 string /* errtype*/ , Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>
122 this.files = new Gee.ArrayList<string>();
124 new Lang_Class(); ///initilizaze lang..
126 //this.tmp = Glib.get_tmp_dir(); // do we have to delete this?
132 // this could be another class really..
134 public enum ResultType {
137 public string to_string() {
139 case err: return "ERR";
140 case warn: return "WARN";
141 default: assert_not_reached();
147 * result of complication - a JSON object containing warnings / errors etc..
149 * warn-TOTAL : X (number of warnings.
150 * err-TOTAL: X (number of errors) << this indicates failure...
153 * line : [ Errors,Errors,.... ]
161 public Json.Object result; // output - what's the complication result
163 public void logError(ResultType type, string filename, int line, string message) {
165 if (!this.result.has_member(type.to_string()+"-TOTAL")) {
166 this.result.set_int_member(type.to_string()+"-TOTAL", 1);
168 this.result.set_int_member(type.to_string()+"-TOTAL",
169 this.result.get_int_member(type.to_string()+"-TOTAL") +1
174 if (!this.result.has_member(type.to_string())) {
175 this.result.set_object_member(type.to_string(), new Json.Object());
177 var t = this.result.get_object_member(type.to_string());
178 if (!t.has_member(filename)) {
179 t.set_object_member(filename, new Json.Object());
181 var tt = t.get_object_member(filename);
182 if (!tt.has_member(line.to_string())) {
183 tt.set_array_member(line.to_string(), new Json.Array());
185 var tl = tt.get_array_member(line.to_string());
186 tl.add_string_element(message);
190 public bool hasErrors(string fn)
192 if (!this.result.has_member(ResultType.err.to_string())) {
199 var t = this.result.get_object_member(ResultType.err.to_string());
201 if (t.has_member(fn)) {
206 public void dumpErrors(ResultType type)
208 if (!this.result.has_member(type.to_string())) {
211 var t = this.result.get_object_member(type.to_string());
212 t.foreach_member((obj, filename, node) => {
213 var linelist = node.dup_object();
214 linelist.foreach_member((linelistobj, linestr, nodear) => {
215 var errors= nodear.dup_array();
216 errors.foreach_element((errorar, ignore, nodestr) => {
217 print("%s: %s:%s %s\n", type.to_string(), filename, linestr, nodestr.get_string());
224 public Gee.HashMap <string,int> result_count; // output - what's the complication result
227 string /* errtype*/ , Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>
230 public void logError(ResultType type, string filename, int line, string message) {
233 if (!this.result_count.has_key(type.to_string()+"-TOTAL")) {
234 this.result_count.set(type.to_string()+"-TOTAL", 1);
236 this.result_count.set(type.to_string()+"-TOTAL",
237 this.result_count.get(type.to_string()+"-TOTAL") +1
243 if (!this.result.has_key(type.to_string())) {
244 this.result.set(type.to_string(),
245 new Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>()
248 var t = this.result.get(type.to_string());
249 if (!t.has_key(filename)) {
250 t.set(filename, new Gee.HashMap<int /*line*/, Gee.ArrayList<string>>());
252 var tt = t.get(filename);
253 if (!tt.has_key(line)) {
254 tt.set(line, new Gee.ArrayList<string>());
256 var tl = tt.get(line);
261 public bool hasErrors(string fn)
263 if (!this.result.has_key(ResultType.err.to_string())) {
270 var t = this.result.get(ResultType.err.to_string());
277 public void dumpErrors(ResultType type)
279 if (!this.result.has_key(type.to_string())) {
282 var t = this.result.get(type.to_string());
283 foreach(string filename in t.keys) {
284 var node = t.get(filename);
285 foreach(int line in node.keys) {
286 var errors = node.get(line);
287 foreach(string errstr in errors) {
288 print("%s: %s:%d %s\n", type.to_string(), filename, line, errstr);
300 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
302 foreach(var f in indexes) {
303 this.loadSourceIndex(f);
307 public void loadFiles(string[] fs)
309 // fixme -- prefix baseDir?
310 foreach(var f in fs) {
311 GLib.debug("add File: %s", f);
312 this.files.add(f); //?? easier way?
315 public void loadFile(string f)
317 // fixme -- prefix baseDir?
318 GLib.debug("add File: %s", f);
320 GLib.debug("FILE LEN: %d", this.files.size);
324 public string pack(string target, string targetDebug = "") throws PackerError
326 this.target = target;
327 this.targetDebug = targetDebug;
329 if (this.files.size < 1) {
330 throw new PackerError.ArgumentError("No Files loaded before pack() called");
332 if (this.target.length > 0 ) {
333 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
335 if (this.targetDebug.length > 0 ) {
336 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
338 return this.packAll();
346 * load a dependancy list -f option
347 * @param {String} srcfile sourcefile to parse
351 public void loadSourceIndex(string in_srcfile)
354 var srcfile = in_srcfile;
355 if (srcfile[0] != '/') {
356 srcfile = this.baseDir + in_srcfile;
359 FileUtils.get_contents(srcfile,out str);
361 var lines = str.split("\n");
362 for(var i =0; i < lines.length;i++) {
364 var f = lines[i].strip();
366 Regex.match_simple ("^/", f) ||
367 !Regex.match_simple ("[a-zA-Z]+", f)
369 continue; // blank comment or not starting with a-z
372 if (Regex.match_simple ("\\.js$", f)) {
378 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
379 // should we prefix? =- or should this be done elsewhere?
381 var add = f.replace(".", "/") + ".js";
384 add = this.baseDir + add;
387 if (this.files.contains(add)) {
393 this.files.add( add );
399 private string packAll() // do the packing (run from constructor)
402 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
403 //File.write(this.transfile, "");
404 if (this.target.length > 0) {
405 this.targetStream.write("".data);
408 if (this.targetDebugStream != null) {
409 this.targetDebugStream.write("".data);
413 var tmpDir = GLib.DirUtils.make_tmp("roojspacker_XXXXXX");
415 foreach(var file in this.files) {
417 print("reading %s\n",file );
419 if (!FileUtils.test (file, FileTest.EXISTS) || FileUtils.test (file, FileTest.IS_DIR)) {
420 print("SKIP (is not a file) %s\n ", file);
424 var loaded_string = false;
425 string file_contents = "";
428 if (this.targetDebugStream !=null) {
430 FileUtils.get_contents(file,out file_contents);
431 this.targetDebugStream.write(file_contents.data);
432 loaded_string = false;
434 // it's a good idea to check with 0 compression to see if the code can parse!!
437 //File.append(dout, str +"\n");
441 var minfile = tmpDir + "/" + file.replace("/", ".");
444 // let's see if we have a min file already?
445 // this might happen if tmpDir is set ..
448 if ( FileUtils.test (minfile, FileTest.EXISTS)) {
450 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
451 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
454 // print("%s : compare : Cache file %s to Orignal Time %s\n", file, mtv.to_iso8601(), otv.to_iso8601());
455 if (mtv.tv_usec > otv.tv_usec) {
456 continue; // file is newer or the same time..
462 print("COMPRESSING to %s\n", minfile);
463 //var codeComp = pack(str, 10, 0, 0);
464 if (PackerRun.opt_clean_cache && FileUtils.test (minfile, FileTest.EXISTS)) {
465 FileUtils.remove(minfile);
467 if (!loaded_string) {
468 FileUtils.get_contents(file,out file_contents);
471 this.packFile(file_contents, file, minfile);
476 // at this point if we have errors, we should stop..
479 this.dumpErrors(ResultType.warn);
480 this.dumpErrors(ResultType.err); // since they are fatal - display them last...
485 if (PackerRun.opt_dump_tokens || this.hasErrors("")) {
487 GLib.Process.exit(0);
489 print("MERGING SOURCE\n");
491 for(var i=0; i < this.files.size; i++) {
492 var file = this.files[i];
493 var minfile = tmpDir + "/" + file.replace("/", ".");
496 if ( !FileUtils.test(minfile, FileTest.EXISTS)) {
497 print("skipping source %s - does not exist\n", minfile);
501 FileUtils.get_contents(minfile, out str);
502 print("using MIN FILE %s\n", minfile);
503 if (str.length > 0) {
504 if (this.targetStream != null) {
505 this.targetStream.write(("// " +
506 ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length) : file ) +
508 this.targetStream.write((str + "\n").data);
511 this.outstr += "//" +
512 ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length) : file ) + "\n";
513 this.outstr += str + "\n";
517 if (PackerRun.opt_clean_cache) {
518 FileUtils.remove(minfile);
522 if (PackerRun.opt_clean_cache) {
523 FileUtils.remove(tmpDir);
526 if (this.target.length > 0 ) {
527 print("Output file: " + this.target);
529 if (this.targetDebug.length > 0) {
530 print("Output debug file: %s\n" , this.targetDebug);
535 // OUTPUT should be handled by PackerRun (so that this can be used as a library...)
536 if (this.outstr.length > 0 ) {
538 // stdout.printf ("%s", this.outstr);
545 * Core packing routine for a file
547 * @param str - str source text..
548 * @param fn - filename (for reference?)
549 * @param minfile - min file location...
553 public string packFile (string str,string fn, string minfile)
556 var tr = new TokenReader(this);
559 tr.keepComments = true;
561 tr.collapseWhite = false;
564 // we can load translation map here...
566 TokenArray toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
568 if (PackerRun.opt_dump_tokens) {
571 //GLib.Process.exit(0);
574 this.activeFile = fn;
576 // and replace if we are generating a different language..
579 //var ts = new TokenStream(toks);
580 //print(JSON.stringify(toks, null,4 )); Seed.quit();
581 var ts = new Collapse(toks.tokens, this, fn);
583 //ts.dumpAll(""); print("Done collaps"); Process.exit(1);
585 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
587 if (!PackerRun.opt_skip_scope) {
588 var sp = new ScopeParser(ts, this, fn);
591 sp.buildSymbolTree();
592 sp.mungeSymboltree();
599 //print(sp.warnings.join("\n"));
600 //(new TokenStream(toks.tokens)).dumpAll(""); GLib.Process.exit(1);
601 // compress works on the original array - in theory the replacements have already been done by now
602 var outf = CompressWhite(new TokenStream(toks.tokens), this, PackerRun.opt_keep_whitespace); // do not kill whitespace..
605 debug("RESULT: \n %s\n", outf);
609 if (outf.length > 0 && minfile.length > 0 && !this.hasErrors(fn)) {
610 FileUtils.set_contents(minfile, outf);
622 public string md5(string str)
625 return GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str);
629 //stringHandler : function(tok) -- not used...