11from __future__ import annotations
22
33import os
4+ from enum import Enum
5+ from functools import lru_cache
46from pathlib import Path
57from tempfile import NamedTemporaryFile
68
79from commitizen import cmd , out
810from commitizen .exceptions import GitCommandError
911
10- _UNIX_EOL = "\n "
11- _WINDOWS_EOL = "\r \n "
12+
13+ class EOLType (Enum ):
14+ """The EOL type from `git config core.eol`."""
15+
16+ LF = "lf"
17+ CRLF = "crlf"
18+ NATIVE = "native"
19+
20+ @classmethod
21+ def for_open (cls ) -> str :
22+ c = cmd .run ("git config core.eol" )
23+ eol = c .out .strip ().upper ()
24+ return cls ._char_for_open ()[cls ._safe_cast (eol )]
25+
26+ @classmethod
27+ def _safe_cast (cls , eol : str ) -> EOLType :
28+ try :
29+ return cls [eol ]
30+ except KeyError :
31+ return cls .NATIVE
32+
33+ @classmethod
34+ @lru_cache
35+ def _char_for_open (cls ) -> dict [EOLType , str ]:
36+ """Get the EOL character for `open()`."""
37+ return {
38+ cls .LF : "\n " ,
39+ cls .CRLF : "\r \n " ,
40+ cls .NATIVE : os .linesep ,
41+ }
1242
1343
1444class GitObject :
@@ -268,18 +298,6 @@ def is_git_project() -> bool:
268298 return c .out .strip () == "true"
269299
270300
271- def get_eol_for_open () -> str :
272- # See: https://git-scm.com/docs/git-config#Documentation/git-config.txt-coreeol
273- c = cmd .run ("git config core.eol" )
274- eol = c .out .strip ().lower ()
275-
276- if eol == "lf" :
277- return _UNIX_EOL
278- if eol == "crlf" :
279- return _WINDOWS_EOL
280- return os .linesep
281-
282-
283301def get_core_editor () -> str | None :
284302 c = cmd .run ("git var GIT_EDITOR" )
285303 if c .out :
@@ -289,7 +307,7 @@ def get_core_editor() -> str | None:
289307
290308def smart_open (* args , ** kwargs ):
291309 """Open a file with the EOL style determined from Git."""
292- return open (* args , newline = get_eol_for_open (), ** kwargs )
310+ return open (* args , newline = EOLType . for_open (), ** kwargs )
293311
294312
295313def _get_log_as_str_list (start : str | None , end : str , args : str ) -> list [str ]:
0 commit comments