pre-commit-bigfix 2.0.1__tar.gz → 2.1.1__tar.gz

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 (45) hide show
  1. {pre_commit_bigfix-2.0.1/pre_commit_bigfix.egg-info → pre_commit_bigfix-2.1.1}/PKG-INFO +14 -2
  2. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/README.md +13 -1
  3. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/__init__.py +1 -1
  4. pre_commit_bigfix-2.1.1/pre_commit_bigfix/run_all.py +581 -0
  5. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1/pre_commit_bigfix.egg-info}/PKG-INFO +14 -2
  6. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_run_all.py +363 -0
  7. pre_commit_bigfix-2.0.1/pre_commit_bigfix/run_all.py +0 -305
  8. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/LICENSE +0 -0
  9. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/MANIFEST.in +0 -0
  10. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/bes_actionscript_lint_schclass.py +0 -0
  11. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/bes_actionscript_validate_prefetch.py +0 -0
  12. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/bes_actionscript_validate_script.py +0 -0
  13. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/bes_common.py +0 -0
  14. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/bes_conventions_check.py +0 -0
  15. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/bes_relevance_convert_group.py +0 -0
  16. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/bes_relevance_lint.py +0 -0
  17. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/bes_schema_validate.py +0 -0
  18. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/bes_siterepo_validate_layout.py +0 -0
  19. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/schclass.py +0 -0
  20. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/schclass_data/ExpandedActionScript.schclass +0 -0
  21. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/schclass_data/bigfix_overrides.schclass +0 -0
  22. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix/schclass_tokenizer.py +0 -0
  23. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix.egg-info/SOURCES.txt +0 -0
  24. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix.egg-info/dependency_links.txt +0 -0
  25. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix.egg-info/entry_points.txt +0 -0
  26. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix.egg-info/requires.txt +0 -0
  27. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pre_commit_bigfix.egg-info/top_level.txt +0 -0
  28. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/pyproject.toml +0 -0
  29. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/setup.cfg +0 -0
  30. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/setup.py +0 -0
  31. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_bes_actionscript_lint_schclass.py +0 -0
  32. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_bes_actionscript_validate_prefetch.py +0 -0
  33. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_bes_actionscript_validate_script.py +0 -0
  34. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_bes_common.py +0 -0
  35. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_bes_conventions_check.py +0 -0
  36. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_bes_relevance_convert_group.py +0 -0
  37. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_bes_relevance_lint.py +0 -0
  38. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_bes_schema_validate.py +0 -0
  39. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_bes_siterepo_validate_layout.py +0 -0
  40. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_hook_declarations.py +0 -0
  41. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_package_metadata.py +0 -0
  42. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_release_workflow.py +0 -0
  43. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_schclass.py +0 -0
  44. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_schclass_tokenizer.py +0 -0
  45. {pre_commit_bigfix-2.0.1 → pre_commit_bigfix-2.1.1}/tests/test_schema_guard.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pre-commit-bigfix
3
- Version: 2.0.1
3
+ Version: 2.1.1
4
4
  Summary: pre-commit hooks for BigFix content
5
5
  Home-page: https://github.com/jgstew/pre-commit-bigfix
6
6
  Author: JGStew
@@ -90,7 +90,19 @@ line per hook is printed at the end. The exit code is 1 if any hook fails, and
90
90
  - Symlinked files found while searching are skipped, as pre-commit skips
91
91
  them. A file named on the command line that no hook checks is reported.
92
92
  - `bes-siterepo-validate-layout` runs once in each git repo that holds a given
93
- path, and is skipped when none does.
93
+ path, and is skipped when none does. It is also skipped, and not counted
94
+ as a failure, in a repo that shows no sign of being a site: git tracks no
95
+ `site.xml` or `siteConfig.xml` file and no `Fixlets`, `NonClientFiles` or
96
+ `OtherFiles` folder at its top (names compared ignoring case).
97
+ - A hook with more than 20 results is summarized instead of listed: a count
98
+ per code, and the files with the most results. The summary table at the end
99
+ shows each hook's result count. If anything was summarized and no log file
100
+ is being written, the last line says to run again with `--log-file`.
101
+ - `--log-file [FILE]` writes every hook's full output to FILE (default
102
+ `pre-commit-bigfix-results.log`), replacing it if it exists. This is the
103
+ only file the command writes, and it will not replace a given path or a
104
+ file some hook checks. Give paths to check before `--log-file`, or use
105
+ `--log-file=FILE`, so a path is not taken as FILE.
94
106
  - `--skip HOOK` (repeatable) leaves a hook out.
95
107
 
96
108
  ## Hooks
@@ -58,7 +58,19 @@ line per hook is printed at the end. The exit code is 1 if any hook fails, and
58
58
  - Symlinked files found while searching are skipped, as pre-commit skips
59
59
  them. A file named on the command line that no hook checks is reported.
60
60
  - `bes-siterepo-validate-layout` runs once in each git repo that holds a given
61
- path, and is skipped when none does.
61
+ path, and is skipped when none does. It is also skipped, and not counted
62
+ as a failure, in a repo that shows no sign of being a site: git tracks no
63
+ `site.xml` or `siteConfig.xml` file and no `Fixlets`, `NonClientFiles` or
64
+ `OtherFiles` folder at its top (names compared ignoring case).
65
+ - A hook with more than 20 results is summarized instead of listed: a count
66
+ per code, and the files with the most results. The summary table at the end
67
+ shows each hook's result count. If anything was summarized and no log file
68
+ is being written, the last line says to run again with `--log-file`.
69
+ - `--log-file [FILE]` writes every hook's full output to FILE (default
70
+ `pre-commit-bigfix-results.log`), replacing it if it exists. This is the
71
+ only file the command writes, and it will not replace a given path or a
72
+ file some hook checks. Give paths to check before `--log-file`, or use
73
+ `--log-file=FILE`, so a path is not taken as FILE.
62
74
  - `--skip HOOK` (repeatable) leaves a hook out.
63
75
 
64
76
  ## Hooks
@@ -1,3 +1,3 @@
1
1
  """To support running this directly as a python module."""
2
2
 
3
- __version__ = "2.0.1"
3
+ __version__ = "2.1.1"
@@ -0,0 +1,581 @@
1
+ #!/usr/bin/env python3
2
+ """Run every pre-commit-bigfix hook over a folder, without pre-commit.
3
+
4
+ uvx pre-commit-bigfix [PATH ...]
5
+
6
+ This is the `pre-commit-bigfix` command. It finds the files under each PATH
7
+ (default: the current folder), gives each hook the ones its `files` pattern in
8
+ .pre-commit-hooks.yaml matches, with that hook's default `args`, and prints a
9
+ pass/fail line per hook. The exit code is 1 when any hook fails, and 2 for
10
+ a PATH that does not exist or a bad option.
11
+
12
+ It is read-only. Run by pre-commit, several hooks fix files in place by
13
+ default; here each one is told not to (--auto-fix=no, or --check for the
14
+ hooks that convert or rename), so fixable problems are reported instead.
15
+ To apply the fixes, run the hook itself, or use pre-commit.
16
+
17
+ Hidden folders (a name starting with `.`, or the hidden flag on macOS and
18
+ Windows) are not searched unless --include-hidden is given, and __pycache__
19
+ and node_modules never are; a PATH that names a folder is searched anyway.
20
+ Symlinked files found while searching are skipped, as pre-commit skips them.
21
+ A named file that no hook checks is reported on stderr.
22
+
23
+ bes-siterepo-validate-layout checks a whole repo from `git ls-files`, so it
24
+ runs once in each git repo that holds a PATH, and is skipped when none does.
25
+ It is also skipped in a repo that shows no sign of being a site: git tracks
26
+ no site.xml or siteConfig.xml file and no Fixlets, NonClientFiles or
27
+ OtherFiles folder at its top (names compared ignoring case).
28
+
29
+ A hook that reports more than 20 results (`path:line: message` or
30
+ `path: message` lines) has them summarized, counted by code and by file,
31
+ instead of listed; with no --log-file, the last line of the run then says
32
+ how to get them all. --log-file writes the full output of every hook to FILE
33
+ (default pre-commit-bigfix-results.log), replacing it if it exists; that is
34
+ the only file this command writes. It will not replace a PATH or a file some
35
+ hook checks. Give PATHs before --log-file, or use --log-file=FILE, so a PATH
36
+ is not taken as FILE.
37
+
38
+ A hook with no matching files is skipped rather than run with no file names:
39
+ run that way, most hooks would search the current folder themselves.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import argparse
45
+ import contextlib
46
+ import importlib
47
+ import io
48
+ import os
49
+ import re
50
+ import stat
51
+ import subprocess
52
+ import sys
53
+ import traceback
54
+ from collections import Counter
55
+ from typing import NamedTuple
56
+
57
+ from . import bes_common
58
+
59
+
60
+ class Hook(NamedTuple):
61
+ """One hook from .pre-commit-hooks.yaml, as the runner calls it."""
62
+
63
+ id: str
64
+ module: str # in this package; its main(argv) is the console script
65
+ files: str | None # the hook's `files` regex; None: it lists its own
66
+ args: tuple[str, ...] = () # the hook's default `args`
67
+ read_only: tuple[str, ...] = () # what keeps it from writing
68
+
69
+ def load(self):
70
+ """Import the hook's module (only when it runs, as some are heavy)."""
71
+ return importlib.import_module(f"{__package__}.{self.module}")
72
+
73
+
74
+ # Same order, ids, `files` and `args` as .pre-commit-hooks.yaml (minus aliases);
75
+ # tests/test_run_all.py keeps the two in step.
76
+ HOOKS = (
77
+ Hook(
78
+ "bes-schema-validate",
79
+ "bes_schema_validate",
80
+ r"\.(bes|ojo)$|(^|/)(siteConfig|site|digest)\.xml$"
81
+ r"|(^|/)Signatures/[^/]+\.xml$",
82
+ ),
83
+ Hook(
84
+ "bes-conventions-check",
85
+ "bes_conventions_check",
86
+ r"\.bes$",
87
+ read_only=("--auto-fix=no",),
88
+ ),
89
+ Hook(
90
+ "bes-actionscript-lint-schclass",
91
+ "bes_actionscript_lint_schclass",
92
+ r"\.bes$",
93
+ read_only=("--auto-fix=no",),
94
+ ),
95
+ Hook(
96
+ "bes-actionscript-validate-prefetch",
97
+ "bes_actionscript_validate_prefetch",
98
+ r"\.bes$",
99
+ # --auto-fix-network is already off by default; say so anyway
100
+ read_only=("--auto-fix=no", "--auto-fix-network=no"),
101
+ ),
102
+ Hook(
103
+ "bes-actionscript-validate-script",
104
+ "bes_actionscript_validate_script",
105
+ r"\.bes$",
106
+ read_only=("--auto-fix=no",),
107
+ ),
108
+ Hook(
109
+ "bes-relevance-lint",
110
+ "bes_relevance_lint",
111
+ r"\.(bes|bes\.xml|ojo|besrpt|beswrpt|webreport|bsr|rel)$",
112
+ args=("--disable", "W601"),
113
+ ),
114
+ Hook(
115
+ "bes-relevance-convert-group",
116
+ "bes_relevance_convert_group",
117
+ r"\.bes$",
118
+ read_only=("--check",),
119
+ ),
120
+ Hook(
121
+ "bes-siterepo-validate-layout",
122
+ "bes_siterepo_validate_layout",
123
+ None,
124
+ read_only=("--check",),
125
+ ),
126
+ )
127
+
128
+ # any file some hook checks; anything else is not worth listing
129
+ ANY_HOOK_RE = re.compile("|".join(f"(?:{h.files})" for h in HOOKS if h.files))
130
+
131
+ # a hook with more results than this has them summarized, not listed
132
+ SUMMARY_OVER = 20
133
+ # files and folders listed in the summary, most results first
134
+ SUMMARY_TOP_FILES = 5
135
+ DEFAULT_LOG_FILE = "pre-commit-bigfix-results.log"
136
+ # the last line of a run that summarized something and wrote no log
137
+ RERUN_HINT = (
138
+ f"Run again with --log-file to write all of them to {DEFAULT_LOG_FILE}"
139
+ " (or --log-file=FILE)."
140
+ )
141
+
142
+ # one result line: `path:line: message`, maybe `[CODE] ` first; a Windows
143
+ # drive letter (C:\...) does not end the path, as `:\d+: ` must follow it
144
+ RESULT_RE = re.compile(r"^(?P<path>.+?):\d+: (?:\[(?P<code>[A-Z]+\d+)\] )?")
145
+
146
+ # a site repo's top folder holds one of these, compared lowercase. The folder
147
+ # names are bes_siterepo_validate_layout.DEFAULT_DIRS, copied so the layout
148
+ # module is only imported when it runs.
149
+ SITE_FILES = frozenset({"site.xml", "siteconfig.xml"})
150
+ SITE_DIRS = frozenset({"fixlets", "nonclientfiles", "otherfiles"})
151
+
152
+
153
+ def _is_hidden(path, name):
154
+ """True for a dot folder, or one with the macOS or Windows hidden flag."""
155
+ if name.startswith("."):
156
+ return True
157
+ try:
158
+ st = os.lstat(path)
159
+ except OSError:
160
+ return False
161
+ # st_flags exists on BSD/macOS and st_file_attributes on Windows; each
162
+ # constant is missing (so 0) on the other platforms
163
+ if getattr(st, "st_flags", 0) & getattr(stat, "UF_HIDDEN", 0):
164
+ return True
165
+ return bool(
166
+ getattr(st, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_HIDDEN", 0)
167
+ )
168
+
169
+
170
+ def _match_path(path):
171
+ """The string a hook's `files` regex is searched in.
172
+
173
+ pre-commit searches the repo-relative path, so `(^|/)Signatures/x.xml`
174
+ sees the folder. The path as given may not hold it (`x.xml`, run from
175
+ inside Signatures/), so the absolute path is used instead.
176
+ """
177
+ return os.path.abspath(path).replace(os.sep, "/")
178
+
179
+
180
+ def discover(paths, include_hidden=False):
181
+ """Return the files under `paths` that some hook checks, sorted, each once.
182
+
183
+ A file named in `paths` is kept even if no hook checks it. Folders are
184
+ walked, skipping symlinked files (pre-commit does not pass them to these
185
+ hooks), bes_common.DISCOVERY_SKIP_DIRS and, unless `include_hidden`, hidden
186
+ folders; a folder named in `paths` is walked even if it is hidden.
187
+ """
188
+ found = set()
189
+ for top in paths:
190
+ if not os.path.isdir(top):
191
+ found.add(os.path.normpath(top))
192
+ continue
193
+ for dirpath, dirnames, filenames in os.walk(top):
194
+ dirnames[:] = [
195
+ d
196
+ for d in dirnames
197
+ if d not in bes_common.DISCOVERY_SKIP_DIRS
198
+ and (include_hidden or not _is_hidden(os.path.join(dirpath, d), d))
199
+ ]
200
+ for name in filenames:
201
+ path = os.path.normpath(os.path.join(dirpath, name))
202
+ if not os.path.islink(path) and ANY_HOOK_RE.search(_match_path(path)):
203
+ found.add(path)
204
+ return sorted(found)
205
+
206
+
207
+ def repo_roots(paths):
208
+ """Return the top folders of the git repos holding `paths`, each once."""
209
+ roots = []
210
+ for path in paths:
211
+ folder = path if os.path.isdir(path) else os.path.dirname(path) or "."
212
+ try:
213
+ result = subprocess.run(
214
+ ["git", "rev-parse", "--show-toplevel"],
215
+ cwd=folder,
216
+ capture_output=True,
217
+ check=False,
218
+ )
219
+ except OSError: # git not installed
220
+ return []
221
+ root = os.fsdecode(result.stdout).strip()
222
+ if result.returncode == 0 and root and root not in roots:
223
+ roots.append(root)
224
+ return roots
225
+
226
+
227
+ def looks_like_site(root):
228
+ """True if git repo `root` tracks a site file or site folder at its top.
229
+
230
+ See SITE_FILES and SITE_DIRS. Only tracked files count, as the layout hook
231
+ sees only what `git ls-files` lists.
232
+ """
233
+ try:
234
+ result = subprocess.run(
235
+ ["git", "ls-files", "-z"], cwd=root, capture_output=True, check=False
236
+ )
237
+ except OSError: # git not installed
238
+ return False
239
+ if result.returncode:
240
+ return False
241
+ for path in os.fsdecode(result.stdout).split("\0"):
242
+ top, slash, _rest = path.partition("/")
243
+ if top.lower() in (SITE_DIRS if slash else SITE_FILES):
244
+ return True
245
+ return False
246
+
247
+
248
+ def _path_prefix(line, paths):
249
+ """The one of `paths` that `line` starts with, followed by `: `; or None."""
250
+ end = line.find(": ")
251
+ while end != -1: # a path may hold ": " itself
252
+ if line[:end] in paths:
253
+ return line[:end]
254
+ end = line.find(": ", end + 1)
255
+ return None
256
+
257
+
258
+ def split_output(text, paths=()):
259
+ """Split a hook's output into its results and its other lines.
260
+
261
+ Returns ([(path, code or None), ...], [other line, ...]). A result is a
262
+ `path:line: message` line, or `path: message` for one of the files the
263
+ hook was given (`paths`), as bes-schema-validate prints when it has no
264
+ line. The indented lines after a result (a suggested fix) belong to it;
265
+ any other line (a count such as `7 warning(s).`, a crash) is kept as is.
266
+ """
267
+ results, other = [], []
268
+ in_result = False
269
+ paths = frozenset(paths)
270
+ for line in text.splitlines():
271
+ match = RESULT_RE.match(line)
272
+ path = None if match else _path_prefix(line, paths)
273
+ if match or path:
274
+ results.append((match["path"], match["code"]) if match else (path, None))
275
+ in_result = True
276
+ elif in_result and line[:1].isspace():
277
+ continue
278
+ else:
279
+ other.append(line)
280
+ in_result = False
281
+ return results, other
282
+
283
+
284
+ def summarize(results, other, log_path):
285
+ """The text printed in place of a hook's output when it has many results."""
286
+ files = Counter(path for path, _code in results)
287
+ lines = [
288
+ (
289
+ f"{len(results)} results in {len(files)} file(s), more than"
290
+ f" {SUMMARY_OVER}, so they are summarized. By code:"
291
+ )
292
+ ]
293
+ codes = Counter(code or "(no code)" for _path, code in results)
294
+ width = max(len(code) for code in codes)
295
+ lines += [f" {code:<{width}} {n}" for code, n in codes.most_common()]
296
+ lines.append("Most results:")
297
+ lines += [f" {n:>5} {path}" for path, n in files.most_common(SUMMARY_TOP_FILES)]
298
+ lines += other
299
+ if log_path:
300
+ lines.append(f"All of them are in {log_path}.")
301
+ # with no log, main() prints RERUN_HINT once, at the very end
302
+ return "\n".join(lines) + "\n"
303
+
304
+
305
+ class _Tee:
306
+ """A text stream that writes to each of `streams`.
307
+
308
+ Not an io.TextIOBase: its __del__ would flush the streams, by then
309
+ perhaps closed (the log).
310
+ """
311
+
312
+ def __init__(self, *streams):
313
+ self.streams = streams
314
+
315
+ def write(self, text):
316
+ for stream in self.streams:
317
+ stream.write(text)
318
+ return len(text)
319
+
320
+ def flush(self):
321
+ for stream in self.streams:
322
+ stream.flush()
323
+
324
+
325
+ class Report:
326
+ """Where the output goes: stdout, and the --log-file if one is given.
327
+
328
+ The log gets every hook's full output; stdout gets it too, unless the
329
+ hook has more than SUMMARY_OVER results, when it gets summarize() instead.
330
+ """
331
+
332
+ def __init__(self, log=None, log_path=None):
333
+ self.log = log
334
+ self.log_path = log_path
335
+ self.summarized = False # some hook's output was summarized
336
+
337
+ def show(self, text):
338
+ """Write `text` to stdout only."""
339
+ sys.stdout.write(text)
340
+ sys.stdout.flush()
341
+
342
+ def write(self, text):
343
+ """Write `text` to stdout and the log."""
344
+ self.show(text)
345
+ if self.log:
346
+ self.log.write(text)
347
+
348
+ def _capture(self, hook, argv, folder):
349
+ """Run `hook` in `folder` (None: here) with stdout caught; return (code,
350
+ text).
351
+ """
352
+ caught = io.StringIO()
353
+ # stderr (warnings, a crash's traceback) is not summarized: it is
354
+ # shown as it comes, and copied to the log
355
+ err = (
356
+ contextlib.redirect_stderr(_Tee(sys.stderr, self.log))
357
+ if self.log
358
+ else contextlib.nullcontext()
359
+ )
360
+ here = os.getcwd()
361
+ try:
362
+ with contextlib.redirect_stdout(caught), err:
363
+ if folder: # a whole-repo hook finds its repo from the current folder
364
+ os.chdir(folder)
365
+ try:
366
+ code = _call(hook, argv)
367
+ finally:
368
+ os.chdir(here)
369
+ except BaseException: # Ctrl-C: _call already catches the rest
370
+ self.write(caught.getvalue()) # what the hook printed before it
371
+ raise
372
+ return code, caught.getvalue()
373
+
374
+ def run(self, hook, argv, folders=(None,), paths=()):
375
+ """Run `hook` once in each of `folders`; return (worst code, result count).
376
+
377
+ `paths` are the files the hook is given, for split_output(). Each run
378
+ goes to the log as it ends. Stdout gets each run under its own
379
+ `=== hook (folder)` line, or, when all of them together have more than
380
+ SUMMARY_OVER results, one summary of them.
381
+ """
382
+ headers = [
383
+ f"=== {hook.id}" + (f" ({folder})" if folder else "") + "\n"
384
+ for folder in folders
385
+ ]
386
+ if len(folders) == 1:
387
+ self.show(headers[0]) # before it runs, to show which hook is busy
388
+ worst, results, other, texts = 0, [], [], []
389
+ for header, folder in zip(headers, folders):
390
+ if self.log:
391
+ self.log.write(header)
392
+ code, text = self._capture(hook, argv, folder)
393
+ if self.log:
394
+ self.log.write(text)
395
+ worst = max(worst, code)
396
+ found, rest = split_output(text, paths)
397
+ results += found
398
+ other += rest
399
+ texts.append(text)
400
+ if len(results) > SUMMARY_OVER:
401
+ if len(folders) > 1:
402
+ self.show(f"=== {hook.id} ({', '.join(folders)})\n")
403
+ self.show(summarize(results, other, self.log_path))
404
+ self.summarized = True
405
+ else:
406
+ for header, text in zip(headers, texts):
407
+ self.show(text if len(folders) == 1 else header + text)
408
+ return worst, len(results)
409
+
410
+
411
+ def _call(hook, argv):
412
+ """Run `hook`'s main(argv); return its exit code, a crash counting as 1."""
413
+ try:
414
+ code = hook.load().main(argv)
415
+ except SystemExit as exc: # argparse errors, or a hook that exits
416
+ code = exc.code
417
+ except Exception: # noqa: BLE001 - one broken hook must not hide the rest
418
+ traceback.print_exc()
419
+ print(f"{hook.id}: crashed")
420
+ return 1
421
+ if code is None:
422
+ return 0
423
+ return code if isinstance(code, int) else 1
424
+
425
+
426
+ def run_hook(hook, files, roots, report=None):
427
+ """Run one hook read-only; return (status, code, result count).
428
+
429
+ A file hook gets the `files` its pattern matches; a whole-repo hook runs in
430
+ each of the git repos `roots` that looks_like_site(). status is "passed",
431
+ "failed" or "skipped: <why>".
432
+ """
433
+ report = report or Report()
434
+ if hook.files is None:
435
+ if not roots:
436
+ return "skipped: not a git repo", 0, 0
437
+ sites = [root for root in roots if looks_like_site(root)]
438
+ if not sites:
439
+ return "skipped: not a site repo", 0, 0
440
+ code, count = report.run(hook, [*hook.args, *hook.read_only], sites)
441
+ else:
442
+ pattern = re.compile(hook.files)
443
+ matched = [path for path in files if pattern.search(_match_path(path))]
444
+ if not matched:
445
+ return "skipped: no files", 0, 0
446
+ # `--` so a file named like an option (-h.bes) is still a file name
447
+ argv = [*hook.args, *hook.read_only, "--", *matched]
448
+ code, count = report.run(hook, argv, paths=matched)
449
+ return ("failed" if code else "passed"), code, count
450
+
451
+
452
+ def build_parser():
453
+ parser = argparse.ArgumentParser(
454
+ prog="pre-commit-bigfix",
455
+ description=__doc__,
456
+ formatter_class=argparse.RawDescriptionHelpFormatter,
457
+ )
458
+ parser.add_argument(
459
+ "paths",
460
+ nargs="*",
461
+ default=["."],
462
+ metavar="PATH",
463
+ help="files or folders to check (default: the current folder)",
464
+ )
465
+ parser.add_argument(
466
+ "--skip",
467
+ action="append",
468
+ default=[],
469
+ choices=[hook.id for hook in HOOKS],
470
+ metavar="HOOK",
471
+ help="a hook id not to run; repeatable",
472
+ )
473
+ parser.add_argument(
474
+ "--include-hidden",
475
+ action="store_true",
476
+ help="also search hidden folders (see above)",
477
+ )
478
+ parser.add_argument(
479
+ "--log-file",
480
+ nargs="?",
481
+ const=DEFAULT_LOG_FILE,
482
+ metavar="FILE",
483
+ help="write every hook's full output to FILE, replacing it"
484
+ f" (default FILE: {DEFAULT_LOG_FILE})",
485
+ )
486
+ return parser
487
+
488
+
489
+ def main(argv=None):
490
+ """Execution starts here; returns 1 if any hook failed, 2 for a bad PATH."""
491
+ args = build_parser().parse_args(argv)
492
+ # a file name the console cannot show (an ASCII or cp1252 console, or not
493
+ # UTF-8) is escaped rather than crash the run; the layout hook does this
494
+ # itself, but its stdout is a StringIO here
495
+ for stream in (sys.stdout, sys.stderr):
496
+ if hasattr(stream, "reconfigure"):
497
+ stream.reconfigure(errors="backslashreplace")
498
+
499
+ missing = [path for path in args.paths if not os.path.exists(path)]
500
+ if missing:
501
+ for path in missing:
502
+ print(f"pre-commit-bigfix: no such file or folder: {path}", file=sys.stderr)
503
+ return 2
504
+
505
+ files = discover(args.paths, include_hidden=args.include_hidden)
506
+ for path in args.paths:
507
+ if os.path.isfile(path) and not ANY_HOOK_RE.search(_match_path(path)):
508
+ print(f"{path}: not checked by any hook", file=sys.stderr)
509
+ roots = repo_roots(args.paths)
510
+
511
+ if not args.log_file:
512
+ report = Report()
513
+ code = _run_all(args, files, roots, report)
514
+ if report.summarized:
515
+ print(f"\n{RERUN_HINT}")
516
+ return code
517
+ if _would_replace_input(args.log_file, args.paths):
518
+ print(
519
+ f"pre-commit-bigfix: --log-file {args.log_file} is a file to check,"
520
+ " not a log; give PATHs before --log-file, or --log-file=FILE",
521
+ file=sys.stderr,
522
+ )
523
+ return 2
524
+ try:
525
+ # "w": a log from an earlier run is replaced, not added to. Not a
526
+ # `with` here, so that only open()'s own error is caught
527
+ log = open( # noqa: SIM115 - closed by the `with log:` below
528
+ args.log_file, "w", encoding="utf-8", errors="backslashreplace"
529
+ )
530
+ except OSError as exc:
531
+ print(
532
+ f"pre-commit-bigfix: cannot write {args.log_file}: {exc}",
533
+ file=sys.stderr,
534
+ )
535
+ return 2
536
+ with log:
537
+ code = _run_all(args, files, roots, Report(log, args.log_file))
538
+ print(f"Full results written to {args.log_file}")
539
+ return code
540
+
541
+
542
+ def _would_replace_input(log_file, paths):
543
+ """True if `log_file` is a file some hook checks, or one of `paths`.
544
+
545
+ --log-file FILE takes the next argument when FILE is left out, so
546
+ `--log-file x.bes` would otherwise empty x.bes before it is checked.
547
+ """
548
+ if ANY_HOOK_RE.search(_match_path(log_file)):
549
+ return True
550
+ if not os.path.exists(log_file):
551
+ return False
552
+ for path in paths:
553
+ try:
554
+ if os.path.samefile(path, log_file):
555
+ return True
556
+ except OSError:
557
+ continue
558
+ return False
559
+
560
+
561
+ def _run_all(args, files, roots, report):
562
+ """Run every hook not skipped, then write the summary table; return the exit
563
+ code.
564
+ """
565
+ results = []
566
+ for hook in HOOKS:
567
+ if hook.id in args.skip:
568
+ results.append((hook.id, "skipped: --skip", 0, 0))
569
+ continue
570
+ results.append((hook.id, *run_hook(hook, files, roots, report)))
571
+
572
+ width = max(len(hook.id) for hook in HOOKS) + 3
573
+ report.write("\n")
574
+ for hook_id, status, _code, count in results:
575
+ found = f" ({count} result{'' if count == 1 else 's'})" if count else ""
576
+ report.write(f"{hook_id} {'.' * (width - len(hook_id))} {status}{found}\n")
577
+ return 1 if any(code for _id, _status, code, _count in results) else 0
578
+
579
+
580
+ if __name__ == "__main__":
581
+ sys.exit(main(sys.argv[1:]))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pre-commit-bigfix
3
- Version: 2.0.1
3
+ Version: 2.1.1
4
4
  Summary: pre-commit hooks for BigFix content
5
5
  Home-page: https://github.com/jgstew/pre-commit-bigfix
6
6
  Author: JGStew
@@ -90,7 +90,19 @@ line per hook is printed at the end. The exit code is 1 if any hook fails, and
90
90
  - Symlinked files found while searching are skipped, as pre-commit skips
91
91
  them. A file named on the command line that no hook checks is reported.
92
92
  - `bes-siterepo-validate-layout` runs once in each git repo that holds a given
93
- path, and is skipped when none does.
93
+ path, and is skipped when none does. It is also skipped, and not counted
94
+ as a failure, in a repo that shows no sign of being a site: git tracks no
95
+ `site.xml` or `siteConfig.xml` file and no `Fixlets`, `NonClientFiles` or
96
+ `OtherFiles` folder at its top (names compared ignoring case).
97
+ - A hook with more than 20 results is summarized instead of listed: a count
98
+ per code, and the files with the most results. The summary table at the end
99
+ shows each hook's result count. If anything was summarized and no log file
100
+ is being written, the last line says to run again with `--log-file`.
101
+ - `--log-file [FILE]` writes every hook's full output to FILE (default
102
+ `pre-commit-bigfix-results.log`), replacing it if it exists. This is the
103
+ only file the command writes, and it will not replace a given path or a
104
+ file some hook checks. Give paths to check before `--log-file`, or use
105
+ `--log-file=FILE`, so a path is not taken as FILE.
94
106
  - `--skip HOOK` (repeatable) leaves a hook out.
95
107
 
96
108
  ## Hooks