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/local.py ADDED
@@ -0,0 +1,436 @@
1
+ """This machine (src/local.js): git found and run defensively, files read without following links, the origin remote.
2
+
3
+ git comes from an absolute PATH entry outside the checkout (never ./git or node_modules/.bin), runs in the checkout's
4
+ top folder without a shell, with core.fsmonitor and hooks off, no transport and no lazy fetch, external diff and textconv
5
+ drivers off, submodules as one line, the checkout's own filter drivers neutralized, and `--` after every revision list.
6
+ Its output is read up to a byte cap (the process is killed past it) within one total timeout.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ import stat
13
+ import subprocess
14
+ import sys
15
+ import threading
16
+
17
+ from .diff import MAX_DIFF_BYTES
18
+ from .policy import POLICY_MAX_BYTES
19
+ from .preflight import clean_origin, evaluate_preflight
20
+ from .text import GitBillsError, decode_utf8, fail
21
+ from .vouch import clean_repo
22
+
23
+ # No prompts, no locks, no lazy fetch, and no transport at all (GIT_ALLOW_PROTOCOL=none also holds where an older git
24
+ # ignores GIT_NO_LAZY_FETCH, and over any protocol.*.allow the checkout's config sets).
25
+ GIT_ENV = {'GIT_TERMINAL_PROMPT': '0', 'GIT_OPTIONAL_LOCKS': '0', 'GIT_NO_LAZY_FETCH': '1', 'GIT_ALLOW_PROTOCOL': 'none',
26
+ 'GIT_PAGER': 'cat', 'PAGER': 'cat'}
27
+ # Before every command: no fsmonitor, no hooks, no index refresh, and submodules as one line each (see src/local.js).
28
+ GIT_PRE = ('-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=%s' % ('//./NUL' if sys.platform == 'win32' else '/dev/null'), '-c', 'diff.autoRefreshIndex=false',
29
+ '-c', 'diff.submodule=short')
30
+ _BASE_RE = re.compile(r'^[A-Za-z0-9_@][A-Za-z0-9._/@{}~^+-]{0,254}\Z', re.ASCII)
31
+ _SHA_RE = re.compile(r'^[0-9a-f]{40,64}\Z', re.ASCII)
32
+ # The pull request's base, upstream first: after `gh repo fork --clone`, origin is the fork and upstream the base.
33
+ AUTO_BASES = ('upstream/HEAD', 'upstream/main', 'upstream/master', 'origin/HEAD', 'origin/main', 'origin/master')
34
+ _GIT_TIMEOUT_S = 60
35
+ _WIN = sys.platform == 'win32'
36
+ _REPARSE_TAGS = (0xA000000C, 0xA0000003) # IO_REPARSE_TAG_SYMLINK, IO_REPARSE_TAG_MOUNT_POINT (junction)
37
+ READ_ERRORS = {
38
+ 'missing': 'no such file',
39
+ 'symlink': 'a symbolic link or junction is not followed: pass the file itself',
40
+ 'not_regular': 'not a regular file',
41
+ 'too_large': 'the file is too large',
42
+ 'unreadable': 'the file cannot be read',
43
+ }
44
+
45
+
46
+ def _real(p):
47
+ try:
48
+ return os.path.realpath(p, strict=True)
49
+ except (OSError, ValueError):
50
+ return None
51
+
52
+
53
+ def _inside(d, root):
54
+ a, b = (d.lower(), root.lower()) if _WIN else (d, root)
55
+ try:
56
+ rel = os.path.relpath(a, b)
57
+ except ValueError:
58
+ return False
59
+ return rel == '.' or not (rel == '..' or rel.startswith('..' + os.sep) or os.path.isabs(rel))
60
+
61
+
62
+ def find_executable(name, env=None, untrusted_dirs=()):
63
+ """An executable by absolute path from PATH, skipping relative entries, folders inside untrusted_dirs and any
64
+ node_modules folder; None if none."""
65
+ env = os.environ if env is None else env
66
+ roots = [r for r in (_real(d) for d in untrusted_dirs) if r]
67
+ path_var = env.get('PATH') or env.get('Path') or env.get('path') or ''
68
+ for raw in path_var.split(os.pathsep):
69
+ d = raw.strip('"')
70
+ if not d or not os.path.isabs(d):
71
+ continue
72
+ real = _real(d)
73
+ if not real or any(seg.lower() == 'node_modules' for seg in re.split(r'[\\/]', real)) or any(_inside(real, r) for r in roots):
74
+ continue
75
+ cand = os.path.join(real, name + '.exe' if _WIN else name)
76
+ try:
77
+ if not os.path.isfile(cand) or (not _WIN and not os.access(cand, os.X_OK)):
78
+ continue
79
+ except OSError:
80
+ continue
81
+ return cand
82
+ return None
83
+
84
+
85
+ def run_git(git, args, cwd, env=None, max_bytes=4_194_304, pre=(), extra_env=None):
86
+ """{'ok': True, 'bytes'} | {'ok': False, 'over'?: True}: git with no shell, stdin closed, stderr dropped. stdout is
87
+ read in chunks and the process is killed past max_bytes or the 60-second timeout."""
88
+ full_env = dict(os.environ if env is None else env)
89
+ full_env.update(GIT_ENV)
90
+ full_env.update(extra_env or {})
91
+ try:
92
+ p = subprocess.Popen([git, *GIT_PRE, *pre, *args], cwd=cwd, env=full_env, stdin=subprocess.DEVNULL,
93
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, shell=False)
94
+ except (OSError, ValueError, subprocess.SubprocessError):
95
+ return {'ok': False}
96
+ timer = threading.Timer(_GIT_TIMEOUT_S, p.kill)
97
+ timer.daemon = True
98
+ timer.start()
99
+ chunks, n, over = [], 0, False
100
+ try:
101
+ while True:
102
+ b = p.stdout.read1(65_536)
103
+ if not b:
104
+ break
105
+ n += len(b)
106
+ if n > max_bytes:
107
+ over = True
108
+ p.kill()
109
+ break
110
+ chunks.append(b)
111
+ p.wait()
112
+ except OSError:
113
+ p.kill()
114
+ p.wait()
115
+ return {'ok': False}
116
+ finally:
117
+ timer.cancel()
118
+ p.stdout.close()
119
+ if over:
120
+ return {'ok': False, 'over': True}
121
+ if p.returncode != 0:
122
+ return {'ok': False}
123
+ return {'ok': True, 'bytes': b''.join(chunks)}
124
+
125
+
126
+ def _filter_neutralizers(git, cwd, env):
127
+ r = run_git(git, ['config', '--show-scope', '--null', '--name-only', '--get-regexp', r'^filter\.'], cwd, env, 65_536)
128
+ if not r['ok']:
129
+ return {'pre': []}
130
+ fields = decode_utf8(r['bytes']).split('\0')
131
+ names = set()
132
+ for i in range(0, len(fields) - 1, 2):
133
+ if fields[i] not in ('local', 'worktree'):
134
+ continue
135
+ m = re.match(r'^filter\.(.+)\.[^.]+\Z', fields[i + 1], re.DOTALL)
136
+ if m:
137
+ names.add(m.group(1))
138
+ if any(not re.match(r'^[A-Za-z0-9._-]{1,100}\Z', n, re.ASCII) for n in names):
139
+ return {'refuse': True}
140
+ pre = []
141
+ for n in sorted(names):
142
+ pre += ['-c', 'filter.%s.clean=' % n, '-c', 'filter.%s.smudge=' % n, '-c', 'filter.%s.process=' % n,
143
+ '-c', 'filter.%s.required=false' % n]
144
+ return {'pre': pre}
145
+
146
+
147
+ def _is_link(st):
148
+ if stat.S_ISLNK(st.st_mode):
149
+ return True
150
+ attrs = getattr(st, 'st_file_attributes', 0)
151
+ return bool(attrs & 0x400) and getattr(st, 'st_reparse_tag', 0) in _REPARSE_TAGS
152
+
153
+
154
+ def _link_below(within, file):
155
+ """Whether a folder between `within` and `file` is a link or junction (folders above `within` are the caller's)."""
156
+ top = os.path.abspath(within)
157
+ try:
158
+ rel = os.path.relpath(os.path.dirname(os.path.abspath(file)), top)
159
+ except ValueError:
160
+ return False
161
+ if rel in ('.', '..') or rel.startswith('..' + os.sep) or os.path.isabs(rel):
162
+ return False
163
+ d = top
164
+ for seg in rel.split(os.sep):
165
+ d = os.path.join(d, seg)
166
+ try:
167
+ if _is_link(os.lstat(d)):
168
+ return True
169
+ except OSError:
170
+ return True
171
+ return False
172
+
173
+
174
+ def safe_read_file(path, max_bytes, within=None):
175
+ """Read a regular file without following a symbolic link or junction: {'bytes'} or {'error'}. The file opened must
176
+ be the one looked at (same device and inode), and with `within`, no folder between it and the file may be a link."""
177
+ try:
178
+ st = os.lstat(path)
179
+ except (OSError, ValueError):
180
+ return {'error': 'missing'}
181
+ if _is_link(st):
182
+ return {'error': 'symlink'}
183
+ if not stat.S_ISREG(st.st_mode):
184
+ return {'error': 'not_regular'}
185
+ if st.st_size > max_bytes:
186
+ return {'error': 'too_large'}
187
+ if within is not None and _link_below(within, path):
188
+ return {'error': 'symlink'}
189
+ flags = os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0) | getattr(os, 'O_BINARY', 0)
190
+ try:
191
+ fd = os.open(path, flags)
192
+ except OSError:
193
+ return {'error': 'unreadable'}
194
+ try:
195
+ now = os.fstat(fd)
196
+ if not stat.S_ISREG(now.st_mode) or now.st_dev != st.st_dev or now.st_ino != st.st_ino:
197
+ return {'error': 'symlink'}
198
+ chunks, n = [], 0
199
+ while n <= max_bytes:
200
+ b = os.read(fd, min(65_536, max_bytes + 1 - n))
201
+ if not b:
202
+ break
203
+ chunks.append(b)
204
+ n += len(b)
205
+ return {'error': 'too_large'} if n > max_bytes else {'bytes': b''.join(chunks)}
206
+ except OSError:
207
+ return {'error': 'unreadable'}
208
+ finally:
209
+ os.close(fd)
210
+
211
+
212
+ def find_repo_root(start):
213
+ d = os.path.abspath(start)
214
+ for _ in range(64):
215
+ try:
216
+ os.lstat(os.path.join(d, '.git'))
217
+ return d
218
+ except OSError:
219
+ pass
220
+ up = os.path.dirname(d)
221
+ if up == d:
222
+ return None
223
+ d = up
224
+ return None
225
+
226
+
227
+ _REMOTE_RE = re.compile(r'^(?:https://(?:[^@/]+@)?github\.com/|ssh://git@github\.com(?::22)?/|git@github\.com:|git://github\.com/)'
228
+ r'([A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))/([A-Za-z0-9_.-]{1,100}?)(?:\.git)?/?\Z', re.ASCII)
229
+ _NOT_LOCAL_RE = re.compile(r'^[\\/]{2}|[?*\x00]', re.ASCII)
230
+
231
+
232
+ def _local_target(p):
233
+ """A gitdir: or commondir target that stays on this machine: never a UNC, device or other two-slash path."""
234
+ return not _NOT_LOCAL_RE.search(p) and not (_WIN and ':' in re.sub(r'^[A-Za-z]:', '', p, count=1))
235
+
236
+
237
+ def detect_github_repo(root):
238
+ """owner/repo (lowercase) of the checkout's origin remote on github.com, read from .git/config (git is not run)."""
239
+ if not root:
240
+ return None
241
+ git_dir = os.path.join(root, '.git')
242
+ dot = safe_read_file(git_dir, 4096)
243
+ if 'bytes' in dot:
244
+ m = re.match(r'^gitdir:[ \t]*([^\r\n]+)', decode_utf8(dot['bytes']))
245
+ if not m or not _local_target(m.group(1).strip()):
246
+ return None
247
+ git_dir = os.path.normpath(os.path.join(root, m.group(1).strip()))
248
+ common = safe_read_file(os.path.join(git_dir, 'commondir'), 4096)
249
+ if 'bytes' in common:
250
+ c = decode_utf8(common['bytes']).strip()
251
+ if not _local_target(c):
252
+ return None
253
+ git_dir = os.path.normpath(os.path.join(git_dir, c))
254
+ if not _local_target(git_dir):
255
+ return None
256
+ cfg = safe_read_file(os.path.join(git_dir, 'config'), 262_144)
257
+ if 'bytes' not in cfg:
258
+ return None
259
+ section = None
260
+ for raw in re.split(r'\r?\n', decode_utf8(cfg['bytes'])):
261
+ line = raw.strip()
262
+ head = re.match(r'^\[([^\]]+)\]$', line)
263
+ if head:
264
+ section = head.group(1).strip()
265
+ continue
266
+ if section != 'remote "origin"':
267
+ continue
268
+ kv = re.match(r'^url[ \t]*=[ \t]*(\S+)$', line)
269
+ if not kv:
270
+ continue
271
+ m = _REMOTE_RE.match(kv.group(1))
272
+ return ('%s/%s' % (m.group(1), m.group(2))).lower() if m else None
273
+ return None
274
+
275
+
276
+ def read_policy_file(root, file=None):
277
+ """A policy file from the working tree: the root AGENTS.md, or `file`: {'text', 'source'} (text None when absent)."""
278
+ target = file if file is not None else os.path.join(root, 'AGENTS.md')
279
+ label = file if file is not None else 'AGENTS.md'
280
+ r = safe_read_file(target, POLICY_MAX_BYTES, root if _inside(os.path.abspath(target), os.path.abspath(root)) else None)
281
+ if r.get('error') == 'missing' and file is None:
282
+ return {'text': None, 'source': None}
283
+ if 'error' in r:
284
+ return {'text': None, 'source': label, 'error': r['error']}
285
+ return {'text': decode_utf8(r['bytes']), 'source': label}
286
+
287
+
288
+ def repo_path(root, file):
289
+ """The repository path (a/b, forward slashes) of a file inside `root`; None outside it."""
290
+ if not root or not _inside(os.path.abspath(file), os.path.abspath(root)):
291
+ return None
292
+ rel = os.path.relpath(os.path.abspath(file), os.path.abspath(root)).replace(os.sep, '/')
293
+ return None if rel == '.' else rel
294
+
295
+
296
+ def _read_tree_file(git, cwd, env, pre, rev, file, max_bytes, label):
297
+ """A regular file as commit `rev` holds it (never a link or a submodule)."""
298
+ ls = run_git(git, ['ls-tree', '-z', '--full-tree', rev, '--', file], cwd, env, 65_536, pre)
299
+ if not ls['ok']:
300
+ return {'error': 'unreadable', 'source': label}
301
+ entry = decode_utf8(ls['bytes']).split('\0')[0]
302
+ if not entry:
303
+ return {'text': None, 'source': None}
304
+ parts = entry.split('\t')[0].split(' ')
305
+ mode, kind, sha = (parts + ['', '', ''])[:3]
306
+ if mode == '120000':
307
+ return {'error': 'symlink', 'source': label}
308
+ if kind != 'blob' or not _SHA_RE.match(sha):
309
+ return {'error': 'not_regular', 'source': label}
310
+ size = run_git(git, ['cat-file', '-s', sha], cwd, env, 64, pre)
311
+ text = decode_utf8(size['bytes']).strip() if size['ok'] else ''
312
+ if not re.match(r'^[0-9]{1,15}\Z', text, re.ASCII):
313
+ return {'error': 'unreadable', 'source': label}
314
+ if int(text) > max_bytes:
315
+ return {'error': 'too_large', 'source': label}
316
+ blob = run_git(git, ['cat-file', 'blob', sha], cwd, env, max_bytes, pre)
317
+ if not blob['ok']:
318
+ return {'error': 'too_large' if blob.get('over') else 'unreadable', 'source': label}
319
+ return {'text': decode_utf8(blob['bytes']), 'source': label}
320
+
321
+
322
+ def collect_git_diff(cwd, base=None, env=None, max_bytes=MAX_DIFF_BYTES, policy=False):
323
+ """The diff a pull request from this checkout would carry (see src/local.js collectGitDiff)."""
324
+ env = os.environ if env is None else env
325
+ root = find_repo_root(cwd) or cwd
326
+ git = find_executable('git', env, (cwd, root, os.getcwd()))
327
+ if not git:
328
+ return {'error': 'git was not found on PATH (outside this checkout): pass --diff FILE, or - for standard input'}
329
+ neut = _filter_neutralizers(git, root, env)
330
+ if neut.get('refuse'):
331
+ return {'error': "this checkout's git config names a filter driver that cannot be switched off: pass --diff FILE"}
332
+ pre = neut['pre']
333
+
334
+ def rev(ref):
335
+ r = run_git(git, ['rev-parse', '--verify', '--quiet', '--end-of-options', ref + '^{commit}'], root, env, 4096, pre)
336
+ sha = decode_utf8(r['bytes']).strip() if r['ok'] else ''
337
+ return sha if _SHA_RE.match(sha) else None
338
+
339
+ bases = AUTO_BASES if base is None else list(base) if isinstance(base, (list, tuple)) else [base]
340
+ if not bases or any(not isinstance(b, str) or not _BASE_RE.match(b) or '..' in b for b in bases):
341
+ return {'error': '--base must name one git revision, such as origin/main (not an option or a range)', 'code': 2}
342
+ head = rev('HEAD')
343
+ if not head:
344
+ return {'error': 'this checkout has no commit yet: commit first, or pass --diff FILE', 'code': 2}
345
+ base_sha = name = None
346
+ for cand in bases:
347
+ base_sha = rev(cand)
348
+ if base_sha:
349
+ name = cand
350
+ break
351
+ if not base_sha:
352
+ return {'error': 'could not tell the pull request base (no upstream or origin default branch): pass --base REF'
353
+ if base is None else '--base %s is not a commit in this checkout (fetch it first)' % ' or '.join(bases), 'code': 2}
354
+ m = run_git(git, ['merge-base', base_sha, head], root, env, 4096, pre)
355
+ mb = decode_utf8(m['bytes']).strip() if m['ok'] else ''
356
+ if not _SHA_RE.match(mb):
357
+ return {'error': 'HEAD and %s share no commit: pass --base REF (a shallow clone needs git fetch --unshallow)' % name, 'code': 2}
358
+ if mb == head:
359
+ return {'error': '%s already holds HEAD, so it cannot be the pull request base: commit on a branch, or pass --base REF' % name,
360
+ 'code': 2}
361
+ label = '%s merge base...working tree' % name if base is None else '%s...HEAD' % name
362
+ rng = [mb] if base is None else [mb, head]
363
+ r = run_git(git, ['--no-pager', 'diff', '--no-ext-diff', '--no-textconv', '--no-color', '--no-relative', '--submodule=short',
364
+ '--ignore-submodules=dirty', '--src-prefix=a/', '--dst-prefix=b/', *rng, '--'], root, env, max_bytes, pre,
365
+ {'GIT_ATTR_SOURCE': mb})
366
+ if r.get('over'):
367
+ return {'error': 'the diff (%s) is over %d bytes: check it in smaller parts with --diff' % (label, max_bytes), 'code': 2}
368
+ if not r['ok']:
369
+ return {'error': 'git diff %s failed: run this inside the checkout, or pass --diff FILE' % label}
370
+ roots = _ai_config_roots(git, mb, root, env, pre)
371
+ note = None
372
+ if base is None:
373
+ u = run_git(git, ['ls-files', '-z', '--others', '--exclude-standard', '--full-name', '--', ':/'], root, env, 1_048_576, pre)
374
+ names = [n for n in decode_utf8(u['bytes']).split('\0') if n] if u['ok'] else []
375
+ if names:
376
+ note = '%d untracked file(s) are not in the diff: git add the ones the pull request needs' % len(names)
377
+ out = {'diff': decode_utf8(r['bytes']), 'label': label, 'roots': roots, 'note': note,
378
+ 'base': {'name': name, 'sha': base_sha, 'merge_base': mb}}
379
+ if policy:
380
+ out['policy'] = _read_tree_file(git, root, env, pre, base_sha, 'AGENTS.md', POLICY_MAX_BYTES, '%s:AGENTS.md' % name)
381
+ return out
382
+
383
+
384
+ def _ai_config_roots(git, ref, cwd, env, pre):
385
+ r = run_git(git, ['ls-tree', '-z', '--full-tree', ref], cwd, env, 4_194_304, pre)
386
+ if not r['ok']:
387
+ return []
388
+ roots = []
389
+ for entry in decode_utf8(r['bytes']).split('\0'):
390
+ tab = entry.find('\t')
391
+ if tab < 0:
392
+ continue
393
+ parts = entry[:tab].split(' ')
394
+ kind = parts[1] if len(parts) > 1 else ''
395
+ name = entry[tab + 1:]
396
+ if not re.match(r'^[A-Za-z0-9._-]{1,100}\Z', name, re.ASCII):
397
+ continue
398
+ low = name.lower()
399
+ ai = low == '.claude' or low.startswith('.cursor') or low.startswith('.windsurf') or low.startswith('.aider')
400
+ if kind == 'tree' and ai:
401
+ roots.append(name + '/')
402
+ elif kind == 'blob' and (ai or low == 'claude.md'):
403
+ roots.append(name)
404
+ return sorted(roots)[:32]
405
+
406
+
407
+ def preflight_checkout(cwd=None, base=None, title='', body='', repo=None, pr_number=None, policy_file=None,
408
+ no_policy=False, env=None) -> dict:
409
+ """Preflight this checkout in one call (see src/local.js preflightCheckout); base may be a list of candidates."""
410
+ cwd = cwd or os.getcwd()
411
+ env = os.environ if env is None else env
412
+ root = find_repo_root(cwd) or cwd
413
+ r = collect_git_diff(cwd, base, env, MAX_DIFF_BYTES, not no_policy and policy_file is None)
414
+ if 'error' in r:
415
+ fail('git_failed', r['error'])
416
+ policy = source = path = None
417
+ if not no_policy:
418
+ p = r['policy'] if policy_file is None else read_policy_file(root, policy_file)
419
+ if 'error' in p:
420
+ fail('policy_unreadable', '%s: %s' % (p['source'], READ_ERRORS[p['error']]))
421
+ policy, source = p['text'], p['source']
422
+ path = 'AGENTS.md' if policy_file is None else repo_path(root, policy_file)
423
+ slug = None if repo is None else clean_repo(repo)
424
+ if slug is None:
425
+ try:
426
+ d = detect_github_repo(root)
427
+ slug = clean_repo(d) if d else None
428
+ except GitBillsError:
429
+ slug = None
430
+ return evaluate_preflight(r['diff'], title, body, slug, pr_number, policy, source, r['roots'],
431
+ clean_origin(env.get('GITBILLS_ORIGIN')), True, path)
432
+
433
+
434
+ def read_stdin_bounded(max_bytes):
435
+ data = sys.stdin.buffer.read(max_bytes + 1)
436
+ return {'over': True} if len(data) > max_bytes else {'bytes': data}