(
config_file: str,
hook_type: str,
overwrite: bool = False,
skip_on_missing_config: bool = False,
git_dir: str | None = None,
)
| 62 | |
| 63 | |
| 64 | def _install_hook_script( |
| 65 | config_file: str, |
| 66 | hook_type: str, |
| 67 | overwrite: bool = False, |
| 68 | skip_on_missing_config: bool = False, |
| 69 | git_dir: str | None = None, |
| 70 | ) -> None: |
| 71 | hook_path, legacy_path = _hook_paths(hook_type, git_dir=git_dir) |
| 72 | |
| 73 | os.makedirs(os.path.dirname(hook_path), exist_ok=True) |
| 74 | |
| 75 | # If we have an existing hook, move it to pre-commit.legacy |
| 76 | if os.path.lexists(hook_path) and not is_our_script(hook_path): |
| 77 | shutil.move(hook_path, legacy_path) |
| 78 | |
| 79 | # If we specify overwrite, we simply delete the legacy file |
| 80 | if overwrite and os.path.exists(legacy_path): |
| 81 | os.remove(legacy_path) |
| 82 | elif os.path.exists(legacy_path): |
| 83 | output.write_line( |
| 84 | f'Running in migration mode with existing hooks at {legacy_path}\n' |
| 85 | f'Use -f to use only pre-commit.', |
| 86 | ) |
| 87 | |
| 88 | args = ['hook-impl', f'--config={config_file}', f'--hook-type={hook_type}'] |
| 89 | if skip_on_missing_config: |
| 90 | args.append('--skip-on-missing-config') |
| 91 | |
| 92 | with open(hook_path, 'w') as hook_file: |
| 93 | contents = resource_text('hook-tmpl') |
| 94 | before, rest = contents.split(TEMPLATE_START) |
| 95 | _, after = rest.split(TEMPLATE_END) |
| 96 | |
| 97 | # on windows always use `/bin/sh` since `bash` might not be on PATH |
| 98 | # though we use bash-specific features `sh` on windows is actually |
| 99 | # bash in "POSIXLY_CORRECT" mode which still supports the features we |
| 100 | # use: subshells / arrays |
| 101 | if sys.platform == 'win32': # pragma: win32 cover |
| 102 | hook_file.write('#!/bin/sh\n') |
| 103 | |
| 104 | hook_file.write(before + TEMPLATE_START) |
| 105 | hook_file.write(f'INSTALL_PYTHON={shlex.quote(sys.executable)}\n') |
| 106 | args_s = shlex.join(args) |
| 107 | hook_file.write(f'ARGS=({args_s})\n') |
| 108 | hook_file.write(TEMPLATE_END + after) |
| 109 | make_executable(hook_path) |
| 110 | |
| 111 | output.write_line(f'pre-commit installed at {hook_path}') |
| 112 | |
| 113 | |
| 114 | def install( |
no test coverage detected