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/ci.py ADDED
@@ -0,0 +1,88 @@
1
+ """The GitHub Action: check what a push or pull request adds. Runs on GitHub, so it cannot see your computer's
2
+ fingerprints; it checks the general rules, keys, AI traces, and team rules given through a secret."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import subprocess
8
+
9
+ from . import config, gitscan, report
10
+ from .i18n import t
11
+ from .rules import RULES
12
+ from .scanner import Scanner, gitleaks
13
+
14
+ ZERO = '0' * 40
15
+
16
+
17
+ def _git(*args) -> str:
18
+ p = subprocess.run(['git', *args], capture_output=True)
19
+ return p.stdout.decode().strip() if p.returncode == 0 else ''
20
+
21
+
22
+ def _exists(sha) -> bool:
23
+ return bool(sha) and subprocess.run(['git', 'cat-file', '-e', f'{sha}^{{commit}}'], capture_output=True).returncode == 0
24
+
25
+
26
+ def _range() -> list:
27
+ # a checkout without `fetch-depth: 0` has only the latest commit; get the rest so the pushed range can be read
28
+ if _git('rev-parse', '--is-shallow-repository') == 'true':
29
+ subprocess.run(['git', 'fetch', '--no-tags', '--quiet', '--unshallow', 'origin'], capture_output=True)
30
+ event = os.environ.get('GITHUB_EVENT_NAME', '')
31
+ try:
32
+ with open(os.environ.get('GITHUB_EVENT_PATH', ''), encoding='utf-8') as f:
33
+ data = json.load(f)
34
+ except (OSError, ValueError):
35
+ data = {}
36
+ if event.startswith('pull_request'):
37
+ base = data.get('pull_request', {}).get('base', {}).get('sha')
38
+ head = data.get('pull_request', {}).get('head', {}).get('sha')
39
+ if _exists(base) and _exists(head):
40
+ return [f"{_git('merge-base', base, head) or base}..{head}"]
41
+ before, after = data.get('before'), data.get('after') or os.environ.get('GITHUB_SHA', 'HEAD')
42
+ if before != ZERO and _exists(before): # after a force push the old commit may be gone
43
+ return [f'{before}..{after}']
44
+ default = data.get('repository', {}).get('default_branch')
45
+ ref = data.get('ref') or os.environ.get('GITHUB_REF', '')
46
+ if default and ref != f'refs/heads/{default}': # a new branch or tag
47
+ commit = _git('rev-parse', f'{after}^{{commit}}') or after
48
+ mb = _git('merge-base', f'origin/{default}', commit)
49
+ if mb == commit:
50
+ return [] # it points at commits already on the default branch, which were checked when pushed
51
+ if mb:
52
+ return [f'{mb}..{commit}']
53
+ return [after] # the first push of the default branch, or its old commit is gone: check everything
54
+
55
+
56
+ def run(l: str) -> int:
57
+ rules = os.environ.get('INPUT_TEAM_RULES') or os.environ.get('OPEN_PUSHSCAN_RULES') or ''
58
+ if rules.strip():
59
+ config.ensure()
60
+ os.makedirs(config.path('team'), exist_ok=True)
61
+ with open(config.path('team', 'rules.txt'), 'w', encoding='utf-8') as f:
62
+ f.write(rules)
63
+ scanner = Scanner(repo='ci', fingerprints=[])
64
+ rng = _range()
65
+ if not rng:
66
+ print(t('ci_nothing', l))
67
+ return 0
68
+ findings = []
69
+ for c in gitscan.commits(rng):
70
+ findings += scanner.scan_change(c, gitscan.blob, gitscan.size)
71
+ findings += gitleaks(rng)
72
+ findings, notes = report.split(findings)
73
+ for f in notes:
74
+ loc = f'file={f.path},line={f.line},' if f.path and f.line else ''
75
+ print(f'::warning {loc}title=open-pushscan::{t("notes", l, n=1).rstrip("::")}')
76
+ if notes:
77
+ print(report.render_notes(notes, l))
78
+ items = report.group(findings)
79
+ if not items:
80
+ print(t('check_clean', l, what=' '.join(rng)))
81
+ return 0
82
+ for item in items:
83
+ rule = RULES.get(item['rule'])
84
+ title = rule.title[l] if rule else item['rule']
85
+ loc = f"file={item['path']},line={item['line']}," if item.get('path') and item.get('line') else (f"file={item['path']}," if item.get('path') else '')
86
+ print(f'::error {loc}title=open-pushscan::{title}')
87
+ print(report.render(items, t('ci_found', l, n=len(items)), [], l, limit=10_000))
88
+ return 1
open_pushscan/cli.py ADDED
@@ -0,0 +1,534 @@
1
+ """Command line: setup, check, publish-check, allow, status, uninstall (and the hook and ci entry points)."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+
9
+ from . import __version__, agents, config, gitscan, hooks, report, visibility
10
+ from . import fingerprints as fpmod
11
+ from .i18n import command, lang, t
12
+ from .scanner import Scanner, gitleaks
13
+
14
+ TEXT = {
15
+ 'setup_title': ('open-pushscan 設定', '{cmd} setup'),
16
+ 'migrated': ('已經把 git-public-check 的設定搬過來了:{files}', 'Copied your git-public-check settings: {files}'),
17
+ 'fp_step': ('1/4 找出你的指紋(會洩漏你是誰、用哪台電腦的名稱和位址)', '1/4 Finding your fingerprints (names and addresses that identify you)'),
18
+ 'fp_found': (' 找到 {n} 個:{summary}', ' Found {n}: {summary}'),
19
+ 'fp_new': (' 其中 {n} 個是這次新找到的', ' {n} of them are new'),
20
+ 'fp_file': (' 全部列在 {path}\n 想加或拿掉,直接改那個檔案(不想查的在那一行最前面加「-」)',
21
+ ' All listed in {path}\n Edit that file to add or remove any (put "-" in front of a line to stop checking it)'),
22
+ 'fp_ask': (' 還有別的名稱要查嗎?例如公司名稱、機器暱稱(用逗號分隔,直接按 Enter 跳過):',
23
+ ' Any other names to check, e.g. your company or machine nicknames? (comma-separated, Enter to skip): '),
24
+ 'fp_added': (' 加好了 {n} 個', ' Added {n}'),
25
+ 'team_step': ('2/4 團隊規則', '2/4 Team rules'),
26
+ 'team_ask': (' 有團隊規則的 GitHub 網址嗎?(沒有就按 Enter):', ' GitHub address of your team rules? (Enter to skip): '),
27
+ 'team_ok': (' 已經接上團隊規則({n} 條),之後每天自動更新', ' Team rules connected ({n} rules); updated once a day'),
28
+ 'team_fail': (' 抓不到這個 repo,請確認網址和你有沒有權限;之後可以再跑一次 {cmd} setup',
29
+ ' Could not fetch that repository; check the address and your access, then run {cmd} setup again'),
30
+ 'team_keep': (' 繼續用原本的團隊規則:{url}', ' Keeping your team rules: {url}'),
31
+ 'team_skip': (' 跳過', ' Skipped'),
32
+ 'install_step': ('3/4 裝到這台電腦', '3/4 Installing on this computer'),
33
+ 'install_ok': (' 完成:這台電腦上所有 repo(包括之後 clone 的)commit 和 push 時都會自動檢查',
34
+ ' Done: every repository on this computer (including future clones) is checked on commit and push'),
35
+ 'install_prev': (' 你原本設定了別的 hooks 資料夾({prev}),它裡面的檢查會接在後面照樣跑',
36
+ ' You already had a hooks folder ({prev}); its hooks still run after ours'),
37
+ 'ai_step': ('4/4 AI 寫程式助手', '4/4 AI coding assistants'),
38
+ 'ai_none': (' 沒有找到 Claude Code 或 Codex(之後裝了,再跑一次 {cmd} setup)',
39
+ ' No Claude Code or Codex found (after installing one, run {cmd} setup again)'),
40
+ 'ai_found': (' 找到:{names}', ' Found: {names}'),
41
+ 'ai_ask': (' 要讓它們不能跳過或關掉檢查嗎?會在它們的設定加一個檢查和一段說明 [Y/n]:',
42
+ ' Stop them from skipping or switching off the checks? This adds a check and a short note to their settings [Y/n]: '),
43
+ 'ai_ok': (' {name}:完成,改了 {files}', ' {name}: done; changed {files}'),
44
+ 'ai_fail': (' {name}:沒有改,{path} 讀不懂(不是正確的 JSON)', ' {name}: not changed; {path} is not valid JSON'),
45
+ 'ai_codex': (' Codex 還要做一步:打開 Codex 輸入 /hooks,信任 open-pushscan 的檢查,再重開 Codex',
46
+ ' One more step for Codex: open Codex, type /hooks, trust the open-pushscan check, then restart Codex'),
47
+ 'ai_skip': (' 跳過', ' Skipped'),
48
+ 'done': ('好了!以後照常 commit、push,有問題才會出現。\n想現在檢查一次目前的 repo:{cmd} check',
49
+ 'All set. Commit and push as usual; you only hear from open-pushscan when something is wrong.\n'
50
+ 'To check the current repository now: {cmd} check'),
51
+ 'action_ok': ('已經建好 {path},commit 並推上去之後,GitHub 每次收到推送都會檢查一次',
52
+ 'Created {path}. Commit and push it, and GitHub checks every push too'),
53
+ 'action_exists': ('{path} 已經有了,沒有改它', '{path} already exists; left as it is'),
54
+ 'not_repo': ('這裡不是 git repo,請先 cd 到專案資料夾', 'This is not a git repository; cd into a project first'),
55
+ 'allow_person': ('放行要由你自己在終端機執行(AI 助手不能代為放行):{cmd} allow {nums}',
56
+ 'Allowing must be done by you, in your own terminal (an AI assistant cannot do it): {cmd} allow {nums}'),
57
+ 'allow_confirm': ('確定放行以上 {n} 項?[y/N]:', 'Allow the item(s) above? [y/N]: '),
58
+ 'allow_cancel': ('沒有放行任何一項', 'Nothing was allowed'),
59
+ 'allow_none': ('找不到上一次的報告,請先跑 {cmd} check(或重新 commit/push 一次)',
60
+ 'No recent report; run {cmd} check first (or commit/push again)'),
61
+ 'allow_bad': ('上一次的報告沒有第 {n} 項(共 {total} 項)', 'The last report has no item {n} (it has {total})'),
62
+ 'allow_ok': ('好,以後{scope}「{text}」這一項不再提醒', 'OK: "{text}" will no longer be reported{scope}'),
63
+ 'scope_repo': ('在這個 repo 裡,', ' in this repository'),
64
+ 'scope_all': ('在所有 repo 裡,', ' in any repository'),
65
+ 'status_installed': ('已裝好:這台電腦所有 repo 都有保護', 'Installed: every repository on this computer is protected'),
66
+ 'status_not': ('還沒裝:請跑 {cmd} setup', 'Not installed: run {cmd} setup'),
67
+ 'status_other': ('git 的 hooks 指到別的地方({path}),open-pushscan 沒有在檢查;請跑 {cmd} setup',
68
+ 'git hooks point somewhere else ({path}), so open-pushscan is not checking; run {cmd} setup'),
69
+ 'status_settings': ('設定資料夾:{path}', 'Settings folder: {path}'),
70
+ 'status_fp': ('你的指紋:{n} 個{note}', 'Your fingerprints: {n}{note}'),
71
+ 'status_fp_live': ('(還沒跑 setup,先用自動找到的)', ' (setup not run yet; using what was found automatically)'),
72
+ 'status_team': ('團隊規則:{n} 條,來自 {url},上次更新 {when}', 'Team rules: {n}, from {url}, last updated {when}'),
73
+ 'status_team_none': ('團隊規則:沒有接', 'Team rules: none'),
74
+ 'status_ai': ('AI 助手:{state}', 'AI assistants: {state}'),
75
+ 'ai_on': ('{name} 已保護', '{name} protected'),
76
+ 'ai_off': ('{name} 沒有保護(跑 {cmd} setup)', '{name} not protected (run {cmd} setup)'),
77
+ 'ai_absent': ('沒有找到 Claude Code 或 Codex', 'no Claude Code or Codex found'),
78
+ 'status_rules': ('你的自訂規則:{n} 條;已放行:{a} 項', 'Your own rules: {n}; allowed items: {a}'),
79
+ 'status_gitleaks': ('gitleaks:{state}', 'gitleaks: {state}'),
80
+ 'gl_yes': ('有裝,會一起用來找金鑰', 'installed; also used to find keys'),
81
+ 'gl_no': ('沒裝(可以不裝;裝了會多一層金鑰檢查)', 'not installed (optional; adds another layer of key checks)'),
82
+ 'status_repo': ('目前的 repo:{top}\n 推到:{url}({vis})', 'Current repository: {top}\n Pushes to: {url} ({vis})'),
83
+ 'status_override': (' 注意:這個 repo 自己設了 hooks 資料夾({path}),open-pushscan 在這裡不會檢查。\n'
84
+ ' 要接上,在那個資料夾的 pre-commit、commit-msg、pre-push 最前面加一行:\n'
85
+ ' {cmd} hook <名稱> "$@" || exit 1',
86
+ ' Note: this repository sets its own hooks folder ({path}), so open-pushscan does not run here.\n'
87
+ ' To connect it, add this line at the top of pre-commit, commit-msg and pre-push in that folder:\n'
88
+ ' {cmd} hook <name> "$@" || exit 1'),
89
+ 'status_find': ('自己設了 hooks 資料夾、所以沒有被檢查的 repo:', 'Repositories with their own hooks folder (not checked):'),
90
+ 'status_find_none': ('沒有找到自己設 hooks 資料夾的 repo', 'No repositories with their own hooks folder were found'),
91
+ 'vis_public': ('公開', 'public'), 'vis_private': ('私人', 'private'), 'vis_unknown': ('查不到,當作公開', 'unknown, treated as public'),
92
+ 'no_remote': ('還沒設定', 'not set'),
93
+ 'uninstalled': ('已經移除。設定還留在 {path},要一起刪掉請加 --purge', 'Removed. Settings are kept in {path}; add --purge to delete them'),
94
+ 'purged': ('已經移除,設定也刪掉了', 'Removed, settings deleted too'),
95
+ }
96
+
97
+
98
+ def tx(key, l=None, **kw):
99
+ zh, en = TEXT[key]
100
+ kw.setdefault('cmd', command())
101
+ return (zh if (l or lang()) == 'zh' else en).format(**kw)
102
+
103
+
104
+ def _utf8():
105
+ for s in (sys.stdout, sys.stderr):
106
+ try:
107
+ s.reconfigure(encoding='utf-8', errors='replace')
108
+ except (AttributeError, ValueError):
109
+ pass
110
+
111
+
112
+ def _repo():
113
+ top = gitscan.toplevel()
114
+ url = gitscan.remote_url()
115
+ return top, url, config.repo_key(top, url)
116
+
117
+
118
+ # ---------------------------------------------------------------- setup
119
+
120
+ def cmd_setup(args) -> int:
121
+ l = lang()
122
+ interactive = sys.stdin.isatty() and not args.yes
123
+ config.ensure()
124
+ print(tx('setup_title', l))
125
+ print()
126
+ copied = config.migrate_old()
127
+ if copied:
128
+ print(tx('migrated', l, files='、'.join(copied) if l == 'zh' else ', '.join(copied)))
129
+ print()
130
+
131
+ if args.github_action:
132
+ return _write_action(l)
133
+
134
+ print(tx('fp_step', l))
135
+ existing = config.fingerprints(include_off=True)
136
+ known = {f.value.lstrip('-').lower() for f in existing}
137
+ found = fpmod.detect()
138
+ new = [f for f in found if f.value.lower() not in known]
139
+ merged = existing + new
140
+ config.write_fingerprints(merged)
141
+ active = [f for f in merged if not f.value.startswith('-')]
142
+ counts = {}
143
+ for f in active:
144
+ counts[f.label] = counts.get(f.label, 0) + 1
145
+ summary = ('、' if l == 'zh' else ', ').join(f'{fpmod.label_text(k, l)} {v}' for k, v in counts.items())
146
+ print(tx('fp_found', l, n=len(active), summary=summary))
147
+ if existing and new:
148
+ print(tx('fp_new', l, n=len(new)))
149
+ print(tx('fp_file', l, path=config.path('fingerprints.txt')))
150
+ if interactive:
151
+ extra = input(tx('fp_ask', l))
152
+ added = [w.strip() for w in extra.replace(',', ',').split(',') if w.strip() and w.strip().lower() not in known]
153
+ if added:
154
+ merged += [fpmod.Fingerprint(w, 'added') for w in added]
155
+ config.write_fingerprints(merged)
156
+ print(tx('fp_added', l, n=len(added)))
157
+ print()
158
+
159
+ print(tx('team_step', l))
160
+ url = args.team
161
+ current = config.get('team_url')
162
+ if url is None and interactive:
163
+ url = input(tx('team_ask', l)).strip()
164
+ if url:
165
+ ok = config.clone_team(url)
166
+ print(tx('team_ok', l, n=len(config.team_rules())) if ok else tx('team_fail', l))
167
+ elif current:
168
+ print(tx('team_keep', l, url=current))
169
+ else:
170
+ print(tx('team_skip', l))
171
+ print()
172
+
173
+ print(tx('install_step', l))
174
+ prev = hooks.install()
175
+ print(tx('install_ok', l))
176
+ if prev:
177
+ print(tx('install_prev', l, prev=prev))
178
+ print()
179
+
180
+ print(tx('ai_step', l))
181
+ names = agents.found()
182
+ if not names:
183
+ print(tx('ai_none', l))
184
+ else:
185
+ print(tx('ai_found', l, names='、'.join(names) if l == 'zh' else ', '.join(names)))
186
+ if interactive and input(tx('ai_ask', l)).strip().lower() in ('n', 'no', '否'):
187
+ print(tx('ai_skip', l))
188
+ else:
189
+ for name, changed, problem in agents.install(l):
190
+ if problem:
191
+ print(tx('ai_fail', l, name=name, path=problem))
192
+ continue
193
+ home = os.path.expanduser('~')
194
+ shown = [p.replace(home, '~', 1) if p.startswith(home) else p for p in changed]
195
+ print(tx('ai_ok', l, name=name, files=('、' if l == 'zh' else ', ').join(shown)))
196
+ if name == 'Codex':
197
+ print(tx('ai_codex', l))
198
+ print()
199
+ print(tx('done', l))
200
+ return 0
201
+
202
+
203
+ ACTION = """name: open-pushscan
204
+ # Checks every push and pull request for things that should not be public.
205
+ on: [push, pull_request]
206
+ permissions:
207
+ contents: read
208
+ jobs:
209
+ open-pushscan:
210
+ runs-on: ubuntu-latest
211
+ steps:
212
+ - uses: actions/checkout@v4
213
+ with:
214
+ fetch-depth: 0
215
+ - uses: yu-ken0207/open-pushscan@v0
216
+ with:
217
+ team-rules: ${{ secrets.OPEN_PUSHSCAN_RULES }}
218
+ """
219
+
220
+
221
+ def _write_action(l) -> int:
222
+ try:
223
+ top = gitscan.toplevel()
224
+ except gitscan.GitError:
225
+ print(tx('not_repo', l))
226
+ return 1
227
+ rel = os.path.join('.github', 'workflows', 'open-pushscan.yml')
228
+ p = os.path.join(top, rel)
229
+ if os.path.exists(p):
230
+ print(tx('action_exists', l, path=rel))
231
+ return 0
232
+ os.makedirs(os.path.dirname(p), exist_ok=True)
233
+ with open(p, 'w', encoding='utf-8', newline='\n') as f:
234
+ f.write(ACTION)
235
+ print(tx('action_ok', l, path=rel))
236
+ return 0
237
+
238
+
239
+ # ---------------------------------------------------------------- hooks
240
+
241
+ def _finish(findings, mode, vis, key, l) -> int:
242
+ """Print a report for a commit or push. Returns the exit code (1 stops git)."""
243
+ findings, notes = report.split(findings)
244
+ items = report.group(findings)
245
+ out, block = [], False
246
+ if items:
247
+ report.save(key, items)
248
+ block = visibility.blocks(vis)
249
+ if block:
250
+ unknown = vis == visibility.UNKNOWN
251
+ header = t(('blocked_push' if mode == 'push' else 'blocked_commit') + ('_unknown' if unknown else ''), l)
252
+ footer = [t('foot_push' if mode == 'push' else 'foot_commit', l), t('foot_allow', l, n=items[0]['n'])]
253
+ else:
254
+ header = t('warn', l, n=len(items))
255
+ footer = [t('foot_allow_any', l)]
256
+ out.append(report.render(items, header, footer, l))
257
+ if notes:
258
+ out.append(report.render_notes(notes, l))
259
+ sys.stderr.write('\n'.join(out))
260
+ return 1 if block else 0
261
+
262
+
263
+ def cmd_hook(args) -> int:
264
+ l = lang()
265
+ name = args.name
266
+ try:
267
+ top = gitscan.toplevel()
268
+ except gitscan.GitError:
269
+ return 0 # bare repository or outside a work tree: nothing to check
270
+ os.chdir(top)
271
+ url = gitscan.remote_url()
272
+ key = config.repo_key(top, url)
273
+ scanner = Scanner(repo=key)
274
+ if name == 'pre-commit':
275
+ vis = visibility.check(url)
276
+ change = gitscan.staged()
277
+ findings = scanner.scan_change(change, gitscan.blob, gitscan.size) + gitleaks(staged=True)
278
+ return _finish(findings, 'commit', vis, key, l)
279
+ if name == 'commit-msg':
280
+ if not args.rest:
281
+ return 0
282
+ try:
283
+ with open(args.rest[0], encoding='utf-8', errors='replace') as f:
284
+ text = f.read()
285
+ except OSError:
286
+ return 0
287
+ text = text.split('# ------------------------ >8 ------------------------')[0]
288
+ message = '\n'.join(x for x in text.splitlines() if not x.startswith('#'))
289
+ vis = visibility.check(url)
290
+ return _finish(scanner.scan_message(message, ''), 'commit', vis, key, l)
291
+ if name == 'pre-push':
292
+ env = os.environ
293
+ if env.get('PRE_COMMIT_TO_REF'): # run by the pre-commit framework: what is pushed comes in variables
294
+ push_url = env.get('PRE_COMMIT_REMOTE_URL') or url
295
+ pushed = (f"{env.get('PRE_COMMIT_LOCAL_BRANCH') or 'HEAD'} {env['PRE_COMMIT_TO_REF']} "
296
+ f"{env.get('PRE_COMMIT_REMOTE_BRANCH') or '-'} {env.get('PRE_COMMIT_FROM_REF') or gitscan.ZERO}")
297
+ else:
298
+ push_url = args.rest[1] if len(args.rest) > 1 else url
299
+ pushed = sys.stdin.read()
300
+ vis = visibility.check(push_url)
301
+ config.update_team()
302
+ scanner = Scanner(repo=key)
303
+ ranges, tags = gitscan.pushed_ranges(pushed)
304
+ seen, findings = set(), []
305
+ for rng in ranges:
306
+ for c in gitscan.commits(rng):
307
+ if c.commit in seen:
308
+ continue
309
+ seen.add(c.commit)
310
+ findings += scanner.scan_change(c, gitscan.blob, gitscan.size)
311
+ findings += gitleaks(rng)
312
+ for tag in tags:
313
+ findings += scanner.scan_text(tag, 'tag')
314
+ return _finish(findings, 'push', vis, key, l)
315
+ return 0
316
+
317
+
318
+ # ---------------------------------------------------------------- check
319
+
320
+ def cmd_check(args) -> int:
321
+ l = lang()
322
+ try:
323
+ top, url, key = _repo()
324
+ except gitscan.GitError:
325
+ print(tx('not_repo', l))
326
+ return 2
327
+ os.chdir(top)
328
+ scanner = Scanner(repo=key)
329
+ findings = []
330
+ if args.history:
331
+ changes = gitscan.commits(['--all']) if gitscan.has_head() else []
332
+ what = t('what_history', l, n=len(changes))
333
+ rng = ['--all']
334
+ else:
335
+ changes = [gitscan.working()]
336
+ unpushed = gitscan.unpushed_args()
337
+ pushed = gitscan.commits(unpushed) if unpushed else []
338
+ changes += pushed
339
+ what = t('what_working', l) + ('、' if l == 'zh' else ', ') + t('what_unpushed', l, n=len(pushed))
340
+ rng = unpushed
341
+ for c in changes:
342
+ findings += scanner.scan_change(c, gitscan.blob, gitscan.size)
343
+ if rng:
344
+ findings += gitleaks(rng)
345
+ findings, notes = report.split(findings)
346
+ items = report.group(findings)
347
+ report.save(key, items)
348
+ if args.json:
349
+ print(json.dumps(items, ensure_ascii=False, indent=1))
350
+ return 1 if items else 0
351
+ if items:
352
+ print(report.render(items, t('check_found', l, n=len(items)), [t('foot_allow_any', l)], l, limit=10_000))
353
+ else:
354
+ print(t('check_clean', l, what=what))
355
+ if notes:
356
+ print()
357
+ print(report.render_notes(notes, l), end='')
358
+ return 1 if items else 0
359
+
360
+
361
+ # ---------------------------------------------------------------- allow, status, uninstall
362
+
363
+ def cmd_allow(args) -> int:
364
+ l = lang()
365
+ try:
366
+ _top, _url, key = _repo()
367
+ except gitscan.GitError:
368
+ print(tx('not_repo', l))
369
+ return 2
370
+ if not sys.stdin.isatty() or any(os.environ.get(v) for v in agents.AGENT_ENV):
371
+ print(tx('allow_person', l, nums=' '.join(map(str, args.numbers))))
372
+ return 1
373
+ items = config.last_report(key)
374
+ if not items:
375
+ print(tx('allow_none', l))
376
+ return 1
377
+ chosen = []
378
+ for n in args.numbers:
379
+ if 1 <= n <= len(items):
380
+ chosen.append(items[n - 1])
381
+ else:
382
+ print(tx('allow_bad', l, n=n, total=len(items)))
383
+ if not chosen:
384
+ return 1
385
+ for item in chosen:
386
+ print('\n'.join(report.brief(item, l)))
387
+ if input(tx('allow_confirm', l, n=len(chosen))).strip().lower() not in ('y', 'yes', '是'):
388
+ print(tx('allow_cancel', l))
389
+ return 1
390
+ for item in chosen:
391
+ config.add_allowed(item['rule'], item['text'], '*' if args.everywhere else key)
392
+ print(tx('allow_ok', l, text=item['text'], scope=tx('scope_all' if args.everywhere else 'scope_repo', l)))
393
+ return 0
394
+
395
+
396
+ def cmd_status(args) -> int:
397
+ l = lang()
398
+ if hooks.installed():
399
+ print(tx('status_installed', l))
400
+ elif hooks.global_hooks_path():
401
+ print(tx('status_other', l, path=hooks.global_hooks_path()))
402
+ else:
403
+ print(tx('status_not', l))
404
+ print(tx('status_settings', l, path=config.config_dir()))
405
+ stored = config.fingerprints()
406
+ print(tx('status_fp', l, n=len(stored) or len(fpmod.detect()), note='' if stored else tx('status_fp_live', l)))
407
+ team_url = config.get('team_url')
408
+ if team_url:
409
+ try:
410
+ with open(config.path('state', 'team-updated'), encoding='utf-8') as f:
411
+ when = f.read().strip()
412
+ except OSError:
413
+ when = '-'
414
+ print(tx('status_team', l, n=len(config.team_rules()), url=team_url, when=when))
415
+ else:
416
+ print(tx('status_team_none', l))
417
+ print(tx('status_rules', l, n=len(config.personal_rules()), a=len(config.allowed())))
418
+ protected = agents.status()
419
+ state = ('、' if l == 'zh' else ', ').join(tx('ai_on' if ok else 'ai_off', l, name=name) for name, ok in protected)
420
+ print(tx('status_ai', l, state=state or tx('ai_absent', l)))
421
+ import shutil
422
+ print(tx('status_gitleaks', l, state=tx('gl_yes' if shutil.which('gitleaks') else 'gl_no', l)))
423
+ try:
424
+ top, url, _key = _repo()
425
+ vis = visibility.check(url)
426
+ print()
427
+ print(tx('status_repo', l, top=top, url=url or tx('no_remote', l), vis=tx('vis_' + vis, l)))
428
+ override = hooks.repo_override(top)
429
+ if override:
430
+ print(tx('status_override', l, path=override))
431
+ except gitscan.GitError:
432
+ pass
433
+ if args.find_repos:
434
+ print()
435
+ found = hooks.find_overrides(os.path.expanduser('~'))
436
+ if found:
437
+ print(tx('status_find', l))
438
+ for repo, hp in found:
439
+ print(f' {repo} ({hp})')
440
+ else:
441
+ print(tx('status_find_none', l))
442
+ return 0
443
+
444
+
445
+ def cmd_uninstall(args) -> int:
446
+ l = lang()
447
+ hooks.uninstall()
448
+ agents.uninstall()
449
+ if args.purge:
450
+ import shutil
451
+ shutil.rmtree(config.config_dir(), ignore_errors=True)
452
+ print(tx('purged', l))
453
+ else:
454
+ print(tx('uninstalled', l, path=config.config_dir()))
455
+ return 0
456
+
457
+
458
+ def cmd_publish(args) -> int:
459
+ from . import publish
460
+ try:
461
+ gitscan.toplevel()
462
+ except gitscan.GitError:
463
+ print(tx('not_repo'))
464
+ return 2
465
+ return publish.run(lang())
466
+
467
+
468
+ def cmd_ci(args) -> int:
469
+ from . import ci
470
+ return ci.run(lang())
471
+
472
+
473
+ # ---------------------------------------------------------------- entry
474
+
475
+ def main(argv=None) -> int:
476
+ _utf8()
477
+ zh = lang() == 'zh'
478
+ p = argparse.ArgumentParser(prog='open-pushscan', description=(
479
+ '推到公開的地方之前,檢查有沒有洩漏你是誰、用哪台電腦、公司內部資訊,以及密碼和金鑰。' if zh else
480
+ 'Before code goes public, check it for anything that tells who you are, which computer you use, '
481
+ 'what is internal to your organisation, and for passwords and keys.'))
482
+ p.add_argument('--version', action='version', version=f'open-pushscan {__version__}')
483
+ sub = p.add_subparsers(dest='cmd', metavar='')
484
+ s = sub.add_parser('setup', help='第一次用:裝好、找指紋、接團隊規則' if zh else 'first time: install, find fingerprints, team rules')
485
+ s.add_argument('--yes', action='store_true', help='不要問問題' if zh else 'do not ask questions')
486
+ s.add_argument('--team', metavar='URL', help='團隊規則 repo 的網址' if zh else 'address of the team rules repository')
487
+ s.add_argument('--github-action', action='store_true', help='在目前的 repo 建好 GitHub Action 設定檔' if zh else 'add the GitHub Action to this repository')
488
+ c = sub.add_parser('check', help='手動檢查目前的 repo' if zh else 'check the current repository now')
489
+ c.add_argument('--history', action='store_true', help='檢查整段歷史' if zh else 'check the whole history')
490
+ c.add_argument('--json', action='store_true', help='用 JSON 輸出' if zh else 'output JSON')
491
+ sub.add_parser('publish-check', help='私人 repo 改公開前的完整檢查' if zh else 'full check before making a private repo public')
492
+ a = sub.add_parser('allow', help='把報告的第幾項放行' if zh else 'allow an item from the last report')
493
+ a.add_argument('numbers', type=int, nargs='+', metavar='N')
494
+ a.add_argument('--everywhere', action='store_true', help='所有 repo 都放行' if zh else 'allow in every repository')
495
+ st = sub.add_parser('status', help='看有沒有裝好、指紋和規則' if zh else 'show what is installed and checked')
496
+ st.add_argument('--find-repos', action='store_true', help='找出自己設了 hooks 資料夾的 repo' if zh else 'find repositories with their own hooks folder')
497
+ u = sub.add_parser('uninstall', help='移除' if zh else 'remove')
498
+ u.add_argument('--purge', action='store_true', help='連設定一起刪掉' if zh else 'also delete settings')
499
+ h = sub.add_parser('hook')
500
+ h.add_argument('name')
501
+ h.add_argument('rest', nargs=argparse.REMAINDER)
502
+ sub.add_parser('ci')
503
+ sub.add_parser('guard')
504
+ args = p.parse_args(argv)
505
+ handlers = {'setup': cmd_setup, 'check': cmd_check, 'publish-check': cmd_publish, 'allow': cmd_allow,
506
+ 'status': cmd_status, 'uninstall': cmd_uninstall, 'hook': cmd_hook, 'ci': cmd_ci,
507
+ 'guard': lambda _args: agents.guard_main()}
508
+ if not args.cmd:
509
+ p.print_help()
510
+ return 0
511
+ try:
512
+ return handlers[args.cmd](args)
513
+ except KeyboardInterrupt:
514
+ return 130
515
+ except gitscan.GitError as e:
516
+ if args.cmd == 'hook':
517
+ sys.stderr.write(f'open-pushscan: git error, check skipped: {e}\n')
518
+ return 0
519
+ if args.cmd == 'guard':
520
+ return 0
521
+ print(f'open-pushscan: {e}', file=sys.stderr)
522
+ return 2
523
+ except Exception as e: # a bug must never leave someone unable to commit
524
+ if args.cmd == 'guard':
525
+ return 0
526
+ if args.cmd == 'hook':
527
+ sys.stderr.write(('open-pushscan 出錯了,這次沒有檢查:' if zh else 'open-pushscan failed, nothing was checked this time: ')
528
+ + f'{type(e).__name__}: {e}\n')
529
+ return 0
530
+ raise
531
+
532
+
533
+ if __name__ == '__main__':
534
+ sys.exit(main())