Skip to content

Commit 45848bb

Browse files
committed
Add missing trailing newline when adding new value
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.
1 parent fc138ce commit 45848bb

File tree

3 files changed

+12
-0
lines changed

3 files changed

+12
-0
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this
66
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## Unreleased
9+
10+
### Fixed
11+
12+
- In `set_key`, add missing newline character before new entry if necessary. (#361 by
13+
[@bbc2])
14+
815
## [0.19.1] - 2021-08-09
916

1017
### Added

src/dotenv/main.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,13 +167,17 @@ def set_key(
167167

168168
with rewrite(dotenv_path) as (source, dest):
169169
replaced = False
170+
missing_newline = False
170171
for mapping in with_warn_for_invalid_lines(parse_stream(source)):
171172
if mapping.key == key_to_set:
172173
dest.write(line_out)
173174
replaced = True
174175
else:
175176
dest.write(mapping.original.string)
177+
missing_newline = not mapping.original.string.endswith("\n")
176178
if not replaced:
179+
if missing_newline:
180+
dest.write("\n")
177181
dest.write(line_out)
178182

179183
return True, key_to_set, value_to_set

tests/test_main.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ def test_set_key_no_file(tmp_path):
3737
("a=b\nc=d", "a", "e", (True, "a", "e"), "a='e'\nc=d"),
3838
("a=b\nc=d\ne=f", "c", "g", (True, "c", "g"), "a=b\nc='g'\ne=f"),
3939
("a=b\n", "c", "d", (True, "c", "d"), "a=b\nc='d'\n"),
40+
("a=b", "c", "d", (True, "c", "d"), "a=b\nc='d'\n"),
4041
],
4142
)
4243
def test_set_key(dotenv_file, before, key, value, expected, after):

0 commit comments

Comments
 (0)