diff --git a/commitizen/commands/changelog.py b/commitizen/commands/changelog.py index abe03a924..b2ad1ca7b 100644 --- a/commitizen/commands/changelog.py +++ b/commitizen/commands/changelog.py @@ -186,8 +186,8 @@ def _export_template(self, dist: str) -> None: if filename is None: raise NotAllowed("Template filename is not set") - text = Path(filename).read_text() - Path(dist).write_text(text) + text = Path(filename).read_text(encoding="utf-8") + Path(dist).write_text(text, encoding="utf-8") def __call__(self) -> None: commit_parser = self.cz.commit_parser diff --git a/tests/commands/test_changelog_command.py b/tests/commands/test_changelog_command.py index 8922b256f..e8283969c 100644 --- a/tests/commands/test_changelog_command.py +++ b/tests/commands/test_changelog_command.py @@ -1,5 +1,6 @@ from __future__ import annotations +import io import itertools from pathlib import Path from textwrap import dedent @@ -1663,6 +1664,31 @@ def test_export_changelog_template_from_plugin( assert changelog_jinja_file.read_text() == tpl +def test_export_changelog_template_with_non_utf8_locale( + changelog_jinja_file: Path, + mock_plugin: BaseCommitizen, + changelog_format: ChangelogFormat, + tmp_path: Path, + util: UtilFixture, + monkeypatch: pytest.MonkeyPatch, +): + # pathlib falls back to io.text_encoding when no encoding is given. + # Make it return cp949, the locale encoding on Korean Windows. + monkeypatch.setattr( + io, "text_encoding", lambda encoding, stacklevel=2: encoding or "cp949" + ) + src = tmp_path / changelog_format.template + # cp949 cannot decode these UTF-8 bytes, and cannot encode the sparkles + src.write_bytes("## 변경 ✨\n".encode()) + mock_plugin.template_loader = FileSystemLoader(tmp_path) + + util.run_cli("changelog", "--export-template", str(changelog_jinja_file)) + + assert changelog_jinja_file.read_text(encoding="utf-8") == src.read_text( + encoding="utf-8" + ) + + def test_export_changelog_template_fails_when_template_has_no_filename( mocker: MockFixture, changelog_jinja_file: Path,