Coverage for .nox/test-3-9/lib/python3.9/site-packages/nskit/mixer/hooks/git.py: 37%
27 statements
« prev ^ index » next coverage.py v7.4.2, created at 2024-02-25 17:38 +0000
« prev ^ index » next coverage.py v7.4.2, created at 2024-02-25 17:38 +0000
1"""Git hooks."""
2from pathlib import Path
3import subprocess # nosec: B404
4from typing import Any, Dict
6from packaging.version import parse
8from nskit._logging import logger_factory
9from nskit.common.contextmanagers import ChDir
10from nskit.mixer.components import Hook
12logger = logger_factory.get(__name__)
15class GitInit(Hook):
16 """Git Hook to (re) initialise a repo."""
18 def call(self, recipe_path: Path, context: Dict[str, Any]):
19 """(re)initialise the repo."""
20 with ChDir(recipe_path):
21 logger.info('Initialising git repo')
22 try:
23 initial_branch_name = subprocess.check_output(['git', 'config', '--get', 'init.defaultBranch']).decode() # nosec B607, B603
24 except subprocess.CalledProcessError:
25 initial_branch_name = None
26 if not initial_branch_name:
27 initial_branch_name = 'main'
28 initial_branch_name = context.get('git', {}).get('initial_branch_name', initial_branch_name)
29 # Check git version - new versions have --initial-branch arg on init
30 version = subprocess.check_output(['git', 'version']).decode() # nosec B607, B603
31 version = version.replace('git version', '').lstrip()
32 semver = parse('.'.join(version.split(' ')[0].split('.')[:3]))
33 if semver >= parse('2.28.0'):
34 subprocess.check_call(['git', 'init', '--initial-branch', initial_branch_name]) # nosec B607, B603
35 else:
36 subprocess.check_call(['git', 'init']) # nosec B607, B603
37 subprocess.check_call(['git', 'checkout', '-B', initial_branch_name]) # nosec B607, B603
38 logger.info('Done')