open-pushscan 0.3.0__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.
- open_pushscan/__init__.py +2 -0
- open_pushscan/__main__.py +5 -0
- open_pushscan/agents.py +666 -0
- open_pushscan/ci.py +88 -0
- open_pushscan/cli.py +534 -0
- open_pushscan/config.py +256 -0
- open_pushscan/fingerprints.py +153 -0
- open_pushscan/gitscan.py +248 -0
- open_pushscan/hooks.py +121 -0
- open_pushscan/i18n.py +90 -0
- open_pushscan/media.py +318 -0
- open_pushscan/publish.py +160 -0
- open_pushscan/report.py +130 -0
- open_pushscan/rules.py +277 -0
- open_pushscan/scanner.py +226 -0
- open_pushscan/visibility.py +87 -0
- open_pushscan-0.3.0.dist-info/METADATA +193 -0
- open_pushscan-0.3.0.dist-info/RECORD +22 -0
- open_pushscan-0.3.0.dist-info/WHEEL +5 -0
- open_pushscan-0.3.0.dist-info/entry_points.txt +2 -0
- open_pushscan-0.3.0.dist-info/licenses/LICENSE +202 -0
- open_pushscan-0.3.0.dist-info/top_level.txt +1 -0
open_pushscan/config.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Where settings live and how they are read. Nothing here is ever written into a repository.
|
|
2
|
+
|
|
3
|
+
Folder (Linux/macOS ~/.config/open-pushscan, Windows %APPDATA%\\open-pushscan):
|
|
4
|
+
config.ini language, team rules address, large file size, AI checks on/off
|
|
5
|
+
fingerprints.txt names and addresses that identify you (found by setup; you can add or remove lines)
|
|
6
|
+
rules.txt your own rules: a word per line, "re:" + regular expression, or "name<TAB>regular expression"
|
|
7
|
+
allow.txt regular expressions that are always fine
|
|
8
|
+
skip.txt paths (regular expressions) that are never checked
|
|
9
|
+
allowed.json items allowed with `open-pushscan allow`
|
|
10
|
+
team/ a copy of your team's rules repository
|
|
11
|
+
state/ last report of each repository, cache of public/private answers
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import configparser
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import shutil
|
|
21
|
+
import subprocess
|
|
22
|
+
import time
|
|
23
|
+
|
|
24
|
+
from .fingerprints import Fingerprint
|
|
25
|
+
|
|
26
|
+
APP = 'open-pushscan'
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def config_dir() -> str:
|
|
30
|
+
if os.environ.get('OPEN_PUSHSCAN_HOME'):
|
|
31
|
+
return os.environ['OPEN_PUSHSCAN_HOME']
|
|
32
|
+
if os.name == 'nt':
|
|
33
|
+
return os.path.join(os.environ.get('APPDATA') or os.path.expanduser('~'), APP)
|
|
34
|
+
return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), APP)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def path(*parts) -> str:
|
|
38
|
+
return os.path.join(config_dir(), *parts)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def ensure() -> None:
|
|
42
|
+
os.makedirs(path('state'), exist_ok=True)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# ---------------------------------------------------------------- config.ini
|
|
46
|
+
|
|
47
|
+
DEFAULTS = {'language': 'auto', 'team_url': '', 'large_file_mb': '50', 'ai_checks': 'on', 'private_hosts': ''}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load() -> configparser.ConfigParser:
|
|
51
|
+
cp = configparser.ConfigParser()
|
|
52
|
+
cp['open-pushscan'] = dict(DEFAULTS)
|
|
53
|
+
cp.read(path('config.ini'), encoding='utf-8')
|
|
54
|
+
return cp
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def get(key: str) -> str:
|
|
58
|
+
return load()['open-pushscan'].get(key, DEFAULTS.get(key, ''))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def set_value(key: str, value: str) -> None:
|
|
62
|
+
ensure()
|
|
63
|
+
cp = load()
|
|
64
|
+
cp['open-pushscan'][key] = value
|
|
65
|
+
with open(path('config.ini'), 'w', encoding='utf-8') as f:
|
|
66
|
+
cp.write(f)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ---------------------------------------------------------------- simple line files
|
|
70
|
+
|
|
71
|
+
def read_lines(name: str) -> list:
|
|
72
|
+
try:
|
|
73
|
+
with open(path(name), encoding='utf-8') as f:
|
|
74
|
+
return [l.rstrip('\n') for l in f if l.strip() and not l.lstrip().startswith('#')]
|
|
75
|
+
except OSError:
|
|
76
|
+
return []
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def fingerprints(include_off: bool = False) -> list:
|
|
80
|
+
"""Lines look like "value # label". A line starting with "-" is turned off (kept so setup does not add it back)."""
|
|
81
|
+
out = []
|
|
82
|
+
for line in read_lines('fingerprints.txt'):
|
|
83
|
+
value, _, label = line.partition('#')
|
|
84
|
+
value = value.strip()
|
|
85
|
+
off = value.startswith('-')
|
|
86
|
+
if off:
|
|
87
|
+
value = value[1:].strip()
|
|
88
|
+
if value and (include_off or not off):
|
|
89
|
+
out.append(Fingerprint(('-' if off and include_off else '') + value, label.strip() or 'added'))
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def write_fingerprints(items: list) -> None:
|
|
94
|
+
ensure()
|
|
95
|
+
head = ('# open-pushscan: names and addresses that identify you. Anything here is reported when it shows up\n'
|
|
96
|
+
'# in something about to be made public. Add a line to add one; put "-" in front of a line to stop checking it.\n'
|
|
97
|
+
'# 會被當成你的指紋的名稱和位址。要多查一個就加一行;不想查的,在那一行最前面加上「-」。\n')
|
|
98
|
+
width = max((len(f.value) for f in items), default=0) + 4
|
|
99
|
+
with open(path('fingerprints.txt'), 'w', encoding='utf-8') as f:
|
|
100
|
+
f.write(head)
|
|
101
|
+
for fp in items:
|
|
102
|
+
f.write(f'{fp.value.ljust(width)}# {fp.label}\n')
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _rule_lines(lines: list, source: str) -> list:
|
|
106
|
+
"""(name, compiled regex, source) from rule lines."""
|
|
107
|
+
out = []
|
|
108
|
+
for line in lines:
|
|
109
|
+
line = line.strip()
|
|
110
|
+
try:
|
|
111
|
+
if line.startswith('re:'):
|
|
112
|
+
out.append((line[3:].strip(), re.compile(line[3:].strip()), source))
|
|
113
|
+
elif '\t' in line:
|
|
114
|
+
name, _, pat = line.partition('\t')
|
|
115
|
+
out.append((name.strip(), re.compile(pat.strip()), source))
|
|
116
|
+
else:
|
|
117
|
+
word = line
|
|
118
|
+
out.append((word, re.compile(r'(?i)(?<![A-Za-z0-9])' + re.escape(word) + r'(?![A-Za-z0-9])'), source))
|
|
119
|
+
except re.error:
|
|
120
|
+
continue
|
|
121
|
+
return out
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def personal_rules() -> list:
|
|
125
|
+
return _rule_lines(read_lines('rules.txt'), 'personal')
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def team_rules() -> list:
|
|
129
|
+
rules = []
|
|
130
|
+
base = path('team')
|
|
131
|
+
if not os.path.isdir(base):
|
|
132
|
+
return rules
|
|
133
|
+
for root, dirs, files in os.walk(base):
|
|
134
|
+
dirs[:] = [d for d in dirs if d != '.git']
|
|
135
|
+
for name in sorted(files):
|
|
136
|
+
if name.endswith('.txt'):
|
|
137
|
+
try:
|
|
138
|
+
with open(os.path.join(root, name), encoding='utf-8') as f:
|
|
139
|
+
lines = [l.rstrip('\n') for l in f if l.strip() and not l.lstrip().startswith('#')]
|
|
140
|
+
except OSError:
|
|
141
|
+
continue
|
|
142
|
+
rules += _rule_lines(lines, 'team')
|
|
143
|
+
return rules
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def allow_patterns() -> list:
|
|
147
|
+
out = []
|
|
148
|
+
for line in read_lines('allow.txt'):
|
|
149
|
+
try:
|
|
150
|
+
out.append(re.compile(line.strip()))
|
|
151
|
+
except re.error:
|
|
152
|
+
pass
|
|
153
|
+
return out
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def skip_patterns() -> list:
|
|
157
|
+
out = []
|
|
158
|
+
for line in read_lines('skip.txt'):
|
|
159
|
+
try:
|
|
160
|
+
out.append(re.compile(line.strip()))
|
|
161
|
+
except re.error:
|
|
162
|
+
pass
|
|
163
|
+
return out
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# ---------------------------------------------------------------- allowed items and reports
|
|
167
|
+
|
|
168
|
+
def repo_key(top: str, url: str) -> str:
|
|
169
|
+
base = url or top
|
|
170
|
+
return hashlib.sha256(base.encode('utf-8')).hexdigest()[:16]
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def allowed() -> list:
|
|
174
|
+
try:
|
|
175
|
+
with open(path('allowed.json'), encoding='utf-8') as f:
|
|
176
|
+
return json.load(f)
|
|
177
|
+
except (OSError, ValueError):
|
|
178
|
+
return []
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def add_allowed(rule: str, text: str, repo: str) -> None:
|
|
182
|
+
ensure()
|
|
183
|
+
items = allowed()
|
|
184
|
+
entry = {'rule': rule, 'text': text, 'repo': repo, 'added': time.strftime('%Y-%m-%d')}
|
|
185
|
+
if not any(i.get('rule') == rule and i.get('text') == text and i.get('repo') == repo for i in items):
|
|
186
|
+
items.append(entry)
|
|
187
|
+
with open(path('allowed.json'), 'w', encoding='utf-8') as f:
|
|
188
|
+
json.dump(items, f, ensure_ascii=False, indent=1)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def save_report(repo: str, findings: list) -> None:
|
|
192
|
+
ensure()
|
|
193
|
+
with open(path('state', f'report-{repo}.json'), 'w', encoding='utf-8') as f:
|
|
194
|
+
json.dump(findings, f, ensure_ascii=False)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def last_report(repo: str) -> list:
|
|
198
|
+
try:
|
|
199
|
+
with open(path('state', f'report-{repo}.json'), encoding='utf-8') as f:
|
|
200
|
+
return json.load(f)
|
|
201
|
+
except (OSError, ValueError):
|
|
202
|
+
return []
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
# ---------------------------------------------------------------- team rules repository
|
|
206
|
+
|
|
207
|
+
def update_team(force: bool = False) -> bool:
|
|
208
|
+
"""Pull the team rules at most once a day. Never stops a commit or push if it fails."""
|
|
209
|
+
base = path('team')
|
|
210
|
+
if not os.path.isdir(os.path.join(base, '.git')):
|
|
211
|
+
return False
|
|
212
|
+
stamp = path('state', 'team-updated')
|
|
213
|
+
try:
|
|
214
|
+
if not force and time.time() - os.path.getmtime(stamp) < 86400:
|
|
215
|
+
return False
|
|
216
|
+
except OSError:
|
|
217
|
+
pass
|
|
218
|
+
try:
|
|
219
|
+
subprocess.run(['git', '-C', base, 'pull', '--ff-only', '-q'], capture_output=True, timeout=10)
|
|
220
|
+
except (OSError, subprocess.SubprocessError):
|
|
221
|
+
return False
|
|
222
|
+
ensure()
|
|
223
|
+
with open(stamp, 'w') as f:
|
|
224
|
+
f.write(time.strftime('%Y-%m-%d %H:%M'))
|
|
225
|
+
return True
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def clone_team(url: str) -> bool:
|
|
229
|
+
base = path('team')
|
|
230
|
+
if os.path.isdir(base):
|
|
231
|
+
shutil.rmtree(base, ignore_errors=True)
|
|
232
|
+
ensure()
|
|
233
|
+
p = subprocess.run(['git', 'clone', '-q', '--depth', '1', url, base], capture_output=True)
|
|
234
|
+
if p.returncode == 0:
|
|
235
|
+
set_value('team_url', url)
|
|
236
|
+
with open(path('state', 'team-updated'), 'w') as f:
|
|
237
|
+
f.write(time.strftime('%Y-%m-%d %H:%M'))
|
|
238
|
+
return p.returncode == 0
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# ---------------------------------------------------------------- from git-public-check
|
|
242
|
+
|
|
243
|
+
OLD = os.path.expanduser('~/.config/git-public-check')
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def migrate_old() -> list:
|
|
247
|
+
"""Copy git-public-check's rule files the first time. Returns the names copied."""
|
|
248
|
+
copied = []
|
|
249
|
+
pairs = [('patterns.txt', 'rules.txt'), ('allow.txt', 'allow.txt'), ('skip.txt', 'skip.txt')]
|
|
250
|
+
ensure()
|
|
251
|
+
for src, dst in pairs:
|
|
252
|
+
s, d = os.path.join(OLD, src), path(dst)
|
|
253
|
+
if os.path.exists(s) and not os.path.exists(d):
|
|
254
|
+
shutil.copyfile(s, d)
|
|
255
|
+
copied.append(dst)
|
|
256
|
+
return copied
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Find the names and addresses that identify this computer and this person, with no setup.
|
|
2
|
+
|
|
3
|
+
Each value found is a "fingerprint": if it shows up in something about to be made public, it is reported.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import getpass
|
|
8
|
+
import ipaddress
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import platform
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import socket
|
|
15
|
+
import subprocess
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Fingerprint:
|
|
21
|
+
value: str
|
|
22
|
+
label: str # where it came from, shown to people
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# Values too common to report (they would match ordinary words or examples).
|
|
26
|
+
COMMON = {
|
|
27
|
+
'localhost', 'localdomain', 'user', 'users', 'admin', 'administrator', 'root', 'ubuntu', 'debian', 'pi', 'home', 'desktop',
|
|
28
|
+
'laptop', 'windows', 'linux', 'default', 'test', 'dev', 'git', 'guest', 'public', 'workgroup', 'me', 'you', 'runner',
|
|
29
|
+
'vscode', 'codespace', 'docker', 'server', 'computer', 'pc', 'mac', 'macbook', 'github', 'origin', 'main', 'master',
|
|
30
|
+
}
|
|
31
|
+
# Public services often appear in ssh config ("Host github.com"); they say nothing about you.
|
|
32
|
+
PUBLIC_HOSTS = ('github.com', 'gitlab.com', 'bitbucket.org', 'codeberg.org', 'sr.ht', 'azure.com', 'visualstudio.com',
|
|
33
|
+
'huggingface.co', 'hf.co', 'gitee.com', 'sourceforge.net', 'amazonaws.com', 'googlesource.com', 'gitea.com')
|
|
34
|
+
LABELS = {
|
|
35
|
+
'host': {'zh': '主機名稱', 'en': 'host name'},
|
|
36
|
+
'domain': {'zh': 'Windows 網域', 'en': 'Windows domain'},
|
|
37
|
+
'account': {'zh': '帳號名稱', 'en': 'account name'},
|
|
38
|
+
'home': {'zh': '家目錄', 'en': 'home folder'},
|
|
39
|
+
'ip': {'zh': '這台電腦的網路位址', 'en': "this computer's address"},
|
|
40
|
+
'tailscale': {'zh': 'Tailscale 位址或名稱', 'en': 'Tailscale address or name'},
|
|
41
|
+
'ssh': {'zh': 'ssh 設定裡的主機', 'en': 'host from ssh config'},
|
|
42
|
+
'email': {'zh': 'git 設定的 email', 'en': 'email from git config'},
|
|
43
|
+
'added': {'zh': '你自己加的', 'en': 'added by you'},
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _run(args, timeout=4):
|
|
48
|
+
if not shutil.which(args[0]):
|
|
49
|
+
return ''
|
|
50
|
+
try:
|
|
51
|
+
out = subprocess.run(args, capture_output=True, timeout=timeout)
|
|
52
|
+
return out.stdout.decode('utf-8', 'replace') if out.returncode == 0 else ''
|
|
53
|
+
except (OSError, subprocess.SubprocessError):
|
|
54
|
+
return ''
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def public_host(value: str) -> bool:
|
|
58
|
+
v = value.lower().strip('.')
|
|
59
|
+
return any(v == h or v.endswith('.' + h) for h in PUBLIC_HOSTS)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def usable(value: str) -> bool:
|
|
63
|
+
v = value.strip().strip('.')
|
|
64
|
+
return len(v) >= 3 and v.lower() not in COMMON and not v.isdigit() and not public_host(v)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _ip_ok(text: str) -> bool:
|
|
68
|
+
try:
|
|
69
|
+
ip = ipaddress.ip_address(text.split('%')[0])
|
|
70
|
+
except ValueError:
|
|
71
|
+
return False
|
|
72
|
+
return not (ip.is_loopback or ip.is_unspecified or ip.is_multicast or str(ip).startswith('255.') or str(ip).endswith('.255'))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def detect() -> list:
|
|
76
|
+
found = []
|
|
77
|
+
|
|
78
|
+
def add(value, label):
|
|
79
|
+
value = (value or '').strip().rstrip('.')
|
|
80
|
+
if value and usable(value) and all(f.value.lower() != value.lower() for f in found):
|
|
81
|
+
found.append(Fingerprint(value, label))
|
|
82
|
+
|
|
83
|
+
# host and account
|
|
84
|
+
for name in {socket.gethostname(), platform.node(), os.environ.get('COMPUTERNAME', ''), os.environ.get('HOSTNAME', '')}:
|
|
85
|
+
if name:
|
|
86
|
+
add(name, 'host')
|
|
87
|
+
add(name.split('.')[0], 'host')
|
|
88
|
+
domain = os.environ.get('USERDOMAIN', '')
|
|
89
|
+
if domain and domain.upper() != os.environ.get('COMPUTERNAME', '').upper():
|
|
90
|
+
add(domain, 'domain')
|
|
91
|
+
try:
|
|
92
|
+
add(getpass.getuser(), 'account')
|
|
93
|
+
except Exception:
|
|
94
|
+
pass
|
|
95
|
+
home = os.path.expanduser('~')
|
|
96
|
+
if home and home not in ('/', '~') and usable(os.path.basename(home)):
|
|
97
|
+
add(home, 'home')
|
|
98
|
+
add(os.path.basename(home), 'account')
|
|
99
|
+
|
|
100
|
+
# network addresses
|
|
101
|
+
text = _run(['ip', '-o', 'addr', 'show']) or _run(['ipconfig']) or _run(['ifconfig'])
|
|
102
|
+
for m in re.finditer(r'(?<![\d.])(\d{1,3}(?:\.\d{1,3}){3})(?![\d.])', text):
|
|
103
|
+
if _ip_ok(m.group(1)) and not m.group(1).startswith(('255.', '0.')):
|
|
104
|
+
add(m.group(1), 'ip')
|
|
105
|
+
for m in re.finditer(r'inet6 ([0-9a-f:]+)', text):
|
|
106
|
+
ip = m.group(1)
|
|
107
|
+
if _ip_ok(ip) and not ip.startswith('fe80'):
|
|
108
|
+
add(ip, 'ip')
|
|
109
|
+
|
|
110
|
+
# Tailscale: this machine and the other machines in the same tailnet
|
|
111
|
+
ts = _run(['tailscale', 'status', '--json'])
|
|
112
|
+
if ts:
|
|
113
|
+
try:
|
|
114
|
+
data = json.loads(ts)
|
|
115
|
+
except ValueError:
|
|
116
|
+
data = {}
|
|
117
|
+
suffix = (data.get('MagicDNSSuffix') or '').strip('.')
|
|
118
|
+
if suffix:
|
|
119
|
+
add(suffix, 'tailscale')
|
|
120
|
+
add(suffix.split('.')[0], 'tailscale')
|
|
121
|
+
nodes = [data.get('Self') or {}] + list((data.get('Peer') or {}).values())
|
|
122
|
+
for node in nodes:
|
|
123
|
+
for ip in node.get('TailscaleIPs') or []:
|
|
124
|
+
add(ip, 'tailscale')
|
|
125
|
+
dns = (node.get('DNSName') or '').strip('.')
|
|
126
|
+
if dns:
|
|
127
|
+
add(dns, 'tailscale')
|
|
128
|
+
add(dns.split('.')[0], 'tailscale')
|
|
129
|
+
add(node.get('HostName') or '', 'tailscale')
|
|
130
|
+
|
|
131
|
+
# ssh config
|
|
132
|
+
cfg = os.path.join(home, '.ssh', 'config')
|
|
133
|
+
try:
|
|
134
|
+
with open(cfg, encoding='utf-8', errors='replace') as f:
|
|
135
|
+
for line in f:
|
|
136
|
+
parts = line.strip().split(None, 1)
|
|
137
|
+
if len(parts) == 2 and parts[0].lower() in ('host', 'hostname'):
|
|
138
|
+
for v in parts[1].split():
|
|
139
|
+
if not any(c in v for c in '*?!'):
|
|
140
|
+
add(v, 'ssh')
|
|
141
|
+
except OSError:
|
|
142
|
+
pass
|
|
143
|
+
|
|
144
|
+
# git email (the GitHub private address is fine)
|
|
145
|
+
for scope in ('--global', '--system'):
|
|
146
|
+
for email in _run(['git', 'config', scope, '--get-all', 'user.email']).split():
|
|
147
|
+
if 'noreply' not in email:
|
|
148
|
+
add(email, 'email')
|
|
149
|
+
return found
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def label_text(label: str, lang: str) -> str:
|
|
153
|
+
return LABELS.get(label, LABELS['added'])[lang]
|
open_pushscan/gitscan.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Read from git what is about to be committed or pushed: added lines, file names, commit details.
|
|
2
|
+
|
|
3
|
+
Everything uses plain git commands, one call per batch, so a whole history is read in a single pass.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import subprocess
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
ZERO = '0' * 40
|
|
13
|
+
DIFF_OPTS = ['--no-color', '--no-ext-diff', '--no-textconv', '--no-renames', '-U0', '--src-prefix=a/', '--dst-prefix=b/']
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class GitError(Exception):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def git(*args, input=None, check=True, cwd=None) -> str:
|
|
21
|
+
return git_bytes(*args, input=input, check=check, cwd=cwd).decode('utf-8', 'replace')
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def git_bytes(*args, input=None, check=True, cwd=None) -> bytes:
|
|
25
|
+
try:
|
|
26
|
+
p = subprocess.run(['git', '-c', 'core.quotePath=false', *args], input=input, capture_output=True, cwd=cwd)
|
|
27
|
+
except OSError as e:
|
|
28
|
+
raise GitError(str(e))
|
|
29
|
+
if check and p.returncode != 0:
|
|
30
|
+
raise GitError(p.stderr.decode('utf-8', 'replace').strip())
|
|
31
|
+
return p.stdout
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class Change:
|
|
36
|
+
"""One commit, or the staged / uncommitted changes (commit is None)."""
|
|
37
|
+
commit: str | None = None
|
|
38
|
+
author: str = '' # "Name <email>"
|
|
39
|
+
committer: str = ''
|
|
40
|
+
message: str = ''
|
|
41
|
+
lines: list = field(default_factory=list) # (path, line number, text) of added lines
|
|
42
|
+
files: dict = field(default_factory=dict) # path -> 'A' / 'M' / 'D'
|
|
43
|
+
binary: set = field(default_factory=set) # paths shown as binary
|
|
44
|
+
source: str = 'commit' # 'commit', 'staged', 'working'
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _unquote(p: str) -> str:
|
|
48
|
+
if len(p) >= 2 and p[0] == '"' and p[-1] == '"':
|
|
49
|
+
b = p[1:-1].encode('latin-1', 'backslashreplace').decode('unicode_escape').encode('latin-1', 'replace')
|
|
50
|
+
return b.decode('utf-8', 'replace')
|
|
51
|
+
return p
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
HUNK = re.compile(r'^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@')
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _header_path(line: str):
|
|
58
|
+
"""Path from "diff --git a/P b/P" (renames are off, so both sides are the same path)."""
|
|
59
|
+
rest = line[len('diff --git '):]
|
|
60
|
+
if rest.startswith('"'):
|
|
61
|
+
m = re.match(r'^("(?:\\.|[^"\\])*") ("(?:\\.|[^"\\])*")$', rest)
|
|
62
|
+
return _unquote(m.group(2))[2:] if m else None
|
|
63
|
+
if (len(rest) - 5) % 2:
|
|
64
|
+
return None
|
|
65
|
+
n = (len(rest) - 5) // 2
|
|
66
|
+
return rest[2:2 + n] if rest[:2] == 'a/' and rest[2 + n:2 + n + 3] == ' b/' else None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def parse_patch(text: str, change: Change) -> None:
|
|
70
|
+
"""Fill change.lines / files / binary from a unified diff made with DIFF_OPTS."""
|
|
71
|
+
block = None # dict for the file being read
|
|
72
|
+
|
|
73
|
+
def finish():
|
|
74
|
+
if not block:
|
|
75
|
+
return
|
|
76
|
+
path = block['new'] or block['header']
|
|
77
|
+
if not path:
|
|
78
|
+
return
|
|
79
|
+
if block['status'] == 'D':
|
|
80
|
+
change.files[block['old'] or path] = 'D'
|
|
81
|
+
return
|
|
82
|
+
change.files[path] = block['status']
|
|
83
|
+
if block['binary']:
|
|
84
|
+
change.binary.add(path)
|
|
85
|
+
|
|
86
|
+
new_line = old_left = new_left = 0
|
|
87
|
+
for raw in text.split('\n'):
|
|
88
|
+
if old_left > 0 or new_left > 0:
|
|
89
|
+
if raw.startswith('+'):
|
|
90
|
+
if block and block['new']:
|
|
91
|
+
change.lines.append((block['new'], new_line, raw[1:]))
|
|
92
|
+
new_line += 1
|
|
93
|
+
new_left -= 1
|
|
94
|
+
continue
|
|
95
|
+
if raw.startswith('-'):
|
|
96
|
+
old_left -= 1
|
|
97
|
+
continue
|
|
98
|
+
if raw.startswith('\\'):
|
|
99
|
+
continue
|
|
100
|
+
old_left = new_left = 0
|
|
101
|
+
if raw.startswith('diff --git '):
|
|
102
|
+
finish()
|
|
103
|
+
hp = _header_path(raw)
|
|
104
|
+
block = {'header': hp, 'old': hp, 'new': hp, 'status': 'M', 'binary': False}
|
|
105
|
+
elif block is None:
|
|
106
|
+
continue
|
|
107
|
+
elif raw.startswith('new file mode'):
|
|
108
|
+
block['status'] = 'A'
|
|
109
|
+
elif raw.startswith('deleted file mode'):
|
|
110
|
+
block['status'] = 'D'
|
|
111
|
+
elif raw.startswith('--- '):
|
|
112
|
+
name = raw[4:].split('\t')[0]
|
|
113
|
+
block['old'] = None if name == '/dev/null' else _unquote(name)[2:]
|
|
114
|
+
elif raw.startswith('+++ '):
|
|
115
|
+
name = raw[4:].split('\t')[0]
|
|
116
|
+
block['new'] = None if name == '/dev/null' else _unquote(name)[2:]
|
|
117
|
+
elif raw.startswith('Binary files '):
|
|
118
|
+
block['binary'] = True
|
|
119
|
+
elif raw.startswith('@@'):
|
|
120
|
+
m = HUNK.match(raw)
|
|
121
|
+
if m:
|
|
122
|
+
old_left = int(m.group(1)) if m.group(1) is not None else 1
|
|
123
|
+
new_line = int(m.group(2))
|
|
124
|
+
new_left = int(m.group(3)) if m.group(3) is not None else 1
|
|
125
|
+
finish()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ------------------------------------------------------------------- sources
|
|
129
|
+
|
|
130
|
+
def toplevel(cwd=None) -> str:
|
|
131
|
+
return git('rev-parse', '--show-toplevel', cwd=cwd).strip()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def has_head() -> bool:
|
|
135
|
+
return subprocess.run(['git', 'rev-parse', '--verify', '-q', 'HEAD'], capture_output=True).returncode == 0
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def ident(kind='AUTHOR') -> str:
|
|
139
|
+
out = git('var', f'GIT_{kind}_IDENT', check=False).strip()
|
|
140
|
+
return re.sub(r'\s+\d+\s+[+-]\d{4}$', '', out)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def staged() -> Change:
|
|
144
|
+
c = Change(source='staged', author=ident('AUTHOR'), committer=ident('COMMITTER'))
|
|
145
|
+
parse_patch(git('diff', '--cached', *DIFF_OPTS), c)
|
|
146
|
+
return c
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def working() -> Change:
|
|
150
|
+
"""Everything not committed yet: staged, unstaged and untracked files."""
|
|
151
|
+
c = Change(source='working')
|
|
152
|
+
base = ['HEAD'] if has_head() else ['--cached']
|
|
153
|
+
parse_patch(git('diff', *base, *DIFF_OPTS), c)
|
|
154
|
+
for p in git_bytes('ls-files', '--others', '--exclude-standard', '-z').split(b'\0'):
|
|
155
|
+
if not p:
|
|
156
|
+
continue
|
|
157
|
+
path = p.decode('utf-8', 'replace')
|
|
158
|
+
c.files[path] = 'A'
|
|
159
|
+
try:
|
|
160
|
+
with open(path, 'rb') as f:
|
|
161
|
+
data = f.read(2_000_000)
|
|
162
|
+
except OSError:
|
|
163
|
+
continue
|
|
164
|
+
if b'\0' in data[:8000]:
|
|
165
|
+
c.binary.add(path)
|
|
166
|
+
continue
|
|
167
|
+
for i, line in enumerate(data.decode('utf-8', 'replace').split('\n'), 1):
|
|
168
|
+
c.lines.append((path, i, line.rstrip('\r')))
|
|
169
|
+
return c
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
FMT = '%x00%x01%H%x00%an <%ae>%x00%cn <%ce>%x00%B%x00%x02'
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def commits(rev_args) -> list:
|
|
176
|
+
"""Commits selected by git log arguments (e.g. ['abc..def'] or ['--all']), oldest first."""
|
|
177
|
+
out = git('log', '--reverse', '-p', *DIFF_OPTS, f'--format={FMT}', *rev_args)
|
|
178
|
+
result = []
|
|
179
|
+
for chunk in out.split('\x00\x01')[1:]:
|
|
180
|
+
head, _, patch = chunk.partition('\x00\x02')
|
|
181
|
+
parts = head.split('\x00')
|
|
182
|
+
if len(parts) < 4:
|
|
183
|
+
continue
|
|
184
|
+
c = Change(commit=parts[0], author=parts[1], committer=parts[2], message=parts[3].strip('\n'))
|
|
185
|
+
parse_patch(patch, c)
|
|
186
|
+
result.append(c)
|
|
187
|
+
return result
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def unpushed_args() -> list:
|
|
191
|
+
"""git log arguments for commits on this branch that are not on any remote yet."""
|
|
192
|
+
if not has_head():
|
|
193
|
+
return []
|
|
194
|
+
up = subprocess.run(['git', 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], capture_output=True)
|
|
195
|
+
if up.returncode == 0:
|
|
196
|
+
return [f'{up.stdout.decode().strip()}..HEAD']
|
|
197
|
+
return ['HEAD', '--not', '--remotes']
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def pushed_ranges(stdin_text: str) -> tuple:
|
|
201
|
+
"""From pre-push input, the git log arguments for each pushed ref, and pushed tag names."""
|
|
202
|
+
ranges, tags = [], []
|
|
203
|
+
for line in stdin_text.splitlines():
|
|
204
|
+
parts = line.split()
|
|
205
|
+
if len(parts) != 4:
|
|
206
|
+
continue
|
|
207
|
+
local_ref, local_sha, _remote_ref, remote_sha = parts
|
|
208
|
+
if local_sha == ZERO:
|
|
209
|
+
continue
|
|
210
|
+
if local_ref.startswith('refs/tags/'):
|
|
211
|
+
tags.append(local_ref[len('refs/tags/'):])
|
|
212
|
+
known = remote_sha != ZERO and subprocess.run(['git', 'cat-file', '-e', remote_sha + '^{commit}'], capture_output=True).returncode == 0
|
|
213
|
+
ranges.append([f'{remote_sha}..{local_sha}'] if known else [local_sha, '--not', '--remotes'])
|
|
214
|
+
return ranges, tags
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def blob(change: Change, path: str, limit=30_000_000) -> bytes:
|
|
218
|
+
if change.source == 'working':
|
|
219
|
+
try:
|
|
220
|
+
with open(path, 'rb') as f:
|
|
221
|
+
return f.read(limit)
|
|
222
|
+
except OSError:
|
|
223
|
+
return b''
|
|
224
|
+
spec = f':{path}' if change.source == 'staged' else f'{change.commit}:{path}'
|
|
225
|
+
p = subprocess.run(['git', 'cat-file', 'blob', spec], capture_output=True)
|
|
226
|
+
return p.stdout[:limit] if p.returncode == 0 else b''
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def size(change: Change, path: str) -> int:
|
|
230
|
+
if change.source == 'working':
|
|
231
|
+
try:
|
|
232
|
+
return os.path.getsize(path)
|
|
233
|
+
except OSError:
|
|
234
|
+
return 0
|
|
235
|
+
spec = f':{path}' if change.source == 'staged' else f'{change.commit}:{path}'
|
|
236
|
+
p = subprocess.run(['git', 'cat-file', '-s', spec], capture_output=True)
|
|
237
|
+
try:
|
|
238
|
+
return int(p.stdout.strip()) if p.returncode == 0 else 0
|
|
239
|
+
except ValueError:
|
|
240
|
+
return 0
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def remote_url(name: str = '') -> str:
|
|
244
|
+
if not name:
|
|
245
|
+
up = subprocess.run(['git', 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], capture_output=True)
|
|
246
|
+
name = up.stdout.decode().split('/')[0].strip() if up.returncode == 0 else 'origin'
|
|
247
|
+
p = subprocess.run(['git', 'remote', 'get-url', name], capture_output=True)
|
|
248
|
+
return p.stdout.decode().strip() if p.returncode == 0 else ''
|