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..
155 this.tmp = Glib.make_tmp("ROOPKR");
160 // this could be another class really..
162 public enum ResultType {
165 public string to_string() {
167 case err: return "ERR";
168 case warn: return "WARN";
169 default: assert_not_reached();
175 * result of complication - a JSON object containing warnings / errors etc..
177 * warn-TOTAL : X (number of warnings.
178 * err-TOTAL: X (number of errors) << this indicates failure...
181 * line : [ Errors,Errors,.... ]
189 public Json.Object result; // output - what's the complication result
191 public void logError(ResultType type, string filename, int line, string message) {
193 if (!this.result.has_member(type.to_string()+"-TOTAL")) {
194 this.result.set_int_member(type.to_string()+"-TOTAL", 1);
196 this.result.set_int_member(type.to_string()+"-TOTAL",
197 this.result.get_int_member(type.to_string()+"-TOTAL") +1
202 if (!this.result.has_member(type.to_string())) {
203 this.result.set_object_member(type.to_string(), new Json.Object());
205 var t = this.result.get_object_member(type.to_string());
206 if (!t.has_member(filename)) {
207 t.set_object_member(filename, new Json.Object());
209 var tt = t.get_object_member(filename);
210 if (!tt.has_member(line.to_string())) {
211 tt.set_array_member(line.to_string(), new Json.Array());
213 var tl = tt.get_array_member(line.to_string());
214 tl.add_string_element(message);
218 public bool hasErrors(string fn)
220 if (!this.result.has_member(ResultType.err.to_string())) {
227 var t = this.result.get_object_member(ResultType.err.to_string());
229 if (t.has_member(fn)) {
234 public void dumpErrors(ResultType type)
236 if (!this.result.has_member(type.to_string())) {
239 var t = this.result.get_object_member(type.to_string());
240 t.foreach_member((obj, filename, node) => {
241 var linelist = node.dup_object();
242 linelist.foreach_member((linelistobj, linestr, nodear) => {
243 var errors= nodear.dup_array();
244 errors.foreach_element((errorar, ignore, nodestr) => {
245 print("%s: %s:%s %s\n", type.to_string(), filename, linestr, nodestr.get_string());
252 public Gee.HashMap <string,int> result_count; // output - what's the complication result
255 string /* errtype*/ , Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>
258 public void logError(ResultType type, string filename, int line, string message) {
261 if (!this.result_count.has_key(type.to_string()+"-TOTAL")) {
262 this.result_count.set(type.to_string()+"-TOTAL", 1);
264 this.result_count.set(type.to_string()+"-TOTAL",
265 this.result_count.get(type.to_string()+"-TOTAL") +1
271 if (!this.result.has_key(type.to_string())) {
272 this.result.set(type.to_string(),
273 new Gee.HashMap<string /*fn*/, Gee.HashMap<int /*line*/, Gee.ArrayList<string>>>()
276 var t = this.result.get(type.to_string());
277 if (!t.has_key(filename)) {
278 t.set(filename, new Gee.HashMap<int /*line*/, Gee.ArrayList<string>>());
280 var tt = t.get(filename);
281 if (!tt.has_key(line)) {
282 tt.set(line, new Gee.ArrayList<string>());
284 var tl = tt.get(line);
289 public bool hasErrors(string fn)
291 if (!this.result.has_key(ResultType.err.to_string())) {
298 var t = this.result.get(ResultType.err.to_string());
305 public void dumpErrors(ResultType type)
307 if (!this.result.has_key(type.to_string())) {
310 var t = this.result.get(type.to_string());
311 foreach(string filename in t.keys) {
312 var node = t.get(filename);
313 foreach(int line in node.keys) {
314 var errors = node.get(line);
315 foreach(string errstr in errors) {
316 print("%s: %s:%d %s\n", type.to_string(), filename, line, errstr);
328 public void loadSourceIndexes(Gee.ArrayList<string> indexes)
330 foreach(var f in indexes) {
331 this.loadSourceIndex(f);
335 public void loadFiles(string[] fs)
337 // fixme -- prefix baseDir?
338 foreach(var f in fs) {
339 GLib.debug("add File: %s", f);
340 this.files.add(f); //?? easier way?
343 public void loadFile(string f)
345 // fixme -- prefix baseDir?
346 GLib.debug("add File: %s", f);
348 GLib.debug("FILE LEN: %d", this.files.size);
352 public string pack(string target, string targetDebug = "") throws PackerError
354 this.target = target;
355 this.targetDebug = targetDebug;
357 if (this.files.size < 1) {
358 throw new PackerError.ArgumentError("No Files loaded before pack() called");
360 if (this.target.length > 0 ) {
361 this.targetStream = File.new_for_path(this.target).replace(null, false,FileCreateFlags.NONE);
363 if (this.targetDebug.length > 0 ) {
364 this.targetDebugStream = File.new_for_path(this.targetDebug).replace(null, false,FileCreateFlags.NONE);
366 return this.packAll();
374 * load a dependancy list -f option
375 * @param {String} srcfile sourcefile to parse
379 public void loadSourceIndex(string in_srcfile)
382 var srcfile = in_srcfile;
383 if (srcfile[0] != '/') {
384 srcfile = this.baseDir + in_srcfile;
387 FileUtils.get_contents(srcfile,out str);
389 var lines = str.split("\n");
390 for(var i =0; i < lines.length;i++) {
392 var f = lines[i].strip();
394 Regex.match_simple ("^/", f) ||
395 !Regex.match_simple ("[a-zA-Z]+", f)
397 continue; // blank comment or not starting with a-z
400 if (Regex.match_simple ("\\.js$", f)) {
406 // this maps Roo.bootstrap.XXX to Roo/bootstrap/xxx.js
407 // should we prefix? =- or should this be done elsewhere?
409 var add = f.replace(".", "/") + ".js";
412 add = this.baseDir + add;
415 if (this.files.contains(add)) {
421 this.files.add( add );
427 private string packAll() // do the packing (run from constructor)
430 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
431 //File.write(this.transfile, "");
432 if (this.target.length > 0) {
433 this.targetStream.write("".data);
436 if (this.targetDebugStream != null) {
437 this.targetDebugStream.write("".data);
441 foreach(var file in this.files) {
443 print("reading %s\n",file );
445 if (!FileUtils.test (file, FileTest.EXISTS) || FileUtils.test (file, FileTest.IS_DIR)) {
446 print("SKIP (is not a file) %s\n ", file);
450 var loaded_string = false;
451 string file_contents = "";
454 if (this.targetDebugStream !=null) {
456 FileUtils.get_contents(file,out file_contents);
457 this.targetDebugStream.write(file_contents.data);
458 loaded_string = false;
460 // it's a good idea to check with 0 compression to see if the code can parse!!
463 //File.append(dout, str +"\n");
467 var minfile = this.tmpDir + "/" + file.replace("/", ".");
470 // let's see if we have a min file already?
471 // this might happen if tmpDir is set ..
474 if ( FileUtils.test (minfile, FileTest.EXISTS)) {
476 var otv = File.new_for_path(file).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
477 var mtv = File.new_for_path(minfile).query_info (FileAttribute.TIME_MODIFIED, 0).get_modification_time();
480 // print("%s : compare : Cache file %s to Orignal Time %s\n", file, mtv.to_iso8601(), otv.to_iso8601());
481 if (mtv.tv_usec > otv.tv_usec) {
482 continue; // file is newer or the same time..
488 print("COMPRESSING to %s\n", minfile);
489 //var codeComp = pack(str, 10, 0, 0);
490 if (this.cleanup && FileUtils.test (minfile, FileTest.EXISTS)) {
491 FileUtils.remove(minfile);
493 if (!loaded_string) {
494 FileUtils.get_contents(file,out file_contents);
497 this.packFile(file_contents, file, minfile);
502 // at this point if we have errors, we should stop..
505 this.dumpErrors(ResultType.warn);
506 this.dumpErrors(ResultType.err); // since they are fatal - display them last...
511 if (this.dumpTokens || this.hasErrors("")) {
513 GLib.Process.exit(0);
515 print("MERGING SOURCE\n");
517 for(var i=0; i < this.files.size; i++) {
518 var file = this.files[i];
519 var minfile = this.tmpDir + "/" + file.replace("/", ".");
522 if ( !FileUtils.test(minfile, FileTest.EXISTS)) {
523 print("skipping source %s - does not exist\n", minfile);
527 FileUtils.get_contents(minfile, out str);
528 print("using MIN FILE %s\n", minfile);
529 if (str.length > 0) {
530 if (this.targetStream != null) {
531 this.targetStream.write(("// " +
532 ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length) : file ) +
534 this.targetStream.write((str + "\n").data);
537 this.outstr += "//" +
538 ( (file.length > this.baseDir.length) ? file.substring(this.baseDir.length) : file ) + "\n";
539 this.outstr += str + "\n";
544 FileUtils.remove(minfile);
551 if (this.target.length > 0 ) {
552 print("Output file: " + this.target);
554 if (this.targetDebug.length > 0) {
555 print("Output debug file: %s\n" , this.targetDebug);
560 // OUTPUT should be handled by PackerRun (so that this can be used as a library...)
561 if (this.outstr.length > 0 ) {
563 // stdout.printf ("%s", this.outstr);
570 * Core packing routine for a file
572 * @param str - str source text..
573 * @param fn - filename (for reference?)
574 * @param minfile - min file location...
578 public string packFile (string str,string fn, string minfile)
581 var tr = new TokenReader(this);
584 tr.keepComments = true;
586 tr.collapseWhite = false;
589 // we can load translation map here...
591 TokenArray toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
593 if (this.dumpTokens) {
596 //GLib.Process.exit(0);
599 this.activeFile = fn;
601 // and replace if we are generating a different language..
604 //var ts = new TokenStream(toks);
605 //print(JSON.stringify(toks, null,4 )); Seed.quit();
606 var ts = new Collapse(toks.tokens, this, fn);
608 //ts.dumpAll(""); print("Done collaps"); Process.exit(1);
610 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
612 if (!this.skipScope) {
613 var sp = new ScopeParser(ts, this, fn);
616 sp.buildSymbolTree();
617 sp.mungeSymboltree();
624 //print(sp.warnings.join("\n"));
625 //(new TokenStream(toks.tokens)).dumpAll(""); GLib.Process.exit(1);
626 // compress works on the original array - in theory the replacements have already been done by now
627 var outf = CompressWhite(new TokenStream(toks.tokens), this, this.keepWhite); // do not kill whitespace..
630 debug("RESULT: \n %s\n", outf);
634 if (outf.length > 0 && minfile.length > 0 && !this.hasErrors(fn)) {
635 FileUtils.set_contents(minfile, outf);
647 public string md5(string str)
650 return GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str);
654 //stringHandler : function(tok) -- not used...