diff --git a/lib/ini.js b/lib/ini.js index beb390d..8f07586 100644 --- a/lib/ini.js +++ b/lib/ini.js @@ -20,6 +20,10 @@ const encode = (obj, opt = {}) => { const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj) + const encodeKey = k => opt.bracketedArray && k.length > 2 && k.endsWith('[]') + ? JSON.stringify(k).slice(0, -2) + '\\u005d"' + : safe(k) + let padToChars = 0 // If aligning on the separator, then padToChars is determined as follows: // 1. Get the keys @@ -29,15 +33,14 @@ const encode = (obj, opt = {}) => { // 5. Reduce the set to the longest `safe` key // 6. Get the `safe` length if (opt.align) { - padToChars = safe( - ( - keys - .filter(k => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== 'object') - .map(k => Array.isArray(obj[k]) ? `${k}[]` : k) - ) - .concat(['']) - .reduce((a, b) => safe(a).length >= safe(b).length ? a : b) - ).length + padToChars = ( + keys + .filter(k => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== 'object') + .map(k => Array.isArray(obj[k]) ? safe(`${k}[]`) : encodeKey(k)) + ) + .concat(['']) + .reduce((a, b) => a.length >= b.length ? a : b) + .length } let out = '' @@ -52,7 +55,7 @@ const encode = (obj, opt = {}) => { } else if (val && typeof val === 'object') { children.push(k) } else { - out += safe(k).padEnd(padToChars, ' ') + separator + safe(val) + eol + out += encodeKey(k).padEnd(padToChars, ' ') + separator + safe(val) + eol } } @@ -135,7 +138,9 @@ const decode = (str, opt = {}) => { const keyRaw = unsafe(match[2]) let isArray if (opt.bracketedArray) { - isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]' + const rawKey = match[2].trim() + isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]' && + (!isQuoted(rawKey) || rawKey.slice(-3, -1) === '[]') } else { duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1 isArray = duplicates[keyRaw] > 1 diff --git a/test/bar.js b/test/bar.js index 8f7eb23..de4fd51 100644 --- a/test/bar.js +++ b/test/bar.js @@ -8,6 +8,9 @@ var data = { string: { drink: 'white russian' }, boolean: { isTrue: true }, 'nested boolean': { theDude: { abides: true, rugCount: 1 } }, + 'key ending in []': { 'foo[]': 'bar' }, + 'quoted key ending in []': { '[foo[]': 'bar' }, + 'array with a quoted key': { '[foo': ['first', 'second'] }, } test('parse(stringify(x)) is same as x', function (t) { @@ -19,3 +22,15 @@ test('parse(stringify(x)) is same as x', function (t) { t.end() }) + +test('array marker is read without a trailing comment', function (t) { + t.same(ini.parse('flag[] # note'), { flag: [true] }) + t.same(ini.parse('flag # note[]'), { flag: true }) + t.end() +}) + +test('align pads to a quoted key ending in []', function (t) { + var lines = ini.stringify({ 'foo[]': 'bar', x: 'y' }, { align: true }).split('\n') + t.equal(lines[0].indexOf('='), lines[1].indexOf('=')) + t.end() +})