@@ -79,6 +79,8 @@ def is_pre_commit_installed(self) -> bool:
7979
8080
8181class Init :
82+ _PRE_COMMIT_CONFIG_PATH = ".pre-commit-config.yaml"
83+
8284 def __init__ (self , config : BaseConfig , * args : object ) -> None :
8385 self .config : BaseConfig = config
8486 self .encoding = config .settings ["encoding" ]
@@ -323,9 +325,8 @@ def _gen_pre_commit_cmd(self, hook_types: list[str]) -> str:
323325 )
324326 return cmd_str
325327
326- def _install_pre_commit_hook (self , hook_types : list [str ] | None = None ) -> None :
327- pre_commit_config_filename = ".pre-commit-config.yaml"
328- cz_hook_config = {
328+ def _get_config_data (self ) -> dict [str , Any ]:
329+ CZ_HOOK_CONFIG = {
329330 "repo" : "https://github.com/commitizen-tools/commitizen" ,
330331 "rev" : f"v{ __version__ } " ,
331332 "hooks" : [
@@ -334,31 +335,29 @@ def _install_pre_commit_hook(self, hook_types: list[str] | None = None) -> None:
334335 ],
335336 }
336337
337- config_data = {}
338338 if not self .project_info .has_pre_commit_config :
339339 # .pre-commit-config.yaml does not exist
340- config_data ["repos" ] = [cz_hook_config ]
340+ return {"repos" : [CZ_HOOK_CONFIG ]}
341+
342+ with open (self ._PRE_COMMIT_CONFIG_PATH , encoding = self .encoding ) as config_file :
343+ config_data : dict [str , Any ] = yaml .safe_load (config_file ) or {}
344+
345+ if not isinstance (repos := config_data .get ("repos" ), list ):
346+ # .pre-commit-config.yaml exists but there's no "repos" key
347+ config_data ["repos" ] = [CZ_HOOK_CONFIG ]
348+ return config_data
349+
350+ # Check if commitizen pre-commit hook is already in the config
351+ if any ("commitizen" in hook_config ["repo" ] for hook_config in repos ):
352+ out .write ("commitizen already in pre-commit config" )
341353 else :
342- with open (
343- pre_commit_config_filename , encoding = self .encoding
344- ) as config_file :
345- yaml_data = yaml .safe_load (config_file )
346- if yaml_data :
347- config_data = yaml_data
348-
349- if "repos" in config_data :
350- for pre_commit_hook in config_data ["repos" ]:
351- if "commitizen" in pre_commit_hook ["repo" ]:
352- out .write ("commitizen already in pre-commit config" )
353- break
354- else :
355- config_data ["repos" ].append (cz_hook_config )
356- else :
357- # .pre-commit-config.yaml exists but there's no "repos" key
358- config_data ["repos" ] = [cz_hook_config ]
354+ repos .append (CZ_HOOK_CONFIG )
355+ return config_data
359356
357+ def _install_pre_commit_hook (self , hook_types : list [str ] | None = None ) -> None :
358+ config_data = self ._get_config_data ()
360359 with smart_open (
361- pre_commit_config_filename , "w" , encoding = self .encoding
360+ self . _PRE_COMMIT_CONFIG_PATH , "w" , encoding = self .encoding
362361 ) as config_file :
363362 yaml .safe_dump (config_data , stream = config_file )
364363
0 commit comments