@@ -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" ]
@@ -323,9 +325,8 @@ def _gen_pre_commit_cmd(self, hook_types: list[str]) -> str:
323
325
)
324
326
return cmd_str
325
327
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 = {
329
330
"repo" : "https://github.com/commitizen-tools/commitizen" ,
330
331
"rev" : f"v{ __version__ } " ,
331
332
"hooks" : [
@@ -334,31 +335,29 @@ def _install_pre_commit_hook(self, hook_types: list[str] | None = None) -> None:
334
335
],
335
336
}
336
337
337
- config_data = {}
338
338
if not self .project_info .has_pre_commit_config :
339
339
# .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" )
341
353
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
359
356
357
+ def _install_pre_commit_hook (self , hook_types : list [str ] | None = None ) -> None :
358
+ config_data = self ._get_config_data ()
360
359
with smart_open (
361
- pre_commit_config_filename , "w" , encoding = self .encoding
360
+ self . _PRE_COMMIT_CONFIG_PATH , "w" , encoding = self .encoding
362
361
) as config_file :
363
362
yaml .safe_dump (config_data , stream = config_file )
364
363
0 commit comments