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
pre_commit/main.py ADDED
@@ -0,0 +1,472 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import logging
5
+ import os
6
+ import sys
7
+ from collections.abc import Sequence
8
+
9
+ import pre_commit.constants as C
10
+ from pre_commit import clientlib
11
+ from pre_commit import git
12
+ from pre_commit.color import add_color_option
13
+ from pre_commit.commands import hazmat
14
+ from pre_commit.commands.autoupdate import autoupdate
15
+ from pre_commit.commands.clean import clean
16
+ from pre_commit.commands.gc import gc
17
+ from pre_commit.commands.hook_impl import hook_impl
18
+ from pre_commit.commands.init_templatedir import init_templatedir
19
+ from pre_commit.commands.install_uninstall import install
20
+ from pre_commit.commands.install_uninstall import install_hooks
21
+ from pre_commit.commands.install_uninstall import uninstall
22
+ from pre_commit.commands.migrate_config import migrate_config
23
+ from pre_commit.commands.run import run
24
+ from pre_commit.commands.sample_config import sample_config
25
+ from pre_commit.commands.try_repo import try_repo
26
+ from pre_commit.commands.validate_config import validate_config
27
+ from pre_commit.commands.validate_manifest import validate_manifest
28
+ from pre_commit.error_handler import error_handler
29
+ from pre_commit.logging_handler import logging_handler
30
+ from pre_commit.store import Store
31
+
32
+
33
+ logger = logging.getLogger('pre_commit')
34
+
35
+ # https://github.com/pre-commit/pre-commit/issues/217
36
+ # On OSX, making a virtualenv using pyvenv at . causes `virtualenv` and `pip`
37
+ # to install packages to the wrong place. We don't want anything to deal with
38
+ # pyvenv
39
+ os.environ.pop('__PYVENV_LAUNCHER__', None)
40
+
41
+ # https://github.com/getsentry/snuba/pull/5388
42
+ os.environ.pop('PYTHONEXECUTABLE', None)
43
+
44
+ COMMANDS_NO_GIT = {
45
+ 'clean', 'gc', 'hazmat', 'init-templatedir', 'sample-config',
46
+ 'validate-config', 'validate-manifest',
47
+ }
48
+
49
+
50
+ def _add_config_option(parser: argparse.ArgumentParser) -> None:
51
+ parser.add_argument(
52
+ '-c', '--config', default=C.CONFIG_FILE,
53
+ help='Path to alternate config file',
54
+ )
55
+
56
+
57
+ def _add_hook_type_option(parser: argparse.ArgumentParser) -> None:
58
+ parser.add_argument(
59
+ '-t', '--hook-type',
60
+ choices=clientlib.HOOK_TYPES, action='append', dest='hook_types',
61
+ )
62
+
63
+
64
+ def _add_run_options(parser: argparse.ArgumentParser) -> None:
65
+ parser.add_argument('hook', nargs='?', help='A single hook-id to run')
66
+ parser.add_argument('--verbose', '-v', action='store_true')
67
+ mutex_group = parser.add_mutually_exclusive_group(required=False)
68
+ mutex_group.add_argument(
69
+ '--all-files', '-a', action='store_true',
70
+ help='Run on all the files in the repo.',
71
+ )
72
+ mutex_group.add_argument(
73
+ '--files', nargs='*', default=[],
74
+ help='Specific filenames to run hooks on.',
75
+ )
76
+ parser.add_argument(
77
+ '--show-diff-on-failure', action='store_true',
78
+ help='When hooks fail, run `git diff` directly afterward.',
79
+ )
80
+ parser.add_argument(
81
+ '--fail-fast', action='store_true',
82
+ help='Stop after the first failing hook.',
83
+ )
84
+ parser.add_argument(
85
+ '--hook-stage',
86
+ choices=clientlib.STAGES,
87
+ type=clientlib.transform_stage,
88
+ default='pre-commit',
89
+ help='The stage during which the hook is fired. One of %(choices)s',
90
+ )
91
+ parser.add_argument(
92
+ '--remote-branch', help='Remote branch ref used by `git push`.',
93
+ )
94
+ parser.add_argument(
95
+ '--local-branch', help='Local branch ref used by `git push`.',
96
+ )
97
+ parser.add_argument(
98
+ '--from-ref', '--source', '-s',
99
+ help=(
100
+ '(for usage with `--to-ref`) -- this option represents the '
101
+ 'original ref in a `from_ref...to_ref` diff expression. '
102
+ 'For `pre-push` hooks, this represents the branch you are pushing '
103
+ 'to. '
104
+ 'For `post-checkout` hooks, this represents the branch that was '
105
+ 'previously checked out.'
106
+ ),
107
+ )
108
+ parser.add_argument(
109
+ '--to-ref', '--origin', '-o',
110
+ help=(
111
+ '(for usage with `--from-ref`) -- this option represents the '
112
+ 'destination ref in a `from_ref...to_ref` diff expression. '
113
+ 'For `pre-push` hooks, this represents the branch being pushed. '
114
+ 'For `post-checkout` hooks, this represents the branch that is '
115
+ 'now checked out.'
116
+ ),
117
+ )
118
+ parser.add_argument(
119
+ '--pre-rebase-upstream', help=(
120
+ 'The upstream from which the series was forked.'
121
+ ),
122
+ )
123
+ parser.add_argument(
124
+ '--pre-rebase-branch', help=(
125
+ 'The branch being rebased, and is not set when '
126
+ 'rebasing the current branch.'
127
+ ),
128
+ )
129
+ parser.add_argument(
130
+ '--commit-msg-filename',
131
+ help='Filename to check when running during `commit-msg`',
132
+ )
133
+ parser.add_argument(
134
+ '--prepare-commit-message-source',
135
+ help=(
136
+ 'Source of the commit message '
137
+ '(typically the second argument to .git/hooks/prepare-commit-msg)'
138
+ ),
139
+ )
140
+ parser.add_argument(
141
+ '--commit-object-name',
142
+ help=(
143
+ 'Commit object name '
144
+ '(typically the third argument to .git/hooks/prepare-commit-msg)'
145
+ ),
146
+ )
147
+ parser.add_argument(
148
+ '--remote-name', help='Remote name used by `git push`.',
149
+ )
150
+ parser.add_argument('--remote-url', help='Remote url used by `git push`.')
151
+ parser.add_argument(
152
+ '--checkout-type',
153
+ help=(
154
+ 'Indicates whether the checkout was a branch checkout '
155
+ '(changing branches, flag=1) or a file checkout (retrieving a '
156
+ 'file from the index, flag=0).'
157
+ ),
158
+ )
159
+ parser.add_argument(
160
+ '--is-squash-merge',
161
+ help=(
162
+ 'During a post-merge hook, indicates whether the merge was a '
163
+ 'squash merge'
164
+ ),
165
+ )
166
+ parser.add_argument(
167
+ '--rewrite-command',
168
+ help=(
169
+ 'During a post-rewrite hook, specifies the command that invoked '
170
+ 'the rewrite'
171
+ ),
172
+ )
173
+
174
+
175
+ def _adjust_args_and_chdir(args: argparse.Namespace) -> None:
176
+ # `--config` was specified relative to the non-root working directory
177
+ if os.path.exists(args.config):
178
+ args.config = os.path.abspath(args.config)
179
+ if args.command in {'run', 'try-repo'}:
180
+ args.files = [os.path.abspath(filename) for filename in args.files]
181
+ if args.commit_msg_filename is not None:
182
+ args.commit_msg_filename = os.path.abspath(
183
+ args.commit_msg_filename,
184
+ )
185
+ if args.command == 'try-repo' and os.path.exists(args.repo):
186
+ args.repo = os.path.abspath(args.repo)
187
+
188
+ toplevel = git.get_root()
189
+ os.chdir(toplevel)
190
+
191
+ args.config = os.path.relpath(args.config)
192
+ if args.command in {'run', 'try-repo'}:
193
+ args.files = [os.path.relpath(filename) for filename in args.files]
194
+ if args.commit_msg_filename is not None:
195
+ args.commit_msg_filename = os.path.relpath(
196
+ args.commit_msg_filename,
197
+ )
198
+ if args.command == 'try-repo' and os.path.exists(args.repo):
199
+ args.repo = os.path.relpath(args.repo)
200
+
201
+
202
+ def main(argv: Sequence[str] | None = None) -> int:
203
+ argv = argv if argv is not None else sys.argv[1:]
204
+ parser = argparse.ArgumentParser(prog='pre-commit')
205
+
206
+ # https://stackoverflow.com/a/8521644/812183
207
+ parser.add_argument(
208
+ '-V', '--version',
209
+ action='version',
210
+ version=f'%(prog)s {C.VERSION}',
211
+ )
212
+
213
+ subparsers = parser.add_subparsers(dest='command')
214
+
215
+ def _add_cmd(name: str, *, help: str) -> argparse.ArgumentParser:
216
+ parser = subparsers.add_parser(name, help=help)
217
+ add_color_option(parser)
218
+ return parser
219
+
220
+ autoupdate_parser = _add_cmd(
221
+ 'autoupdate',
222
+ help="Auto-update pre-commit config to the latest repos' versions.",
223
+ )
224
+ _add_config_option(autoupdate_parser)
225
+ autoupdate_parser.add_argument(
226
+ '--bleeding-edge', action='store_true',
227
+ help=(
228
+ 'Update to the bleeding edge of `HEAD` instead of the latest '
229
+ 'tagged version (the default behavior).'
230
+ ),
231
+ )
232
+ autoupdate_parser.add_argument(
233
+ '--freeze', action='store_true',
234
+ help='Store "frozen" hashes in `rev` instead of tag names',
235
+ )
236
+ autoupdate_parser.add_argument(
237
+ '--repo', dest='repos', action='append', metavar='REPO', default=[],
238
+ help='Only update this repository -- may be specified multiple times.',
239
+ )
240
+ autoupdate_parser.add_argument(
241
+ '-j', '--jobs', type=int, default=1,
242
+ help='Number of threads to use. (default %(default)s).',
243
+ )
244
+
245
+ _add_cmd('clean', help='Clean out pre-commit files.')
246
+
247
+ _add_cmd('gc', help='Clean unused cached repos.')
248
+
249
+ hazmat_parser = _add_cmd(
250
+ 'hazmat', help='Composable tools for rare use in hook `entry`.',
251
+ )
252
+ hazmat.add_parsers(hazmat_parser)
253
+
254
+ init_templatedir_parser = _add_cmd(
255
+ 'init-templatedir',
256
+ help=(
257
+ 'Install hook script in a directory intended for use with '
258
+ '`git config init.templateDir`.'
259
+ ),
260
+ )
261
+ _add_config_option(init_templatedir_parser)
262
+ init_templatedir_parser.add_argument(
263
+ 'directory', help='The directory in which to write the hook script.',
264
+ )
265
+ init_templatedir_parser.add_argument(
266
+ '--no-allow-missing-config',
267
+ action='store_false',
268
+ dest='allow_missing_config',
269
+ help='Assume cloned repos should have a `pre-commit` config.',
270
+ )
271
+ _add_hook_type_option(init_templatedir_parser)
272
+
273
+ install_parser = _add_cmd('install', help='Install the pre-commit script.')
274
+ _add_config_option(install_parser)
275
+ install_parser.add_argument(
276
+ '-f', '--overwrite', action='store_true',
277
+ help='Overwrite existing hooks / remove migration mode.',
278
+ )
279
+ install_parser.add_argument(
280
+ '--install-hooks', action='store_true',
281
+ help=(
282
+ 'Whether to install hook environments for all environments '
283
+ 'in the config file.'
284
+ ),
285
+ )
286
+ _add_hook_type_option(install_parser)
287
+ install_parser.add_argument(
288
+ '--allow-missing-config', action='store_true',
289
+ help=(
290
+ 'Whether to allow a missing `pre-commit` configuration file '
291
+ 'or exit with a failure code.'
292
+ ),
293
+ )
294
+
295
+ install_hooks_parser = _add_cmd(
296
+ 'install-hooks',
297
+ help=(
298
+ 'Install hook environments for all environments in the config '
299
+ 'file. You may find `pre-commit install --install-hooks` more '
300
+ 'useful.'
301
+ ),
302
+ )
303
+ _add_config_option(install_hooks_parser)
304
+
305
+ migrate_config_parser = _add_cmd(
306
+ 'migrate-config',
307
+ help='Migrate list configuration to new map configuration.',
308
+ )
309
+ _add_config_option(migrate_config_parser)
310
+
311
+ run_parser = _add_cmd('run', help='Run hooks.')
312
+ _add_config_option(run_parser)
313
+ _add_run_options(run_parser)
314
+ run_parser.add_argument(
315
+ '--tool', action='store_true',
316
+ help='Run as a tool: ignores config args, implies --all-files. '
317
+ 'Pass tool args after --.',
318
+ )
319
+
320
+ _add_cmd('sample-config', help=f'Produce a sample {C.CONFIG_FILE} file')
321
+
322
+ try_repo_parser = _add_cmd(
323
+ 'try-repo',
324
+ help='Try the hooks in a repository, useful for developing new hooks.',
325
+ )
326
+ _add_config_option(try_repo_parser)
327
+ try_repo_parser.add_argument(
328
+ 'repo', help='Repository to source hooks from.',
329
+ )
330
+ try_repo_parser.add_argument(
331
+ '--ref', '--rev',
332
+ help=(
333
+ 'Manually select a rev to run against, otherwise the `HEAD` '
334
+ 'revision will be used.'
335
+ ),
336
+ )
337
+ _add_run_options(try_repo_parser)
338
+
339
+ uninstall_parser = _add_cmd(
340
+ 'uninstall', help='Uninstall the pre-commit script.',
341
+ )
342
+ _add_config_option(uninstall_parser)
343
+ _add_hook_type_option(uninstall_parser)
344
+
345
+ validate_config_parser = _add_cmd(
346
+ 'validate-config', help='Validate .pre-commit-config.yaml files',
347
+ )
348
+ validate_config_parser.add_argument('filenames', nargs='*')
349
+
350
+ validate_manifest_parser = _add_cmd(
351
+ 'validate-manifest', help='Validate .pre-commit-hooks.yaml files',
352
+ )
353
+ validate_manifest_parser.add_argument('filenames', nargs='*')
354
+
355
+ # does not use `_add_cmd` because it doesn't use `--color`
356
+ help = subparsers.add_parser(
357
+ 'help', help='Show help for a specific command.',
358
+ )
359
+ help.add_argument('help_cmd', nargs='?', help='Command to show help for.')
360
+
361
+ # not intended for users to call this directly
362
+ hook_impl_parser = subparsers.add_parser('hook-impl')
363
+ add_color_option(hook_impl_parser)
364
+ _add_config_option(hook_impl_parser)
365
+ hook_impl_parser.add_argument('--hook-type')
366
+ hook_impl_parser.add_argument('--hook-dir')
367
+ hook_impl_parser.add_argument(
368
+ '--skip-on-missing-config', action='store_true',
369
+ )
370
+ hook_impl_parser.add_argument(dest='rest', nargs=argparse.REMAINDER)
371
+
372
+ # argparse doesn't really provide a way to use a `default` subparser
373
+ if len(argv) == 0:
374
+ argv = ['run']
375
+
376
+ # split off extra args after `--` for --tool mode (run command only)
377
+ extra_args: list[str] = []
378
+ argv = list(argv)
379
+ if argv and argv[0] == 'run':
380
+ try:
381
+ sep_idx = argv.index('--')
382
+ extra_args = argv[sep_idx + 1:]
383
+ argv = argv[:sep_idx]
384
+ except ValueError:
385
+ pass
386
+
387
+ args = parser.parse_args(argv)
388
+ args.extra_args = extra_args
389
+
390
+ if args.command == 'help' and args.help_cmd:
391
+ parser.parse_args([args.help_cmd, '--help'])
392
+ elif args.command == 'help':
393
+ parser.parse_args(['--help'])
394
+
395
+ with error_handler(), logging_handler(args.color):
396
+ git.check_for_cygwin_mismatch()
397
+
398
+ store = Store()
399
+
400
+ if args.command not in COMMANDS_NO_GIT:
401
+ _adjust_args_and_chdir(args)
402
+ store.mark_config_used(args.config)
403
+
404
+ if args.command == 'autoupdate':
405
+ return autoupdate(
406
+ args.config,
407
+ tags_only=not args.bleeding_edge,
408
+ freeze=args.freeze,
409
+ repos=args.repos,
410
+ jobs=args.jobs,
411
+ )
412
+ elif args.command == 'clean':
413
+ return clean(store)
414
+ elif args.command == 'gc':
415
+ return gc(store)
416
+ elif args.command == 'hazmat':
417
+ return hazmat.impl(args)
418
+ elif args.command == 'hook-impl':
419
+ return hook_impl(
420
+ store,
421
+ config=args.config,
422
+ color=args.color,
423
+ hook_type=args.hook_type,
424
+ hook_dir=args.hook_dir,
425
+ skip_on_missing_config=args.skip_on_missing_config,
426
+ args=args.rest[1:],
427
+ )
428
+ elif args.command == 'install':
429
+ return install(
430
+ args.config, store,
431
+ hook_types=args.hook_types,
432
+ overwrite=args.overwrite,
433
+ hooks=args.install_hooks,
434
+ skip_on_missing_config=args.allow_missing_config,
435
+ )
436
+ elif args.command == 'init-templatedir':
437
+ return init_templatedir(
438
+ args.config, store, args.directory,
439
+ hook_types=args.hook_types,
440
+ skip_on_missing_config=args.allow_missing_config,
441
+ )
442
+ elif args.command == 'install-hooks':
443
+ return install_hooks(args.config, store)
444
+ elif args.command == 'migrate-config':
445
+ return migrate_config(args.config)
446
+ elif args.command == 'run':
447
+ return run(args.config, store, args)
448
+ elif args.command == 'sample-config':
449
+ return sample_config()
450
+ elif args.command == 'try-repo':
451
+ return try_repo(args)
452
+ elif args.command == 'uninstall':
453
+ return uninstall(
454
+ config_file=args.config,
455
+ hook_types=args.hook_types,
456
+ )
457
+ elif args.command == 'validate-config':
458
+ return validate_config(args.filenames)
459
+ elif args.command == 'validate-manifest':
460
+ return validate_manifest(args.filenames)
461
+ else:
462
+ raise NotImplementedError(
463
+ f'Command {args.command} not implemented.',
464
+ )
465
+
466
+ raise AssertionError(
467
+ f'Command {args.command} failed to exit with a returncode',
468
+ )
469
+
470
+
471
+ if __name__ == '__main__':
472
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ from collections.abc import Sequence
5
+
6
+ import pre_commit.constants as C
7
+ from pre_commit import git
8
+ from pre_commit.clientlib import load_config
9
+ from pre_commit.commands.run import Classifier
10
+ from pre_commit.repository import all_hooks
11
+ from pre_commit.store import Store
12
+
13
+
14
+ def check_all_hooks_match_files(config_file: str) -> int:
15
+ config = load_config(config_file)
16
+ classifier = Classifier.from_config(
17
+ git.get_all_files(), config['files'], config['exclude'],
18
+ )
19
+ retv = 0
20
+
21
+ for hook in all_hooks(config, Store()):
22
+ if hook.always_run or hook.language == 'fail':
23
+ continue
24
+ elif not any(classifier.filenames_for_hook(hook)):
25
+ print(f'{hook.id} does not apply to this repository')
26
+ retv = 1
27
+
28
+ return retv
29
+
30
+
31
+ def main(argv: Sequence[str] | None = None) -> int:
32
+ parser = argparse.ArgumentParser()
33
+ parser.add_argument('filenames', nargs='*', default=[C.CONFIG_FILE])
34
+ args = parser.parse_args(argv)
35
+
36
+ retv = 0
37
+ for filename in args.filenames:
38
+ retv |= check_all_hooks_match_files(filename)
39
+ return retv
40
+
41
+
42
+ if __name__ == '__main__':
43
+ raise SystemExit(main())
@@ -0,0 +1,83 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import re
5
+ from collections.abc import Iterable
6
+ from collections.abc import Sequence
7
+
8
+ from cfgv import apply_defaults
9
+
10
+ import pre_commit.constants as C
11
+ from pre_commit import git
12
+ from pre_commit.clientlib import load_config
13
+ from pre_commit.clientlib import MANIFEST_HOOK_DICT
14
+ from pre_commit.commands.run import Classifier
15
+
16
+
17
+ def exclude_matches_any(
18
+ filenames: Iterable[str],
19
+ include: str,
20
+ exclude: str,
21
+ ) -> bool:
22
+ if exclude == '^$':
23
+ return True
24
+ include_re, exclude_re = re.compile(include), re.compile(exclude)
25
+ for filename in filenames:
26
+ if include_re.search(filename) and exclude_re.search(filename):
27
+ return True
28
+ return False
29
+
30
+
31
+ def check_useless_excludes(config_file: str) -> int:
32
+ config = load_config(config_file)
33
+ filenames = git.get_all_files()
34
+ classifier = Classifier.from_config(
35
+ filenames, config['files'], config['exclude'],
36
+ )
37
+ retv = 0
38
+
39
+ exclude = config['exclude']
40
+ if not exclude_matches_any(filenames, '', exclude):
41
+ print(
42
+ f'The global exclude pattern {exclude!r} does not match any files',
43
+ )
44
+ retv = 1
45
+
46
+ for repo in config['repos']:
47
+ for hook in repo['hooks']:
48
+ # the default of manifest hooks is `types: [file]` but we may
49
+ # be configuring a symlink hook while there's a broken symlink
50
+ hook.setdefault('types', [])
51
+ # Not actually a manifest dict, but this more accurately reflects
52
+ # the defaults applied during runtime
53
+ hook = apply_defaults(hook, MANIFEST_HOOK_DICT)
54
+ names = classifier.by_types(
55
+ classifier.filenames,
56
+ hook['types'],
57
+ hook['types_or'],
58
+ hook['exclude_types'],
59
+ )
60
+ include, exclude = hook['files'], hook['exclude']
61
+ if not exclude_matches_any(names, include, exclude):
62
+ print(
63
+ f'The exclude pattern {exclude!r} for {hook["id"]} does '
64
+ f'not match any files',
65
+ )
66
+ retv = 1
67
+
68
+ return retv
69
+
70
+
71
+ def main(argv: Sequence[str] | None = None) -> int:
72
+ parser = argparse.ArgumentParser()
73
+ parser.add_argument('filenames', nargs='*', default=[C.CONFIG_FILE])
74
+ args = parser.parse_args(argv)
75
+
76
+ retv = 0
77
+ for filename in args.filenames:
78
+ retv |= check_useless_excludes(filename)
79
+ return retv
80
+
81
+
82
+ if __name__ == '__main__':
83
+ raise SystemExit(main())
@@ -0,0 +1,17 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from collections.abc import Sequence
5
+
6
+ from pre_commit import output
7
+
8
+
9
+ def main(argv: Sequence[str] | None = None) -> int:
10
+ argv = argv if argv is not None else sys.argv[1:]
11
+ for arg in argv:
12
+ output.write_line(arg)
13
+ return 0
14
+
15
+
16
+ if __name__ == '__main__':
17
+ raise SystemExit(main())
pre_commit/output.py ADDED
@@ -0,0 +1,33 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import sys
5
+ from typing import Any
6
+ from typing import IO
7
+
8
+
9
+ def write(s: str, stream: IO[bytes] = sys.stdout.buffer) -> None:
10
+ stream.write(s.encode())
11
+ stream.flush()
12
+
13
+
14
+ def write_line_b(
15
+ s: bytes | None = None,
16
+ stream: IO[bytes] = sys.stdout.buffer,
17
+ logfile_name: str | None = None,
18
+ ) -> None:
19
+ with contextlib.ExitStack() as exit_stack:
20
+ output_streams = [stream]
21
+ if logfile_name:
22
+ stream = exit_stack.enter_context(open(logfile_name, 'ab'))
23
+ output_streams.append(stream)
24
+
25
+ for output_stream in output_streams:
26
+ if s is not None:
27
+ output_stream.write(s)
28
+ output_stream.write(b'\n')
29
+ output_stream.flush()
30
+
31
+
32
+ def write_line(s: str | None = None, **kwargs: Any) -> None:
33
+ write_line_b(s.encode() if s is not None else s, **kwargs)