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
142 this.result = new Json.Object();
144 this.result_count = new Gee.HashMap <string,int>();
146 this.result = new Gee.HashMap<
147 string /* errtype*/ , Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>
151 this.files = new Gee.ArrayList<string>();
153 new Lang_Class(); ///initilizaze lang..
158 // this could be another class really..
160 public enum ResultType {
163 public string to_string() {
165 case err: return "ERR";
166 case warn: return "WARN";
167 default: assert_not_reached();
173 * result of complication - a JSON object containing warnings / errors etc..
175 * warn-TOTAL : X (number of warnings.
176 * err-TOTAL: X (number of errors) << this indicates failure...
179 * line : [ Errors,Errors,.... ]
187 public Json.Object result; // output - what's the complication result
189 public void logError(ResultType type, string filename, int line, string message) {
191 if (!this.result.has_member(type.to_string()+"-TOTAL")) {
192 this.result.set_int_member(type.to_string()+"-TOTAL", 1);
194 this.result.set_int_member(type.to_string()+"-TOTAL",
195 this.result.get_int_member(type.to_string()+"-TOTAL") +1
200 if (!this.result.has_member(type.to_string())) {
201 this.result.set_object_member(type.to_string(), new Json.Object());
203 var t = this.result.get_object_member(type.to_string());
204 if (!t.has_member(filename)) {
205 t.set_object_member(filename, new Json.Object());
207 var tt = t.get_object_member(filename);
208 if (!tt.has_member(line.to_string())) {
209 tt.set_array_member(line.to_string(), new Json.Array());
211 var tl = tt.get_array_member(line.to_string());
212 tl.add_string_element(message);
216 public bool hasErrors(string fn)
218 if (!this.result.has_member(ResultType.err.to_string())) {
225 var t = this.result.get_object_member(ResultType.err.to_string());
227 if (t.has_member(fn)) {
232 public void dumpErrors(ResultType type)
234 if (!this.result.has_member(type.to_string())) {
237 var t = this.result.get_object_member(type.to_string());
238 t.foreach_member((obj, filename, node) => {
239 var linelist = node.dup_object();
240 linelist.foreach_member((linelistobj, linestr, nodear) => {
241 var errors= nodear.dup_array();
242 errors.foreach_element((errorar, ignore, nodestr) => {
243 print("%s: %s:%s %s\n", type.to_string(), filename, linestr, nodestr.get_string());
250 public Gee.HashMap <string,int> result_count; // output - what's the complication result
253 string /* errtype*/ , Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>
256 public void logError(ResultType type, string filename, int line, string message) {
259 if (!this.result_count.has_key(type.to_string()+"-TOTAL")) {
260 this.result_count.set(type.to_string()+"-TOTAL", 1);
262 this.result_count.set(type.to_string()+"-TOTAL",
263 this.result_count.get(type.to_string()+"-TOTAL") +1
269 if (!this.result.has_key(type.to_string())) {
270 this.result.set(type.to_string(),
271 new Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>()
274 var t = this.result.get(type.to_string());
275 if (!t.has_key(filename)) {
276 t.set(filename, new Gee.HashMap<int /*line*/, Gee.ArrayList<string>());
278 var tt = t.get(filename);
279 if (!tt.has_key(line)) {
280 tt.set_array_member(line, new Gee.ArrayList<string>());
282 var tl = tt.get(line);
287 public bool hasErrors(string fn)
289 if (!this.result.has_key(ResultType.err.to_string())) {
296 var t = this.result.get(ResultType.err.to_string());
303 public void dumpErrors(ResultType type)
305 if (!this.result.has_key(type.to_string())) {
308 var t = this.result.get(type.to_string());
309 t.map_iterator().foreach((filename, node) => {
310 node.map_iterator().foreach(line, errors) => {
312 errors.foreach((errstr) => {
313 print("%s: %s:%d %s\n", type.to_string(), filename, line, errstr);
325 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
327 foreach(var f in indexes) {
328 this.loadSourceIndex(f);
332 public void loadFiles(string[] fs)
334 // fixme -- prefix baseDir?
335 foreach(var f in fs) {
336 GLib.debug("add File: %s", f);
337 this.files.add(f); //?? easier way?
340 public void loadFile(string f)
342 // fixme -- prefix baseDir?
343 GLib.debug("add File: %s", f);
345 GLib.debug("FILE LEN: %d", this.files.size);
349 public string pack(string target, string targetDebug = "") throws PackerError
351 this.target = target;
352 this.targetDebug = targetDebug;
354 if (this.files.size < 1) {
355 throw new PackerError.ArgumentError("No Files loaded before pack() called");
357 if (this.target.length > 0 ) {
358 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
360 if (this.targetDebug.length > 0 ) {
361 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
363 return this.packAll();
371 * load a dependancy list -f option
372 * @param {String} srcfile sourcefile to parse
376 public void loadSourceIndex(string in_srcfile)
379 var srcfile = in_srcfile;
380 if (srcfile[0] != '/') {
381 srcfile = this.baseDir + in_srcfile;
384 FileUtils.get_contents(srcfile,out str);
386 var lines = str.split("\n");
387 for(var i =0; i < lines.length;i++) {
389 var f = lines[i].strip();
391 Regex.match_simple ("^/", f) ||
392 !Regex.match_simple ("[a-zA-Z]+", f)
394 continue; // blank comment or not starting with a-z
397 if (Regex.match_simple ("\\.js$", f)) {
403 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
404 // should we prefix? =- or should this be done elsewhere?
406 var add = f.replace(".", "/") + ".js";
409 add = this.baseDir + add;
412 if (this.files.contains(add)) {
418 this.files.add( add );
424 private string packAll() // do the packing (run from constructor)
427 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
428 //File.write(this.transfile, "");
429 if (this.target.length > 0) {
430 this.targetStream.write("".data);
433 if (this.targetDebugStream != null) {
434 this.targetDebugStream.write("".data);
438 foreach(var file in this.files) {
440 print("reading %s\n",file );
442 if (!FileUtils.test (file, FileTest.EXISTS) || FileUtils.test (file, FileTest.IS_DIR)) {
443 print("SKIP (is not a file) %s\n ", file);
447 var loaded_string = false;
448 string file_contents = "";
451 if (this.targetDebugStream !=null) {
453 FileUtils.get_contents(file,out file_contents);
454 this.targetDebugStream.write(file_contents.data);
455 loaded_string = false;
457 // it's a good idea to check with 0 compression to see if the code can parse!!
460 //File.append(dout, str +"\n");
464 var minfile = this.tmpDir + "/" + file.replace("/", ".");
467 // let's see if we have a min file already?
468 // this might happen if tmpDir is set ..
471 if ( FileUtils.test (minfile, FileTest.EXISTS)) {
473 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
474 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
477 // print("%s : compare : Cache file %s to Orignal Time %s\n", file, mtv.to_iso8601(), otv.to_iso8601());
478 if (mtv.tv_usec > otv.tv_usec) {
479 continue; // file is newer or the same time..
485 print("COMPRESSING to %s\n", minfile);
486 //var codeComp = pack(str, 10, 0, 0);
487 if (this.cleanup && FileUtils.test (minfile, FileTest.EXISTS)) {
488 FileUtils.remove(minfile);
490 if (!loaded_string) {
491 FileUtils.get_contents(file,out file_contents);
494 this.packFile(file_contents, file, minfile);
499 // at this point if we have errors, we should stop..
502 this.dumpErrors(ResultType.warn);
503 this.dumpErrors(ResultType.err); // since they are fatal - display them last...
508 if (this.dumpTokens || this.hasErrors("")) {
510 GLib.Process.exit(0);
512 print("MERGING SOURCE\n");
514 for(var i=0; i < this.files.size; i++) {
515 var file = this.files[i];
516 var minfile = this.tmpDir + "/" + file.replace("/", ".");
519 if ( !FileUtils.test(minfile, FileTest.EXISTS)) {
520 print("skipping source %s - does not exist\n", minfile);
524 FileUtils.get_contents(minfile, out str);
525 print("using MIN FILE %s\n", minfile);
526 if (str.length > 0) {
527 if (this.targetStream != null) {
528 this.targetStream.write(("// " +
529 ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length) : file ) +
531 this.targetStream.write((str + "\n").data);
534 this.outstr += "//" +
535 ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length) : file ) + "\n";
536 this.outstr += str + "\n";
541 FileUtils.remove(minfile);
548 if (this.target.length > 0 ) {
549 print("Output file: " + this.target);
551 if (this.targetDebug.length > 0) {
552 print("Output debug file: %s\n" , this.targetDebug);
557 // OUTPUT should be handled by PackerRun (so that this can be used as a library...)
558 if (this.outstr.length > 0 ) {
560 // stdout.printf ("%s", this.outstr);
567 * Core packing routine for a file
569 * @param str - str source text..
570 * @param fn - filename (for reference?)
571 * @param minfile - min file location...
575 public string packFile (string str,string fn, string minfile)
578 var tr = new TokenReader(this);
581 tr.keepComments = true;
583 tr.collapseWhite = false;
586 // we can load translation map here...
588 TokenArray toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
590 if (this.dumpTokens) {
593 //GLib.Process.exit(0);
596 this.activeFile = fn;
598 // and replace if we are generating a different language..
601 //var ts = new TokenStream(toks);
602 //print(JSON.stringify(toks, null,4 )); Seed.quit();
603 var ts = new Collapse(toks.tokens, this, fn);
605 //ts.dumpAll(""); print("Done collaps"); Process.exit(1);
607 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
609 if (!this.skipScope) {
610 var sp = new ScopeParser(ts, this, fn);
613 sp.buildSymbolTree();
614 sp.mungeSymboltree();
621 //print(sp.warnings.join("\n"));
622 //(new TokenStream(toks.tokens)).dumpAll(""); GLib.Process.exit(1);
623 // compress works on the original array - in theory the replacements have already been done by now
624 var outf = CompressWhite(new TokenStream(toks.tokens), this, this.keepWhite); // do not kill whitespace..
627 debug("RESULT: \n %s\n", outf);
631 if (outf.length > 0 && minfile.length > 0 && !this.hasErrors(fn)) {
632 FileUtils.set_contents(minfile, outf);
644 public string md5(string str)
647 return GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str);
651 //stringHandler : function(tok) -- not used...