From b363ae67ddf9b1232daafb3cc2b2b1e5cb656406 Mon Sep 17 00:00:00 2001 From: Gar Date: Tue, 11 Apr 2023 17:12:11 -0700 Subject: [PATCH] feat: add newline option (#198) Co-authored-by: Francois-Xavier Kowalski --- README.md | 4 ++++ lib/ini.js | 6 ++++-- tap-snapshots/test/foo.js.test.cjs | 12 ++++++++++++ test/foo.js | 8 ++++++++ 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3ff41e8..8dea161 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,10 @@ The `options` object may contain the following: `=` character. By default, whitespace is omitted, to be friendly to some persnickety old parsers that don't tolerate it well. But some find that it's more human-readable and pretty with the whitespace. +* `newline` Boolean to specify whether to put an additional newline + after a section header. Some INI file parsers (for example the TOSHIBA + FlashAir one) need this to parse the file successfully. By default, + the additional newline is omitted. For backwards compatibility reasons, if a `string` options is passed in, then it is assumed to be the `section` value. diff --git a/lib/ini.js b/lib/ini.js index f0fafee..65ffea9 100644 --- a/lib/ini.js +++ b/lib/ini.js @@ -16,6 +16,7 @@ const encode = (obj, opt) => { } else { opt = opt || Object.create(null) opt.whitespace = opt.whitespace === true + opt.newline = opt.newline === true } const separator = opt.whitespace ? ' = ' : '=' @@ -34,16 +35,17 @@ const encode = (obj, opt) => { } if (opt.section && out.length) { - out = '[' + safe(opt.section) + ']' + eol + out + out = '[' + safe(opt.section) + ']' + (opt.newline ? eol + eol : eol) + out } for (const k of children) { const nk = dotSplit(k).join('\\.') const section = (opt.section ? opt.section + '.' : '') + nk - const { whitespace } = opt + const { whitespace, newline } = opt const child = encode(obj[k], { section, whitespace, + newline, }) if (out.length && child.length) { out += eol diff --git a/tap-snapshots/test/foo.js.test.cjs b/tap-snapshots/test/foo.js.test.cjs index 20e521b..28feb7a 100644 --- a/tap-snapshots/test/foo.js.test.cjs +++ b/tap-snapshots/test/foo.js.test.cjs @@ -110,6 +110,18 @@ noHashComment=this\\# this is not a comment ` +exports[`test/foo.js TAP encode with newline > must match snapshot 1`] = ` +[log] + +type=file + +[log.level] + +label=debug +value=10 + +` + exports[`test/foo.js TAP encode with option > must match snapshot 1`] = ` [prefix.log] type=file diff --git a/test/foo.js b/test/foo.js index 5165a9a..5e9c8c8 100644 --- a/test/foo.js +++ b/test/foo.js @@ -44,3 +44,11 @@ test('encode with whitespace', function (t) { t.matchSnapshot(e) t.end() }) + +test('encode with newline', function (t) { + const obj = { log: { type: 'file', level: { label: 'debug', value: 10 } } } + const e = i.encode(obj, { newline: true }) + + t.matchSnapshot(e) + t.end() +})