Skip to content

Commit

Permalink
feat: allow empty sections
Browse files Browse the repository at this point in the history
  • Loading branch information
mja00 committed Jul 25, 2024
1 parent 67a74a3 commit b0895f9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ Sometimes you need to write strings into an `ini` file with quotes around them,
By passing an array of `forceStringifyKeys`, you can specify which keys are forced stringified with `JSON.stringify` and therefore maintain their quotes.
Note: This is pretty limited currently in that it doesn't account for the same key being in different sections, but covers our current use-case.

## New `allowEmptySection` optoin
If you want to allow empty sections, you can set this option to `true`.
```ini
[section]
```
Previously, this would omit the section entirely on encode. Now, it will be included in the output.

## Usage

Consider an ini-file `config.ini` that looks like this:
Expand Down Expand Up @@ -121,6 +128,7 @@ 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.
* `allowEmptySection` Whether to allow empty sections. Defaults to `false`.

For backwards compatibility reasons, if a `string` options is passed
in, then it is assumed to be the `section` value.
Expand Down
4 changes: 3 additions & 1 deletion ini.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const encode = (obj, options) => {
section: options,
whitespace: false,
inlineArrays: false,
allowEmptySection: false,
};
}else{
options = options || Object.create(null);
Expand Down Expand Up @@ -43,7 +44,7 @@ const encode = (obj, options) => {
}
}

if(options.section && out.length > 0){
if((options.section && out.length > 0) || (children.length === 0 && options.allowEmptySection)){
out = '[' + safe(options.section, null, options) + ']' + eol + out;
}

Expand All @@ -55,6 +56,7 @@ const encode = (obj, options) => {
whitespace: options.whitespace,
inlineArrays: options.inlineArrays,
forceStringifyKeys: options.forceStringifyKeys,
allowEmptySection: options.allowEmptySection,
});
if(out.length > 0 && child.length > 0){
out += eol;
Expand Down

0 comments on commit b0895f9

Please sign in to comment.