Repository navigation
Expand file tree
/
Copy path_common.py
More file actions
149 lines (119 loc) · 5.66 KB
/
Copy path_common.py
File metadata and controls
149 lines (119 loc) · 5.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""Helpers shared by the hooks."""
import os
import re
import subprocess
import sys
from ctrlweb_pre_commit_hooks._masking import mask
LANGUAGE_EXTENSIONS = {
'php': ('.php',),
'js': ('.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts'),
}
# A unified diff hunk header, e.g. "@@ -10,5 +12,7 @@", capturing the new start line
_HUNK_HEADER = re.compile(r'^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@')
def split(value, separator='|'):
"""Split a pipe-separated argument into a tuple of non-empty, stripped items."""
return tuple(item.strip() for item in value.split(separator) if item.strip())
# Lookbehinds restricting a call pattern to global function calls, by language
_GLOBAL_CALL = {
# Not a method or static call ($pdo->exec(), Foo::system()), nor a function definition
'php': r'(?<!->)(?<!::)(?<!function )(?<!function &)',
# Not a method call (regex.exec()), except on the global object (window.eval())
'js': r'(?:(?<!\.)|(?<=\bwindow\.)|(?<=\bglobalThis\.)|(?<=\bself\.))',
# Other languages: not a method or static call, nor a function definition
None: r'(?<!\.)(?<!->)(?<!::)(?<!function )(?<!def )',
}
def call_pattern(name, global_only=False, language=None):
"""Compile a regex matching a call to the function `name`.
The name is taken literally (the "." in console.log isn't a wildcard) and must not
follow a letter, digit, "_" or "$": `dd` doesn't match `add(`, `eval` doesn't match
`literal_eval(` or `$eval(`, while `->dd(` and `\\dd(` still match.
With `global_only`, method calls, static calls and function definitions in `language`
don't match either.
"""
lookbehind = r'(?<![\w$])' + (_GLOBAL_CALL[language] if global_only else '')
return re.compile(lookbehind + re.escape(name) + r'\s*\(')
def configure_stdout():
"""Never crash when printing a flagged line: on Windows, piped stdout uses the ANSI code page."""
if hasattr(sys.stdout, 'reconfigure'):
sys.stdout.reconfigure(errors='backslashreplace')
def language_of(path):
"""The language of a file from its extension: "php", "js" or None."""
extension = os.path.splitext(path)[1].lower()
for language, extensions in LANGUAGE_EXTENSIONS.items():
if extension in extensions:
return language
return None
def _git(*args):
"""Run git and return its raw output, or None if it fails."""
try:
result = subprocess.run(
['git', *args],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True,
)
except subprocess.CalledProcessError:
return None
return result.stdout
def _pre_commit_refs():
"""(from, to) refs when pre-commit runs with --from-ref/--to-ref (e.g. in CI), else None."""
from_ref = os.environ.get('PRE_COMMIT_FROM_REF')
to_ref = os.environ.get('PRE_COMMIT_TO_REF')
return (from_ref, to_ref) if from_ref and to_ref else None
def read_committed(path):
"""The text of the file as it will be committed, or None for missing and binary files.
That's the staged version, or the --to-ref version when pre-commit runs with refs.
Files that aren't valid UTF-8 (e.g. latin-1 legacy code) are decoded with replacements.
"""
refs = _pre_commit_refs()
data = _git('show', f'{refs[1] if refs else ""}:{path}')
if data is None:
print(f"Warning: Could not retrieve file {path}. Skipping.")
return None
if b'\0' in data: # Binary file
return None
return data.decode('utf-8', errors='replace')
def modified_line_numbers(path):
"""Line numbers of the lines added or modified in the staged changes of the file.
When pre-commit runs with --from-ref/--to-ref, the changes between those refs are used.
"""
refs = _pre_commit_refs()
diff_range = [f'{refs[0]}...{refs[1]}'] if refs else ['--cached']
# These flags make the output independent of the user's git config (colors, external
# diff tools, textconv); --unified=0 leaves only hunk headers and added/removed lines.
data = _git('diff', '--no-color', '--no-ext-diff', '--no-textconv', '--unified=0', *diff_range, '--', path)
if data is None:
print(f"Warning: Could not retrieve diff for {path}. Skipping.")
return set()
line_numbers = set()
line_num = None # None until the first hunk, to skip the "diff", "---" and "+++" file headers
for line in data.decode('utf-8', errors='replace').split('\n'):
hunk = _HUNK_HEADER.match(line)
if hunk:
line_num = int(hunk.group(1))
elif line_num is not None and line.startswith('+'):
line_numbers.add(line_num)
line_num += 1
# Removed lines ("-") and "\ No newline at end of file" markers aren't in the new file
return line_numbers
def find_calls(text, patterns, language, only_lines=None):
"""(line number, stripped line) for each line where one of `patterns` matches code.
Comments and strings are ignored. With `only_lines`, other lines aren't reported.
"""
found = []
lines = zip(text.split('\n'), mask(text, language).split('\n'))
for line_num, (line, code) in enumerate(lines, start=1):
if only_lines is not None and line_num not in only_lines:
continue
if any(pattern.search(code) for pattern in patterns):
found.append((line_num, line.strip()))
return found
def report(found, label):
"""Print the (path, line number, line) items found and return the hook's exit code."""
if not found:
return 0
s = 's' if len(found) > 1 else ''
print(f"Found {label}{s} in the following file{s}:")
for path, line_num, line in found:
print(f" - '{path}:{line_num}' - {line}")
return 1