aimancli 0.2.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.
- aiman/__init__.py +0 -0
- aiman/cli.py +53 -0
- aiman/core/__init__.py +1 -0
- aiman/core/classifiers.py +38 -0
- aiman/core/pipeline.py +129 -0
- aiman/core/registry.py +15 -0
- aiman/core/safety.py +63 -0
- aiman/core/tagger.py +70 -0
- aiman/core/tool.py +61 -0
- aiman/tools/__init__.py +0 -0
- aiman/tools/find/__init__.py +63 -0
- aiman/tools/find/fixture.py +63 -0
- aiman/tools/find/rules.py +208 -0
- aiman/tools/find/schema.json +98 -0
- aiman/tools/find/slots.py +224 -0
- aiman/tools/find/templates.py +690 -0
- aiman/tools/ls/__init__.py +42 -0
- aiman/tools/ls/fixture.py +88 -0
- aiman/tools/ls/rules.py +109 -0
- aiman/tools/ls/schema.json +28 -0
- aiman/tools/ls/slots.py +245 -0
- aiman/tools/ls/templates.py +422 -0
- aimancli-0.2.0.dist-info/METADATA +99 -0
- aimancli-0.2.0.dist-info/RECORD +28 -0
- aimancli-0.2.0.dist-info/WHEEL +5 -0
- aimancli-0.2.0.dist-info/entry_points.txt +2 -0
- aimancli-0.2.0.dist-info/licenses/LICENSE +674 -0
- aimancli-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""find rules: lexicons, value normalisers and assemble() -- the rule half of slot filling."""
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from .slots import FLAGS
|
|
6
|
+
|
|
7
|
+
# ---------------------------------------------------------------- lexicons
|
|
8
|
+
EXT_LEX = {"python": "py", "py": "py", "javascript": "js", "js": "js", "markdown": "md", "md": "md",
|
|
9
|
+
"log": "log", "logs": "log", "text": "txt", "txt": "txt", "config": "conf", "conf": "conf",
|
|
10
|
+
"jpg": "jpg", "jpeg": "jpg", "png": "png", "c": "c", "shell": "sh", "sh": "sh", "json": "json",
|
|
11
|
+
"yaml": "yaml", "yml": "yaml", "temp": "tmp", "tmp": "tmp", "backup": "bak", "bak": "bak",
|
|
12
|
+
"mp4": "mp4", "pdf": "pdf", "pdfs": "pdf", "csv": "csv", "gzip": "gz", "gz": "gz",
|
|
13
|
+
"iso": "iso", "html": "html", "go": "go", "rust": "rs", "java": "java", "ruby": "rb",
|
|
14
|
+
"typescript": "ts", "sql": "sql", "xml": "xml", "mp3": "mp3", "zip": "zip", "docx": "docx"}
|
|
15
|
+
|
|
16
|
+
SIZE_UNIT = [(r"(gb|g|gig|gigs|gigabytes?)$", "G"), (r"(mb|m|meg|megs|megabytes?)$", "M"),
|
|
17
|
+
(r"(kb|k|kilobytes?)$", "k"), (r"(bytes?|b)$", "c")]
|
|
18
|
+
|
|
19
|
+
DAY_UNITS = {"minute": 1 / 1440, "min": 1 / 1440, "hour": 1 / 24, "day": 1, "week": 7, "month": 30, "year": 365}
|
|
20
|
+
MIN_UNITS = {"minute": 1, "min": 1, "hour": 60, "day": 1440}
|
|
21
|
+
WORDNUM = {"a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "half": 0.5}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def norm_ext(word):
|
|
25
|
+
w = word.lower().strip(".?,'\"")
|
|
26
|
+
w = re.sub(r"^\*?\.", "", w)
|
|
27
|
+
return EXT_LEX.get(w, EXT_LEX.get(w.rstrip("s"), w))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def exts_from_text(text):
|
|
31
|
+
"""fallback when tagger found no EXT: scan for lexicon words before 'files/scripts/images...'"""
|
|
32
|
+
toks = [t.lower().strip("?,") for t in text.split()]
|
|
33
|
+
out = []
|
|
34
|
+
for i, t in enumerate(toks):
|
|
35
|
+
nxt = toks[i + 1] if i + 1 < len(toks) else ""
|
|
36
|
+
if t.startswith("*.") and len(t) > 2:
|
|
37
|
+
out.append(t[2:])
|
|
38
|
+
elif t.startswith(".") and len(t) > 1 and t[1:] in EXT_LEX:
|
|
39
|
+
out.append(EXT_LEX[t[1:]])
|
|
40
|
+
elif t in EXT_LEX and nxt in ("files", "file", "scripts", "images", "photos", "videos", "documents",
|
|
41
|
+
"source", "archives", "pages", "logs", "and"):
|
|
42
|
+
out.append(EXT_LEX[t])
|
|
43
|
+
elif t in ("pdfs", "logs") and t not in out:
|
|
44
|
+
out.append(EXT_LEX[t])
|
|
45
|
+
return list(dict.fromkeys(out))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def norm_size(span, text):
|
|
49
|
+
"""'100MB' -> '100M'; handles '100 MB' via following token; 'a megabyte' -> '1M'"""
|
|
50
|
+
s = span.lower()
|
|
51
|
+
m = re.match(r"^(\d+)\s*([a-z]*)$", s)
|
|
52
|
+
if not m:
|
|
53
|
+
return None
|
|
54
|
+
n, u = m.groups()
|
|
55
|
+
if not u: # unit in next token
|
|
56
|
+
after = re.search(re.escape(span) + r"\s+(\w+)", text, re.I)
|
|
57
|
+
u = after.group(1).lower() if after else "m"
|
|
58
|
+
for pat, unit in SIZE_UNIT:
|
|
59
|
+
if re.search(pat, u):
|
|
60
|
+
return n + unit
|
|
61
|
+
return n + "M"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def size_without_number(text):
|
|
65
|
+
t = text.lower()
|
|
66
|
+
for word, unit in [("gigabyte", "G"), ("megabyte", "M"), ("kilobyte", "k")]:
|
|
67
|
+
if re.search(rf"\ba {word}\b", t):
|
|
68
|
+
return "1" + unit
|
|
69
|
+
if re.search(r"\b(large|big|huge)\b", t):
|
|
70
|
+
return "100M"
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def norm_time(text, flag, span=None):
|
|
75
|
+
"""number of units for `flag` (-mtime/-atime/-ctime: days, -mmin/...: minutes)"""
|
|
76
|
+
t = text.lower()
|
|
77
|
+
units = MIN_UNITS if flag.endswith("min") else DAY_UNITS
|
|
78
|
+
if span is not None:
|
|
79
|
+
m = re.search(re.escape(span) + r"\s*-?\s*(\w+)", t)
|
|
80
|
+
n = float(re.sub(r"\D", "", span) or 1)
|
|
81
|
+
unit = m.group(1) if m else ("minute" if flag.endswith("min") else "day")
|
|
82
|
+
elif re.search(r"\b(\d+)\s*(minute|min|hour|day|week|month|year)", t): # untagged number
|
|
83
|
+
m = re.search(r"\b(\d+)\s*(minute|min|hour|day|week|month|year)", t)
|
|
84
|
+
n, unit = float(m.group(1)), m.group(2)
|
|
85
|
+
else: # 'a week', 'a month', 'half hour', 'yesterday', 'today'
|
|
86
|
+
if "yesterday" in t or re.search(r"\b(last|past) day\b", t):
|
|
87
|
+
return "1"
|
|
88
|
+
if "today" in t or "midnight" in t:
|
|
89
|
+
return "0"
|
|
90
|
+
m = re.search(r"\b(a|an|one|two|three|half)\s+(?:a\s+)?(minute|min|hour|day|week|month|year)", t)
|
|
91
|
+
if not m:
|
|
92
|
+
m2 = re.search(r"\b(last|past|this|the)\s+(minute|hour|day|week|month|year)", t)
|
|
93
|
+
if not m2:
|
|
94
|
+
return None
|
|
95
|
+
n, unit = 1, m2.group(2)
|
|
96
|
+
else:
|
|
97
|
+
n, unit = WORDNUM[m.group(1)], m.group(2)
|
|
98
|
+
unit = unit.rstrip("s")
|
|
99
|
+
for k, f in units.items():
|
|
100
|
+
if unit.startswith(k):
|
|
101
|
+
v = n * f
|
|
102
|
+
return str(max(int(round(v)), 0)) if v >= 1 or flag.endswith("min") else "1"
|
|
103
|
+
return str(int(n))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
PATH_LEX = [(r"\ball home directories\b", "/home"), (r"\btemp(orary)? directory\b", "/tmp"),
|
|
108
|
+
(r"(\bin|under|inside)\s+~(\s|\?|$)", "~"), (r"\bmy home (directory|folder|dir)\b", "~"),
|
|
109
|
+
(r"\bhome( folder| directory)?(\s|\?|$)", "~"),
|
|
110
|
+
(r"\b(whole system|entire filesystem|everywhere|from root)\b", "/")]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _exts(text, paths):
|
|
114
|
+
"""extensions from text, ignoring words used as a directory ('in logs')"""
|
|
115
|
+
return [e for e in exts_from_text(" ".join(w for w in text.split() if w.strip("?,") not in paths))]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def assemble(text, sp, c):
|
|
120
|
+
"""Predicted spans `sp` + classifier labels `c` -> (slots, error)."""
|
|
121
|
+
t = text.lower()
|
|
122
|
+
s = {"path": [], "follow": False, "type": None, "name": [], "iname": False, "name_neg": False,
|
|
123
|
+
"size": [], "time": [], "perm": [], "user": None, "user_neg": False, "group": None,
|
|
124
|
+
"maxdepth": None, "mindepth": None, "exclude": [], "daystart": False, "xdev": False,
|
|
125
|
+
"empty": False, "access": None, "action": c["action"], "args": {}}
|
|
126
|
+
for f in FLAGS:
|
|
127
|
+
s[f] = c[f] == "True"
|
|
128
|
+
|
|
129
|
+
# path
|
|
130
|
+
paths = [p.rstrip("/") if p not in ("/",) else p for p in sp.get("PATH", [])]
|
|
131
|
+
if not paths:
|
|
132
|
+
m = re.search(r"\b(?:in|under|inside|from)\s+(\w[\w.-]*/)", text) # 'src/'
|
|
133
|
+
paths = [m.group(1).rstrip("/")] if m else []
|
|
134
|
+
if not paths: # bare dir name that exists on this machine: "in logs"
|
|
135
|
+
for m in re.finditer(r"\b(?:in|under|inside|from)\s+([\w.-]+)", text):
|
|
136
|
+
if m.group(1) not in (".", "..", "the", "my", "all", "this") and os.path.isdir(m.group(1)):
|
|
137
|
+
paths = [m.group(1)]; break
|
|
138
|
+
if not paths:
|
|
139
|
+
for pat, val in PATH_LEX:
|
|
140
|
+
if re.search(pat, t):
|
|
141
|
+
paths = [val]; break
|
|
142
|
+
s["path"] = paths or [c["path_default"] if c["path_default"] != "tagged" else "."]
|
|
143
|
+
|
|
144
|
+
s["type"] = None if c["type"] == "none" else c["type"]
|
|
145
|
+
|
|
146
|
+
# name
|
|
147
|
+
kind = c["name_kind"]
|
|
148
|
+
if kind == "none" and (sp.get("EXT") or _exts(text, paths)):
|
|
149
|
+
kind = "ext"
|
|
150
|
+
if kind == "ext":
|
|
151
|
+
exts = [norm_ext(e) for e in sp.get("EXT", []) if e not in paths] or _exts(text, paths)
|
|
152
|
+
s["name"] = [f"*.{e}" for e in dict.fromkeys(exts)]
|
|
153
|
+
elif kind in ("contains", "prefix", "exact") and sp.get("NAME"):
|
|
154
|
+
w = sp["NAME"][0].strip("'*")
|
|
155
|
+
s["name"] = [{"contains": f"*{w}*", "prefix": f"{w}*", "exact": w}[kind]]
|
|
156
|
+
|
|
157
|
+
# size
|
|
158
|
+
sizes = [norm_size(x, text) for x in sp.get("SIZE", [])]
|
|
159
|
+
sizes = [x for x in sizes if x]
|
|
160
|
+
if c["size_dir"] == "range" and len(sizes) >= 2:
|
|
161
|
+
s["size"] = ["+" + sizes[0], "-" + sizes[1]]
|
|
162
|
+
elif c["size_dir"] != "none":
|
|
163
|
+
v = sizes[0] if sizes else size_without_number(text)
|
|
164
|
+
if v:
|
|
165
|
+
s["size"] = [("" if c["size_dir"] == "=" else c["size_dir"]) + v]
|
|
166
|
+
|
|
167
|
+
# time
|
|
168
|
+
if c["time_flag"] != "none":
|
|
169
|
+
v = norm_time(text, c["time_flag"], sp["TIME"][0] if "TIME" in sp else None)
|
|
170
|
+
if v is not None:
|
|
171
|
+
s["time"] = [[c["time_flag"], ("" if c["time_dir"] == "=" else c["time_dir"]) + v]]
|
|
172
|
+
|
|
173
|
+
s["perm"] = [] if c["perm"] == "none" else c["perm"].split(" && ")
|
|
174
|
+
s["access"] = None if c["access"] == "none" else c["access"]
|
|
175
|
+
s["user"] = next((u for u in [x[:-2] if x.endswith("'s") else x for x in sp.get("USER", [])]
|
|
176
|
+
if re.search(rf"(owned by|belonging to|user|not owned by)\s+{re.escape(u)}\b|\b{re.escape(u)}'s\b",
|
|
177
|
+
text, re.I)), None)
|
|
178
|
+
s["group"] = (sp.get("GROUP") or [None])[0]
|
|
179
|
+
s["exclude"] = sp.get("EXCLUDE", [])
|
|
180
|
+
m = re.search(r"\b(?:excluding|skip|ignoring the|ignoring)\s+([\w./-]+)(?:\s+and\s+([\w./-]+))?", text)
|
|
181
|
+
if m:
|
|
182
|
+
found = [x for x in m.groups() if x and x not in ("directory", "the", "case")]
|
|
183
|
+
if found:
|
|
184
|
+
s["exclude"] = found
|
|
185
|
+
|
|
186
|
+
# depth
|
|
187
|
+
if sp.get("DEPTH"):
|
|
188
|
+
s["maxdepth"] = re.sub(r"\D", "", sp["DEPTH"][0]) or None
|
|
189
|
+
elif re.search(r"non-recursive|without recursing|top level|not in subdirectories|immediate", t):
|
|
190
|
+
s["maxdepth"] = "1"
|
|
191
|
+
if re.search(r"immediate subdirectories|except the starting directory", t):
|
|
192
|
+
s["mindepth"] = "1"
|
|
193
|
+
|
|
194
|
+
# action args
|
|
195
|
+
need = re.findall(r"\{([A-Z]+)\}", s["action"])
|
|
196
|
+
for k in need:
|
|
197
|
+
v = (sp.get(k) or (sp.get("USER") if k == "OWNER" else None) or [None])[0]
|
|
198
|
+
if v is None:
|
|
199
|
+
if k in ("DEST", "FILE"):
|
|
200
|
+
m = re.search(r"\bto\s+(\S+)\s*$", text); v = m.group(1) if m else None
|
|
201
|
+
if v is None and k == "N":
|
|
202
|
+
m = re.search(r"\b(\d+)\b", text); v = m.group(1) if m else "10"
|
|
203
|
+
if v is None:
|
|
204
|
+
return s, f"missing value for {k}"
|
|
205
|
+
if k == "OWNER" and s["user"] == v:
|
|
206
|
+
s["user"] = None
|
|
207
|
+
s["args"][k] = v.strip("'\"")
|
|
208
|
+
return s, None
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
{
|
|
2
|
+
"tool": "find",
|
|
3
|
+
"description": "GNU find: intent -> command via slot filling",
|
|
4
|
+
"span_slots": {
|
|
5
|
+
"PATH": "starting directory",
|
|
6
|
+
"EXT": "file extension",
|
|
7
|
+
"NAME": "name or name fragment",
|
|
8
|
+
"SIZE": "size number (+unit)",
|
|
9
|
+
"TIME": "time number",
|
|
10
|
+
"USER": "owner",
|
|
11
|
+
"GROUP": "group",
|
|
12
|
+
"DEPTH": "-maxdepth number",
|
|
13
|
+
"EXCLUDE": "directory pruned",
|
|
14
|
+
"WORD": "grep pattern for -exec grep",
|
|
15
|
+
"N": "how many results",
|
|
16
|
+
"DEST": "mv/cp destination",
|
|
17
|
+
"MODE": "chmod mode",
|
|
18
|
+
"OWNER": "chown owner",
|
|
19
|
+
"FILE": "-fprint output file"
|
|
20
|
+
},
|
|
21
|
+
"class_slots": {
|
|
22
|
+
"type": [
|
|
23
|
+
"f",
|
|
24
|
+
"d",
|
|
25
|
+
"l",
|
|
26
|
+
"s",
|
|
27
|
+
"p",
|
|
28
|
+
"b",
|
|
29
|
+
"c",
|
|
30
|
+
"f,d,l",
|
|
31
|
+
"none"
|
|
32
|
+
],
|
|
33
|
+
"action": "template, e.g. -delete | -exec grep -l '{WORD}' {} + | -print0 | xargs -0 rm -f",
|
|
34
|
+
"path_default": [
|
|
35
|
+
".",
|
|
36
|
+
"~",
|
|
37
|
+
"/",
|
|
38
|
+
"tagged"
|
|
39
|
+
],
|
|
40
|
+
"time_flag": [
|
|
41
|
+
"-mtime",
|
|
42
|
+
"-mmin",
|
|
43
|
+
"-atime",
|
|
44
|
+
"-amin",
|
|
45
|
+
"-ctime",
|
|
46
|
+
"-cmin",
|
|
47
|
+
"none"
|
|
48
|
+
],
|
|
49
|
+
"time_dir": [
|
|
50
|
+
"+",
|
|
51
|
+
"-",
|
|
52
|
+
"=",
|
|
53
|
+
"none"
|
|
54
|
+
],
|
|
55
|
+
"size_dir": [
|
|
56
|
+
"+",
|
|
57
|
+
"-",
|
|
58
|
+
"=",
|
|
59
|
+
"range",
|
|
60
|
+
"none"
|
|
61
|
+
],
|
|
62
|
+
"perm": "-perm expression(s)",
|
|
63
|
+
"access": [
|
|
64
|
+
"-executable",
|
|
65
|
+
"-readable",
|
|
66
|
+
"-writable",
|
|
67
|
+
"! -readable",
|
|
68
|
+
"none"
|
|
69
|
+
],
|
|
70
|
+
"name_kind": [
|
|
71
|
+
"ext",
|
|
72
|
+
"exact",
|
|
73
|
+
"contains",
|
|
74
|
+
"prefix",
|
|
75
|
+
"none"
|
|
76
|
+
],
|
|
77
|
+
"flags": [
|
|
78
|
+
"iname",
|
|
79
|
+
"name_neg",
|
|
80
|
+
"user_neg",
|
|
81
|
+
"empty",
|
|
82
|
+
"follow",
|
|
83
|
+
"xdev",
|
|
84
|
+
"daystart"
|
|
85
|
+
]
|
|
86
|
+
},
|
|
87
|
+
"out_of_schema": [
|
|
88
|
+
"-newer",
|
|
89
|
+
"-newermt",
|
|
90
|
+
"-regex",
|
|
91
|
+
"-path",
|
|
92
|
+
"-links",
|
|
93
|
+
"-samefile",
|
|
94
|
+
"-xtype",
|
|
95
|
+
"-fprintf",
|
|
96
|
+
"comma operator"
|
|
97
|
+
]
|
|
98
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""find slots: command <-> slots, BIO tags for the tagger, targets for the classifiers.
|
|
2
|
+
|
|
3
|
+
parse(cmd) -> slots dict, or None when the command is outside the schema
|
|
4
|
+
build(slots) -> canonical find command (the rule engine)
|
|
5
|
+
tag(intent, slots) -> (tokens, BIO tags)
|
|
6
|
+
targets(slots, intent) -> {classifier: label}
|
|
7
|
+
"""
|
|
8
|
+
import re
|
|
9
|
+
import shlex
|
|
10
|
+
|
|
11
|
+
FLAGS = ["iname", "name_neg", "user_neg", "empty", "follow", "xdev", "daystart"]
|
|
12
|
+
|
|
13
|
+
TIME_FLAGS = {"-mtime", "-mmin", "-atime", "-amin", "-ctime", "-cmin"}
|
|
14
|
+
|
|
15
|
+
# action templates: placeholder args become slots ({WORD},{N},{MODE},{OWNER},{DEST},{FILE})
|
|
16
|
+
ACTION_PATTERNS = [
|
|
17
|
+
(r"^-exec grep -l '(?P<WORD>[^']+)' \{\} \+$", "-exec grep -l '{WORD}' {} +"),
|
|
18
|
+
(r"^-exec chmod (?P<MODE>\d+) \{\} \+$", "-exec chmod {MODE} {} +"),
|
|
19
|
+
(r"^-exec chown (?P<OWNER>\S+) \{\} \+$", "-exec chown {OWNER} {} +"),
|
|
20
|
+
(r"^-exec mv -t (?P<DEST>\S+) \{\} \+$", "-exec mv -t {DEST} {} +"),
|
|
21
|
+
(r"^-exec cp \{\} (?P<DEST>\S+) \\;$", "-exec cp {} {DEST} \\;"),
|
|
22
|
+
(r"^-fprint (?P<FILE>\S+)$", "-fprint {FILE}"),
|
|
23
|
+
(r"^-printf '%s %p\\n' \| sort -rn \| head -n (?P<N>\d+)$", "-printf '%s %p\\n' | sort -rn | head -n {N}"),
|
|
24
|
+
(r"^-printf '%T@ %p\\n' \| sort -rn \| head -n (?P<N>\d+)$", "-printf '%T@ %p\\n' | sort -rn | head -n {N}"),
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _tok(cmd):
|
|
29
|
+
return shlex.split(cmd, posix=False)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse(cmd):
|
|
33
|
+
"""Return slots dict, or None if the command uses features outside the schema."""
|
|
34
|
+
pipe = ""
|
|
35
|
+
if " | " in cmd:
|
|
36
|
+
cmd, pipe = cmd.split(" | ", 1)
|
|
37
|
+
t = _tok(cmd)
|
|
38
|
+
if t[0] != "find":
|
|
39
|
+
return None
|
|
40
|
+
i = 1
|
|
41
|
+
s = {"path": [], "follow": False, "type": None, "name": [], "iname": False, "name_neg": False,
|
|
42
|
+
"size": [], "time": [], "perm": [], "user": None, "user_neg": False, "group": None,
|
|
43
|
+
"maxdepth": None, "mindepth": None, "exclude": [], "daystart": False, "xdev": False,
|
|
44
|
+
"empty": False, "access": None, "action": "-print", "args": {}}
|
|
45
|
+
if t[i] == "-L":
|
|
46
|
+
s["follow"] = True; i += 1
|
|
47
|
+
while i < len(t) and not (t[i].startswith("-") or t[i] in ("\\(", "!", "\\!")):
|
|
48
|
+
s["path"].append(t[i]); i += 1
|
|
49
|
+
rest = t[i:]
|
|
50
|
+
|
|
51
|
+
# exclude: [\( -name a -o -name b \) | -name a] -prune -o ... -print
|
|
52
|
+
if "-prune" in rest and "-o" in rest and rest[-1] == "-print":
|
|
53
|
+
k = rest.index("-prune")
|
|
54
|
+
head = rest[:k]
|
|
55
|
+
if head[:1] == ["-name"] and len(head) == 2:
|
|
56
|
+
s["exclude"] = [head[1]]
|
|
57
|
+
elif head and head[0] == "\\(" and head[-1] == "\\)":
|
|
58
|
+
inner = [x for x in head[1:-1] if x not in ("-name", "-o")]
|
|
59
|
+
s["exclude"] = inner
|
|
60
|
+
else:
|
|
61
|
+
return None
|
|
62
|
+
rest = rest[k + 2:-1] # drop '-prune -o' and trailing '-print'
|
|
63
|
+
|
|
64
|
+
# split filters from action
|
|
65
|
+
act_start = len(rest)
|
|
66
|
+
for j, x in enumerate(rest):
|
|
67
|
+
if x in ("-delete", "-exec", "-execdir", "-ok", "-ls", "-printf", "-print", "-print0", "-fprint", "-quit"):
|
|
68
|
+
act_start = j; break
|
|
69
|
+
filt, act = rest[:act_start], rest[act_start:]
|
|
70
|
+
action = " ".join(act) or "-print"
|
|
71
|
+
if pipe:
|
|
72
|
+
action = (action + " | " + pipe) if act else "| " + pipe
|
|
73
|
+
s["action"] = action
|
|
74
|
+
for pat, tmpl in ACTION_PATTERNS:
|
|
75
|
+
m = re.match(pat, action)
|
|
76
|
+
if m:
|
|
77
|
+
s["action"], s["args"] = tmpl, m.groupdict(); break
|
|
78
|
+
|
|
79
|
+
j, neg = 0, False
|
|
80
|
+
while j < len(filt):
|
|
81
|
+
x = filt[j]
|
|
82
|
+
nxt = filt[j + 1] if j + 1 < len(filt) else None
|
|
83
|
+
if x in ("!", "\\!", "-not"):
|
|
84
|
+
neg = True; j += 1; continue
|
|
85
|
+
if x == "-type":
|
|
86
|
+
s["type"] = nxt; j += 2
|
|
87
|
+
elif x in ("-name", "-iname"):
|
|
88
|
+
s["name"].append(nxt.strip("'")); s["iname"] = x == "-iname"; s["name_neg"] = neg; j += 2
|
|
89
|
+
elif x == "\\(": # multi-name OR group
|
|
90
|
+
if "\\)" not in filt[j:]:
|
|
91
|
+
return None
|
|
92
|
+
k = filt.index("\\)", j)
|
|
93
|
+
grp = filt[j + 1:k]
|
|
94
|
+
if any(g not in ("-name", "-o") and not g.startswith("'") for g in grp):
|
|
95
|
+
return None
|
|
96
|
+
s["name"] += [g.strip("'") for g in grp if g.startswith("'")]
|
|
97
|
+
j = k + 1
|
|
98
|
+
elif x == "-size":
|
|
99
|
+
s["size"].append(nxt); j += 2
|
|
100
|
+
elif x in TIME_FLAGS:
|
|
101
|
+
s["time"].append([x, nxt]); j += 2
|
|
102
|
+
elif x == "-perm":
|
|
103
|
+
s["perm"].append(("! " if neg else "") + nxt); j += 2
|
|
104
|
+
elif x == "-user":
|
|
105
|
+
s["user"] = nxt; s["user_neg"] = neg; j += 2
|
|
106
|
+
elif x == "-group":
|
|
107
|
+
s["group"] = nxt; j += 2
|
|
108
|
+
elif x == "-maxdepth":
|
|
109
|
+
s["maxdepth"] = nxt; j += 2
|
|
110
|
+
elif x == "-mindepth":
|
|
111
|
+
s["mindepth"] = nxt; j += 2
|
|
112
|
+
elif x == "-daystart":
|
|
113
|
+
s["daystart"] = True; j += 1
|
|
114
|
+
elif x == "-xdev":
|
|
115
|
+
s["xdev"] = True; j += 1
|
|
116
|
+
elif x == "-empty":
|
|
117
|
+
s["empty"] = True; j += 1
|
|
118
|
+
elif x in ("-executable", "-readable", "-writable"):
|
|
119
|
+
s["access"] = ("! " if neg else "") + x; j += 1
|
|
120
|
+
else:
|
|
121
|
+
return None # -newer, -regex, -path, -links ... -> fallback
|
|
122
|
+
if x not in ("-perm", "-user", "-name", "-iname", "-executable", "-readable", "-writable"):
|
|
123
|
+
if neg:
|
|
124
|
+
return None
|
|
125
|
+
neg = False
|
|
126
|
+
if not s["path"]:
|
|
127
|
+
return None
|
|
128
|
+
return s
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def build(s):
|
|
132
|
+
"""Rule engine: slots -> canonical find command."""
|
|
133
|
+
out = ["find"] + (["-L"] if s["follow"] else []) + s["path"]
|
|
134
|
+
if s["daystart"]: out.append("-daystart")
|
|
135
|
+
if s["xdev"]: out.append("-xdev")
|
|
136
|
+
if s["mindepth"]: out += ["-mindepth", s["mindepth"]]
|
|
137
|
+
if s["maxdepth"]: out += ["-maxdepth", s["maxdepth"]]
|
|
138
|
+
filt = []
|
|
139
|
+
if s["type"]: filt += ["-type", s["type"]]
|
|
140
|
+
nm = "-iname" if s["iname"] else "-name"
|
|
141
|
+
if len(s["name"]) == 1:
|
|
142
|
+
filt += (["!"] if s["name_neg"] else []) + [nm, f"'{s['name'][0]}'"]
|
|
143
|
+
elif len(s["name"]) > 1:
|
|
144
|
+
g = []
|
|
145
|
+
for k, n in enumerate(s["name"]):
|
|
146
|
+
g += (["-o"] if k else []) + [nm, f"'{n}'"]
|
|
147
|
+
filt += ["\\("] + g + ["\\)"]
|
|
148
|
+
for z in s["size"]: filt += ["-size", z]
|
|
149
|
+
for f, v in s["time"]: filt += [f, v]
|
|
150
|
+
for p in s["perm"]: filt += p.split(" ")[:-1] + ["-perm", p.split(" ")[-1]]
|
|
151
|
+
if s["user"]: filt += (["!"] if s["user_neg"] else []) + ["-user", s["user"]]
|
|
152
|
+
if s["group"]: filt += ["-group", s["group"]]
|
|
153
|
+
if s["empty"]: filt.append("-empty")
|
|
154
|
+
if s["access"]: filt += s["access"].split(" ")
|
|
155
|
+
action = s["action"]
|
|
156
|
+
for k, v in s["args"].items():
|
|
157
|
+
action = action.replace("{" + k + "}", v)
|
|
158
|
+
if s["exclude"]:
|
|
159
|
+
if len(s["exclude"]) == 1:
|
|
160
|
+
ex = ["-name", s["exclude"][0]]
|
|
161
|
+
else:
|
|
162
|
+
ex = ["\\("] + sum([(["-o"] if k else []) + ["-name", e] for k, e in enumerate(s["exclude"])], []) + ["\\)"]
|
|
163
|
+
return " ".join(out + ex + ["-prune", "-o"] + filt + ["-print"])
|
|
164
|
+
if action == "-print":
|
|
165
|
+
return " ".join(out + filt)
|
|
166
|
+
if action.startswith("| "):
|
|
167
|
+
return " ".join(out + filt) + " " + action
|
|
168
|
+
return " ".join(out + filt + [action])
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
# ---------------------------------------------------------------- BIO tagging
|
|
172
|
+
def tag(intent, s):
|
|
173
|
+
toks = intent.split()
|
|
174
|
+
tags = ["O"] * len(toks)
|
|
175
|
+
low = [w.lower().strip("?,.'\"") for w in toks]
|
|
176
|
+
|
|
177
|
+
def mark(val, label, numeric_only=False):
|
|
178
|
+
if not val: return
|
|
179
|
+
v = str(val).lower().strip("'~+-")
|
|
180
|
+
if numeric_only:
|
|
181
|
+
v = re.sub(r"[^\d]", "", v)
|
|
182
|
+
if not v: return
|
|
183
|
+
for k, w in enumerate(low):
|
|
184
|
+
if tags[k] != "O": continue
|
|
185
|
+
ww = w if not numeric_only else re.sub(r"[^\d]", "", w)
|
|
186
|
+
if ww == v or (not numeric_only and (w == "." + v or w.rstrip("s") == v)):
|
|
187
|
+
tags[k] = "B-" + label; return
|
|
188
|
+
|
|
189
|
+
for p in s["path"]:
|
|
190
|
+
if p not in (".", "~", "/"):
|
|
191
|
+
mark(p, "PATH")
|
|
192
|
+
for n in s["name"]:
|
|
193
|
+
core = n.replace("*", "")
|
|
194
|
+
mark(core.lstrip("."), "NAME") if not n.startswith("*.") else mark(core.lstrip("."), "EXT")
|
|
195
|
+
for z in s["size"]: mark(z, "SIZE", numeric_only=True)
|
|
196
|
+
for _, v in s["time"]: mark(v, "TIME", numeric_only=True)
|
|
197
|
+
mark(s["user"], "USER"); mark(s["group"], "GROUP")
|
|
198
|
+
mark(s["maxdepth"], "DEPTH", numeric_only=True)
|
|
199
|
+
for e in s["exclude"]: mark(e, "EXCLUDE")
|
|
200
|
+
for k, v in s["args"].items(): mark(v, k)
|
|
201
|
+
return toks, tags
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def targets(s, text):
|
|
206
|
+
t = {
|
|
207
|
+
"type": s["type"] or "none",
|
|
208
|
+
"action": s["action"],
|
|
209
|
+
"path_default": "tagged" if any(p not in (".", "~", "/") for p in s["path"]) else s["path"][0],
|
|
210
|
+
"time_flag": s["time"][0][0] if s["time"] else "none",
|
|
211
|
+
"time_dir": (s["time"][0][1][0] if s["time"][0][1][0] in "+-" else "=") if s["time"] else "none",
|
|
212
|
+
"size_dir": (s["size"][0][0] if s["size"][0][0] in "+-" else "=") if len(s["size"]) == 1 else
|
|
213
|
+
("range" if s["size"] else "none"),
|
|
214
|
+
"perm": " && ".join(s["perm"]) or "none",
|
|
215
|
+
"access": s["access"] or "none",
|
|
216
|
+
"name_kind": "none",
|
|
217
|
+
}
|
|
218
|
+
if s["name"]:
|
|
219
|
+
n = s["name"][0]
|
|
220
|
+
t["name_kind"] = ("ext" if n.startswith("*.") else "contains" if n.startswith("*") and n.endswith("*")
|
|
221
|
+
else "prefix" if n.endswith("*") else "exact")
|
|
222
|
+
for f in FLAGS:
|
|
223
|
+
t[f] = str(bool(s[f]))
|
|
224
|
+
return t
|