Repository navigation
Expand file tree
/
Copy pathskill-gate.py
More file actions
executable file
·1219 lines (1071 loc) · 57.9 KB
/
Copy pathskill-gate.py
File metadata and controls
executable file
·1219 lines (1071 loc) · 57.9 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""The publish gate.
NOT AUDITED — AI-generated tooling. Review before executing in any privileged context.
A command that would push, post, merge, close, delete, mark ready or force-push is
refused unless the user typed its slash command in the turn, per skills/shortcuts.md;
so is a commit whose identity is set by hand. A pre-commit hook refuses a gitlink no
remote holds and a workflow script that does not parse. Reading a skill before writing
its artifact is a rule, not something this gate checks.
./scripts/skill-gate.py hook-claude Claude Code PreToolUse adapter on Bash, hook JSON on stdin:
exit 2 with the reason on a refused command
./scripts/skill-gate.py pre-commit the refusals on the commit staged in the repo at cwd
Another harness wires its before-command hook to `hook-claude` when its payload carries
tool_name and tool_input the same way. The commit hook holds without any harness.
Lives in the skills repository as scripts/skill-gate.py; a workspace mounting it at skills/
wires its hooks to skills/scripts/skill-gate.py, or keeps a shim at scripts/skill-gate.py.
"""
import json
import os
import re
import shutil
import shlex
import subprocess
import sys
import urllib.parse
from pathlib import Path
WRAPPERS = {'command', 'exec', 'sudo', 'env', 'nice', 'timeout', 'nohup', 'xargs', 'setsid'}
SHELLS = {'bash', 'sh', 'zsh', 'dash'}
HEREDOC = re.compile(r'(?<!<)<<(?!<)-?\s*([\'"]?)(\w+)\1')
def root():
"""The workspace: SKILL_GATE_ROOT, else the nearest ancestor holding an AGENTS.md and the skills/ this file lives in."""
env = os.environ.get('SKILL_GATE_ROOT')
if env:
return Path(env)
here = Path(__file__).resolve()
for d in here.parents:
if (d / 'AGENTS.md').is_file() and (d / 'skills').is_dir():
return d
return here.parent.parent
def _git(cwd, *args):
return subprocess.run(['git', *args], cwd=cwd, capture_output=True, text=True, check=True).stdout
def cmd_pre_commit(cwd):
top = Path(_git(cwd, 'rev-parse', '--show-toplevel').strip())
staged = [line for line in _git(cwd, 'diff', '--cached', '--name-only', '--diff-filter=ACMR').splitlines() if line]
refused = runner_parse_errors(top, staged) + unpushed_gitlinks(top, cwd)
for line in refused:
print(f'refused: {line}', file=sys.stderr)
return 1 if refused else 0
def runner_parse_errors(top, staged):
"""A staged workflow script that does not parse, wrapped as the async function body the harness runs it as: a bare
backtick in a prompt string once shipped and every launch died before an agent ran, and `node --check` on the raw
file fails on the top-level return a healthy script carries. Nothing is checked when node is absent."""
scripts = [p for p in staged if p.startswith('scripts/workflows/') and p.endswith('.js')]
if not scripts or shutil.which('node') is None:
return []
out = []
for p in scripts:
src = (top / p).read_text()
wrapped = '(async()=>{' + re.sub(r'^export const meta', 'const meta', src, count=1, flags=re.M) + '})'
run = subprocess.run(['node', '-e', 'new (require("vm").Script)(require("fs").readFileSync(0, "utf8"))'],
input=wrapped, capture_output=True, text=True)
if run.returncode != 0:
first = next((l for l in run.stderr.splitlines() if l.strip()), 'syntax error')
out.append(f'{p} does not parse as a workflow script: {first.strip()}')
return out
def _own_repo_env():
"""The environment minus every variable that ties git to the repository at hand, as `git rev-parse --local-env-vars`
lists them: a hook in a linked worktree gets an absolute GIT_DIR, and a `git -C <submodule>` under it reads the
parent's object store."""
local = set(subprocess.run(['git', 'rev-parse', '--local-env-vars'], capture_output=True, text=True).stdout.split())
local = local or {'GIT_DIR', 'GIT_INDEX_FILE', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_OBJECT_DIRECTORY'}
return {k: v for k, v in os.environ.items() if k not in local}
def unpushed_gitlinks(top, cwd):
"""A staged submodule pointer at a commit no remote branch of that submodule holds: a clone cannot resolve it and
every later push of this repository is refused over it, so the submodule is pushed first."""
out = []
env = _own_repo_env()
for line in _git(cwd, 'diff', '--cached', '--raw').splitlines():
parts = line.split('\t')
if len(parts) != 2 or not parts[0].startswith(':'):
continue
meta, path = parts[0].split(), parts[1]
if len(meta) < 4 or meta[1] != '160000':
continue
sha = meta[3]
sub = top / path
if not (sub / '.git').exists():
continue
def held():
r = subprocess.run(['git', '-C', str(sub), 'branch', '-r', '--contains', sha], capture_output=True, text=True,
env=env)
return r.returncode == 0 and r.stdout.strip()
if held():
continue
# A fresh worktree's submodule carries the remote-tracking refs of its clone, stale until fetched.
# Bounded and non-interactive: the hook runs on every commit, network or not.
quiet = {**env, 'GIT_TERMINAL_PROMPT': '0', 'GIT_SSH_COMMAND': 'ssh -o BatchMode=yes -o ConnectTimeout=10'}
try:
subprocess.run(['git', '-C', str(sub), 'fetch', '-q', 'origin'], capture_output=True, env=quiet,
stdin=subprocess.DEVNULL, timeout=20)
except subprocess.TimeoutExpired:
pass
if not held():
out.append(f'{path} points at {sha[:9]}, which no remote branch of that submodule holds: push the submodule '
'first, or fetch it where the push already landed')
return out
# What the user typed this turn: the prompt that opened it and every message queued into it
# while it ran. A publish, a push outside the standing list and a forced push each wait for
# their word there, per Invariants 1, 2, 3 and 8 of skills/core.md.
#
# This is a net for an honest agent's slip, read from the command's text, and never a sandbox: a
# shell can send a push in more forms than a reading can follow, a script generated at run time
# for one. Where the reading cannot place a push it asks for the word; the words themselves, in
# core.md and the workspace's standing words, stay the control.
NOT_TYPED = ('<task-notification', '<command-', '<local-command-', '<system-reminder', '[SYSTEM NOTIFICATION',
'Another Claude session sent a message:', '<cross-session-message', '<side-sessions-event',
'<ci-monitor-event', 'Background (from the session that started this one)')
LEADING_REMINDERS = re.compile(r'\s*(?:<system-reminder>.*?</system-reminder>\s*)+', re.S)
COMMAND = '\x1f' # opens the line turn_text writes for a typed slash command, a character no keyboard types
COMMAND_NAME = re.compile(r'<command-name>(/[\w:-]+)</command-name>')
COMMAND_ARGS = re.compile(r'<command-args>(.*?)</command-args>', re.S)
COMMAND_TAGS = re.compile(r'(?:\s*<command-(message|name|args)>.*?</command-\1>)+\s*', re.S)
def turn_text(transcript):
"""The user's typed text this turn, or None when the transcript cannot be read."""
try:
lines = open(transcript, encoding='utf-8', errors='replace').read().split('\n')
except (OSError, TypeError):
return None
rows, raws = [], []
for line in lines:
line = line.strip().strip('\x00')
if not line:
continue
try:
row = json.loads(line)
except ValueError:
continue
if isinstance(row, dict):
rows.append(row)
raws.append(line)
starts = []
for i, e in enumerate(rows):
if e.get('type') == 'user' and not e.get('isMeta') and not e.get('isCompactSummary'):
typed = _said(e)
if typed is not None:
starts.append((i, typed))
if not starts:
return ''
# A turn the API killed never finished: a retry typed after it resumes that turn, so the
# words given there still hold, however many retries it took. A question asked while the
# request's work still runs ends no word either, per Consent in skills/core.md.
k = len(starts) - 1
while k > 0 and (RETRY.match(starts[k][1]) and _died(rows[starts[k - 1][0]:starts[k][0]])
or _status_question(starts[k][1]) and _still_running(rows, raws, starts[k][0])):
k -= 1
parts = []
for n, (start, first) in enumerate(starts[k:], k):
end = starts[n + 1][0] if n + 1 < len(starts) else len(rows)
parts.append(first)
for e in rows[start + 1:end]:
a = e.get('attachment') or {}
if e.get('type') == 'attachment' and a.get('type') == 'queued_command' \
and (a.get('origin') or {}).get('kind') == 'human':
queued = str(a.get('prompt', '')).replace(COMMAND, '')
parts.append(COMMAND + ' '.join(queued.split()) if queued.startswith('/') else queued)
return '\n'.join(parts)
RETRY = re.compile(r'(?i)^\s*(try again|retry)\W*$')
def _died(rows):
"""The turn these rows hold ended on an API error rather than a reply."""
last = next((e for e in reversed(rows) if e.get('type') == 'assistant'), None)
return bool(last and last.get('isApiErrorMessage'))
# A question about the work in flight: one line, ending on `?` or opening on a word that asks.
ASKS = re.compile(r'(?i)(?:why|what|how|did|does|is|are|where|when|wyd|hello|status|all good|ag|still)\b')
NOTIFIED = re.compile(r'<task-id>([\w-]+)</task-id>|<agent-message from="([\w-]+)"')
def _status_question(text):
t = text.strip()
return bool(t) and '\n' not in t and (t.endswith('?') or bool(ASKS.match(t)))
def _still_running(rows, raws, at):
"""Work launched before row `at` reports after it: a notification names a task an earlier row holds."""
for e in rows[at + 1:]:
for task in _notified(e):
if any(task in r for r in raws[:at]):
return True
return False
def _notified(e):
"""The tasks a harness notification names; a typed message and a tool result name none."""
a = e.get('attachment') or {}
if e.get('type') == 'attachment' and a.get('type') == 'queued_command':
if (a.get('origin') or {}).get('kind') == 'human':
return []
text = str(a.get('prompt', ''))
elif e.get('type') == 'user':
if _said(e) is not None:
return []
text = _typed(e) or ''
else:
return []
return [x or y for x, y in NOTIFIED.findall(text)]
def _said(e):
"""What the user typed in a user entry, past the reminders the app puts in front of it; None where nobody typed."""
text = _typed(e)
if text is None:
return None
lead = LEADING_REMINDERS.match(text)
if lead:
# A session's message or an event follows a reminder too, and only the human origin tells them apart.
if (e.get('origin') or {}).get('kind') != 'human' or lead.end() == len(text):
return None
text = text[lead.end():]
# A slash command the user typed reaches the transcript as tags, which turn_text keeps as one COMMAND line; tags
# it cannot read still open a turn, which then gives nothing, and another session's never count.
if text.lstrip().startswith('<command-'):
name = COMMAND_NAME.search(text) if COMMAND_TAGS.fullmatch(text) else None
if not name or (e.get('origin') or {}).get('kind') not in (None, 'human'):
return ''
args = COMMAND_ARGS.search(text)
return COMMAND + name.group(1) + ' ' + ' '.join((args.group(1) if args else '').split())
return None if text.lstrip().startswith(NOT_TYPED) else text.replace(COMMAND, '')
def _typed(e):
"""A user entry's typed text: a string, or the text blocks of a list holding no tool result."""
c = (e.get('message') or {}).get('content')
if isinstance(c, str):
return c
if isinstance(c, list) and c and not any(isinstance(b, dict) and b.get('type') == 'tool_result' for b in c):
return '\n'.join(b.get('text', '') for b in c if isinstance(b, dict) and b.get('type') == 'text')
return None
# The slash commands that give the gate's words, per skills/shortcuts.md, each under the NAMESPACE that
# commands/<namespace>/ gives it; typed prose gives none. Each leading argument that is one of the command's FLAGS,
# the arguments its file lists, gives its words too, and the first other word, a target, ends them:
# `/ws:push delete` pushes and deletes, `/ws:review ai o/r#5` posts, `/ws:fix merge conflict` merges nothing.
# `/ws:push` pushes what the closing block named and posts nothing; `/ws:post` pushes what its draft links, then posts.
NAMESPACE = 'ws:'
COMMANDS = {
'push': {'push'}, 'post': {'post', 'push'}, 'upload': {'upload'}, 'merge': {'merge', 'ready'}, 'close': {'close'},
'delete': {'delete'}, 'ready': {'ready'}, 'review': set(), 'fix': set(),
}
FLAGS = {
'push': {'review': set(), 'loop': set(), 'force': {'force'},
**{w: {w} for w in ('delete', 'close', 'ready')}, 'merge': {'merge', 'ready'}},
'post': {'ai': set()},
'review': {'ai': {'post'}, 'merge': {'review-merge'}, **dict.fromkeys(('quick', 'deep', 'all', 'plan', 'branch', 'public', 'cost'), set())},
'fix': {'ai': {'push', 'post'}, 'quick': {'push', 'post', 'own-merge'}},
}
# review-merge allows a plain `gh pr merge` and nothing else a merge word allows: no push, no --auto, no --admin,
# no branch delete; own-merge allows the same on a repository the user's login owns. Each holds only beside the
# command's leading arguments listed here.
PINNED_MERGE_BESIDE = {'review': {'quick', 'deep', 'ai', 'merge'}, 'fix': {'quick'}}
def _command(word):
"""A command's name without its slash and namespace; a name outside the namespace is no command."""
word = word[1:] if word.startswith('/') else word
return word[len(NAMESPACE):] if word.startswith(NAMESPACE) else ''
def command_words(text):
"""The gate's words the turn's slash commands give, read from the lines turn_text marks with COMMAND."""
given = set()
for line in text.splitlines():
if line.startswith(COMMAND):
name, *args = line[len(COMMAND):].lower().split() or ['']
name = _command(name)
if name not in COMMANDS:
continue
words, led = set(COMMANDS[name]), []
for a in args:
flag = FLAGS.get(name, {}).get(a)
if flag is None:
break
led.append(a)
words |= flag
# `/ws:review merge` merges one round's pull request: beside a scope, a dry run or a `set` it merges nothing.
if set(led) - PINNED_MERGE_BESIDE.get(name, set()) or args[len(led):len(led) + 1] == ['set']:
words -= {'review-merge', 'own-merge'}
given |= words
return given
def gives_force(text):
"""The turn approves a forced push: `/ws:push force`."""
return 'force' in command_words(text)
def gives(text, word):
"""The turn gives the word: one of its slash commands gives it."""
return word in command_words(text)
# A Co-authored-by trailer is refused only where it names a model or a bot: a human reviewer whose
# fix a commit applies is credited with one, per *Commit identity* in skills/git.md.
MARKER = re.compile(r'(?i)co-authored-by:[^\n"]*(?:claude|anthropic|copilot|openai|chatgpt|gemini|\bai\b|\[bot\])'
r'|generated with \[?claude|assisted by ai|\U0001F916')
SHELL_LEAD = {'do', 'then', 'else', 'elif', 'if', 'while', 'until', '{', '(', '!', 'and', 'or', 'not'}
RUNNERS = {'bash', 'sh', 'zsh', 'fish', 'python', 'python3'}
# A wrapper and the options it takes a value for; its first bare word after them may be its own argument.
WRAPPERS = {'timeout': ({'-s', '--signal', '-k', '--kill-after'}, 1), 'nice': ({'-n', '--adjustment'}, 0),
'sudo': ({'-u', '-g', '-C', '-h', '-p', '-U'}, 0), 'env': ({'-u', '--unset', '-C', '--chdir'}, 0),
'xargs': ({'-I', '-L', '-n', '-P', '-d', '-E', '-s', '-a'}, 0), 'time': ({'-f', '-o'}, 0),
'stdbuf': ({'-i', '-o', '-e'}, 0), 'nohup': (set(), 0), 'exec': ({'-a'}, 0), 'command': (set(), 0)}
SHELLS = {'bash', 'sh', 'zsh', 'fish', 'dash'}
POST_SCRIPTS = {'post', 'post-review.sh', 'post-replies', 'post-fix.sh', 'post-pr-review.py', 'pr-body-apply'}
def _names(cmd):
"""The shell variables a line assigns, NAME=value, for filling a path or a repository."""
return dict(re.findall(r'(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=["\']?([^\s;&|()"\']+)', cmd))
def _fill(v, names):
for _ in range(4):
v = re.sub(r'\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?', lambda m: names.get(m.group(1), os.environ.get(m.group(1), m.group(0))), v)
return os.path.expanduser(v.strip('"\''))
def _shell_script(cmd, path, cwd=None):
"""What a shell runs from a file or from stdin: the file, the heredoc this line writes into it,
or the heredoc fed straight to the shell. The workspace's own scripts/ are its tooling, governed
by their own words, and are not read."""
names = _names(cmd)
if path:
full = os.path.realpath(os.path.join(cwd or os.getcwd(), _fill(path, names)))
tooling = [str(root() / 'scripts'), str(root() / 'skills' / 'scripts')]
if any(full.startswith(d + os.sep) for d in tooling):
return None
try:
if os.path.isfile(full):
return _to_exit(open(full, encoding='utf-8', errors='replace').read())
except (OSError, ValueError):
pass
for m in re.finditer(r'>\s*(\S+)\s*<<-?\s*([\'"]?)(\w+)\2.*?\n(.*?)\n\s*\3\b', cmd, re.S):
if os.path.realpath(os.path.join(cwd or os.getcwd(), _fill(m.group(1), names))) == full:
return _to_exit(m.group(4))
return None
bodies = [m.group(4) for m in re.finditer(r'\b(bash|sh|zsh|dash)\b[^\n]*?<<-?\s*([\'"]?)(\w+)\2.*?\n(.*?)\n\s*\3\b', cmd, re.S)]
return '\n'.join(bodies) or None
def _to_exit(script):
"""A script up to its first top-level exit: what follows it never runs as shell."""
m = re.search(r'^exit\b.*$', script, re.M)
return script[:m.start()] if m else script
def _strip_heredocs(cmd):
out, lines, i = [], cmd.split('\n'), 0
while i < len(lines):
out.append(lines[i])
m = HEREDOC.search(lines[i])
i += 1
if m:
while i < len(lines) and lines[i].strip() != m.group(2):
i += 1
i += 1
return '\n'.join(out)
def _split(cmd, ops=False):
lex = shlex.shlex(cmd, posix=True, punctuation_chars=';&|\n()<>')
lex.whitespace = ' \t\r'
lex.whitespace_split = True
seg = []
try:
for tok in lex:
if tok and set(tok) <= set(';&|\n()'):
if seg:
yield seg
seg = []
if ops:
for ch in tok:
if ch in '()':
yield ['\x00' + ch]
else:
seg.append(tok)
except ValueError:
for line in cmd.split('\n'):
for part in re.split(r'&&|\|\||;|\||\(|\)', line):
if part.split():
yield part.split()
return
if seg:
yield seg
def _shell_files(t):
"""A shell's operands past its options: -o, -O, +o and +O take a value, and so does a cluster ending in o or O."""
out, i = [], 1
while i < len(t):
x = t[i]
if x in ('-o', '+o', '-O', '+O') or re.match(r'^[-+][A-Za-z]*[oO]$', x):
i += 2
continue
if not x.startswith(('-', '+')):
out.append(x)
i += 1
return out
def _segments(cmd, depth=0, ops=False, cwd=None, collect=None):
"""The simple commands of a shell line: heredoc bodies dropped, split outside quotes, a leading
keyword, environment assignment or $( stripped, and a `bash -c` string read as its own line."""
here = cwd
for t in _split(_strip_heredocs(cmd), ops):
if t and t[0].startswith('\x00'):
yield t
continue
if len(t) >= 2 and t[0] in ('cd', 'pushd') and here:
here = os.path.join(here, _fill(t[1], _names(cmd)))
t = [x.rstrip('$').lstrip('`') for x in t]
t = [x for x in t if x]
while t:
head = os.path.basename(t[0])
if t[0] in SHELL_LEAD or re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', t[0]):
t = t[1:]
elif head in WRAPPERS:
takes, bare = WRAPPERS[head]
i = 1
while i < len(t) and (t[i].startswith('-') or re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', t[i])):
i += 2 if t[i] in takes else 1
t = t[i + bare:]
else:
break
kept, drop = [], False
for x in t:
if drop:
drop = False
elif x and set(x) <= set('<>&-') and ('<' in x or '>' in x):
# A redirection: the operator, its target and a file-descriptor number before it.
if kept and kept[-1].isdigit():
kept.pop()
drop = True
else:
kept.append(x)
t = kept
if not t:
continue
files = _shell_files(t) if os.path.basename(t[0]) in SHELLS else [x for x in t[1:] if not x.startswith('-')]
if os.path.basename(t[0]) in SHELLS and any(re.match(r'^-[A-Za-z]*n[A-Za-z]*$', x) for x in t[1:]):
continue # -n reads a script for syntax and runs nothing
if os.path.basename(t[0]) in SHELLS and files and os.path.basename(files[0]) in POST_SCRIPTS:
t = t[t.index(files[0]):]
elif os.path.basename(t[0]) in SHELLS and depth < 3 and not any(re.match(r'^-[A-Za-z]*c[A-Za-z]*$', x) for x in t[1:]):
if any(re.match(r'^-[A-Za-z]*n[A-Za-z]*$', x) for x in t[1:]):
continue # -n reads the script for syntax and runs nothing
script = _shell_script(cmd, files[0] if files else None, here)
if script:
if collect is not None:
collect.append(script)
# A script runs in a shell of its own: its cd ends with it.
if ops:
yield ['\x00(']
yield from _segments(script, depth + 1, ops, here, collect)
if ops:
yield ['\x00)']
continue
if t[0] == 'eval' and depth < 3:
yield from _segments(' '.join(t[1:]), depth + 1)
continue
if os.path.basename(t[0]) in RUNNERS and depth < 3:
i, script = 1, None
while i < len(t) and t[i].startswith(('-', '+')):
if t[i] in ('-o', '+o', '-O', '+O') or re.match(r'^[-+][A-Za-z]*[oO]$', t[i]):
i += 2
continue
if re.match(r'^-[A-Za-z]*c[A-Za-z]*$', t[i]) and i + 1 < len(t):
script = t[i + 1]
break
i += 1
if script is not None:
yield from _segments(script, depth + 1, ops)
continue
if os.path.basename(t[0]) in RUNNERS and len(t) > 1 and not t[1].startswith('-'):
t = t[1:]
t[0] = os.path.basename(t[0]) if t[0].endswith(('/gh', '/git')) else t[0]
yield t
def _dry(tokens):
return any(x in ('--dry-run', '--help', '-h', '--list') for x in tokens)
def _git_sub(t):
"""git's subcommand, past -C <dir>, -c <k=v> and other global options."""
i = 1
while i < len(t) and t[i].startswith('-'):
i += 2 if t[i] in ('-C', '-c', '--git-dir', '--work-tree', '--namespace') else 1
return (t[i], i) if i < len(t) else (None, i)
def _gh_verb(t):
"""gh's two-word verb past -R <repo> and other global flags."""
rest, i = [], 1
while i < len(t):
if t[i] in ('-R', '--repo', '--hostname'):
i += 2
continue
rest.append(t[i])
i += 1
return rest
def _field_values(t):
out = []
for i, x in enumerate(t):
if x in ('-f', '-F', '--field', '--raw-field') and i + 1 < len(t):
out.append(t[i + 1])
elif x.startswith(('-f', '-F')) and len(x) > 2 and not x.startswith('--'):
out.append(x[2:])
elif x.startswith(('--field=', '--raw-field=')):
out.append(x.split('=', 1)[1])
return out
def _read_at(value):
if value.startswith('@'):
try:
return open(os.path.expanduser(value[1:]), encoding='utf-8', errors='replace').read()
except OSError:
return value
return value
def every_change_repos():
try:
return {norm_repo(r) for r in json.loads((root() / 'workspace.json').read_text()).get('word_for_every_change', [])}
except (OSError, ValueError):
return set()
def norm_repo(x):
x = re.sub(r'^(https?://)?(www\.)?github\.com[:/]', '', x.strip().strip('"\'')).rstrip('/')
x = re.sub(r'\.git$', '', x)
return '/'.join(x.split('/')[:2]).lower()
def _gh_repos(t, cwd, line=''):
out = {norm_repo(v) for v in re.findall(r'\bGH_REPO=(\S+)', line)}
for i, x in enumerate(t):
if x in ('-R', '--repo') and i + 1 < len(t):
out.add(norm_repo(t[i + 1]))
elif x.startswith('--repo='):
out.add(norm_repo(x.split('=', 1)[1]))
elif x.startswith('-R') and len(x) > 2:
out.add(norm_repo(x[2:]))
m = re.match(r'https://github\.com/([^/\s]+/[^/\s]+)/pull/\d+', x)
if m:
out.add(norm_repo(m.group(1)))
if not out and cwd:
out |= _remote_repos(cwd)
return out
def _remote_repos(cwd):
remotes = subprocess.run(['git', '-C', cwd, 'remote', '-v'], capture_output=True, text=True).stdout
return {norm_repo(f'{a}/{b}') for a, b in re.findall(r'github\.com[:/]([^/\s]+)/([^/\s]+?)(?:\.git)?\s', remotes)}
def own_login():
try:
return json.loads((root() / 'workspace.json').read_text())['identities']['public']['name'].lower()
except (OSError, ValueError, KeyError, TypeError):
return None
def merges_off():
"""Whether the consumer's workspace.json sets `merges` to anything but true: then this gate refuses every merge
command it sees, whatever word. With the key left out, or no workspace.json, merges stay on; a misspelt value, or a
workspace.json that is not a valid JSON object, turns them off."""
try:
return json.loads((root() / 'workspace.json').read_text()).get('merges', True) is not True
except OSError:
return False
except (ValueError, AttributeError):
return True
# Under merges off, a command reaching GitHub that names a merge by any route, or a GraphQL query the gate cannot read.
MERGE_ROUTE = re.compile(r'pulls/[^/\s"\']+/merge\b|\b(mergePullRequest|enablePullRequestAutoMerge|enqueuePullRequest|'
r'mergeBranch)\b|\bgh\s+pr\s+merge\b|\bgh\s+api\s+graphql\b[^|;&\n]*(=@|\$\(|`)')
UNMERGE_ONLY = re.compile(r'^\s*gh\s+pr\s+merge\b[^|;&\n]*--disable-auto[^|;&\n]*$')
def merge_refused(cmd, needs):
"""The refusal under merges off, else None; turning auto-merge off is no merge and stays allowed."""
if UNMERGE_ONLY.match(cmd) or not merges_off():
return None
calls_out = re.search(r'(^|[|;&(]|&&|\|\|)\s*(\S+=\S*\s+)*(gh|curl|wget|http)\b', cmd)
if any('merge' in n for n in needs) or (calls_out and MERGE_ROUTE.search(cmd)):
return ('a pull request merge, which workspace.json turns off with "merges": false, per Invariant 1 of '
'skills/core.md; the user merges it by hand or sets the key back.')
return None
def _own_unforked(repo):
"""Whether the user's login owns the repository and GitHub says it is no fork; a failed lookup says no."""
login = own_login()
return bool(login and repo) and repo.split('/')[0] == login and _gh_api(f'repos/{repo}', '.fork') == 'false\n'
def _closes_own_quietly(t, cwd, line=''):
"""Whether a gh pr close targets only the user's own repositories and says nothing and deletes nothing."""
login, repos = own_login(), _gh_repos(t, cwd, line)
loud = any(x.split('=')[0] in ('-c', '--comment', '-d', '--delete-branch') for x in t)
return bool(login and repos) and not loud and all(r.split('/')[0] == login for r in repos)
def standing_publish_draft():
"""The repositories where the user's own draft pull request, its text and its comments go up unasked."""
try:
return {norm_repo(r) for r in json.loads((root() / 'workspace.json').read_text()).get('standing_publish_draft', [])}
except (OSError, ValueError):
return set()
def standing_publish_review():
"""The repositories where a finished review round's draft goes up unasked, behind the AI marker."""
try:
return {norm_repo(r) for r in json.loads((root() / 'workspace.json').read_text()).get('standing_publish_review', [])}
except (OSError, ValueError):
return set()
def standing_issue_edit():
"""The issues, each `owner/repo#number`, whose body goes up unasked."""
try:
return {x.lower() for x in json.loads((root() / 'workspace.json').read_text()).get('standing_issue_edit', [])}
except (OSError, ValueError):
return set()
def _own_draft(repo, number):
"""Whether a pull request is an open draft the user authored; a failed read keeps the word."""
out = _gh_api(f'repos/{repo}/pulls/{number}', '[.state, .draft, .user.login] | map(tostring | ascii_downcase) | @tsv')
return bool(out) and out.split() == ['open', 'true', own_login()]
def _gh_target(t):
"""The pull request or issue number a gh verb names: its URL, or its first argument that no flag takes."""
for x in t:
m = re.match(r'https://github\.com/[^/\s]+/[^/\s]+/(?:pull|issues)/(\d+)', x)
if m:
return m.group(1)
r = _gh_verb(t)
return next((x for i, x in enumerate(r) if i > 1 and x.isdigit() and not r[i - 1].startswith('-')), None)
def _drafts_only(t, cwd, line=''):
"""Whether a gh verb posts only on the user's own draft, on a repository whose standing word covers one."""
repos, number = _gh_repos(t, cwd, line), _gh_target(t)
return bool(number and repos) and repos <= standing_publish_draft() and all(_own_draft(r, number) for r in repos)
def _post_fix_opens_draft(t, cwd):
"""Whether post-fix.sh opens a pull request alone, on a repository whose standing word covers a draft."""
dirs = [Path(cwd or os.getcwd(), x) for x in t[1:] if not x.startswith('-')]
if not dirs or ('--pr-only' not in t and any((d / 'issue.md').is_file() for d in dirs)):
return False
try:
bodies = [d / 'pr-body.md' for d in dirs if (d / 'pr-body.md').is_file()]
heads = [re.search(r'^Target:\s*https://github\.com/([^/\s]+/[^/\s]+)/compare/', b.read_text(), re.M) for b in bodies]
except OSError:
return False
return bool(heads) and all(m and norm_repo(m.group(1)) in standing_publish_draft() for m in heads)
def _sends_finished_round(t, cwd):
"""Whether post-review.sh sends one draft with `--as-ai` its one flag, to a repository whose standing word covers a round."""
args = [x for x in t[1:] if not re.fullmatch(r'\d*>\S*', x)]
drafts = [x for x in args if x != '--as-ai']
if len(args) != 2 or len(drafts) != 1 or drafts[0].startswith('-'):
return False
try:
title = Path(cwd or os.getcwd(), drafts[0]).read_text().split('\n', 1)[0]
except OSError:
return False
m = re.search(r'\(https://github\.com/([^/\s]+/[^/\s]+)/pull/\d+\)', title)
return bool(m) and norm_repo(m.group(1)) in standing_publish_review()
def _edits_beyond_body(t):
"""Whether a gh pr edit sets anything but the body: a flag's value, `-` for stdin among them, is skipped."""
free, i = ('--body', '-b', '--body-file', '-F', '-R', '--repo'), 3
while i < len(t):
x = t[i]
if x.split('=')[0] in free:
i += 1 if '=' in x else 2
continue
if x.startswith('-') and x != '-':
return True
i += 1
return False
def publish_words(cmd, cwd=None):
"""Each set is one publish on the line, satisfied by any of its words; every set needs its own."""
needs = []
strict = every_change_repos()
own = standing_publish() - strict
read = []
list(_segments(cmd, cwd=cwd, collect=read))
names = _names('\n'.join([cmd] + read))
for t in _segments(cmd, cwd=cwd):
t = [_fill(x, names) if '$' in x and not x.startswith('$(') else x for x in t]
if len(t) >= 2 and t[0] in ('cd', 'pushd'):
cwd = os.path.join(cwd or os.getcwd(), os.path.expanduser(t[1].strip('"\'')))
continue
name = os.path.basename(t[0])
# A draft on a repository listed in standing_publish_draft waits for no word, per the workspace's *Standing words*.
pos = [x for x in t[1:] if not x.startswith('-')]
if name == 'post-fix.sh' and _post_fix_opens_draft(t, cwd):
continue
# --record-read writes the body's hash into the local draft and exits before any call to GitHub.
if name == 'post-fix.sh' and '--record-read' in t:
continue
if name == 'post-replies' and len(pos) >= 2 and norm_repo(pos[0]) in standing_publish_draft() \
and _own_draft(norm_repo(pos[0]), pos[1]):
continue
if name == 'post-review.sh' and _sends_finished_round(t, cwd):
continue
if name in POST_SCRIPTS - {'pr-body-apply'} and not _dry(t):
needs.append({'post', 'upload'})
# pr-body-apply needs no word: it refuses a pull request the signed-in account
# did not author, and a revised body on the user's own one is a standing word.
if t[0] != 'gh':
continue
r = _gh_verb(t)
if len(r) < 2:
continue
verb = (r[0], r[1])
# Opening, editing, commenting on or readying a pull request on the user's own repository
# waits for no word; a merge, a close and a delete still do.
if own and verb in {('pr', 'create'), ('pr', 'comment'), ('pr', 'review'), ('pr', 'edit'), ('pr', 'ready'),
('issue', 'comment')}:
repos = _gh_repos(t, cwd, cmd)
if repos and repos <= own:
continue
# A new issue on a repository the user's login owns, no fork, waits for no word, per Consent in core.md.
if verb == ('issue', 'create'):
repos = _gh_repos(t, cwd, cmd)
if repos and all(_own_unforked(r) for r in repos):
continue
if verb == ('pr', 'create') and {'--draft', '-d'} & set(t):
repos = _gh_repos(t, cwd, cmd)
if repos and repos <= standing_publish_draft():
continue
if verb in {('pr', 'comment'), ('pr', 'edit'), ('issue', 'comment')} and _drafts_only(t, cwd, cmd):
continue
if verb == ('issue', 'edit') and not _edits_beyond_body(t):
repos, number = _gh_repos(t, cwd, cmd), _gh_target(t)
if number and repos and all(f'{r}#{number}' in standing_issue_edit() for r in repos):
continue
if verb in {('pr', 'create'), ('pr', 'comment'), ('pr', 'review'), ('pr', 'reopen'), ('issue', 'create'),
('issue', 'comment'), ('issue', 'reopen'), ('issue', 'edit'), ('issue', 'lock'), ('issue', 'transfer'),
('release', 'create'), ('release', 'upload'), ('gist', 'create'), ('repo', 'create'), ('repo', 'edit')}:
needs.append({'post'})
elif verb == ('pr', 'ready'):
needs.append({'post', 'ready'})
elif verb == ('pr', 'merge'):
flags = [a.split('=')[0] for a in t]
unwatched = any(a in ('--auto', '--admin', '--delete-branch', '--disable-auto') or re.fullmatch(r'-[a-zA-Z]*d[a-zA-Z]*', a)
for a in flags) or '--match-head-commit' not in flags
repos = _gh_repos(t, cwd, cmd)
owned = bool(repos) and all(_own_unforked(r) for r in repos)
needs.append({'merge'} if unwatched else {'merge', 'review-merge'} | ({'own-merge'} if owned else set()))
elif verb == ('pr', 'close') and _closes_own_quietly(t, cwd, cmd):
# The fork's pull request closes unasked once the upstream one opens, per *Presenting the
# change* in skills/change.md: a close with no comment on the user's own repository.
continue
elif verb in {('pr', 'close'), ('issue', 'close')}:
needs.append({'close'})
elif r[1] == 'delete':
needs.append({'delete'})
elif verb == ('repo', 'sync'):
# A sync writes a branch of the user's repository: a push, and with --force a reset,
# which Invariant 8 never allows.
needs.append({'\x00never'} if '--force' in t else {'push'})
elif verb == ('pr', 'edit') and (_gh_repos(t, cwd, cmd) & strict or _edits_beyond_body(t)):
# Consent lets an open pull request's body go up unasked; a title, a label, a reviewer or a
# base on it, and any change where every change takes the word, wait for post.
needs.append({'post'})
elif r[0] == 'api':
method = None
for i, x in enumerate(t):
if x in ('-X', '--method') and i + 1 < len(t):
method = t[i + 1].upper()
elif x.startswith('--method='):
method = x.split('=', 1)[1].upper()
elif x.startswith('-X') and len(x) > 2:
method = x[2:].upper()
fields = _field_values(t)
has_input = '--input' in t
path = next((x for x in r[1:] if not x.startswith('-') and ('/' in x or x in ('graphql', 'markdown'))), '')
if path.lstrip('/').split('/')[0] == 'markdown':
continue
if path == 'graphql':
base = cwd or os.getcwd()
sources = [v.split('=', 1)[1] for v in fields if v.startswith('query=')]
if has_input and t.index('--input') + 1 < len(t):
sources.append('@' + t[t.index('--input') + 1])
query, unreadable = '', False
for src in sources:
# A GraphQL variable, `($org: String!)` or `login: $org`, follows `(`, `,`, `:` or `[`;
# a `$` anywhere else is the shell's, and what it expands to is unread.
if '$' in re.sub(r'([(,:\[]\s*)\$[A-Za-z_]\w*', r'\1', src) or '`' in src:
unreadable = True
elif src.startswith('@'):
path_ = os.path.join(base, os.path.expanduser(src[1:]))
if os.path.isfile(path_):
query += _read_at('@' + path_)
else:
unreadable = True
else:
query += src
bodies = ' '.join(m.group(3) for m in re.finditer(r'<<-?\s*([\'"]?)(\w+)\1.*?\n(.*?)\n\s*\2\b', cmd, re.S))
if unreadable or re.search(r'\bmutation\b', query) or re.search(r'\bmutation\b', bodies):
needs.append({'post'})
# A merge by mutation keeps the merge's own word, as the REST merge below does.
if re.search(r'\b(mergePullRequest|enablePullRequestAutoMerge|enqueuePullRequest|mergeBranch)\b', query + bodies):
needs.append({'merge'})
continue
method = method or ('POST' if fields or has_input else 'GET')
if method == 'GET':
continue
# An open pull request's own body or title edit goes up unasked, per Consent in skills/core.md.
keys = {v.split('=', 1)[0] for v in fields}
repo = norm_repo('/'.join(path.lstrip('/').split('/')[1:3])) if path.lstrip('/').startswith('repos/') else ''
if '{owner}' in path or '{repo}' in path:
here_repos = _remote_repos(cwd) if cwd else set()
repo = next(iter(here_repos & strict), next(iter(here_repos), ''))
if method == 'PATCH' and re.search(r'/pulls/(\d+|\$\{?\w+\}?)/?$', path) and keys and keys <= {'body'} \
and repo not in strict:
continue
if method == 'PUT' and '/contents/' in path:
# A file written to a repository's branch is a push: free on a standing repository.
if repo in {norm_repo(x) for x in standing_push()}:
continue
needs.append({'upload', 'push'})
continue
# Taking a label, an assignee or a reviewer off an issue or a pull request edits it:
# post, as adding one does. Any other DELETE removes the thing itself.
edit = re.search(r'/issues/[^/]+/(labels|assignees)(/|$)|/pulls/[^/]+/requested_reviewers/?$', path)
if method == 'DELETE' and not edit:
needs.append({'delete'})
# A merge and a close keep their own words on the user's repositories too, and so does a new
# issue on any repository the user's login does not own or that is a fork.
elif re.search(r'/pulls/[^/]+/merge/?$', path):
needs.append({'merge'})
elif 'state=closed' in fields or re.search(r'"state"\s*:\s*"closed"', body := (
_read_at('@' + t[t.index('--input') + 1]) if has_input and t.index('--input') + 1 < len(t) else '')):
needs.append({'close'})
elif body.startswith('@'):
# an --input file the gate cannot read could carry anything
needs.append({'post'})
elif method == 'POST' and re.search(r'/issues/?$', path):
# `{owner}/{repo}` may resolve to any remote, so every one must be the user's own.
targets = _remote_repos(cwd) if ('{owner}' in path or '{repo}' in path) and cwd else {repo}
if not (targets and all(_own_unforked(r) for r in targets)):
needs.append({'post'})
elif repo in own and re.search(r'/(pulls|issues)(/|$)', path):
continue
elif repo in standing_publish_draft() and not keys & {'state', 'draft', 'base'} \
and (m := re.search(r'/(?:pulls|issues)/(\d+)(?:/(?:comments(?:/\d+/replies)?|labels(?:/[^/]+)?))?/?$', path)) \
and _own_draft(repo, m.group(1)):
continue
else:
needs.append({'post'})
return needs
def commit_messages(cmd):
out = []
for t in _segments(cmd):
is_git_commit = t[0] == 'git' and _git_sub(t)[0] == 'commit'
is_gh_write = t[0] == 'gh' and len(_gh_verb(t)) > 1 and _gh_verb(t)[1] in ('create', 'comment', 'review', 'edit')
if not (t[0].endswith('scripts/commit') or is_git_commit or is_gh_write):
continue
for i, x in enumerate(t):
if x in ('-m', '--message', '--body', '-b', '--title', '-t', '--trailer', '-am') and i + 1 < len(t):
out.append(t[i + 1])
elif x.startswith(('--message=', '--body=', '--title=', '--trailer=')):
out.append(x.split('=', 1)[1])
elif x.startswith('-m') and len(x) > 2 and not x.startswith('--'):
out.append(x[2:])
elif x in ('--body-file', '-F', '--file') and i + 1 < len(t) and t[i + 1] != '-':
out.append(_read_at('@' + t[i + 1]))
elif x.startswith(('--file=', '--body-file=')):
out.append(_read_at('@' + x.split('=', 1)[1]))
for t in _segments(cmd):
commits = t and (t[0].endswith('scripts/commit') or (t[0] == 'git' and _git_sub(t)[0] == 'commit'))
from_heredoc = any('<<' in x or x == 'cat' for x in t) or any(
x in ('-F', '--file') and i + 1 < len(t) and t[i + 1] == '-' for i, x in enumerate(t))
if commits and from_heredoc:
# A message written through $(cat <<EOF ...) or -F - <<EOF lives in the heredoc body the
# segmenter drops, so the bodies on this line are read for the marker.
out.extend(m.group(0) for m in re.finditer(r'<<-?\s*([\'"]?)(\w+)\1.*?\n(.*?)\n\s*\2\b', cmd, re.S))
return out
def push_targets(cmd, cwd):
"""(repository, forced, deleted, branches) for each git push on the line; repository is owner/name or None, and
branches the remote branch each refspec writes, or None where one cannot be named."""
out = []
here = cwd or os.getcwd()
here_raw = ''
read = []
list(_segments(cmd, cwd=here, collect=read))
cmd_all = '\n'.join([cmd] + read)
names = dict(re.findall(r'(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=["\']?([^\s;&|()"\']+)', cmd_all))
def fill(v):
for _ in range(4): # a name defined through another name, R=...; C=$R/x
v = re.sub(r'\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?', lambda m: names.get(m.group(1), os.environ.get(m.group(1), m.group(0))), v)
return os.path.expanduser(v.strip('"\''))
stack = []
temp_names = set(re.findall(r'([A-Za-z_][A-Za-z0-9_]*)=["\']?\$\(mktemp\b', cmd))
made = set()
for t in _segments(cmd):
if t[0] == 'git' and _git_sub(t)[0] in ('init', 'clone'):
dests = [x for x in t[_git_sub(t)[1] + 1:] if not x.startswith('-')]
if dests:
made.add(dests[-1].rstrip('/'))
# A line that points a remote, a git dir or a repository somewhere, runs a function or pops a
# directory can send a push anywhere: every push on it waits for the word.
# Read outside quotes and heredoc bodies, so an email address or a sentence never counts.
bare = re.sub(r"'[^']*'|\"(?:\\.|[^\"\\])*\"", ' ', _strip_heredocs(cmd))
unsure = bool(re.search(r'\bremote\s+(add|set-url)\b|--git-dir|\bGIT_DIR=|'
r'\bGIT_WORK_TREE=|\bpopd\b|\(\)\s*\{|(^|[;&|\n])\s*function\s+\w', bare))
for t in _segments(cmd):
if t[0] == 'git' and _git_sub(t)[0] == 'config':
rest_c = t[_git_sub(t)[1] + 1:]
if not any(x in ('--get', '--get-all', '--get-regexp', '--list', '-l', '--show-origin', '--show-scope')
for x in rest_c) and len([x for x in rest_c if not x.startswith('-')]) >= 2:
unsure = True
if t[0] == 'git' and _git_sub(t)[0] == 'clone':
src = [x for x in t[_git_sub(t)[1] + 1:] if not x.startswith('-')]
if src and re.match(r'^(https?://|ssh://|git@|[\w.-]+@[\w.-]+:)', src[0]):
unsure = True
def scratch(raw):
raw = raw.strip('"\'').rstrip('/')
if unsure or '..' in raw.split('/'):
return False
head = re.match(r'^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?', raw)
return bool(head and head.group(1) in temp_names) or any(raw == d or raw.startswith(d + '/') for d in made)
for t in _segments(cmd, ops=True, cwd=cwd or os.getcwd()):
if t == ['\x00(']:
stack.append((here, here_raw))
continue
if t == ['\x00)']:
here, here_raw = stack.pop() if stack else (here, here_raw)
continue
if len(t) >= 2 and t[0] in ('cd', 'pushd'):
here, here_raw = os.path.join(here, fill(t[1])), t[1]
continue
if t[0] != 'git':
continue
sub, at = _git_sub(t)
if sub != 'push':