Skip to content

Commit

Permalink
Add missing trailing newline when adding new value
Browse files Browse the repository at this point in the history
Sometimes, the source file doesn't have a trailing newline.  If we add a
new binding in such a case, we need to add a newline before the new
binding.
  • Loading branch information
bbc2 committed Nov 11, 2021
1 parent fc138ce commit 45848bb
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

### Fixed

- In `set_key`, add missing newline character before new entry if necessary. (#361 by
[@bbc2])

## [0.19.1] - 2021-08-09

### Added
Expand Down
4 changes: 4 additions & 0 deletions src/dotenv/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,13 +167,17 @@ def set_key(

with rewrite(dotenv_path) as (source, dest):
replaced = False
missing_newline = False
for mapping in with_warn_for_invalid_lines(parse_stream(source)):
if mapping.key == key_to_set:
dest.write(line_out)
replaced = True
else:
dest.write(mapping.original.string)
missing_newline = not mapping.original.string.endswith("\n")
if not replaced:
if missing_newline:
dest.write("\n")
dest.write(line_out)

return True, key_to_set, value_to_set
Expand Down
1 change: 1 addition & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def test_set_key_no_file(tmp_path):
("a=b\nc=d", "a", "e", (True, "a", "e"), "a='e'\nc=d"),
("a=b\nc=d\ne=f", "c", "g", (True, "c", "g"), "a=b\nc='g'\ne=f"),
("a=b\n", "c", "d", (True, "c", "d"), "a=b\nc='d'\n"),
("a=b", "c", "d", (True, "c", "d"), "a=b\nc='d'\n"),
],
)
def test_set_key(dotenv_file, before, key, value, expected, after):
Expand Down

0 comments on commit 45848bb

Please sign in to comment.