Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. require("string.prototype.codepointat");
  2. var fs = require("fs");
  3. function Iterator(text) {
  4. var pos = 0, length = text.length;
  5. this.peek = function(num) {
  6. num = num || 0;
  7. if(pos + num >= length) { return null; }
  8. return text.charAt(pos + num);
  9. };
  10. this.next = function(inc) {
  11. inc = inc || 1;
  12. if(pos >= length) { return null; }
  13. return text.charAt((pos += inc) - inc);
  14. };
  15. this.pos = function() {
  16. return pos;
  17. };
  18. }
  19. var rWhitespace = /\s/;
  20. function isWhitespace(chr) {
  21. return rWhitespace.test(chr);
  22. }
  23. function consumeWhiteSpace(iter) {
  24. var start = iter.pos();
  25. while(isWhitespace(iter.peek())) { iter.next(); }
  26. return { type: "whitespace", start: start, end: iter.pos() };
  27. }
  28. function startsComment(chr) {
  29. return chr === "!" || chr === "#";
  30. }
  31. function isEOL(chr) {
  32. return chr == null || chr === "\n" || chr === "\r";
  33. }
  34. function consumeComment(iter) {
  35. var start = iter.pos();
  36. while(!isEOL(iter.peek())) { iter.next(); }
  37. return { type: "comment", start: start, end: iter.pos() };
  38. }
  39. function startsKeyVal(chr) {
  40. return !isWhitespace(chr) && !startsComment(chr);
  41. }
  42. function startsSeparator(chr) {
  43. return chr === "=" || chr === ":" || isWhitespace(chr);
  44. }
  45. function startsEscapedVal(chr) {
  46. return chr === "\\";
  47. }
  48. function consumeEscapedVal(iter) {
  49. var start = iter.pos();
  50. iter.next(); // move past "\"
  51. var curChar = iter.next();
  52. if(curChar === "u") { // encoded unicode char
  53. iter.next(4); // Read in the 4 hex values
  54. }
  55. return { type: "escaped-value", start: start, end: iter.pos() };
  56. }
  57. function consumeKey(iter) {
  58. var start = iter.pos(), children = [];
  59. var curChar;
  60. while((curChar = iter.peek()) !== null) {
  61. if(startsSeparator(curChar)) { break; }
  62. if(startsEscapedVal(curChar)) { children.push(consumeEscapedVal(iter)); continue; }
  63. iter.next();
  64. }
  65. return { type: "key", start: start, end: iter.pos(), children: children };
  66. }
  67. function consumeKeyValSeparator(iter) {
  68. var start = iter.pos();
  69. var seenHardSep = false, curChar;
  70. while((curChar = iter.peek()) !== null) {
  71. if(isEOL(curChar)) { break; }
  72. if(isWhitespace(curChar)) { iter.next(); continue; }
  73. if(seenHardSep) { break; }
  74. seenHardSep = (curChar === ":" || curChar === "=");
  75. if(seenHardSep) { iter.next(); continue; }
  76. break; // curChar is a non-separtor char
  77. }
  78. return { type: "key-value-separator", start: start, end: iter.pos() };
  79. }
  80. function startsLineBreak(iter) {
  81. return iter.peek() === "\\" && isEOL(iter.peek(1));
  82. }
  83. function consumeLineBreak(iter) {
  84. var start = iter.pos();
  85. iter.next(); // consume \
  86. if(iter.peek() === "\r") { iter.next(); }
  87. iter.next(); // consume \n
  88. var curChar;
  89. while((curChar = iter.peek()) !== null) {
  90. if(isEOL(curChar)) { break; }
  91. if(!isWhitespace(curChar)) { break; }
  92. iter.next();
  93. }
  94. return { type: "line-break", start: start, end: iter.pos() };
  95. }
  96. function consumeVal(iter) {
  97. var start = iter.pos(), children = [];
  98. var curChar;
  99. while((curChar = iter.peek()) !== null) {
  100. if(startsLineBreak(iter)) { children.push(consumeLineBreak(iter)); continue; }
  101. if(startsEscapedVal(curChar)) { children.push(consumeEscapedVal(iter)); continue; }
  102. if(isEOL(curChar)) { break; }
  103. iter.next();
  104. }
  105. return { type: "value", start: start, end: iter.pos(), children: children };
  106. }
  107. function consumeKeyVal(iter) {
  108. return {
  109. type: "key-value",
  110. start: iter.pos(),
  111. children: [
  112. consumeKey(iter),
  113. consumeKeyValSeparator(iter),
  114. consumeVal(iter)
  115. ],
  116. end: iter.pos()
  117. };
  118. }
  119. var renderChild = {
  120. "escaped-value": function(child, text) {
  121. var type = text.charAt(child.start + 1);
  122. if(type === "t") { return "\t"; }
  123. if(type === "r") { return "\r"; }
  124. if(type === "n") { return "\n"; }
  125. if(type === "f") { return "\f"; }
  126. if(type !== "u") { return type; }
  127. return String.fromCharCode(parseInt(text.substr(child.start + 2, 4), 16));
  128. },
  129. "line-break": function (child, text) {
  130. return "";
  131. }
  132. };
  133. function rangeToBuffer(range, text) {
  134. var start = range.start, buffer = [];
  135. for(var i = 0; i < range.children.length; i++) {
  136. var child = range.children[i];
  137. buffer.push(text.substring(start, child.start));
  138. buffer.push(renderChild[child.type](child, text));
  139. start = child.end;
  140. }
  141. buffer.push(text.substring(start, range.end));
  142. return buffer;
  143. }
  144. function rangesToObject(ranges, text) {
  145. var obj = Object.create(null); // Creates to a true hash map
  146. for(var i = 0; i < ranges.length; i++) {
  147. var range = ranges[i];
  148. if(range.type !== "key-value") { continue; }
  149. var key = rangeToBuffer(range.children[0], text).join("");
  150. var val = rangeToBuffer(range.children[2], text).join("");
  151. obj[key] = val;
  152. }
  153. return obj;
  154. }
  155. function stringToRanges(text) {
  156. var iter = new Iterator(text), ranges = [];
  157. var curChar;
  158. while((curChar = iter.peek()) !== null) {
  159. if(isWhitespace(curChar)) { ranges.push(consumeWhiteSpace(iter)); continue; }
  160. if(startsComment(curChar)) { ranges.push(consumeComment(iter)); continue; }
  161. if(startsKeyVal(curChar)) { ranges.push(consumeKeyVal(iter)); continue; }
  162. throw Error("Something crazy happened. text: '" + text + "'; curChar: '" + curChar + "'");
  163. }
  164. return ranges;
  165. }
  166. function isNewLineRange(range) {
  167. if(!range) { return false; }
  168. if(range.type === "whitespace") { return true; }
  169. if(range.type === "literal") {
  170. return isWhitespace(range.text) && range.text.indexOf("\n") > -1;
  171. }
  172. return false;
  173. }
  174. function escapeMaker(escapes) {
  175. return function escapeKey(key) {
  176. var zeros = [ "", "0", "00", "000" ];
  177. var buf = [];
  178. for(var i = 0; i < key.length; i++) {
  179. var chr = key.charAt(i);
  180. if(escapes[chr]) { buf.push(escapes[chr]); continue; }
  181. var code = chr.codePointAt(0);
  182. if(code <= 0x7F) { buf.push(chr); continue; }
  183. var hex = code.toString(16);
  184. buf.push("\\u");
  185. buf.push(zeros[4 - hex.length]);
  186. buf.push(hex);
  187. }
  188. return buf.join("");
  189. };
  190. }
  191. var escapeKey = escapeMaker({ " ": "\\ ", "\n": "\\n", ":": "\\:", "=": "\\=" });
  192. var escapeVal = escapeMaker({ "\n": "\\n" });
  193. function Editor(text, options) {
  194. if (typeof text === 'object') {
  195. options = text;
  196. text = null;
  197. }
  198. text = text || "";
  199. var path = options.path;
  200. var separator = options.separator || '=';
  201. var ranges = stringToRanges(text);
  202. var obj = rangesToObject(ranges, text);
  203. var keyRange = Object.create(null); // Creates to a true hash map
  204. for(var i = 0; i < ranges.length; i++) {
  205. var range = ranges[i];
  206. if(range.type !== "key-value") { continue; }
  207. var key = rangeToBuffer(range.children[0], text).join("");
  208. keyRange[key] = range;
  209. }
  210. this.addHeadComment = function(comment) {
  211. if(comment == null) { return; }
  212. ranges.unshift({ type: "literal", text: "# " + comment.replace(/\n/g, "\n# ") + "\n" });
  213. };
  214. this.get = function(key) { return obj[key]; };
  215. this.set = function(key, val, comment) {
  216. if(val == null) { this.unset(key); return; }
  217. obj[key] = val;
  218. var escapedKey = escapeKey(key);
  219. var escapedVal = escapeVal(val);
  220. var range = keyRange[key];
  221. if(!range) {
  222. keyRange[key] = range = {
  223. type: "literal",
  224. text: escapedKey + separator + escapedVal
  225. };
  226. var prevRange = ranges[ranges.length - 1];
  227. if(prevRange != null && !isNewLineRange(prevRange)) {
  228. ranges.push({ type: "literal", text: "\n" });
  229. }
  230. ranges.push(range);
  231. }
  232. // comment === null deletes comment. if comment === undefined, it's left alone
  233. if(comment !== undefined) {
  234. range.comment = comment && "# " + comment.replace(/\n/g, "\n# ") + "\n";
  235. }
  236. if(range.type === "literal") {
  237. range.text = escapedKey + separator + escapedVal;
  238. if(range.comment != null) { range.text = range.comment + range.text; }
  239. } else if(range.type === "key-value") {
  240. range.children[2] = { type: "literal", text: escapedVal };
  241. } else {
  242. throw "Unknown node type: " + range.type;
  243. }
  244. };
  245. this.unset = function(key) {
  246. if(!(key in obj)) { return; }
  247. var range = keyRange[key];
  248. var idx = ranges.indexOf(range);
  249. ranges.splice(idx, (isNewLineRange(ranges[idx + 1]) ? 2 : 1));
  250. delete keyRange[key];
  251. delete obj[key];
  252. };
  253. this.valueOf = this.toString = function() {
  254. var buffer = [], stack = [].concat(ranges);
  255. var node;
  256. while((node = stack.shift()) != null) {
  257. switch(node.type) {
  258. case "literal":
  259. buffer.push(node.text);
  260. break;
  261. case "key":
  262. case "value":
  263. case "comment":
  264. case "whitespace":
  265. case "key-value-separator":
  266. case "escaped-value":
  267. case "line-break":
  268. buffer.push(text.substring(node.start, node.end));
  269. break;
  270. case "key-value":
  271. Array.prototype.unshift.apply(stack, node.children);
  272. if(node.comment) { stack.unshift({ type: "literal", text: node.comment }); }
  273. break;
  274. }
  275. }
  276. return buffer.join("");
  277. };
  278. this.save = function(newPath, callback) {
  279. if(typeof newPath === 'function') {
  280. callback = newPath;
  281. newPath = path;
  282. }
  283. newPath = newPath || path;
  284. if(!newPath) {
  285. if (callback) {
  286. return callback("Unknown path");
  287. }
  288. throw new Error("Unknown path");
  289. }
  290. if (callback) {
  291. fs.writeFile(newPath, this.toString(), callback);
  292. } else {
  293. fs.writeFileSync(newPath, this.toString());
  294. }
  295. };
  296. }
  297. function createEditor(/*path, options, callback*/) {
  298. var path, options, callback;
  299. var args = Array.prototype.slice.call(arguments);
  300. for (var i = 0; i < args.length; i ++) {
  301. var arg = args[i];
  302. if (!path && typeof arg === 'string') {
  303. path = arg;
  304. } else if (!options && typeof arg === 'object') {
  305. options = arg;
  306. } else if (!callback && typeof arg === 'function') {
  307. callback = arg;
  308. }
  309. }
  310. options = options || {};
  311. path = path || options.path;
  312. callback = callback || options.callback;
  313. options.path = path;
  314. if(!path) { return new Editor(options); }
  315. if(!callback) { return new Editor(fs.readFileSync(path).toString(), options); }
  316. return fs.readFile(path, function(err, text) {
  317. if(err) { return callback(err, null); }
  318. text = text.toString();
  319. return callback(null, new Editor(text, options));
  320. });
  321. }
  322. function parse(text) {
  323. text = text.toString();
  324. var ranges = stringToRanges(text);
  325. return rangesToObject(ranges, text);
  326. }
  327. function read(path, callback) {
  328. if(!callback) { return parse(fs.readFileSync(path)); }
  329. return fs.readFile(path, function(err, data) {
  330. if(err) { return callback(err, null); }
  331. return callback(null, parse(data));
  332. });
  333. }
  334. module.exports = { parse: parse, read: read, createEditor: createEditor };