Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow empty sections #3

Merged
merged 2 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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` option
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
Loading