pre-commit-ex 4.5.1__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. pre_commit/__init__.py +0 -0
  2. pre_commit/__main__.py +7 -0
  3. pre_commit/all_languages.py +50 -0
  4. pre_commit/clientlib.py +551 -0
  5. pre_commit/color.py +109 -0
  6. pre_commit/commands/__init__.py +0 -0
  7. pre_commit/commands/autoupdate.py +215 -0
  8. pre_commit/commands/clean.py +16 -0
  9. pre_commit/commands/gc.py +98 -0
  10. pre_commit/commands/hazmat.py +95 -0
  11. pre_commit/commands/hook_impl.py +272 -0
  12. pre_commit/commands/init_templatedir.py +39 -0
  13. pre_commit/commands/install_uninstall.py +167 -0
  14. pre_commit/commands/migrate_config.py +135 -0
  15. pre_commit/commands/run.py +474 -0
  16. pre_commit/commands/sample_config.py +18 -0
  17. pre_commit/commands/try_repo.py +77 -0
  18. pre_commit/commands/validate_config.py +18 -0
  19. pre_commit/commands/validate_manifest.py +18 -0
  20. pre_commit/constants.py +13 -0
  21. pre_commit/envcontext.py +62 -0
  22. pre_commit/error_handler.py +81 -0
  23. pre_commit/errors.py +5 -0
  24. pre_commit/file_lock.py +75 -0
  25. pre_commit/git.py +245 -0
  26. pre_commit/hook.py +60 -0
  27. pre_commit/lang_base.py +196 -0
  28. pre_commit/languages/__init__.py +0 -0
  29. pre_commit/languages/conda.py +77 -0
  30. pre_commit/languages/coursier.py +76 -0
  31. pre_commit/languages/dart.py +97 -0
  32. pre_commit/languages/docker.py +181 -0
  33. pre_commit/languages/docker_image.py +32 -0
  34. pre_commit/languages/dotnet.py +111 -0
  35. pre_commit/languages/fail.py +27 -0
  36. pre_commit/languages/golang.py +161 -0
  37. pre_commit/languages/haskell.py +56 -0
  38. pre_commit/languages/julia.py +133 -0
  39. pre_commit/languages/lua.py +75 -0
  40. pre_commit/languages/node.py +110 -0
  41. pre_commit/languages/perl.py +50 -0
  42. pre_commit/languages/pygrep.py +133 -0
  43. pre_commit/languages/python.py +228 -0
  44. pre_commit/languages/r.py +278 -0
  45. pre_commit/languages/ruby.py +145 -0
  46. pre_commit/languages/rust.py +160 -0
  47. pre_commit/languages/swift.py +50 -0
  48. pre_commit/languages/unsupported.py +10 -0
  49. pre_commit/languages/unsupported_script.py +32 -0
  50. pre_commit/logging_handler.py +42 -0
  51. pre_commit/main.py +472 -0
  52. pre_commit/meta_hooks/__init__.py +0 -0
  53. pre_commit/meta_hooks/check_hooks_apply.py +43 -0
  54. pre_commit/meta_hooks/check_useless_excludes.py +83 -0
  55. pre_commit/meta_hooks/identity.py +17 -0
  56. pre_commit/output.py +33 -0
  57. pre_commit/parse_shebang.py +85 -0
  58. pre_commit/prefix.py +18 -0
  59. pre_commit/repository.py +237 -0
  60. pre_commit/resources/__init__.py +0 -0
  61. pre_commit/resources/empty_template_.npmignore +1 -0
  62. pre_commit/resources/empty_template_Cargo.toml +7 -0
  63. pre_commit/resources/empty_template_LICENSE.renv +7 -0
  64. pre_commit/resources/empty_template_Makefile.PL +6 -0
  65. pre_commit/resources/empty_template_activate.R +440 -0
  66. pre_commit/resources/empty_template_environment.yml +9 -0
  67. pre_commit/resources/empty_template_go.mod +1 -0
  68. pre_commit/resources/empty_template_main.go +3 -0
  69. pre_commit/resources/empty_template_main.rs +1 -0
  70. pre_commit/resources/empty_template_package.json +4 -0
  71. pre_commit/resources/empty_template_pre-commit-package-dev-1.rockspec +12 -0
  72. pre_commit/resources/empty_template_pre_commit_placeholder_package.gemspec +6 -0
  73. pre_commit/resources/empty_template_pubspec.yaml +4 -0
  74. pre_commit/resources/empty_template_renv.lock +20 -0
  75. pre_commit/resources/empty_template_setup.py +4 -0
  76. pre_commit/resources/hook-tmpl +20 -0
  77. pre_commit/resources/rbenv.tar.gz +0 -0
  78. pre_commit/resources/ruby-build.tar.gz +0 -0
  79. pre_commit/resources/ruby-download.tar.gz +0 -0
  80. pre_commit/staged_files_only.py +113 -0
  81. pre_commit/store.py +235 -0
  82. pre_commit/util.py +239 -0
  83. pre_commit/xargs.py +184 -0
  84. pre_commit/yaml.py +19 -0
  85. pre_commit/yaml_rewrite.py +52 -0
  86. pre_commit_ex-4.5.1.dist-info/METADATA +63 -0
  87. pre_commit_ex-4.5.1.dist-info/RECORD +91 -0
  88. pre_commit_ex-4.5.1.dist-info/WHEEL +6 -0
  89. pre_commit_ex-4.5.1.dist-info/entry_points.txt +2 -0
  90. pre_commit_ex-4.5.1.dist-info/licenses/LICENSE +19 -0
  91. pre_commit_ex-4.5.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,81 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import functools
5
+ import os.path
6
+ import sys
7
+ import traceback
8
+ from collections.abc import Generator
9
+ from typing import IO
10
+
11
+ import pre_commit.constants as C
12
+ from pre_commit import output
13
+ from pre_commit.errors import FatalError
14
+ from pre_commit.store import Store
15
+ from pre_commit.util import cmd_output_b
16
+ from pre_commit.util import force_bytes
17
+
18
+
19
+ def _log_and_exit(
20
+ msg: str,
21
+ ret_code: int,
22
+ exc: BaseException,
23
+ formatted: str,
24
+ ) -> None:
25
+ error_msg = f'{msg}: {type(exc).__name__}: '.encode() + force_bytes(exc)
26
+ output.write_line_b(error_msg)
27
+
28
+ _, git_version_b, _ = cmd_output_b('git', '--version', check=False)
29
+ git_version = git_version_b.decode(errors='backslashreplace').rstrip()
30
+
31
+ storedir = Store().directory
32
+ log_path = os.path.join(storedir, 'pre-commit.log')
33
+ with contextlib.ExitStack() as ctx:
34
+ if os.access(storedir, os.W_OK):
35
+ output.write_line(f'Check the log at {log_path}')
36
+ log: IO[bytes] = ctx.enter_context(open(log_path, 'wb'))
37
+ else: # pragma: win32 no cover
38
+ output.write_line(f'Failed to write to log at {log_path}')
39
+ log = sys.stdout.buffer
40
+
41
+ _log_line = functools.partial(output.write_line, stream=log)
42
+ _log_line_b = functools.partial(output.write_line_b, stream=log)
43
+
44
+ _log_line('### version information')
45
+ _log_line()
46
+ _log_line('```')
47
+ _log_line(f'pre-commit version: {C.VERSION}')
48
+ _log_line(f'git --version: {git_version}')
49
+ _log_line('sys.version:')
50
+ for line in sys.version.splitlines():
51
+ _log_line(f' {line}')
52
+ _log_line(f'sys.executable: {sys.executable}')
53
+ _log_line(f'os.name: {os.name}')
54
+ _log_line(f'sys.platform: {sys.platform}')
55
+ _log_line('```')
56
+ _log_line()
57
+
58
+ _log_line('### error information')
59
+ _log_line()
60
+ _log_line('```')
61
+ _log_line_b(error_msg)
62
+ _log_line('```')
63
+ _log_line()
64
+ _log_line('```')
65
+ _log_line(formatted.rstrip())
66
+ _log_line('```')
67
+ raise SystemExit(ret_code)
68
+
69
+
70
+ @contextlib.contextmanager
71
+ def error_handler() -> Generator[None]:
72
+ try:
73
+ yield
74
+ except (Exception, KeyboardInterrupt) as e:
75
+ if isinstance(e, FatalError):
76
+ msg, ret_code = 'An error has occurred', 1
77
+ elif isinstance(e, KeyboardInterrupt):
78
+ msg, ret_code = 'Interrupted (^C)', 130
79
+ else:
80
+ msg, ret_code = 'An unexpected error has occurred', 3
81
+ _log_and_exit(msg, ret_code, e, traceback.format_exc())
pre_commit/errors.py ADDED
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class FatalError(RuntimeError):
5
+ pass
@@ -0,0 +1,75 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import errno
5
+ import sys
6
+ from collections.abc import Callable
7
+ from collections.abc import Generator
8
+
9
+
10
+ if sys.platform == 'win32': # pragma: no cover (windows)
11
+ import msvcrt
12
+
13
+ # https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/locking
14
+
15
+ # on windows we lock "regions" of files, we don't care about the actual
16
+ # byte region so we'll just pick *some* number here.
17
+ _region = 0xffff
18
+
19
+ @contextlib.contextmanager
20
+ def _locked(
21
+ fileno: int,
22
+ blocked_cb: Callable[[], None],
23
+ ) -> Generator[None]:
24
+ try:
25
+ msvcrt.locking(fileno, msvcrt.LK_NBLCK, _region)
26
+ except OSError:
27
+ blocked_cb()
28
+ while True:
29
+ try:
30
+ msvcrt.locking(fileno, msvcrt.LK_LOCK, _region)
31
+ except OSError as e:
32
+ # Locking violation. Returned when the _LK_LOCK or _LK_RLCK
33
+ # flag is specified and the file cannot be locked after 10
34
+ # attempts.
35
+ if e.errno != errno.EDEADLOCK:
36
+ raise
37
+ else:
38
+ break
39
+
40
+ try:
41
+ yield
42
+ finally:
43
+ # From cursory testing, it seems to get unlocked when the file is
44
+ # closed so this may not be necessary.
45
+ # The documentation however states:
46
+ # "Regions should be locked only briefly and should be unlocked
47
+ # before closing a file or exiting the program."
48
+ msvcrt.locking(fileno, msvcrt.LK_UNLCK, _region)
49
+ else: # pragma: win32 no cover
50
+ import fcntl
51
+
52
+ @contextlib.contextmanager
53
+ def _locked(
54
+ fileno: int,
55
+ blocked_cb: Callable[[], None],
56
+ ) -> Generator[None]:
57
+ try:
58
+ fcntl.flock(fileno, fcntl.LOCK_EX | fcntl.LOCK_NB)
59
+ except OSError: # pragma: no cover (tests are single-threaded)
60
+ blocked_cb()
61
+ fcntl.flock(fileno, fcntl.LOCK_EX)
62
+ try:
63
+ yield
64
+ finally:
65
+ fcntl.flock(fileno, fcntl.LOCK_UN)
66
+
67
+
68
+ @contextlib.contextmanager
69
+ def lock(
70
+ path: str,
71
+ blocked_cb: Callable[[], None],
72
+ ) -> Generator[None]:
73
+ with open(path, 'a+') as f:
74
+ with _locked(f.fileno(), blocked_cb):
75
+ yield
pre_commit/git.py ADDED
@@ -0,0 +1,245 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os.path
5
+ import sys
6
+ from collections.abc import Mapping
7
+
8
+ from pre_commit.errors import FatalError
9
+ from pre_commit.util import CalledProcessError
10
+ from pre_commit.util import cmd_output
11
+ from pre_commit.util import cmd_output_b
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # see #2046
16
+ NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false')
17
+
18
+
19
+ def zsplit(s: str) -> list[str]:
20
+ s = s.strip('\0')
21
+ if s:
22
+ return s.split('\0')
23
+ else:
24
+ return []
25
+
26
+
27
+ def no_git_env(_env: Mapping[str, str] | None = None) -> dict[str, str]:
28
+ # Too many bugs dealing with environment variables and GIT:
29
+ # https://github.com/pre-commit/pre-commit/issues/300
30
+ # In git 2.6.3 (maybe others), git exports GIT_WORK_TREE while running
31
+ # pre-commit hooks
32
+ # In git 1.9.1 (maybe others), git exports GIT_DIR and GIT_INDEX_FILE
33
+ # while running pre-commit hooks in submodules.
34
+ # GIT_DIR: Causes git clone to clone wrong thing
35
+ # GIT_INDEX_FILE: Causes 'error invalid object ...' during commit
36
+ _env = _env if _env is not None else os.environ
37
+ return {
38
+ k: v for k, v in _env.items()
39
+ if not k.startswith('GIT_') or
40
+ k.startswith(('GIT_CONFIG_KEY_', 'GIT_CONFIG_VALUE_')) or
41
+ k in {
42
+ 'GIT_EXEC_PATH', 'GIT_SSH', 'GIT_SSH_COMMAND', 'GIT_SSL_CAINFO',
43
+ 'GIT_SSL_NO_VERIFY', 'GIT_CONFIG_COUNT',
44
+ 'GIT_HTTP_PROXY_AUTHMETHOD',
45
+ 'GIT_ALLOW_PROTOCOL',
46
+ 'GIT_ASKPASS',
47
+ }
48
+ }
49
+
50
+
51
+ def get_root() -> str:
52
+ # Git 2.25 introduced a change to "rev-parse --show-toplevel" that exposed
53
+ # underlying volumes for Windows drives mapped with SUBST. We use
54
+ # "rev-parse --show-cdup" to get the appropriate path, but must perform
55
+ # an extra check to see if we are in the .git directory.
56
+ try:
57
+ root = os.path.abspath(
58
+ cmd_output('git', 'rev-parse', '--show-cdup')[1].strip(),
59
+ )
60
+ inside_git_dir = cmd_output(
61
+ 'git', 'rev-parse', '--is-inside-git-dir',
62
+ )[1].strip()
63
+ except CalledProcessError:
64
+ raise FatalError(
65
+ 'git failed. Is it installed, and are you in a Git repository '
66
+ 'directory?',
67
+ )
68
+ if inside_git_dir != 'false':
69
+ raise FatalError(
70
+ 'git toplevel unexpectedly empty! make sure you are not '
71
+ 'inside the `.git` directory of your repository.',
72
+ )
73
+ return root
74
+
75
+
76
+ def get_git_dir(git_root: str = '.') -> str:
77
+ opt = '--git-dir'
78
+ _, out, _ = cmd_output('git', 'rev-parse', opt, cwd=git_root)
79
+ git_dir = out.strip()
80
+ if git_dir != opt:
81
+ return os.path.normpath(os.path.join(git_root, git_dir))
82
+ else:
83
+ raise AssertionError('unreachable: no git dir')
84
+
85
+
86
+ def get_git_common_dir(git_root: str = '.') -> str:
87
+ opt = '--git-common-dir'
88
+ _, out, _ = cmd_output('git', 'rev-parse', opt, cwd=git_root)
89
+ git_common_dir = out.strip()
90
+ if git_common_dir != opt:
91
+ return os.path.normpath(os.path.join(git_root, git_common_dir))
92
+ else: # pragma: no cover (git < 2.5)
93
+ return get_git_dir(git_root)
94
+
95
+
96
+ def is_in_merge_conflict() -> bool:
97
+ git_dir = get_git_dir('.')
98
+ return (
99
+ os.path.exists(os.path.join(git_dir, 'MERGE_MSG')) and
100
+ os.path.exists(os.path.join(git_dir, 'MERGE_HEAD'))
101
+ )
102
+
103
+
104
+ def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]:
105
+ # Conflicted files start with tabs
106
+ return [
107
+ line.lstrip(b'#').strip().decode()
108
+ for line in merge_msg.splitlines()
109
+ # '#\t' for git 2.4.1
110
+ if line.startswith((b'\t', b'#\t'))
111
+ ]
112
+
113
+
114
+ def get_conflicted_files() -> set[str]:
115
+ logger.info('Checking merge-conflict files only.')
116
+ # Need to get the conflicted files from the MERGE_MSG because they could
117
+ # have resolved the conflict by choosing one side or the other
118
+ with open(os.path.join(get_git_dir('.'), 'MERGE_MSG'), 'rb') as f:
119
+ merge_msg = f.read()
120
+ merge_conflict_filenames = parse_merge_msg_for_conflicts(merge_msg)
121
+
122
+ # This will get the rest of the changes made after the merge.
123
+ # If they resolved the merge conflict by choosing a mesh of both sides
124
+ # this will also include the conflicted files
125
+ tree_hash = cmd_output('git', 'write-tree')[1].strip()
126
+ merge_diff_filenames = zsplit(
127
+ cmd_output(
128
+ 'git', 'diff', '--name-only', '--no-ext-diff', '-z',
129
+ '-m', tree_hash, 'HEAD', 'MERGE_HEAD', '--',
130
+ )[1],
131
+ )
132
+ return set(merge_conflict_filenames) | set(merge_diff_filenames)
133
+
134
+
135
+ def get_staged_files(cwd: str | None = None) -> list[str]:
136
+ return zsplit(
137
+ cmd_output(
138
+ 'git', 'diff', '--staged', '--name-only', '--no-ext-diff', '-z',
139
+ # Everything except for D
140
+ '--diff-filter=ACMRTUXB',
141
+ cwd=cwd,
142
+ )[1],
143
+ )
144
+
145
+
146
+ def intent_to_add_files() -> list[str]:
147
+ _, stdout, _ = cmd_output(
148
+ 'git', 'diff', '--no-ext-diff', '--ignore-submodules',
149
+ '--diff-filter=A', '--name-only', '-z',
150
+ )
151
+ return zsplit(stdout)
152
+
153
+
154
+ def get_all_files() -> list[str]:
155
+ return zsplit(cmd_output('git', 'ls-files', '-z')[1])
156
+
157
+
158
+ def get_changed_files(old: str, new: str) -> list[str]:
159
+ diff_cmd = ('git', 'diff', '--name-only', '--no-ext-diff', '-z')
160
+ try:
161
+ _, out, _ = cmd_output(*diff_cmd, f'{old}...{new}')
162
+ except CalledProcessError: # pragma: no cover (new git)
163
+ # on newer git where old and new do not have a merge base git fails
164
+ # so we try a full diff (this is what old git did for us!)
165
+ _, out, _ = cmd_output(*diff_cmd, f'{old}..{new}')
166
+
167
+ return zsplit(out)
168
+
169
+
170
+ def head_rev(remote: str) -> str:
171
+ _, out, _ = cmd_output('git', 'ls-remote', '--exit-code', remote, 'HEAD')
172
+ return out.split()[0]
173
+
174
+
175
+ def has_diff(*args: str, repo: str = '.') -> bool:
176
+ cmd = ('git', 'diff', '--quiet', '--no-ext-diff', *args)
177
+ return cmd_output_b(*cmd, cwd=repo, check=False)[0] == 1
178
+
179
+
180
+ def has_core_hookpaths_set() -> bool:
181
+ _, out, _ = cmd_output_b('git', 'config', 'core.hooksPath', check=False)
182
+ return bool(out.strip())
183
+
184
+
185
+ def init_repo(path: str, remote: str) -> None:
186
+ if os.path.isdir(remote):
187
+ remote = os.path.abspath(remote)
188
+
189
+ git = ('git', *NO_FS_MONITOR)
190
+ env = no_git_env()
191
+ # avoid the user's template so that hooks do not recurse
192
+ cmd_output_b(*git, 'init', '--template=', path, env=env)
193
+ cmd_output_b(*git, 'remote', 'add', 'origin', remote, cwd=path, env=env)
194
+
195
+
196
+ def commit(repo: str = '.') -> None:
197
+ env = no_git_env()
198
+ name, email = 'pre-commit', 'asottile+pre-commit@umich.edu'
199
+ env['GIT_AUTHOR_NAME'] = env['GIT_COMMITTER_NAME'] = name
200
+ env['GIT_AUTHOR_EMAIL'] = env['GIT_COMMITTER_EMAIL'] = email
201
+ cmd = ('git', 'commit', '--no-edit', '--no-gpg-sign', '-n', '-minit')
202
+ cmd_output_b(*cmd, cwd=repo, env=env)
203
+
204
+
205
+ def git_path(name: str, repo: str = '.') -> str:
206
+ _, out, _ = cmd_output('git', 'rev-parse', '--git-path', name, cwd=repo)
207
+ return os.path.join(repo, out.strip())
208
+
209
+
210
+ def check_for_cygwin_mismatch() -> None:
211
+ """See https://github.com/pre-commit/pre-commit/issues/354"""
212
+ if sys.platform in ('cygwin', 'win32'): # pragma: no cover (windows)
213
+ is_cygwin_python = sys.platform == 'cygwin'
214
+ try:
215
+ toplevel = get_root()
216
+ except FatalError: # skip the check if we're not in a git repo
217
+ return
218
+ is_cygwin_git = toplevel.startswith('/')
219
+
220
+ if is_cygwin_python ^ is_cygwin_git:
221
+ exe_type = {True: '(cygwin)', False: '(windows)'}
222
+ logger.warning(
223
+ f'pre-commit has detected a mix of cygwin python / git\n'
224
+ f'This combination is not supported, it is likely you will '
225
+ f'receive an error later in the program.\n'
226
+ f'Make sure to use cygwin git+python while using cygwin\n'
227
+ f'These can be installed through the cygwin installer.\n'
228
+ f' - python {exe_type[is_cygwin_python]}\n'
229
+ f' - git {exe_type[is_cygwin_git]}\n',
230
+ )
231
+
232
+
233
+ def get_best_candidate_tag(rev: str, git_repo: str) -> str:
234
+ """Get the best tag candidate.
235
+
236
+ Multiple tags can exist on a SHA. Sometimes a moving tag is attached
237
+ to a version tag. Try to pick the tag that looks like a version.
238
+ """
239
+ tags = cmd_output(
240
+ 'git', *NO_FS_MONITOR, 'tag', '--points-at', rev, cwd=git_repo,
241
+ )[1].splitlines()
242
+ for tag in tags:
243
+ if '.' in tag:
244
+ return tag
245
+ return rev
pre_commit/hook.py ADDED
@@ -0,0 +1,60 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections.abc import Sequence
5
+ from typing import Any
6
+ from typing import NamedTuple
7
+
8
+ from pre_commit.prefix import Prefix
9
+
10
+ logger = logging.getLogger('pre_commit')
11
+
12
+
13
+ class Hook(NamedTuple):
14
+ src: str
15
+ prefix: Prefix
16
+ id: str
17
+ name: str
18
+ entry: str
19
+ language: str
20
+ alias: str
21
+ files: str
22
+ exclude: str
23
+ types: Sequence[str]
24
+ types_or: Sequence[str]
25
+ exclude_types: Sequence[str]
26
+ additional_dependencies: Sequence[str]
27
+ args: Sequence[str]
28
+ always_run: bool
29
+ fail_fast: bool
30
+ pass_filenames: bool
31
+ description: str
32
+ language_version: str
33
+ log_file: str
34
+ minimum_pre_commit_version: str
35
+ require_serial: bool
36
+ stages: Sequence[str]
37
+ verbose: bool
38
+
39
+ @property
40
+ def install_key(self) -> tuple[Prefix, str, str, tuple[str, ...]]:
41
+ return (
42
+ self.prefix,
43
+ self.language,
44
+ self.language_version,
45
+ tuple(self.additional_dependencies),
46
+ )
47
+
48
+ @classmethod
49
+ def create(cls, src: str, prefix: Prefix, dct: dict[str, Any]) -> Hook:
50
+ # TODO: have cfgv do this (?)
51
+ extra_keys = set(dct) - _KEYS
52
+ if extra_keys:
53
+ logger.warning(
54
+ f'Unexpected key(s) present on {src} => {dct["id"]}: '
55
+ f'{", ".join(sorted(extra_keys))}',
56
+ )
57
+ return cls(src=src, prefix=prefix, **{k: dct[k] for k in _KEYS})
58
+
59
+
60
+ _KEYS = frozenset(set(Hook._fields) - {'src', 'prefix'})
@@ -0,0 +1,196 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import os
5
+ import random
6
+ import re
7
+ import shlex
8
+ import sys
9
+ from collections.abc import Generator
10
+ from collections.abc import Sequence
11
+ from typing import Any
12
+ from typing import ContextManager
13
+ from typing import NoReturn
14
+ from typing import Protocol
15
+
16
+ import pre_commit.constants as C
17
+ from pre_commit import parse_shebang
18
+ from pre_commit import xargs
19
+ from pre_commit.prefix import Prefix
20
+ from pre_commit.util import cmd_output_b
21
+
22
+ FIXED_RANDOM_SEED = 1542676187
23
+
24
+ SHIMS_RE = re.compile(r'[/\\]shims[/\\]')
25
+
26
+
27
+ class Language(Protocol):
28
+ # Use `None` for no installation / environment
29
+ @property
30
+ def ENVIRONMENT_DIR(self) -> str | None: ...
31
+ # return a value to replace `'default` for `language_version`
32
+ def get_default_version(self) -> str: ...
33
+ # return whether the environment is healthy (or should be rebuilt)
34
+ def health_check(self, prefix: Prefix, version: str) -> str | None: ...
35
+
36
+ # install a repository for the given language and language_version
37
+ def install_environment(
38
+ self,
39
+ prefix: Prefix,
40
+ version: str,
41
+ additional_dependencies: Sequence[str],
42
+ ) -> None:
43
+ ...
44
+
45
+ # modify the environment for hook execution
46
+ def in_env(self, prefix: Prefix, version: str) -> ContextManager[None]: ...
47
+
48
+ # execute a hook and return the exit code and output
49
+ def run_hook(
50
+ self,
51
+ prefix: Prefix,
52
+ entry: str,
53
+ args: Sequence[str],
54
+ file_args: Sequence[str],
55
+ *,
56
+ is_local: bool,
57
+ require_serial: bool,
58
+ color: bool,
59
+ ) -> tuple[int, bytes]:
60
+ ...
61
+
62
+
63
+ def exe_exists(exe: str) -> bool:
64
+ found = parse_shebang.find_executable(exe)
65
+ if found is None: # exe exists
66
+ return False
67
+
68
+ homedir = os.path.expanduser('~')
69
+ try:
70
+ common: str | None = os.path.commonpath((found, homedir))
71
+ except ValueError: # on windows, different drives raises ValueError
72
+ common = None
73
+
74
+ return (
75
+ # it is not in a /shims/ directory
76
+ not SHIMS_RE.search(found) and
77
+ (
78
+ # the homedir is / (docker, service user, etc.)
79
+ os.path.dirname(homedir) == homedir or
80
+ # the exe is not contained in the home directory
81
+ common != homedir
82
+ )
83
+ )
84
+
85
+
86
+ def setup_cmd(prefix: Prefix, cmd: tuple[str, ...], **kwargs: Any) -> None:
87
+ cmd_output_b(*cmd, cwd=prefix.prefix_dir, **kwargs)
88
+
89
+
90
+ def environment_dir(prefix: Prefix, d: str, language_version: str) -> str:
91
+ return prefix.path(f'{d}-{language_version}')
92
+
93
+
94
+ def assert_version_default(binary: str, version: str) -> None:
95
+ if version != C.DEFAULT:
96
+ raise AssertionError(
97
+ f'for now, pre-commit requires system-installed {binary} -- '
98
+ f'you selected `language_version: {version}`',
99
+ )
100
+
101
+
102
+ def assert_no_additional_deps(
103
+ lang: str,
104
+ additional_deps: Sequence[str],
105
+ ) -> None:
106
+ if additional_deps:
107
+ raise AssertionError(
108
+ f'for now, pre-commit does not support '
109
+ f'additional_dependencies for {lang} -- '
110
+ f'you selected `additional_dependencies: {additional_deps}`',
111
+ )
112
+
113
+
114
+ def basic_get_default_version() -> str:
115
+ return C.DEFAULT
116
+
117
+
118
+ def basic_health_check(prefix: Prefix, language_version: str) -> str | None:
119
+ return None
120
+
121
+
122
+ def no_install(
123
+ prefix: Prefix,
124
+ version: str,
125
+ additional_dependencies: Sequence[str],
126
+ ) -> NoReturn:
127
+ raise AssertionError('This language is not installable')
128
+
129
+
130
+ @contextlib.contextmanager
131
+ def no_env(prefix: Prefix, version: str) -> Generator[None]:
132
+ yield
133
+
134
+
135
+ def target_concurrency() -> int:
136
+ if 'PRE_COMMIT_NO_CONCURRENCY' in os.environ:
137
+ return 1
138
+ else:
139
+ # Travis appears to have a bunch of CPUs, but we can't use them all.
140
+ if 'TRAVIS' in os.environ:
141
+ return 2
142
+ else:
143
+ return xargs.cpu_count()
144
+
145
+
146
+ def _shuffled(seq: Sequence[str]) -> list[str]:
147
+ """Deterministically shuffle"""
148
+ fixed_random = random.Random()
149
+ fixed_random.seed(FIXED_RANDOM_SEED, version=1)
150
+
151
+ seq = list(seq)
152
+ fixed_random.shuffle(seq)
153
+ return seq
154
+
155
+
156
+ def run_xargs(
157
+ cmd: tuple[str, ...],
158
+ file_args: Sequence[str],
159
+ *,
160
+ require_serial: bool,
161
+ color: bool,
162
+ ) -> tuple[int, bytes]:
163
+ if require_serial:
164
+ jobs = 1
165
+ else:
166
+ # Shuffle the files so that they more evenly fill out the xargs
167
+ # partitions, but do it deterministically in case a hook cares about
168
+ # ordering.
169
+ file_args = _shuffled(file_args)
170
+ jobs = target_concurrency()
171
+ return xargs.xargs(cmd, file_args, target_concurrency=jobs, color=color)
172
+
173
+
174
+ def hook_cmd(entry: str, args: Sequence[str]) -> tuple[str, ...]:
175
+ cmd = shlex.split(entry)
176
+ if cmd[:2] == ['pre-commit', 'hazmat']:
177
+ cmd = [sys.executable, '-m', 'pre_commit.commands.hazmat', *cmd[2:]]
178
+ return (*cmd, *args)
179
+
180
+
181
+ def basic_run_hook(
182
+ prefix: Prefix,
183
+ entry: str,
184
+ args: Sequence[str],
185
+ file_args: Sequence[str],
186
+ *,
187
+ is_local: bool,
188
+ require_serial: bool,
189
+ color: bool,
190
+ ) -> tuple[int, bytes]:
191
+ return run_xargs(
192
+ hook_cmd(entry, args),
193
+ file_args,
194
+ require_serial=require_serial,
195
+ color=color,
196
+ )
File without changes