Repository navigation
Expand file tree
/
Copy pathshell.nim
More file actions
235 lines (229 loc) · 8.08 KB
/
Copy pathshell.nim
File metadata and controls
235 lines (229 loc) · 8.08 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
## Shell command analysis for the read cache.
##
## Does NOT run any commands - pure parsing only. Tokenizes shell snippets and
## extracts the mutation target (if any) so the read cache can invalidate
## stale entries when a file is written via shell (sed -i, tee, cp, mv, etc.)
## rather than the `write`/`patch` tools.
import std/strutils
proc shellTokens*(s: string): seq[string] =
## Tokenize a shell snippet by whitespace, honoring single + double quotes.
## Backslash-escapes the next character outside quotes. Not a real shell
## parser — used only for path extraction for the read cache.
var cur = ""
var quote: char = '\0'
var i = 0
while i < s.len:
let c = s[i]
if quote != '\0':
if c == quote: quote = '\0'
else: cur.add c
inc i
elif c in {'\'', '"'}:
quote = c
inc i
elif c == '\\' and i + 1 < s.len:
cur.add s[i+1]
i += 2
elif c in {' ', '\t', '\n'}:
if cur.len > 0: result.add cur; cur = ""
inc i
else:
cur.add c; inc i
if cur.len > 0: result.add cur
proc splitStatements*(cmd: string): seq[string] =
## Split on top-level `;`, `&&`, `||`, `|` (not inside quotes). Pipeline
## stages count as separate statements so `tee`/`sed -i` mid-pipeline
## still get extracted. Background `&` is left alone.
result.add ""
var quote: char = '\0'
var i = 0
while i < cmd.len:
let c = cmd[i]
if quote != '\0':
result[^1].add c
if c == quote: quote = '\0'
inc i
continue
if c in {'\'', '"'}:
quote = c
result[^1].add c
inc i
continue
if c == ';':
result.add ""
inc i
continue
if (c == '&' or c == '|') and i + 1 < cmd.len and cmd[i+1] == c:
result.add ""
i += 2
continue
if c == '|':
result.add ""
inc i
continue
result[^1].add c
inc i
proc bashMutationPath*(cmd: string): string =
## Best-effort: return the first file path that this bash command would
## mutate, or "" if no mutation pattern matches. Surfaces `sed -i` and
## similar so the read cache knows the file changed even when the model
## never emits a dedicated write action.
##
## Recognised patterns (per top-level statement):
## - explicit redirect: `> path`, `>> path`, `>path`, `>>path`
## - `sed -i`, `perl -i` (file is the last positional)
## - `tee [-a] path`
## - `cp/mv path... DEST` (destination is the last positional)
## - `rm path`, `touch path`
for stmt in splitStatements(cmd):
let raw = shellTokens(stmt.strip)
if raw.len == 0: continue
var toks: seq[string]
var i = 0
while i < raw.len:
let t = raw[i]
if t == ">" or t == ">>":
if i + 1 < raw.len: return raw[i+1]
i += 2
continue
if t.startsWith(">") and t.len > 1 and t[1] != '&':
return if t.startsWith(">>"): t[2..^1] else: t[1..^1]
if t == "<" or t == "2>" or t == "&>" or t == "2>>":
i += 2
continue
if t.startsWith("<") or t.startsWith("2>") or t.startsWith("&>"):
inc i
continue
toks.add t
inc i
if toks.len == 0: continue
case toks[0]
of "sed", "perl":
var inPlace = false
for t in toks[1..^1]:
if t == "-i" or t.startsWith("-i.") or t.startsWith("-i'") or
t.startsWith("-i\""):
inPlace = true; break
if inPlace:
for j in countdown(toks.len - 1, 1):
if not toks[j].startsWith("-"): return toks[j]
of "ed", "ex":
# Line editors that read a script and write the file. `ed -s file`
# / `ex -s -c '…' file` etc. — last positional is the file. Also the
# zero-positional case (`ed file`); short flags like `-s`, `-c CMD`,
# `-G`, `-V`, `-p PROMPT` get filtered by the leading-dash check.
for j in countdown(toks.len - 1, 1):
let t = toks[j]
if t.startsWith("-"): continue
# ex uses `-c CMD` — skip the value if the previous token is `-c`.
if j >= 2 and toks[j-1] in ["-c", "-p"]: continue
return t
of "tee":
for t in toks[1..^1]:
if t.startsWith("-"): continue
return t
of "cp", "mv":
var last = ""
for t in toks[1..^1]:
if not t.startsWith("-"): last = t
if last.len > 0: return last
of "rm", "touch":
for t in toks[1..^1]:
if t.startsWith("-"): continue
return t
else: discard
""
proc bashReadPath*(cmd: string): tuple[path: string, fullFile: bool] =
## Best-effort: return the file path of a pure single-statement read command,
## with `fullFile = true` for `cat path` (the only form eligible for
## cache-dedupe of unchanged-since-last-read). Returns ("", false) on
## anything compound, piped, redirected, or unrecognised. Used to:
## - port the read-cache stale-write guard onto cat/sed-n (so `patch`
## after an external edit still errors)
## - dedupe a re-read of an unchanged file
let stmts = splitStatements(cmd)
if stmts.len != 1: return ("", false)
let raw = shellTokens(stmts[0].strip)
if raw.len == 0: return ("", false)
var toks: seq[string]
for t in raw:
if t == ">" or t == ">>" or t == "<" or t == "2>" or t == "&>" or t == "2>>":
return ("", false)
if t.startsWith(">") or t.startsWith("<") or
t.startsWith("2>") or t.startsWith("&>"):
return ("", false)
toks.add t
if toks.len < 2: return ("", false)
case toks[0]
of "cat":
var paths: seq[string]
for t in toks[1..^1]:
if t.startsWith("-"): continue
paths.add t
if paths.len == 1: return (paths[0], true)
of "sed":
var hasN = false
var paths: seq[string]
var i = 1
while i < toks.len:
let t = toks[i]
if t == "-n": hasN = true; inc i; continue
if t == "-e" or t == "--expression" or t == "-f":
i += 2; continue
if t.startsWith("-"): inc i; continue
paths.add t
inc i
# `sed -n 'A,Bp' path` → paths = ['A,Bp', path]; the script counts as a
# positional but isn't a file. Require exactly two positionals (script +
# one file) so we don't false-positive on `sed -n '1p' a b`.
if hasN and paths.len == 2: return (paths[1], false)
of "head", "tail":
var paths: seq[string]
var i = 1
while i < toks.len:
let t = toks[i]
if t == "-n" or t == "-c":
i += 2; continue
if t.startsWith("-"): inc i; continue
paths.add t
inc i
if paths.len == 1: return (paths[0], false)
else: discard
("", false)
proc semanticExitNote*(cmd: string, code: int, body: string): string =
## Non-error interpretation of exit codes that weak models read as
## failures and panic-retry. grep/find/diff/test exit 1 on "no match" /
## "condition false" / "files differ" by POSIX design; `test`/`[` exit 1
## means the tested condition is false. Returning a one-line verdict
## (zcode-style) keeps the model from re-running the same command or
## switching strategies over a successful lookup. Empty for codes we
## can't interpret: the raw failure path is untouched.
if code != 1: return ""
let first = cmd.strip.splitLines[0].strip
# Shell pipelines report the LAST command's status, so qualify on the
# final segment after the last pipe/&&/; (that is whose exit 1 this is).
var seg = first
for sep in ["|", "&&", ";"]:
let i = seg.rfind(sep)
if i >= 0: seg = seg[i + sep.len ..^ 1].strip
let words = seg.split(Whitespace)
if words.len == 0: return ""
# Strip a leading sudo/env/nohup prefix to find the real program.
var wi = 0
while wi < words.len and words[wi] in ["sudo", "env", "nohup"]: inc wi
if wi >= words.len: return ""
let pw = words[wi].split("/")[^1]
case pw
of "grep", "egrep", "fgrep", "rg":
if body.strip.len == 0:
"[exit 1: no matches — this is a normal grep/rg result, not an error]"
else:
"[exit 1: matches found but a pattern/test in the command failed]"
of "find":
"[exit 1: some traversed directories were inaccessible; results above are what was reachable]"
of "diff":
"[exit 1: files differ — that is diff's success signal, not an error]"
of "test", "[", "[[":
"[exit 1: condition is false]"
else:
""