1
1
from __future__ import annotations
2
2
3
3
import os
4
+ from enum import Enum
5
+ from functools import lru_cache
4
6
from pathlib import Path
5
7
from tempfile import NamedTemporaryFile
6
8
7
9
from commitizen import cmd , out
8
10
from commitizen .exceptions import GitCommandError
9
11
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
+ }
12
42
13
43
14
44
class GitObject :
@@ -268,18 +298,6 @@ def is_git_project() -> bool:
268
298
return c .out .strip () == "true"
269
299
270
300
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
-
283
301
def get_core_editor () -> str | None :
284
302
c = cmd .run ("git var GIT_EDITOR" )
285
303
if c .out :
@@ -289,7 +307,7 @@ def get_core_editor() -> str | None:
289
307
290
308
def smart_open (* args , ** kwargs ):
291
309
"""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 )
293
311
294
312
295
313
def _get_log_as_str_list (start : str | None , end : str , args : str ) -> list [str ]:
0 commit comments