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 public Gee.ArrayList<string> files;
92 * @cfg activeFile ??? used???
95 public string activeFile = "";
97 public string outstr = ""; // if no target is specified - then this will contain the result
99 public PackerRun config;
101 public Packer(PackerRun config)
103 this.config = config;
105 this.result = new Json.Object();
107 this.result_count = new Gee.HashMap <string,int>();
109 this.result = new Gee.HashMap<
110 string /* errtype*/ , Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>
114 this.files = new Gee.ArrayList<string>();
116 new Lang_Class(); ///initilizaze lang..
118 //this.tmp = Glib.get_tmp_dir(); // do we have to delete this?
124 // this could be another class really..
126 public enum ResultType {
129 public string to_string() {
131 case err: return "ERR";
132 case warn: return "WARN";
133 default: assert_not_reached();
139 * result of complication - a JSON object containing warnings / errors etc..
141 * warn-TOTAL : X (number of warnings.
142 * err-TOTAL: X (number of errors) << this indicates failure...
145 * line : [ Errors,Errors,.... ]
153 public Json.Object result; // output - what's the complication result
155 public void logError(ResultType type, string filename, int line, string message) {
157 if (!this.result.has_member(type.to_string()+"-TOTAL")) {
158 this.result.set_int_member(type.to_string()+"-TOTAL", 1);
160 this.result.set_int_member(type.to_string()+"-TOTAL",
161 this.result.get_int_member(type.to_string()+"-TOTAL") +1
166 if (!this.result.has_member(type.to_string())) {
167 this.result.set_object_member(type.to_string(), new Json.Object());
169 var t = this.result.get_object_member(type.to_string());
170 if (!t.has_member(filename)) {
171 t.set_object_member(filename, new Json.Object());
173 var tt = t.get_object_member(filename);
174 if (!tt.has_member(line.to_string())) {
175 tt.set_array_member(line.to_string(), new Json.Array());
177 var tl = tt.get_array_member(line.to_string());
178 tl.add_string_element(message);
182 public bool hasErrors(string fn)
184 if (!this.result.has_member(ResultType.err.to_string())) {
191 var t = this.result.get_object_member(ResultType.err.to_string());
193 if (t.has_member(fn)) {
198 public void dumpErrors(ResultType type)
200 if (!this.result.has_member(type.to_string())) {
203 var t = this.result.get_object_member(type.to_string());
204 t.foreach_member((obj, filename, node) => {
205 var linelist = node.dup_object();
206 linelist.foreach_member((linelistobj, linestr, nodear) => {
207 var errors= nodear.dup_array();
208 errors.foreach_element((errorar, ignore, nodestr) => {
209 print("%s: %s:%s %s\n", type.to_string(), filename, linestr, nodestr.get_string());
216 public Gee.HashMap <string,int> result_count; // output - what's the complication result
219 string /* errtype*/ , Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>
222 public void logError(ResultType type, string filename, int line, string message) {
225 if (!this.result_count.has_key(type.to_string()+"-TOTAL")) {
226 this.result_count.set(type.to_string()+"-TOTAL", 1);
228 this.result_count.set(type.to_string()+"-TOTAL",
229 this.result_count.get(type.to_string()+"-TOTAL") +1
235 if (!this.result.has_key(type.to_string())) {
236 this.result.set(type.to_string(),
237 new Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>()
240 var t = this.result.get(type.to_string());
241 if (!t.has_key(filename)) {
242 t.set(filename, new Gee.HashMap<int /*line*/, Gee.ArrayList<string>>());
244 var tt = t.get(filename);
245 if (!tt.has_key(line)) {
246 tt.set(line, new Gee.ArrayList<string>());
248 var tl = tt.get(line);
253 public bool hasErrors(string fn)
255 if (!this.result.has_key(ResultType.err.to_string())) {
262 var t = this.result.get(ResultType.err.to_string());
269 public void dumpErrors(ResultType type)
271 if (!this.result.has_key(type.to_string())) {
274 var t = this.result.get(type.to_string());
275 foreach(string filename in t.keys) {
276 var node = t.get(filename);
277 foreach(int line in node.keys) {
278 var errors = node.get(line);
279 foreach(string errstr in errors) {
280 print("%s: %s:%d %s\n", type.to_string(), filename, line, errstr);
292 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
294 foreach(var f in indexes) {
295 this.loadSourceIndex(f);
299 public void loadFiles(string[] fs)
301 // fixme -- prefix baseDir?
302 foreach(var f in fs) {
303 GLib.debug("add File: %s", f);
304 this.files.add(f); //?? easier way?
307 public void loadFile(string f)
309 // fixme -- prefix baseDir?
310 GLib.debug("add File: %s", f);
312 GLib.debug("FILE LEN: %d", this.files.size);
316 public string pack(string target, string targetDebug = "") throws PackerError
318 this.target = target;
319 this.targetDebug = targetDebug;
321 if (this.files.size < 1) {
322 throw new PackerError.ArgumentError("No Files loaded before pack() called");
324 if (this.target.length > 0 ) {
325 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
327 if (this.targetDebug.length > 0 ) {
328 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
330 return this.packAll();
338 * load a dependancy list -f option
339 * @param {String} srcfile sourcefile to parse
343 public void loadSourceIndex(string in_srcfile)
346 var srcfile = in_srcfile;
347 if (srcfile[0] != '/') {
348 srcfile = config.opt_real_basedir + in_srcfile;
351 FileUtils.get_contents(srcfile,out str);
353 var lines = str.split("\n");
354 for(var i =0; i < lines.length;i++) {
356 var f = lines[i].strip();
358 Regex.match_simple ("^/", f) ||
359 !Regex.match_simple ("[a-zA-Z]+", f)
361 continue; // blank comment or not starting with a-z
364 if (Regex.match_simple ("\\.js$", f)) {
370 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
371 // should we prefix? =- or should this be done elsewhere?
373 var add = f.replace(".", "/") + ".js";
376 add = config.opt_real_basedir + add;
379 if (this.files.contains(add)) {
385 this.files.add( add );
391 private string packAll() // do the packing (run from constructor)
394 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
395 //File.write(this.transfile, "");
396 if (this.target.length > 0) {
397 this.targetStream.write("".data);
400 if (this.targetDebugStream != null) {
401 this.targetDebugStream.write("".data);
405 var tmpDir = GLib.DirUtils.make_tmp("roojspacker_XXXXXX");
407 foreach(var file in this.files) {
409 print("reading %s\n",file );
411 if (!FileUtils.test (file, FileTest.EXISTS) || FileUtils.test (file, FileTest.IS_DIR)) {
412 print("SKIP (is not a file) %s\n ", file);
416 var loaded_string = false;
417 string file_contents = "";
420 if (this.targetDebugStream !=null) {
422 FileUtils.get_contents(file,out file_contents);
423 this.targetDebugStream.write(file_contents.data);
424 loaded_string = false;
426 // it's a good idea to check with 0 compression to see if the code can parse!!
429 //File.append(dout, str +"\n");
433 var minfile = tmpDir + "/" + file.replace("/", ".");
436 // let's see if we have a min file already?
437 // this might happen if tmpDir is set ..
440 if ( FileUtils.test (minfile, FileTest.EXISTS)) {
442 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
443 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
446 // print("%s : compare : Cache file %s to Orignal Time %s\n", file, mtv.to_iso8601(), otv.to_iso8601());
447 if (mtv.tv_usec > otv.tv_usec) {
448 continue; // file is newer or the same time..
454 print("COMPRESSING to %s\n", minfile);
455 //var codeComp = pack(str, 10, 0, 0);
456 if (config.opt_clean_cache && FileUtils.test (minfile, FileTest.EXISTS)) {
457 FileUtils.remove(minfile);
459 if (!loaded_string) {
460 FileUtils.get_contents(file,out file_contents);
463 this.packFile(file_contents, file, minfile);
468 // at this point if we have errors, we should stop..
471 this.dumpErrors(ResultType.warn);
472 this.dumpErrors(ResultType.err); // since they are fatal - display them last...
477 if (config.opt_dump_tokens || this.hasErrors("")) {
479 GLib.Process.exit(0);
481 print("MERGING SOURCE\n");
483 for(var i=0; i < this.files.size; i++) {
484 var file = this.files[i];
485 var minfile = tmpDir + "/" + file.replace("/", ".");
488 if ( !FileUtils.test(minfile, FileTest.EXISTS)) {
489 print("skipping source %s - does not exist\n", minfile);
493 FileUtils.get_contents(minfile, out str);
494 print("using MIN FILE %s\n", minfile);
495 if (str.length > 0) {
496 if (this.targetStream != null) {
497 this.targetStream.write(("// " +
498 ( (file.length > config.opt_real_basedir.length) ? file.substring(config.opt_real_basedir.length) : file ) +
501 this.targetStream.write((str + "\n").data);
504 this.outstr += "//" +
505 ( (file.length > config.opt_real_basedir.length) ? file.substring(config.opt_real_basedir.length) : file ) + "\n";
506 this.outstr += "//" + file +"\n";
508 this.outstr += str + "\n";
512 if (config.opt_clean_cache) {
513 FileUtils.remove(minfile);
517 if (config.opt_clean_cache) {
518 FileUtils.remove(tmpDir);
521 if (this.target.length > 0 ) {
522 print("Output file: " + this.target);
524 if (this.targetDebug.length > 0) {
525 print("Output debug file: %s\n" , this.targetDebug);
530 // OUTPUT should be handled by PackerRun (so that this can be used as a library...)
531 if (this.outstr.length > 0 ) {
533 // stdout.printf ("%s", this.outstr);
540 * Core packing routine for a file
542 * @param str - str source text..
543 * @param fn - filename (for reference?)
544 * @param minfile - min file location...
548 public string packFile (string str,string fn, string minfile)
551 var tr = new TokenReader(this);
554 tr.keepComments = true;
556 tr.collapseWhite = false;
559 // we can load translation map here...
561 TokenArray toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
563 if (config.opt_dump_tokens) {
566 //GLib.Process.exit(0);
569 this.activeFile = fn;
571 // and replace if we are generating a different language..
574 //var ts = new TokenStream(toks);
575 //print(JSON.stringify(toks, null,4 )); Seed.quit();
576 var ts = new Collapse(toks.tokens, this, fn);
578 //ts.dumpAll(""); print("Done collaps"); Process.exit(1);
580 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
582 if (!config.opt_skip_scope) {
583 var sp = new ScopeParser(ts, this, fn);
586 sp.buildSymbolTree();
587 sp.mungeSymboltree();
594 //print(sp.warnings.join("\n"));
595 //(new TokenStream(toks.tokens)).dumpAll(""); GLib.Process.exit(1);
596 // compress works on the original array - in theory the replacements have already been done by now
597 var outf = CompressWhite(new TokenStream(toks.tokens), this, config.opt_keep_whitespace); // do not kill whitespace..
600 // debug("RESULT: \n %s\n", outf);
604 if (outf.length > 0 && minfile.length > 0 && !this.hasErrors(fn)) {
605 FileUtils.set_contents(minfile, outf);
617 public string md5(string str)
620 return GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str);
624 //stringHandler : function(tok) -- not used...