diff --git a/lib/ini.js b/lib/ini.js index beb390d..7a53420 100644 --- a/lib/ini.js +++ b/lib/ini.js @@ -17,6 +17,7 @@ const encode = (obj, opt = {}) => { const eol = opt.platform === 'win32' ? '\r\n' : '\n' const separator = opt.whitespace ? ' = ' : '=' const children = [] + const hasSection = opt.section || opt.section === '' const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj) @@ -56,13 +57,13 @@ const encode = (obj, opt = {}) => { } } - if (opt.section && out.length) { + if (hasSection && out.length) { out = '[' + safe(opt.section) + ']' + (opt.newline ? eol + eol : eol) + out } for (const k of children) { const nk = splitSections(k, '.').join('\\.') - const section = (opt.section ? opt.section + '.' : '') + nk + const section = (hasSection ? opt.section + '.' : '') + nk const child = encode(obj[k], { ...opt, section, diff --git a/test/empty-section.js b/test/empty-section.js new file mode 100644 index 0000000..90f2af2 --- /dev/null +++ b/test/empty-section.js @@ -0,0 +1,24 @@ +const ini = require('../') +const t = require('tap') + +t.test('empty section names round trip', t => { + for (const text of [ + '[]\na=1\n', + 'top=value\n[]\na=1\n', + '[]\na[]=1\na[]=2\n[.child]\nb=3\n', + '[parent.]\na=1\n[parent..child]\nb=2\n', + ]) { + const parsed = ini.parse(text) + t.same(ini.parse(ini.stringify(parsed)), parsed, text) + } + t.end() +}) + +t.test('explicit empty section option writes its header', t => { + const eol = require('os').EOL + t.equal(ini.stringify({ a: '1' }, { section: '', platform: 'linux' }), '[]\na=1\n') + t.equal(ini.stringify({ a: '1' }, ''), `[]${eol}a=1${eol}`) + t.equal(ini.stringify({ a: '1' }, { platform: 'linux' }), 'a=1\n') + t.equal(ini.stringify({}, { section: '' }), '') + t.end() +})