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,474 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import contextlib
5
+ import functools
6
+ import logging
7
+ import os
8
+ import re
9
+ import subprocess
10
+ import time
11
+ import unicodedata
12
+ from collections.abc import Generator
13
+ from collections.abc import Iterable
14
+ from collections.abc import MutableMapping
15
+ from collections.abc import Sequence
16
+ from typing import Any
17
+
18
+ from identify.identify import tags_from_path
19
+
20
+ from pre_commit import color
21
+ from pre_commit import git
22
+ from pre_commit import output
23
+ from pre_commit.all_languages import languages
24
+ from pre_commit.clientlib import load_config
25
+ from pre_commit.hook import Hook
26
+ from pre_commit.repository import all_hooks
27
+ from pre_commit.repository import install_hook_envs
28
+ from pre_commit.staged_files_only import staged_files_only
29
+ from pre_commit.store import Store
30
+ from pre_commit.util import cmd_output_b
31
+
32
+
33
+ logger = logging.getLogger('pre_commit')
34
+
35
+
36
+ def _len_cjk(msg: str) -> int:
37
+ widths = {'A': 1, 'F': 2, 'H': 1, 'N': 1, 'Na': 1, 'W': 2}
38
+ return sum(widths[unicodedata.east_asian_width(c)] for c in msg)
39
+
40
+
41
+ def _start_msg(*, start: str, cols: int, end_len: int) -> str:
42
+ dots = '.' * (cols - _len_cjk(start) - end_len - 1)
43
+ return f'{start}{dots}'
44
+
45
+
46
+ def _full_msg(
47
+ *,
48
+ start: str,
49
+ cols: int,
50
+ end_msg: str,
51
+ end_color: str,
52
+ use_color: bool,
53
+ postfix: str = '',
54
+ ) -> str:
55
+ dots = '.' * (cols - _len_cjk(start) - len(postfix) - len(end_msg) - 1)
56
+ end = color.format_color(end_msg, end_color, use_color)
57
+ return f'{start}{dots}{postfix}{end}\n'
58
+
59
+
60
+ def filter_by_include_exclude(
61
+ names: Iterable[str],
62
+ include: str,
63
+ exclude: str,
64
+ ) -> Generator[str]:
65
+ include_re, exclude_re = re.compile(include), re.compile(exclude)
66
+ return (
67
+ filename for filename in names
68
+ if include_re.search(filename)
69
+ if not exclude_re.search(filename)
70
+ )
71
+
72
+
73
+ class Classifier:
74
+ def __init__(self, filenames: Iterable[str]) -> None:
75
+ self.filenames = [f for f in filenames if os.path.lexists(f)]
76
+
77
+ @functools.cache
78
+ def _types_for_file(self, filename: str) -> set[str]:
79
+ return tags_from_path(filename)
80
+
81
+ def by_types(
82
+ self,
83
+ names: Iterable[str],
84
+ types: Iterable[str],
85
+ types_or: Iterable[str],
86
+ exclude_types: Iterable[str],
87
+ ) -> Generator[str]:
88
+ types = frozenset(types)
89
+ types_or = frozenset(types_or)
90
+ exclude_types = frozenset(exclude_types)
91
+ for filename in names:
92
+ tags = self._types_for_file(filename)
93
+ if (
94
+ tags >= types and
95
+ (not types_or or tags & types_or) and
96
+ not tags & exclude_types
97
+ ):
98
+ yield filename
99
+
100
+ def filenames_for_hook(self, hook: Hook) -> Generator[str]:
101
+ return self.by_types(
102
+ filter_by_include_exclude(
103
+ self.filenames,
104
+ hook.files,
105
+ hook.exclude,
106
+ ),
107
+ hook.types,
108
+ hook.types_or,
109
+ hook.exclude_types,
110
+ )
111
+
112
+ @classmethod
113
+ def from_config(
114
+ cls,
115
+ filenames: Iterable[str],
116
+ include: str,
117
+ exclude: str,
118
+ ) -> Classifier:
119
+ # on windows we normalize all filenames to use forward slashes
120
+ # this makes it easier to filter using the `files:` regex
121
+ # this also makes improperly quoted shell-based hooks work better
122
+ # see #1173
123
+ if os.altsep == '/' and os.sep == '\\':
124
+ filenames = (f.replace(os.sep, os.altsep) for f in filenames)
125
+ filenames = filter_by_include_exclude(filenames, include, exclude)
126
+ return Classifier(filenames)
127
+
128
+
129
+ def _get_skips(environ: MutableMapping[str, str]) -> set[str]:
130
+ skips = environ.get('SKIP', '')
131
+ return {skip.strip() for skip in skips.split(',') if skip.strip()}
132
+
133
+
134
+ SKIPPED = 'Skipped'
135
+ NO_FILES = '(no files to check)'
136
+
137
+
138
+ def _subtle_line(s: str, use_color: bool) -> None:
139
+ output.write_line(color.format_color(s, color.SUBTLE, use_color))
140
+
141
+
142
+ def _run_single_hook(
143
+ classifier: Classifier,
144
+ hook: Hook,
145
+ skips: set[str],
146
+ cols: int,
147
+ diff_before: bytes,
148
+ verbose: bool,
149
+ use_color: bool,
150
+ is_tool: bool = False,
151
+ extra_args: Sequence[str] = (),
152
+ ) -> tuple[bool, bytes]:
153
+ filenames = tuple(classifier.filenames_for_hook(hook))
154
+
155
+ if hook.id in skips or hook.alias in skips:
156
+ output.write(
157
+ _full_msg(
158
+ start=hook.name,
159
+ end_msg=SKIPPED,
160
+ end_color=color.YELLOW,
161
+ use_color=use_color,
162
+ cols=cols,
163
+ ),
164
+ )
165
+ duration = None
166
+ retcode = 0
167
+ diff_after = diff_before
168
+ files_modified = False
169
+ out = b''
170
+ elif not filenames and not hook.always_run:
171
+ output.write(
172
+ _full_msg(
173
+ start=hook.name,
174
+ postfix=NO_FILES,
175
+ end_msg=SKIPPED,
176
+ end_color=color.TURQUOISE,
177
+ use_color=use_color,
178
+ cols=cols,
179
+ ),
180
+ )
181
+ duration = None
182
+ retcode = 0
183
+ diff_after = diff_before
184
+ files_modified = False
185
+ out = b''
186
+ else:
187
+ # print hook and dots first in case the hook takes a while to run
188
+ output.write(_start_msg(start=hook.name, end_len=6, cols=cols))
189
+
190
+ if not hook.pass_filenames:
191
+ filenames = ()
192
+ time_before = time.monotonic()
193
+ language = languages[hook.language]
194
+ with language.in_env(hook.prefix, hook.language_version):
195
+ hook_args = tuple(extra_args) if is_tool else hook.args
196
+ retcode, out = language.run_hook(
197
+ hook.prefix,
198
+ hook.entry,
199
+ hook_args,
200
+ filenames,
201
+ is_local=hook.src == 'local',
202
+ require_serial=hook.require_serial,
203
+ color=use_color,
204
+ )
205
+ duration = round(time.monotonic() - time_before, 2) or 0
206
+ diff_after = _get_diff()
207
+
208
+ # if the hook makes changes, fail the commit
209
+ files_modified = diff_before != diff_after
210
+
211
+ if retcode or files_modified:
212
+ print_color = color.RED
213
+ status = 'Failed'
214
+ else:
215
+ print_color = color.GREEN
216
+ status = 'Passed'
217
+
218
+ output.write_line(color.format_color(status, print_color, use_color))
219
+
220
+ if verbose or hook.verbose or retcode or files_modified:
221
+ _subtle_line(f'- hook id: {hook.id}', use_color)
222
+
223
+ if (verbose or hook.verbose) and duration is not None:
224
+ _subtle_line(f'- duration: {duration}s', use_color)
225
+
226
+ if retcode:
227
+ _subtle_line(f'- exit code: {retcode}', use_color)
228
+
229
+ # Print a message if failing due to file modifications
230
+ if files_modified:
231
+ _subtle_line('- files were modified by this hook', use_color)
232
+
233
+ if out.strip():
234
+ output.write_line()
235
+ output.write_line_b(out.strip(), logfile_name=hook.log_file)
236
+ output.write_line()
237
+
238
+ return files_modified or bool(retcode), diff_after
239
+
240
+
241
+ def _compute_cols(hooks: Sequence[Hook]) -> int:
242
+ """Compute the number of columns to display hook messages. The widest
243
+ that will be displayed is in the no files skipped case:
244
+
245
+ Hook name...(no files to check) Skipped
246
+ """
247
+ if hooks:
248
+ name_len = max(_len_cjk(hook.name) for hook in hooks)
249
+ else:
250
+ name_len = 0
251
+
252
+ cols = name_len + 3 + len(NO_FILES) + 1 + len(SKIPPED)
253
+ return max(cols, 80)
254
+
255
+
256
+ def _all_filenames(args: argparse.Namespace) -> Iterable[str]:
257
+ # these hooks do not operate on files
258
+ if args.hook_stage in {
259
+ 'post-checkout', 'post-commit', 'post-merge', 'post-rewrite',
260
+ 'pre-rebase',
261
+ }:
262
+ return ()
263
+ elif args.hook_stage in {'prepare-commit-msg', 'commit-msg'}:
264
+ return (args.commit_msg_filename,)
265
+ elif args.from_ref and args.to_ref:
266
+ return git.get_changed_files(args.from_ref, args.to_ref)
267
+ elif args.files:
268
+ return args.files
269
+ elif args.all_files:
270
+ return git.get_all_files()
271
+ elif git.is_in_merge_conflict():
272
+ return git.get_conflicted_files()
273
+ else:
274
+ return git.get_staged_files()
275
+
276
+
277
+ def _get_diff() -> bytes:
278
+ _, out, _ = cmd_output_b(
279
+ 'git', 'diff', '--no-ext-diff', '--no-textconv', '--ignore-submodules',
280
+ check=False,
281
+ )
282
+ return out
283
+
284
+
285
+ def _run_hooks(
286
+ config: dict[str, Any],
287
+ hooks: Sequence[Hook],
288
+ skips: set[str],
289
+ args: argparse.Namespace,
290
+ is_tool: bool = False,
291
+ extra_args: Sequence[str] = (),
292
+ ) -> int:
293
+ """Actually run the hooks."""
294
+ cols = _compute_cols(hooks)
295
+ classifier = Classifier.from_config(
296
+ _all_filenames(args), config['files'], config['exclude'],
297
+ )
298
+ retval = 0
299
+ prior_diff = _get_diff()
300
+ for hook in hooks:
301
+ current_retval, prior_diff = _run_single_hook(
302
+ classifier, hook, skips, cols, prior_diff,
303
+ verbose=args.verbose, use_color=args.color,
304
+ is_tool=is_tool, extra_args=extra_args,
305
+ )
306
+ retval |= current_retval
307
+ fail_fast = (config['fail_fast'] or hook.fail_fast or args.fail_fast)
308
+ if current_retval and fail_fast:
309
+ break
310
+ if retval and args.show_diff_on_failure and prior_diff:
311
+ if args.all_files:
312
+ output.write_line(
313
+ 'pre-commit hook(s) made changes.\n'
314
+ 'If you are seeing this message in CI, '
315
+ 'reproduce locally with: `pre-commit run --all-files`.\n'
316
+ 'To run `pre-commit` as part of git workflow, use '
317
+ '`pre-commit install`.',
318
+ )
319
+ output.write_line('All changes made by hooks:')
320
+ # args.color is a boolean.
321
+ # See user_color function in color.py
322
+ git_color_opt = 'always' if args.color else 'never'
323
+ subprocess.call((
324
+ 'git', '--no-pager', 'diff', '--no-ext-diff',
325
+ f'--color={git_color_opt}',
326
+ ))
327
+
328
+ return retval
329
+
330
+
331
+ def _has_unmerged_paths() -> bool:
332
+ _, stdout, _ = cmd_output_b('git', 'ls-files', '--unmerged')
333
+ return bool(stdout.strip())
334
+
335
+
336
+ def _has_unstaged_config(config_file: str) -> bool:
337
+ retcode, _, _ = cmd_output_b(
338
+ 'git', 'diff', '--quiet', '--no-ext-diff', config_file, check=False,
339
+ )
340
+ # be explicit, other git errors don't mean it has an unstaged config.
341
+ return retcode == 1
342
+
343
+
344
+ def run(
345
+ config_file: str,
346
+ store: Store,
347
+ args: argparse.Namespace,
348
+ environ: MutableMapping[str, str] = os.environ,
349
+ ) -> int:
350
+ extra_args = getattr(args, 'extra_args', [])
351
+ is_tool = getattr(args, 'tool', False)
352
+
353
+ if extra_args and not is_tool:
354
+ logger.error('`--` args require `--tool`.')
355
+ return 1
356
+
357
+ if is_tool:
358
+ if not args.hook:
359
+ logger.error('`--tool` requires a specific hook id.')
360
+ return 1
361
+ args.all_files = True
362
+ args.hook_stage = 'manual'
363
+
364
+ stash = not args.all_files and not args.files
365
+
366
+ # Check if we have unresolved merge conflict files and fail fast.
367
+ if stash and _has_unmerged_paths():
368
+ logger.error('Unmerged files. Resolve before committing.')
369
+ return 1
370
+ if bool(args.from_ref) != bool(args.to_ref):
371
+ logger.error('Specify both --from-ref and --to-ref.')
372
+ return 1
373
+ if stash and _has_unstaged_config(config_file):
374
+ logger.error(
375
+ f'Your pre-commit configuration is unstaged.\n'
376
+ f'`git add {config_file}` to fix this.',
377
+ )
378
+ return 1
379
+ if (
380
+ args.hook_stage in {'prepare-commit-msg', 'commit-msg'} and
381
+ not args.commit_msg_filename
382
+ ):
383
+ logger.error(
384
+ f'`--commit-msg-filename` is required for '
385
+ f'`--hook-stage {args.hook_stage}`',
386
+ )
387
+ return 1
388
+ # prevent recursive post-checkout hooks (#1418)
389
+ if (
390
+ args.hook_stage == 'post-checkout' and
391
+ environ.get('_PRE_COMMIT_SKIP_POST_CHECKOUT')
392
+ ):
393
+ return 0
394
+
395
+ # Expose prepare_commit_message_source / commit_object_name
396
+ # as environment variables for the hooks
397
+ if args.prepare_commit_message_source:
398
+ environ['PRE_COMMIT_COMMIT_MSG_SOURCE'] = (
399
+ args.prepare_commit_message_source
400
+ )
401
+
402
+ if args.commit_object_name:
403
+ environ['PRE_COMMIT_COMMIT_OBJECT_NAME'] = args.commit_object_name
404
+
405
+ # Expose from-ref / to-ref as environment variables for hooks to consume
406
+ if args.from_ref and args.to_ref:
407
+ # legacy names
408
+ environ['PRE_COMMIT_ORIGIN'] = args.from_ref
409
+ environ['PRE_COMMIT_SOURCE'] = args.to_ref
410
+ # new names
411
+ environ['PRE_COMMIT_FROM_REF'] = args.from_ref
412
+ environ['PRE_COMMIT_TO_REF'] = args.to_ref
413
+
414
+ if args.pre_rebase_upstream and args.pre_rebase_branch:
415
+ environ['PRE_COMMIT_PRE_REBASE_UPSTREAM'] = args.pre_rebase_upstream
416
+ environ['PRE_COMMIT_PRE_REBASE_BRANCH'] = args.pre_rebase_branch
417
+
418
+ if (
419
+ args.remote_name and args.remote_url and
420
+ args.remote_branch and args.local_branch
421
+ ):
422
+ environ['PRE_COMMIT_LOCAL_BRANCH'] = args.local_branch
423
+ environ['PRE_COMMIT_REMOTE_BRANCH'] = args.remote_branch
424
+ environ['PRE_COMMIT_REMOTE_NAME'] = args.remote_name
425
+ environ['PRE_COMMIT_REMOTE_URL'] = args.remote_url
426
+
427
+ if args.checkout_type:
428
+ environ['PRE_COMMIT_CHECKOUT_TYPE'] = args.checkout_type
429
+
430
+ if args.is_squash_merge:
431
+ environ['PRE_COMMIT_IS_SQUASH_MERGE'] = args.is_squash_merge
432
+
433
+ if args.rewrite_command:
434
+ environ['PRE_COMMIT_REWRITE_COMMAND'] = args.rewrite_command
435
+
436
+ # Set pre_commit flag
437
+ environ['PRE_COMMIT'] = '1'
438
+
439
+ with contextlib.ExitStack() as exit_stack:
440
+ if stash:
441
+ exit_stack.enter_context(staged_files_only(store.directory))
442
+
443
+ config = load_config(config_file)
444
+ hooks = [
445
+ hook
446
+ for hook in all_hooks(config, store)
447
+ if not args.hook or hook.id == args.hook or hook.alias == args.hook
448
+ if args.hook_stage in hook.stages
449
+ ]
450
+
451
+ if args.hook and not hooks:
452
+ output.write_line(
453
+ f'No hook with id `{args.hook}` in stage `{args.hook_stage}`',
454
+ )
455
+ return 1
456
+
457
+ if is_tool:
458
+ hooks = [hook._replace(always_run=True) for hook in hooks]
459
+
460
+ skips = _get_skips(environ)
461
+ to_install = [
462
+ hook
463
+ for hook in hooks
464
+ if hook.id not in skips and hook.alias not in skips
465
+ ]
466
+ install_hook_envs(to_install, store)
467
+
468
+ return _run_hooks(
469
+ config, hooks, skips, args,
470
+ is_tool=is_tool, extra_args=extra_args,
471
+ )
472
+
473
+ # https://github.com/python/mypy/issues/7726
474
+ raise AssertionError('unreachable')
@@ -0,0 +1,18 @@
1
+ from __future__ import annotations
2
+ SAMPLE_CONFIG = '''\
3
+ # See https://pre-commit.com for more information
4
+ # See https://pre-commit.com/hooks.html for more hooks
5
+ repos:
6
+ - repo: https://github.com/pre-commit/pre-commit-hooks
7
+ rev: v3.2.0
8
+ hooks:
9
+ - id: trailing-whitespace
10
+ - id: end-of-file-fixer
11
+ - id: check-yaml
12
+ - id: check-added-large-files
13
+ '''
14
+
15
+
16
+ def sample_config() -> int:
17
+ print(SAMPLE_CONFIG, end='')
18
+ return 0
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import logging
5
+ import os.path
6
+ import tempfile
7
+
8
+ import pre_commit.constants as C
9
+ from pre_commit import git
10
+ from pre_commit import output
11
+ from pre_commit.clientlib import load_manifest
12
+ from pre_commit.commands.run import run
13
+ from pre_commit.store import Store
14
+ from pre_commit.util import cmd_output_b
15
+ from pre_commit.xargs import xargs
16
+ from pre_commit.yaml import yaml_dump
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def _repo_ref(tmpdir: str, repo: str, ref: str | None) -> tuple[str, str]:
22
+ # if `ref` is explicitly passed, use it
23
+ if ref is not None:
24
+ return repo, ref
25
+
26
+ ref = git.head_rev(repo)
27
+ # if it exists on disk, we'll try and clone it with the local changes
28
+ if os.path.exists(repo) and git.has_diff('HEAD', repo=repo):
29
+ logger.warning('Creating temporary repo with uncommitted changes...')
30
+
31
+ shadow = os.path.join(tmpdir, 'shadow-repo')
32
+ cmd_output_b('git', 'clone', repo, shadow)
33
+ cmd_output_b('git', 'checkout', ref, '-b', '_pc_tmp', cwd=shadow)
34
+
35
+ idx = git.git_path('index', repo=shadow)
36
+ objs = git.git_path('objects', repo=shadow)
37
+ env = dict(os.environ, GIT_INDEX_FILE=idx, GIT_OBJECT_DIRECTORY=objs)
38
+
39
+ staged_files = git.get_staged_files(cwd=repo)
40
+ if staged_files:
41
+ xargs(('git', 'add', '--'), staged_files, cwd=repo, env=env)
42
+
43
+ cmd_output_b('git', 'add', '-u', cwd=repo, env=env)
44
+ git.commit(repo=shadow)
45
+
46
+ return shadow, git.head_rev(shadow)
47
+ else:
48
+ return repo, ref
49
+
50
+
51
+ def try_repo(args: argparse.Namespace) -> int:
52
+ with tempfile.TemporaryDirectory() as tempdir:
53
+ repo, ref = _repo_ref(tempdir, args.repo, args.ref)
54
+
55
+ store = Store(tempdir)
56
+ if args.hook:
57
+ hooks = [{'id': args.hook}]
58
+ else:
59
+ repo_path = store.clone(repo, ref)
60
+ manifest = load_manifest(os.path.join(repo_path, C.MANIFEST_FILE))
61
+ manifest = sorted(manifest, key=lambda hook: hook['id'])
62
+ hooks = [{'id': hook['id']} for hook in manifest]
63
+
64
+ config = {'repos': [{'repo': repo, 'rev': ref, 'hooks': hooks}]}
65
+ config_s = yaml_dump(config)
66
+
67
+ config_filename = os.path.join(tempdir, C.CONFIG_FILE)
68
+ with open(config_filename, 'w') as cfg:
69
+ cfg.write(config_s)
70
+
71
+ output.write_line('=' * 79)
72
+ output.write_line('Using config:')
73
+ output.write_line('=' * 79)
74
+ output.write(config_s)
75
+ output.write_line('=' * 79)
76
+
77
+ return run(config_filename, store, args)
@@ -0,0 +1,18 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+
5
+ from pre_commit import clientlib
6
+
7
+
8
+ def validate_config(filenames: Sequence[str]) -> int:
9
+ ret = 0
10
+
11
+ for filename in filenames:
12
+ try:
13
+ clientlib.load_config(filename)
14
+ except clientlib.InvalidConfigError as e:
15
+ print(e)
16
+ ret = 1
17
+
18
+ return ret
@@ -0,0 +1,18 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+
5
+ from pre_commit import clientlib
6
+
7
+
8
+ def validate_manifest(filenames: Sequence[str]) -> int:
9
+ ret = 0
10
+
11
+ for filename in filenames:
12
+ try:
13
+ clientlib.load_manifest(filename)
14
+ except clientlib.InvalidManifestError as e:
15
+ print(e)
16
+ ret = 1
17
+
18
+ return ret
@@ -0,0 +1,13 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib.metadata
4
+
5
+ CONFIG_FILE = '.pre-commit-config.yaml'
6
+ MANIFEST_FILE = '.pre-commit-hooks.yaml'
7
+
8
+ # Bump when modifying `empty_template`
9
+ LOCAL_REPO_VERSION = '1'
10
+
11
+ VERSION = importlib.metadata.version('pre_commit_ex')
12
+
13
+ DEFAULT = 'default'
@@ -0,0 +1,62 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import enum
5
+ import os
6
+ from collections.abc import Generator
7
+ from collections.abc import MutableMapping
8
+ from typing import NamedTuple
9
+ from typing import Union
10
+
11
+ _Unset = enum.Enum('_Unset', 'UNSET')
12
+ UNSET = _Unset.UNSET
13
+
14
+
15
+ class Var(NamedTuple):
16
+ name: str
17
+ default: str = ''
18
+
19
+
20
+ SubstitutionT = tuple[Union[str, Var], ...]
21
+ ValueT = Union[str, _Unset, SubstitutionT]
22
+ PatchesT = tuple[tuple[str, ValueT], ...]
23
+
24
+
25
+ def format_env(parts: SubstitutionT, env: MutableMapping[str, str]) -> str:
26
+ return ''.join(
27
+ env.get(part.name, part.default) if isinstance(part, Var) else part
28
+ for part in parts
29
+ )
30
+
31
+
32
+ @contextlib.contextmanager
33
+ def envcontext(
34
+ patch: PatchesT,
35
+ _env: MutableMapping[str, str] | None = None,
36
+ ) -> Generator[None]:
37
+ """In this context, `os.environ` is modified according to `patch`.
38
+
39
+ `patch` is an iterable of 2-tuples (key, value):
40
+ `key`: string
41
+ `value`:
42
+ - string: `environ[key] == value` inside the context.
43
+ - UNSET: `key not in environ` inside the context.
44
+ - template: A template is a tuple of strings and Var which will be
45
+ replaced with the previous environment
46
+ """
47
+ env = os.environ if _env is None else _env
48
+ before = dict(env)
49
+
50
+ for k, v in patch:
51
+ if v is UNSET:
52
+ env.pop(k, None)
53
+ elif isinstance(v, tuple):
54
+ env[k] = format_env(v, before)
55
+ else:
56
+ env[k] = v
57
+
58
+ try:
59
+ yield
60
+ finally:
61
+ env.clear()
62
+ env.update(before)