config-codec.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. // This is for working with git config files like .git/config and .gitmodules.
  3. // I believe this is just INI format.
  4. module.exports = {
  5. encode: encode,
  6. decode: decode
  7. };
  8. function encode(config) {
  9. var lines = [];
  10. Object.keys(config).forEach(function (name) {
  11. var obj = config[name];
  12. var deep = {};
  13. var values = {};
  14. var hasValues = false;
  15. Object.keys(obj).forEach(function (key) {
  16. var value = obj[key];
  17. if (typeof value === 'object') {
  18. deep[key] = value;
  19. }
  20. else {
  21. hasValues = true;
  22. values[key] = value;
  23. }
  24. });
  25. if (hasValues) {
  26. encodeBody('[' + name + ']', values);
  27. }
  28. Object.keys(deep).forEach(function (sub) {
  29. var child = deep[sub];
  30. encodeBody('[' + name + ' "' + sub + '"]', child);
  31. });
  32. });
  33. return lines.join("\n") + "\n";
  34. function encodeBody(header, obj) {
  35. lines.push(header);
  36. Object.keys(obj).forEach(function (name) {
  37. lines.push( "\t" + name + " = " + obj[name]);
  38. });
  39. }
  40. }
  41. function decode(text) {
  42. var config = {};
  43. var section;
  44. text.split(/[\r\n]+/).forEach(function (line) {
  45. var match = line.match(/\[([^ \t"\]]+) *(?:"([^"]+)")?\]/);
  46. if (match) {
  47. section = config[match[1]] || (config[match[1]] = {});
  48. if (match[2]) {
  49. section = section[match[2]] = {};
  50. }
  51. return;
  52. }
  53. match = line.match(/([^ \t=]+)[ \t]*=[ \t]*(.+)/);
  54. if (match) {
  55. section[match[1]] = match[2];
  56. }
  57. });
  58. return config;
  59. }