diff --git a/bumpversion/cli.py b/bumpversion/cli.py index 7c17b9a..b684362 100644 --- a/bumpversion/cli.py +++ b/bumpversion/cli.py @@ -197,7 +197,9 @@ def main(original_args=None): logger.info("Reading config file {}:".format(config_file)) # TODO: this is a DEBUG level log - logger.info(io.open(config_file, "rt", encoding="utf-8").read()) + with io.open(config_file, "rt", encoding="utf-8") as f: + logger.info(f.read()) + config_new_lines = f.newlines try: # TODO: we're reading the config file twice. @@ -580,7 +582,7 @@ def main(original_args=None): logger.info(new_config.getvalue()) if write_to_config_file: - with io.open(config_file, "wt", encoding="utf-8") as f: + with io.open(config_file, "wt", encoding="utf-8", newline=config_new_lines) as f: f.write(new_config.getvalue()) except UnicodeEncodeError: diff --git a/bumpversion/utils.py b/bumpversion/utils.py index 5b3be13..29f2b1b 100644 --- a/bumpversion/utils.py +++ b/bumpversion/utils.py @@ -91,6 +91,7 @@ def replace(self, current_version, new_version, context, dry_run): with io.open(self.path, "rt", encoding="utf-8") as f: file_content_before = f.read() + file_new_lines = f.newlines context["current_version"] = self._versionconfig.serialize( current_version, context @@ -135,7 +136,7 @@ def replace(self, current_version, new_version, context, dry_run): ) if not dry_run: - with io.open(self.path, "wt", encoding="utf-8") as f: + with io.open(self.path, "wt", encoding="utf-8", newline=file_new_lines) as f: f.write(file_content_after) def __str__(self): diff --git a/tests/test_cli.py b/tests/test_cli.py index f19e0ee..f615c6a 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1916,6 +1916,28 @@ def test_correct_interpolation_for_setup_cfg_files(tmpdir, configfile): assert "current_version = 1.0.0" in tmpdir.join(configfile).read() +@pytest.mark.parametrize("newline", [b'\n', b'\r\n']) +def test_retain_newline(tmpdir, configfile, newline): + tmpdir.join("file.py").write_binary(dedent(""" + 0.7.2 + Some Content + """).strip().encode(encoding='UTF-8').replace(b'\n', newline)) + tmpdir.chdir() + + tmpdir.join(configfile).write_binary(dedent(""" + [bumpversion] + current_version = 0.7.2 + search = {current_version} + replace = {new_version} + [bumpversion:file:file.py] + """).strip().encode(encoding='UTF-8').replace(b'\n', newline)) + + main(["major"]) + + assert newline in tmpdir.join("file.py").read_binary() + assert newline in tmpdir.join(configfile).read_binary() + + class TestSplitArgsInOptionalAndPositional: def test_all_optional(self):