@@ -79,6 +79,8 @@ def is_pre_commit_installed(self) -> bool:
79
79
80
80
81
81
class Init :
82
+ _PRE_COMMIT_CONFIG_PATH = ".pre-commit-config.yaml"
83
+
82
84
def __init__ (self , config : BaseConfig , * args : object ) -> None :
83
85
self .config : BaseConfig = config
84
86
self .encoding = config .settings ["encoding" ]
@@ -320,9 +322,8 @@ def _gen_pre_commit_cmd(self, hook_types: list[str]) -> str:
320
322
f"--hook-type { ty } " for ty in hook_types
321
323
)
322
324
323
- def _install_pre_commit_hook (self , hook_types : list [str ] | None = None ) -> None :
324
- pre_commit_config_filename = ".pre-commit-config.yaml"
325
- cz_hook_config = {
325
+ def _get_config_data (self ) -> dict [str , Any ]:
326
+ CZ_HOOK_CONFIG = {
326
327
"repo" : "https://github.com/commitizen-tools/commitizen" ,
327
328
"rev" : f"v{ __version__ } " ,
328
329
"hooks" : [
@@ -331,31 +332,29 @@ def _install_pre_commit_hook(self, hook_types: list[str] | None = None) -> None:
331
332
],
332
333
}
333
334
334
- config_data = {}
335
335
if not self .project_info .has_pre_commit_config :
336
336
# .pre-commit-config.yaml does not exist
337
- config_data ["repos" ] = [cz_hook_config ]
337
+ return {"repos" : [CZ_HOOK_CONFIG ]}
338
+
339
+ with open (self ._PRE_COMMIT_CONFIG_PATH , encoding = self .encoding ) as config_file :
340
+ config_data : dict [str , Any ] = yaml .safe_load (config_file ) or {}
341
+
342
+ if not isinstance (repos := config_data .get ("repos" ), list ):
343
+ # .pre-commit-config.yaml exists but there's no "repos" key
344
+ config_data ["repos" ] = [CZ_HOOK_CONFIG ]
345
+ return config_data
346
+
347
+ # Check if commitizen pre-commit hook is already in the config
348
+ if any ("commitizen" in hook_config ["repo" ] for hook_config in repos ):
349
+ out .write ("commitizen already in pre-commit config" )
338
350
else :
339
- with open (
340
- pre_commit_config_filename , encoding = self .encoding
341
- ) as config_file :
342
- yaml_data = yaml .safe_load (config_file )
343
- if yaml_data :
344
- config_data = yaml_data
345
-
346
- if "repos" in config_data :
347
- for pre_commit_hook in config_data ["repos" ]:
348
- if "commitizen" in pre_commit_hook ["repo" ]:
349
- out .write ("commitizen already in pre-commit config" )
350
- break
351
- else :
352
- config_data ["repos" ].append (cz_hook_config )
353
- else :
354
- # .pre-commit-config.yaml exists but there's no "repos" key
355
- config_data ["repos" ] = [cz_hook_config ]
351
+ repos .append (CZ_HOOK_CONFIG )
352
+ return config_data
356
353
354
+ def _install_pre_commit_hook (self , hook_types : list [str ] | None = None ) -> None :
355
+ config_data = self ._get_config_data ()
357
356
with smart_open (
358
- pre_commit_config_filename , "w" , encoding = self .encoding
357
+ self . _PRE_COMMIT_CONFIG_PATH , "w" , encoding = self .encoding
359
358
) as config_file :
360
359
yaml .safe_dump (config_data , stream = config_file )
361
360
0 commit comments