From b135f761cfae9b4213f8bab601c2c3252dab91b0 Mon Sep 17 00:00:00 2001 From: pan93412 Date: Wed, 10 Aug 2022 12:22:56 +0800 Subject: [PATCH] feat: Determine newline to write with Git Determine the newline character to write with `git config core.eof`. Close #492 --- commitizen/bump.py | 4 +-- commitizen/commands/changelog.py | 7 +++-- commitizen/commands/commit.py | 3 +- commitizen/commands/init.py | 4 +-- commitizen/config/json_config.py | 6 ++-- commitizen/config/yaml_config.py | 6 ++-- commitizen/git.py | 51 ++++++++++++++++++++++++++++++++ tests/test_git.py | 21 +++++++++++++ 8 files changed, 91 insertions(+), 11 deletions(-) diff --git a/commitizen/bump.py b/commitizen/bump.py index 2b5d77a9f2..701b7d662e 100644 --- a/commitizen/bump.py +++ b/commitizen/bump.py @@ -8,7 +8,7 @@ from commitizen.defaults import MAJOR, MINOR, PATCH, bump_message from commitizen.exceptions import CurrentVersionNotFoundError -from commitizen.git import GitCommit +from commitizen.git import GitCommit, smart_open def find_increment( @@ -164,7 +164,7 @@ def update_version_in_files( ) # Write the file out again - with open(filepath, "w") as file: + with smart_open(filepath, "w") as file: file.write("".join(version_file)) diff --git a/commitizen/commands/changelog.py b/commitizen/commands/changelog.py index 58c0ceaeef..3790dd0c8b 100644 --- a/commitizen/commands/changelog.py +++ b/commitizen/commands/changelog.py @@ -13,7 +13,7 @@ NotAGitProjectError, NotAllowed, ) -from commitizen.git import GitTag +from commitizen.git import GitTag, smart_open def similar(a, b): @@ -89,7 +89,7 @@ def write_changelog( ) changelog_hook: Optional[Callable] = self.cz.changelog_hook - with open(self.file_name, "w") as changelog_file: + with smart_open(self.file_name, "w") as changelog_file: partial_changelog: Optional[str] = None if self.incremental: new_lines = changelog.incremental_build( @@ -121,6 +121,9 @@ def __call__(self): if self.incremental and self.rev_range: raise NotAllowed("--incremental cannot be combined with a rev_range") + # Don't continue if no `file_name` specified. + assert self.file_name + tags = git.get_tags() if not tags: tags = [] diff --git a/commitizen/commands/commit.py b/commitizen/commands/commit.py index a4c0301732..13e61abe6d 100644 --- a/commitizen/commands/commit.py +++ b/commitizen/commands/commit.py @@ -16,6 +16,7 @@ NotAGitProjectError, NothingToCommitError, ) +from commitizen.git import smart_open class Commit: @@ -89,7 +90,7 @@ def __call__(self): out.error(c.err) # Create commit backup - with open(self.temp_file, "w") as f: + with smart_open(self.temp_file, "w") as f: f.write(m) raise CommitError() diff --git a/commitizen/commands/init.py b/commitizen/commands/init.py index 73d76e9022..3b10a58230 100644 --- a/commitizen/commands/init.py +++ b/commitizen/commands/init.py @@ -10,7 +10,7 @@ from commitizen.cz import registry from commitizen.defaults import config_files from commitizen.exceptions import NoAnswersError -from commitizen.git import get_latest_tag_name, get_tag_names +from commitizen.git import get_latest_tag_name, get_tag_names, smart_open class Init: @@ -138,7 +138,7 @@ def _install_pre_commit_hook(self): # .pre-commit-config exists but there's no "repos" key config_data["repos"] = [cz_hook_config] - with open(pre_commit_config_filename, "w") as config_file: + with smart_open(pre_commit_config_filename, "w") as config_file: yaml.safe_dump(config_data, stream=config_file) c = cmd.run("pre-commit install --hook-type commit-msg") diff --git a/commitizen/config/json_config.py b/commitizen/config/json_config.py index a40a8ceb20..34a81a9ef7 100644 --- a/commitizen/config/json_config.py +++ b/commitizen/config/json_config.py @@ -2,6 +2,8 @@ from pathlib import Path from typing import Union +from commitizen.git import smart_open + from .base_config import BaseConfig @@ -13,7 +15,7 @@ def __init__(self, *, data: Union[bytes, str], path: Union[Path, str]): self.add_path(path) def init_empty_config_content(self): - with open(self.path, "a") as json_file: + with smart_open(self.path, "a") as json_file: json.dump({"commitizen": {}}, json_file) def set_key(self, key, value): @@ -26,7 +28,7 @@ def set_key(self, key, value): parser = json.load(f) parser["commitizen"][key] = value - with open(self.path, "w") as f: + with smart_open(self.path, "w") as f: json.dump(parser, f, indent=2) return self diff --git a/commitizen/config/yaml_config.py b/commitizen/config/yaml_config.py index 1d44e64f3b..503b32ce06 100644 --- a/commitizen/config/yaml_config.py +++ b/commitizen/config/yaml_config.py @@ -3,6 +3,8 @@ import yaml +from commitizen.git import smart_open + from .base_config import BaseConfig @@ -14,7 +16,7 @@ def __init__(self, *, data: Union[bytes, str], path: Union[Path, str]): self.add_path(path) def init_empty_config_content(self): - with open(self.path, "a") as json_file: + with smart_open(self.path, "a") as json_file: yaml.dump({"commitizen": {}}, json_file) def _parse_setting(self, data: Union[bytes, str]) -> None: @@ -41,7 +43,7 @@ def set_key(self, key, value): parser = yaml.load(yaml_file, Loader=yaml.FullLoader) parser["commitizen"][key] = value - with open(self.path, "w") as yaml_file: + with smart_open(self.path, "w") as yaml_file: yaml.dump(parser, yaml_file) return self diff --git a/commitizen/git.py b/commitizen/git.py index 3767147877..935686c317 100644 --- a/commitizen/git.py +++ b/commitizen/git.py @@ -1,10 +1,33 @@ import os +from enum import Enum +from os import linesep from pathlib import Path from tempfile import NamedTemporaryFile from typing import List, Optional from commitizen import cmd +UNIX_EOL = "\n" +WINDOWS_EOL = "\r\n" + + +class EOLTypes(Enum): + """The EOL type from `git config core.eol`.""" + + LF = "lf" + CRLF = "crlf" + NATIVE = "native" + + def get_eol_for_open(self) -> str: + """Get the EOL character for `open()`.""" + map = { + EOLTypes.CRLF: WINDOWS_EOL, + EOLTypes.LF: UNIX_EOL, + EOLTypes.NATIVE: linesep, + } + + return map[self] + class GitObject: rev: str @@ -177,3 +200,31 @@ def is_git_project() -> bool: if c.out.strip() == "true": return True return False + + +def get_eol_style() -> EOLTypes: + c = cmd.run("git config core.eol") + eol = c.out.strip().lower() + + # We enumerate the EOL types of the response of + # `git config core.eol`, and map it to our enumration EOLTypes. + # + # It is just like the varient of the "match" syntax. + map = { + "lf": EOLTypes.LF, + "crlf": EOLTypes.CRLF, + "native": EOLTypes.NATIVE, + } + + # If the response of `git config core.eol` is in the map: + if eol in map: + return map[eol] + else: + # The default value is "native". + # https://git-scm.com/docs/git-config#Documentation/git-config.txt-coreeol + return map["native"] + + +def smart_open(*args, **kargs): + """Open a file with the EOL style determined from Git.""" + return open(*args, newline=get_eol_style().get_eol_for_open(), **kargs) diff --git a/tests/test_git.py b/tests/test_git.py index c764a6d65a..42fd2e08be 100644 --- a/tests/test_git.py +++ b/tests/test_git.py @@ -1,4 +1,5 @@ import inspect +import os import shutil from typing import List, Optional @@ -203,3 +204,23 @@ def test_is_staging_clean_when_updating_file(tmp_commitizen_project): cmd.run("git add test_file") assert git.is_staging_clean() is False + + +def test_git_eol_style(tmp_commitizen_project): + with tmp_commitizen_project.as_cwd(): + assert git.get_eol_style() == git.EOLTypes.NATIVE + + cmd.run("git config core.eol lf") + assert git.get_eol_style() == git.EOLTypes.LF + + cmd.run("git config core.eol crlf") + assert git.get_eol_style() == git.EOLTypes.CRLF + + cmd.run("git config core.eol native") + assert git.get_eol_style() == git.EOLTypes.NATIVE + + +def test_eoltypes_get_eol_for_open(): + assert git.EOLTypes.get_eol_for_open(git.EOLTypes.NATIVE) == os.linesep + assert git.EOLTypes.get_eol_for_open(git.EOLTypes.LF) == "\n" + assert git.EOLTypes.get_eol_for_open(git.EOLTypes.CRLF) == "\r\n"