feat: add options for disabling venv in python

This commit is contained in:
alec.tu 2024-03-28 15:41:28 +08:00
parent 7b4667e9e6
commit 9cbd9f69ff
3 changed files with 45 additions and 24 deletions

View file

@ -132,6 +132,7 @@ MANIFEST_HOOK_DICT = cfgv.Map(
cfgv.Optional('language_version', cfgv.check_string, C.DEFAULT), cfgv.Optional('language_version', cfgv.check_string, C.DEFAULT),
cfgv.Optional('log_file', cfgv.check_string, ''), cfgv.Optional('log_file', cfgv.check_string, ''),
cfgv.Optional('require_serial', cfgv.check_bool, False), cfgv.Optional('require_serial', cfgv.check_bool, False),
cfgv.Optional('require_venv', cfgv.check_bool, True),
StagesMigration('stages', []), StagesMigration('stages', []),
cfgv.Optional('verbose', cfgv.check_bool, False), cfgv.Optional('verbose', cfgv.check_bool, False),
) )

View file

@ -33,6 +33,7 @@ class Hook(NamedTuple):
log_file: str log_file: str
minimum_pre_commit_version: str minimum_pre_commit_version: str
require_serial: bool require_serial: bool
require_venv: bool
stages: Sequence[str] stages: Sequence[str]
verbose: bool verbose: bool

View file

@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
import sys
import json import json
import logging import logging
import os import os
@ -85,6 +86,23 @@ def _hook_install(hook: Hook) -> None:
hook.language_version, hook.language_version,
) )
if hook.language == 'python' and not hook.require_venv:
logger.info(f'Disabling creation of virtual environment for hook {hook.src}')
# Path to the Python executable inside the virtual environment
python_executable = sys.executable
# Get the directory containing the Python executable
executable_dir = os.path.dirname(python_executable)
# Virtual environment's base directory is one level up from the executable directory
venv_dir = os.path.dirname(executable_dir)
# Remove existing directory or link if necessary
if os.path.islink(venv):
os.remove(venv)
if os.path.exists(venv):
rmtree(venv)
# Create a symbolic link pointing venv_dir to envdir
os.symlink(venv_dir, venv)
else:
# There's potentially incomplete cleanup from previous runs # There's potentially incomplete cleanup from previous runs
# Clean it up! # Clean it up!
if os.path.exists(venv): if os.path.exists(venv):
@ -225,6 +243,7 @@ def install_hook_envs(hooks: Sequence[Hook], store: Store) -> None:
seen: set[tuple[Prefix, str, str, tuple[str, ...]]] = set() seen: set[tuple[Prefix, str, str, tuple[str, ...]]] = set()
ret = [] ret = []
for hook in hooks: for hook in hooks:
# print(f'hook={hook.src}, install_key={hook.install_key}')
if hook.install_key not in seen and not _hook_installed(hook): if hook.install_key not in seen and not _hook_installed(hook):
ret.append(hook) ret.append(hook)
seen.add(hook.install_key) seen.add(hook.install_key)