gitbills 0.1.2__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.
gitbills/diff.py ADDED
@@ -0,0 +1,268 @@
1
+ """Unified diff parsing shared by the security scan, the slop heuristics and the AGENTS.md policy check (src/diff.js).
2
+
3
+ Hunks are read by their declared line counts, so a changed line that looks like a header is still a changed line.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import re
8
+
9
+ from .text import decode_utf8, js_len, utf16_key
10
+
11
+ MAX_DIFF_BYTES = 1_048_576
12
+ _A = re.ASCII
13
+ _HUNK_RE = re.compile(r'^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@', _A)
14
+ _HEADER_PAIR_RE = re.compile(r'^("(?:\\[^\n]|[^"\\])*"|a/[^\n]*?) ("(?:\\[^\n]|[^"\\])*"|b/[^\n]*)$', _A)
15
+ _QUOTED_RE = re.compile(r'^"((?:\\[^\n]|[^"\\])*)"(?:\t[^\n]*)?$', _A)
16
+ _RAW_BREAK_RE = re.compile('[\r\u2028\u2029]')
17
+ _META_RE = re.compile(r'^(?:index |similarity index |dissimilarity index |old mode |new mode |new file mode |'
18
+ r'deleted file mode |copy from |copy to |rename from |rename to )', _A)
19
+ _MODE_RE = re.compile(r'^(new file mode|deleted file mode|old mode|new mode) ([0-7]{6})$', _A)
20
+ _INDEX_MODE_RE = re.compile(r' ([0-7]{6})$', _A)
21
+ _BINARY_RE = re.compile(r'^Binary files [^\n]{1,4096} differ$', _A)
22
+ _OCT_RE = re.compile(r'^[0-7]{1,3}', _A)
23
+ _GIT_ESCAPES = {'a': 7, 'b': 8, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13, '"': 34, '\\': 92}
24
+ _MAX_PROBLEMS = 16
25
+ _UNDEFINED = object()
26
+
27
+
28
+ def unquote_path(raw: str, strip: bool = True):
29
+ """A path from a diff header: git's C-quoting undone (octal bytes read as UTF-8), a/ or b/ dropped.
30
+
31
+ None for /dev/null; the _UNDEFINED sentinel for a malformed path.
32
+ """
33
+ s = raw
34
+ if s.startswith('"'):
35
+ m = _QUOTED_RE.match(s)
36
+ if not m:
37
+ return _UNDEFINED
38
+ out = bytearray()
39
+ c = m.group(1)
40
+ i = 0
41
+ while i < len(c):
42
+ if c[i] != '\\':
43
+ out += c[i].encode('utf-8', 'surrogatepass')
44
+ i += 1
45
+ continue
46
+ oct_m = _OCT_RE.match(c[i + 1:i + 4])
47
+ if oct_m:
48
+ out.append(int(oct_m.group(0), 8) & 0xFF)
49
+ i += 1 + len(oct_m.group(0))
50
+ continue
51
+ e = c[i + 1] if i + 1 < len(c) else ''
52
+ if e not in _GIT_ESCAPES:
53
+ return _UNDEFINED
54
+ out.append(_GIT_ESCAPES[e])
55
+ i += 2
56
+ s = decode_utf8(bytes(out))
57
+ else:
58
+ tab = s.find('\t')
59
+ if tab >= 0:
60
+ s = s[:tab]
61
+ if s == '/dev/null':
62
+ return None
63
+ if strip and (s.startswith('a/') or s.startswith('b/')):
64
+ s = s[2:]
65
+ return s if s else _UNDEFINED
66
+
67
+
68
+ def _new_file(old_path=None, new_path=None):
69
+ return {'oldPath': old_path, 'newPath': new_path, 'path': None, 'isNew': False, 'isDeleted': False,
70
+ 'isBinary': False, 'renamedFrom': None, 'oldMode': None, 'newMode': None, 'sawOld': False,
71
+ 'sawNew': False, 'hunks': 0, 'added': [], 'removed': [], 'context': []}
72
+
73
+
74
+ def parse_diff(text) -> dict:
75
+ """Parse a unified diff (git diff or diff -u). Never raises."""
76
+ lines = ('' if text is None else str(text)).split('\n')
77
+ files: list = []
78
+ problems: list = []
79
+ st = {'file': None, 'hunk': None, 'binary': False, 'added': 0, 'removed': 0}
80
+
81
+ def problem(kind, line):
82
+ if len(problems) < _MAX_PROBLEMS:
83
+ problems.append({'kind': kind, 'line': line})
84
+
85
+ def start():
86
+ f = _new_file()
87
+ files.append(f)
88
+ st['file'], st['hunk'], st['binary'] = f, None, False
89
+ return f
90
+
91
+ def set_path(side, raw, line, strip=True):
92
+ p = unquote_path(raw, strip)
93
+ if p is _UNDEFINED:
94
+ problem('malformed_path', line)
95
+ else:
96
+ st['file'][side] = p
97
+ return p
98
+
99
+ def add_line(text_line, new_line, diff_line):
100
+ st['added'] += 1
101
+ st['file']['added'].append({'text': text_line, 'line': new_line, 'diffLine': diff_line})
102
+
103
+ n_lines = len(lines)
104
+ for i, raw in enumerate(lines):
105
+ line = raw[:-1] if raw.endswith('\r') else raw
106
+ dl = i + 1
107
+ hunk, file = st['hunk'], st['file']
108
+ if hunk and (hunk['oldRem'] > 0 or hunk['newRem'] > 0):
109
+ c = line[:1]
110
+ if c == '+':
111
+ add_line(line[1:], hunk['next'], dl)
112
+ hunk['next'] += 1
113
+ hunk['newRem'] -= 1
114
+ continue
115
+ if c == '-':
116
+ st['removed'] += 1
117
+ file['removed'].append(line[1:])
118
+ hunk['oldRem'] -= 1
119
+ continue
120
+ if c == ' ' or (line == '' and i < n_lines - 1):
121
+ file['context'].append({'text': line[1:], 'line': hunk['next']})
122
+ hunk['oldRem'] -= 1
123
+ hunk['newRem'] -= 1
124
+ hunk['next'] += 1
125
+ continue
126
+ if line.startswith('\\'):
127
+ continue
128
+ problem('hunk_count_mismatch', dl)
129
+ st['hunk'] = None
130
+ if line.startswith('\\'):
131
+ continue
132
+ if line.startswith('diff --git '):
133
+ header = line[11:]
134
+ pair = _HEADER_PAIR_RE.match(header) if js_len(header) <= 4096 and not _RAW_BREAK_RE.search(header) else None
135
+ start()
136
+ if pair:
137
+ set_path('oldPath', pair.group(1), dl)
138
+ set_path('newPath', pair.group(2), dl)
139
+ else:
140
+ problem('malformed_header', dl)
141
+ continue
142
+ if st['binary']:
143
+ continue
144
+ file = st['file']
145
+ if line.startswith('@@'):
146
+ m = _HUNK_RE.match(line)
147
+ if not m:
148
+ problem('malformed_hunk', dl)
149
+ st['hunk'] = None
150
+ continue
151
+ if not file:
152
+ file = start()
153
+ problem('missing_file_header', dl)
154
+ file['hunks'] += 1
155
+ st['hunk'] = {'oldRem': 1 if m.group(2) is None else int(m.group(2)),
156
+ 'newRem': 1 if m.group(4) is None else int(m.group(4)), 'next': int(m.group(3))}
157
+ continue
158
+ if line.startswith('--- ') and (lines[i + 1] if i + 1 < n_lines else '').startswith('+++ '):
159
+ if not file or file['sawOld'] or file['hunks'] > 0:
160
+ file = start()
161
+ p = set_path('oldPath', line[4:], dl)
162
+ file['sawOld'] = True
163
+ if p is None:
164
+ file['isNew'] = True
165
+ continue
166
+ if line.startswith('+++ ') and file and file['sawOld'] and not file['sawNew'] and file['hunks'] == 0:
167
+ p = set_path('newPath', line[4:], dl)
168
+ file['sawNew'] = True
169
+ if p is None:
170
+ file['isDeleted'] = True
171
+ continue
172
+ if file and file['hunks'] == 0 and _META_RE.match(line):
173
+ mode = _MODE_RE.match(line)
174
+ if mode:
175
+ kind, value = mode.group(1), mode.group(2)
176
+ if kind == 'new file mode':
177
+ file['isNew'], file['newMode'] = True, value
178
+ elif kind == 'deleted file mode':
179
+ file['isDeleted'], file['oldMode'] = True, value
180
+ elif kind == 'old mode':
181
+ file['oldMode'] = value
182
+ else:
183
+ file['newMode'] = value
184
+ elif line.startswith('index '):
185
+ idx = _INDEX_MODE_RE.search(line)
186
+ if idx and file['newMode'] is None:
187
+ file['newMode'] = idx.group(1)
188
+ elif line.startswith('rename from ') or line.startswith('copy from '):
189
+ p = set_path('oldPath', re.sub(r'^(?:rename|copy) from ', '', line, count=1), dl, False)
190
+ if line.startswith('rename') and isinstance(p, str):
191
+ file['renamedFrom'] = p
192
+ elif line.startswith('rename to ') or line.startswith('copy to '):
193
+ set_path('newPath', re.sub(r'^(?:rename|copy) to ', '', line, count=1), dl, False)
194
+ continue
195
+ if file and (line == 'GIT binary patch' or _BINARY_RE.match(line)):
196
+ file['isBinary'] = True
197
+ st['binary'] = line == 'GIT binary patch'
198
+ continue
199
+ if line.startswith('Submodule '):
200
+ continue
201
+ if line == '' and i == n_lines - 1:
202
+ continue
203
+ if line.startswith('+') and file:
204
+ problem('change_outside_hunk', dl)
205
+ add_line(line[1:], None, dl)
206
+ continue
207
+ if line.startswith('-') and file:
208
+ problem('change_outside_hunk', dl)
209
+ st['removed'] += 1
210
+ file['removed'].append(line[1:])
211
+ continue
212
+ if line and file:
213
+ problem('malformed_line', dl)
214
+ hunk = st['hunk']
215
+ if hunk and (hunk['oldRem'] > 0 or hunk['newRem'] > 0):
216
+ problem('hunk_count_mismatch', n_lines)
217
+ for f in files:
218
+ f['path'] = f['newPath'] if f['newPath'] is not None else f['oldPath']
219
+ paths = sorted({f['path'] for f in files if isinstance(f['path'], str)}, key=utf16_key)
220
+ return {'files': files, 'paths': paths, 'linesAdded': st['added'], 'linesRemoved': st['removed'], 'problems': problems}
221
+
222
+
223
+ _TEST_PATH_RE = re.compile(r'(?:^|/)(?:tests?|__tests__|specs?|e2e|fixtures?|testdata)/|'
224
+ r'(?:\.test\.|\.spec\.|_test\.|(?:^|/)test_)[^/]*\Z', re.I | _A)
225
+ _DOC_PATH_RE = re.compile(r'\.(?:md|mdx|markdown|rst|txt|adoc)$|(?:^|/)docs?/', re.I | _A)
226
+ _WORKFLOW_PATH_RE = re.compile(r'(?:^|/)\.github/workflows/[^/]+\.ya?ml\Z|(?:^|/)action\.ya?ml\Z', re.I | _A)
227
+ _PACKAGE_RE = re.compile(r'(?:^|/)package\.json\Z', _A)
228
+ _PY_RE = re.compile(r'\.py\Z', re.I | _A)
229
+ _JS_RE = re.compile(r'\.[cm]?[jt]sx?\Z', re.I | _A)
230
+
231
+
232
+ def is_test_path(p) -> bool:
233
+ return bool(_TEST_PATH_RE.search(p or ''))
234
+
235
+
236
+ def is_doc_path(p) -> bool:
237
+ return bool(_DOC_PATH_RE.search(p or ''))
238
+
239
+
240
+ def is_workflow_path(p) -> bool:
241
+ return bool(_WORKFLOW_PATH_RE.search(p or ''))
242
+
243
+
244
+ def is_package_json_path(p) -> bool:
245
+ return bool(_PACKAGE_RE.search(p or ''))
246
+
247
+
248
+ def is_python_path(p) -> bool:
249
+ return bool(_PY_RE.search(p or ''))
250
+
251
+
252
+ def is_js_path(p) -> bool:
253
+ return bool(_JS_RE.search(p or ''))
254
+
255
+
256
+ _DRIVE_RE = re.compile(r'^[A-Za-z]:', _A)
257
+ _CTRL_RE = re.compile(r'[\x00-\x1f\x7f]', _A)
258
+ _DOTGIT_RE = re.compile(r'^\.git[. ]*\Z', re.I | _A)
259
+ _GIT8_RE = re.compile(r'^git~1(?:\.|$)', re.I | _A)
260
+
261
+
262
+ def is_unsafe_path(p) -> bool:
263
+ """A path that escapes the repository or writes into .git."""
264
+ if not isinstance(p, str) or not p:
265
+ return True
266
+ if p.startswith('/') or '\\' in p or _DRIVE_RE.search(p) or _CTRL_RE.search(p):
267
+ return True
268
+ return any(not seg or seg in ('.', '..') or _DOTGIT_RE.search(seg) or _GIT8_RE.search(seg) for seg in p.split('/'))