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,42 @@
|
|
|
1
|
+
"""aiman plugin for GNU ls. Read-only: no destructive pattern, no preview, nothing to refuse."""
|
|
2
|
+
from aiman.core.tool import Tool
|
|
3
|
+
|
|
4
|
+
from . import fixture, rules, slots, templates
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class LsTool(Tool):
|
|
8
|
+
name = "ls"
|
|
9
|
+
destructive_pattern = None
|
|
10
|
+
|
|
11
|
+
def generate(self, seed=42):
|
|
12
|
+
return templates.generate(seed)
|
|
13
|
+
|
|
14
|
+
def validate(self, cmd):
|
|
15
|
+
return fixture.validate(cmd)
|
|
16
|
+
|
|
17
|
+
def parse(self, cmd):
|
|
18
|
+
return slots.parse(cmd)
|
|
19
|
+
|
|
20
|
+
def build(self, s):
|
|
21
|
+
return slots.build(s)
|
|
22
|
+
|
|
23
|
+
def tag(self, intent, s):
|
|
24
|
+
return slots.tag(intent, s)
|
|
25
|
+
|
|
26
|
+
def targets(self, s, intent):
|
|
27
|
+
return slots.targets(s, intent)
|
|
28
|
+
|
|
29
|
+
def assemble(self, intent, spans, classes):
|
|
30
|
+
return rules.assemble(intent, spans, classes)
|
|
31
|
+
|
|
32
|
+
def equivalent(self, a, b):
|
|
33
|
+
"""Same slots. Spelling differences (flag order, long options, trailing /) parse the same.
|
|
34
|
+
Output equality on the fixture is deliberately not used: `ls` and `ls -L` print the
|
|
35
|
+
same there but mean different things."""
|
|
36
|
+
if a == b:
|
|
37
|
+
return True
|
|
38
|
+
pa = slots.parse(a)
|
|
39
|
+
return pa is not None and pa == slots.parse(b)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
TOOL = LsTool()
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Sandbox for ls commands: a throwaway tree whose name, size and time orders all differ,
|
|
2
|
+
plus a rewriter that points every path argument at it.
|
|
3
|
+
|
|
4
|
+
validate(cmd) -> (ok, err) option errors in stderr
|
|
5
|
+
run(cmd) -> output lines in ls's order (order is what -t/-S/-r change, so no sorting)
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shlex
|
|
10
|
+
import subprocess
|
|
11
|
+
import tempfile
|
|
12
|
+
|
|
13
|
+
_FX = None
|
|
14
|
+
_ERR = re.compile(r"(invalid option|unrecognized option|invalid argument|ambiguous argument|"
|
|
15
|
+
r"option requires|invalid line width|invalid tab size|unexpected EOF|syntax error)", re.I)
|
|
16
|
+
_ENV = {**os.environ, "LC_ALL": "C", "TZ": "UTC"}
|
|
17
|
+
_ENV.pop("LS_COLORS", None)
|
|
18
|
+
|
|
19
|
+
# name, size, mtime offset (minutes); sizes and times deliberately not in name order
|
|
20
|
+
_FILES = [("a.py", 120, 50), ("b.txt", 3000, 5), ("c.log", 900, 30), ("file1", 10, 70), ("file2", 40, 10),
|
|
21
|
+
("file10", 20, 60), ("notes.md", 500, 20), ("notes.md~", 480, 80), (".env", 60, 40),
|
|
22
|
+
(".bashrc", 30, 90), ("report-2024.pdf", 8000, 15), ("report-old.pdf", 700, 100),
|
|
23
|
+
("image.jpg", 20000, 25), ("run.sh", 80, 35), ("empty.txt", 0, 45), ("data.csv", 1500, 55),
|
|
24
|
+
("src/main.c", 200, 12), ("src/util.py", 90, 22), ("logs/x.log", 70, 33),
|
|
25
|
+
("node_modules/m.js", 15, 44), ("docs/guide.md", 300, 66)]
|
|
26
|
+
_DIRS = [("src", 8), ("logs", 95), ("docs", 18), ("node_modules", 3), ("emptydir", 75)]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def fixture():
|
|
30
|
+
global _FX
|
|
31
|
+
if _FX is None:
|
|
32
|
+
fx = tempfile.mkdtemp(prefix="aiman_ls_fx_")
|
|
33
|
+
base = 1_700_000_000
|
|
34
|
+
for d, _ in _DIRS:
|
|
35
|
+
os.makedirs(os.path.join(fx, d), exist_ok=True)
|
|
36
|
+
for name, size, off in _FILES:
|
|
37
|
+
p = os.path.join(fx, name)
|
|
38
|
+
with open(p, "w") as h:
|
|
39
|
+
h.write("x" * size)
|
|
40
|
+
# atime order differs from mtime order
|
|
41
|
+
os.utime(p, (base + 7200 - off * 37 % 97 * 60, base - off * 60))
|
|
42
|
+
os.chmod(os.path.join(fx, "run.sh"), 0o755)
|
|
43
|
+
os.symlink("a.py", os.path.join(fx, "link"))
|
|
44
|
+
for d, off in _DIRS:
|
|
45
|
+
os.utime(os.path.join(fx, d), (base + 9000, base - off * 60))
|
|
46
|
+
_FX = fx
|
|
47
|
+
return _FX
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def sandbox(cmd):
|
|
51
|
+
"""Rewrite every path argument of the ls part to the fixture, keeping any glob."""
|
|
52
|
+
fx = fixture()
|
|
53
|
+
head, sep, pipe = cmd.partition(" | ")
|
|
54
|
+
try:
|
|
55
|
+
toks = shlex.split(head, posix=False)
|
|
56
|
+
except ValueError:
|
|
57
|
+
return cmd
|
|
58
|
+
out, skip = [], False
|
|
59
|
+
for k, x in enumerate(toks):
|
|
60
|
+
if k == 0 or skip or x.startswith("-"):
|
|
61
|
+
skip = x == "-I" or (x.startswith("-") and not x.startswith("--") and x.endswith("I"))
|
|
62
|
+
out.append(x)
|
|
63
|
+
continue
|
|
64
|
+
if any(ch in x for ch in "*?["):
|
|
65
|
+
if x.endswith("*/"):
|
|
66
|
+
g = "*/"
|
|
67
|
+
else:
|
|
68
|
+
g = x.rpartition("/")[2]
|
|
69
|
+
out.append(f"{fx}/{g}")
|
|
70
|
+
else:
|
|
71
|
+
out.append(fx)
|
|
72
|
+
return " ".join(out) + (sep + pipe if sep else "")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _exec(cmd):
|
|
76
|
+
return subprocess.run(["bash", "-c", sandbox(cmd)], capture_output=True, text=True,
|
|
77
|
+
timeout=10, cwd=fixture(), env=_ENV)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def validate(cmd):
|
|
81
|
+
r = _exec(cmd)
|
|
82
|
+
m = _ERR.search(r.stderr)
|
|
83
|
+
return (False, r.stderr.strip().splitlines()[0]) if m else (True, "")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def run(cmd):
|
|
87
|
+
fx = fixture()
|
|
88
|
+
return [l.replace(fx, "FX") for l in _exec(cmd).stdout.splitlines()]
|
aiman/tools/ls/rules.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""ls rules: lexicons, normalisers and assemble() -- the rule half of slot filling."""
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
from aiman.tools.find.rules import EXT_LEX as _FIND_EXT
|
|
5
|
+
|
|
6
|
+
from .slots import FLAGS, empty
|
|
7
|
+
|
|
8
|
+
EXT_LEX = {**_FIND_EXT, "pyc": "pyc", "o": "o", "swp": "swp", "jsx": "jsx", "tsx": "tsx", "deb": "deb",
|
|
9
|
+
"images": "jpg", "photos": "jpg", "videos": "mp4", "spreadsheets": "csv"}
|
|
10
|
+
|
|
11
|
+
PATH_LEX = [
|
|
12
|
+
(r"\bdownloads?( folder| directory| dir)?\b", "~/Downloads"),
|
|
13
|
+
(r"\bdocuments( folder| directory| dir)?\b", "~/Documents"),
|
|
14
|
+
(r"\bdesktop( folder| directory)?\b", "~/Desktop"),
|
|
15
|
+
(r"\bpictures( folder| directory)?\b", "~/Pictures"),
|
|
16
|
+
(r"\b(temp|tmp|temporary) (folder|directory|dir)\b", "/tmp"),
|
|
17
|
+
(r"\b(system logs?|log (folder|directory|dir))\b", "/var/log"),
|
|
18
|
+
(r"\b(config|configuration|etc) (folder|directory|dir)\b", "/etc"),
|
|
19
|
+
(r"\bweb root\b", "/srv/www"),
|
|
20
|
+
(r"\b(src|source) (folder|directory|dir)\b", "src"),
|
|
21
|
+
(r"\bhome (folder|directory|dir)s?\b|\bin home\b", "~"),
|
|
22
|
+
(r"\broot (folder|directory|dir)\b|\bfilesystem root\b", "/"),
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
IGNORE_CUE = r"(?:ignoring|excluding|except|hiding|without|skip|skipping)"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def norm_ext(word):
|
|
29
|
+
w = word.lower().strip(".?,'\"*")
|
|
30
|
+
return EXT_LEX.get(w, EXT_LEX.get(w[:-1] if w.endswith("s") else w, w))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def ext_from_text(text, skip_after_cue=True):
|
|
34
|
+
"""fallback when the tagger found no EXT: first lexicon word before files/scripts/images..."""
|
|
35
|
+
toks = [t.lower().strip("?,") for t in text.split()]
|
|
36
|
+
for i, t in enumerate(toks):
|
|
37
|
+
if skip_after_cue and i and re.fullmatch(IGNORE_CUE, toks[i - 1]):
|
|
38
|
+
continue
|
|
39
|
+
nxt = toks[i + 1] if i + 1 < len(toks) else ""
|
|
40
|
+
if t.startswith("*.") and len(t) > 2:
|
|
41
|
+
return t[2:]
|
|
42
|
+
if t.startswith(".") and t[1:] in EXT_LEX:
|
|
43
|
+
return EXT_LEX[t[1:]]
|
|
44
|
+
if t in EXT_LEX and nxt in ("files", "file", "scripts", "images", "photos", "videos",
|
|
45
|
+
"documents", "sources", "source", "archives", "pages", "logs"):
|
|
46
|
+
return EXT_LEX[t]
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _no(v):
|
|
51
|
+
return None if v == "none" else v
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def assemble(text, sp, c):
|
|
55
|
+
"""Predicted spans `sp` + classifier labels `c` -> (slots, error)."""
|
|
56
|
+
t = text.lower()
|
|
57
|
+
s = empty()
|
|
58
|
+
for f in FLAGS:
|
|
59
|
+
s[f] = c[f] == "True"
|
|
60
|
+
s["format"], s["all"], s["sort"] = _no(c["format"]), _no(c["all"]), _no(c["sort"])
|
|
61
|
+
s["time"], s["indicator"], s["time_style"] = _no(c["time_field"]), _no(c["indicator"]), _no(c["time_style"])
|
|
62
|
+
|
|
63
|
+
# path
|
|
64
|
+
paths = [p.rstrip("/") or "/" for p in sp.get("PATH", [])]
|
|
65
|
+
if not paths and c["path_default"] in ("lex", "tagged"):
|
|
66
|
+
paths = [next((v for pat, v in PATH_LEX if re.search(pat, t)), ".")]
|
|
67
|
+
s["path"] = paths or [c["path_default"] if c["path_default"] in (".", "~", "/") else "."]
|
|
68
|
+
|
|
69
|
+
# glob
|
|
70
|
+
kind = c["glob_kind"]
|
|
71
|
+
if kind == "ext":
|
|
72
|
+
e = norm_ext(sp["EXT"][0]) if sp.get("EXT") else ext_from_text(text)
|
|
73
|
+
s["glob"] = f"*.{e}" if e else None
|
|
74
|
+
elif kind in ("prefix", "contains") and sp.get("NAME"):
|
|
75
|
+
w = sp["NAME"][0].strip("'*")
|
|
76
|
+
s["glob"] = f"{w}*" if kind == "prefix" else f"*{w}*"
|
|
77
|
+
elif kind == "dirs":
|
|
78
|
+
s["glob"], s["directory"] = "*/", True
|
|
79
|
+
elif kind == "hidden":
|
|
80
|
+
s["glob"], s["directory"] = ".*", True
|
|
81
|
+
if s["glob"] and len(s["path"]) > 1:
|
|
82
|
+
s["path"] = s["path"][:1]
|
|
83
|
+
if s["glob"] and s["recursive"] and kind not in ("dirs", "hidden"):
|
|
84
|
+
return s, "ls can't filter by name recursively; try: aiman find"
|
|
85
|
+
|
|
86
|
+
# ignore
|
|
87
|
+
if c["ignore_kind"] != "none":
|
|
88
|
+
ig = sp.get("IGNORE", [None])[0]
|
|
89
|
+
if c["ignore_kind"] == "ext":
|
|
90
|
+
if ig is None:
|
|
91
|
+
m = re.search(IGNORE_CUE + r"\s+(?:the\s+|all\s+)?(\S+)", t)
|
|
92
|
+
ig = m.group(1) if m else None
|
|
93
|
+
s["ignore"] = f"*.{norm_ext(ig)}" if ig else None
|
|
94
|
+
else:
|
|
95
|
+
s["ignore"] = ig.strip("'\"") if ig else None
|
|
96
|
+
|
|
97
|
+
# -h needs a size column
|
|
98
|
+
if s["human"] and s["format"] in (None, "1") and not s["blocks"]:
|
|
99
|
+
s["format"] = "l"
|
|
100
|
+
|
|
101
|
+
# action
|
|
102
|
+
s["action"] = c["action"]
|
|
103
|
+
if "{N}" in s["action"]:
|
|
104
|
+
n = (sp.get("N") or [None])[0]
|
|
105
|
+
if n is None:
|
|
106
|
+
m = re.search(r"\b(\d+)\b", text)
|
|
107
|
+
n = m.group(1) if m else "10"
|
|
108
|
+
s["args"] = {"N": re.sub(r"\D", "", n) or "10"}
|
|
109
|
+
return s, None
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"tool": "ls",
|
|
3
|
+
"description": "GNU ls: intent -> command via slot filling",
|
|
4
|
+
"span_slots": {
|
|
5
|
+
"PATH": "directory or file to list",
|
|
6
|
+
"EXT": "extension for a *.ext glob",
|
|
7
|
+
"NAME": "name fragment for a prefix* or *contains* glob",
|
|
8
|
+
"IGNORE": "pattern for -I",
|
|
9
|
+
"N": "how many entries for head/tail"
|
|
10
|
+
},
|
|
11
|
+
"class_slots": {
|
|
12
|
+
"format": ["none", "l", "g", "o", "n", "1"],
|
|
13
|
+
"all": ["none", "a", "A"],
|
|
14
|
+
"sort": ["none", "t", "S", "X", "v", "U"],
|
|
15
|
+
"time_field": ["none", "u", "c", "birth"],
|
|
16
|
+
"indicator": ["none", "F", "p"],
|
|
17
|
+
"time_style": ["none", "full-time", "long-iso"],
|
|
18
|
+
"glob_kind": ["none", "ext", "prefix", "contains", "dirs", "hidden"],
|
|
19
|
+
"ignore_kind": ["none", "ext", "exact"],
|
|
20
|
+
"path_default": [".", "~", "/", "tagged", "lex"],
|
|
21
|
+
"action": ["none", "| head -n {N}", "| tail -n {N}", "| wc -l"],
|
|
22
|
+
"flags": ["human", "reverse", "recursive", "directory", "inode", "blocks", "backups", "deref", "dirs_first"]
|
|
23
|
+
},
|
|
24
|
+
"canonical": "ls -<l|g|o|n|1><a|A><h><t|S|X|v|U><u|c><r><R><d><i><s><F|p><B><L> [--group-directories-first] [--full-time|--time-style=long-iso] [--time=birth] [-I 'pat'] [path[/glob]...] [| head -n N | tail -n N | wc -l]",
|
|
25
|
+
"out_of_schema": ["-b", "-C", "-D", "-f", "-G", "-H", "-k", "-m", "-N", "-q", "-Q", "-T", "-w", "-x", "-Z",
|
|
26
|
+
"--zero", "--color", "--hyperlink", "--author", "--dired", "--file-type", "--si",
|
|
27
|
+
"--block-size", "--quoting-style", "--time-style=+FORMAT", "--hide", "multiple globs"]
|
|
28
|
+
}
|
aiman/tools/ls/slots.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""ls 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 ls command (the rule engine)
|
|
5
|
+
tag(intent, slots) -> (tokens, BIO tags)
|
|
6
|
+
targets(slots, intent) -> {classifier: label}
|
|
7
|
+
|
|
8
|
+
Canonical form: one short-flag bundle in a fixed order, then long options, then -I, then paths:
|
|
9
|
+
ls -<l|g|o|n|1><a|A><h><t|S|X|v|U><u|c><r><R><d><i><s><F|p><B><L> [long] [-I 'pat'] [path[/glob]]
|
|
10
|
+
"""
|
|
11
|
+
import re
|
|
12
|
+
import shlex
|
|
13
|
+
|
|
14
|
+
BOOLS = {"human": "h", "reverse": "r", "recursive": "R", "directory": "d", "inode": "i",
|
|
15
|
+
"blocks": "s", "backups": "B", "deref": "L"}
|
|
16
|
+
FLAGS = list(BOOLS) + ["dirs_first"]
|
|
17
|
+
FORMATS, ALLS, SORTS, TIMES, INDICATORS = "lgon1", "aA", "tSXvU", "uc", "Fp"
|
|
18
|
+
ACTIONS = ["| head -n {N}", "| tail -n {N}", "| wc -l"]
|
|
19
|
+
|
|
20
|
+
LONG = { # long option -> short flag char
|
|
21
|
+
"--all": "a", "--almost-all": "A", "--human-readable": "h", "--reverse": "r", "--recursive": "R",
|
|
22
|
+
"--directory": "d", "--inode": "i", "--size": "s", "--classify": "F", "--indicator-style=classify": "F",
|
|
23
|
+
"--indicator-style=slash": "p", "--ignore-backups": "B", "--dereference": "L",
|
|
24
|
+
"--numeric-uid-gid": "n", "--format=long": "l", "--format=verbose": "l", "--format=single-column": "1",
|
|
25
|
+
"--sort=size": "S", "--sort=time": "t", "--sort=extension": "X", "--sort=version": "v",
|
|
26
|
+
"--sort=none": "U", "--time=atime": "u", "--time=access": "u", "--time=use": "u",
|
|
27
|
+
"--time=ctime": "c", "--time=status": "c",
|
|
28
|
+
}
|
|
29
|
+
SPECIAL = {"--time=birth": ("time", "birth"), "--time=creation": ("time", "birth"),
|
|
30
|
+
"--full-time": ("time_style", "full-time"), "--time-style=long-iso": ("time_style", "long-iso"),
|
|
31
|
+
"--group-directories-first": ("dirs_first", True),
|
|
32
|
+
"--time=mtime": None, "--time=modification": None, "--sort=name": None}
|
|
33
|
+
|
|
34
|
+
GLOB_KINDS = [(r"^\*/$", "dirs"), (r"^\.\*$", "hidden"), (r"^\*\.[\w]+$", "ext"),
|
|
35
|
+
(r"^\*[^*/]+\*$", "contains"), (r"^[^*/.][^*/]*\*$", "prefix")]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def empty():
|
|
39
|
+
s = {"path": ["."], "glob": None, "format": None, "all": None, "sort": None, "time": None,
|
|
40
|
+
"indicator": None, "time_style": None, "ignore": None, "action": "none", "args": {}}
|
|
41
|
+
for f in FLAGS:
|
|
42
|
+
s[f] = False
|
|
43
|
+
return s
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def glob_kind(g):
|
|
47
|
+
if g is None:
|
|
48
|
+
return "none"
|
|
49
|
+
return next((k for pat, k in GLOB_KINDS if re.match(pat, g)), None)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _split_glob(arg):
|
|
53
|
+
if arg.endswith("*/"):
|
|
54
|
+
base, g = arg[:-2], "*/"
|
|
55
|
+
else:
|
|
56
|
+
base, sep, g = arg.rpartition("/")
|
|
57
|
+
if sep and not base:
|
|
58
|
+
base = "/"
|
|
59
|
+
base = base.rstrip("/") or ("/" if base.startswith("/") else ".")
|
|
60
|
+
return base, g
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _pipe(p):
|
|
64
|
+
m = re.fullmatch(r"(head|tail)(?: -n (\d+)| -(\d+))?", p)
|
|
65
|
+
if m:
|
|
66
|
+
return f"| {m.group(1)} -n {{N}}", {"N": m.group(2) or m.group(3) or "10"}
|
|
67
|
+
if p == "wc -l":
|
|
68
|
+
return "| wc -l", {}
|
|
69
|
+
return None, None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def parse(cmd):
|
|
73
|
+
"""Return slots dict, or None if the command uses features outside the schema."""
|
|
74
|
+
s = empty()
|
|
75
|
+
if " | " in cmd:
|
|
76
|
+
cmd, pipe = cmd.split(" | ", 1)
|
|
77
|
+
s["action"], s["args"] = _pipe(pipe.strip())
|
|
78
|
+
if s["action"] is None:
|
|
79
|
+
return None
|
|
80
|
+
try:
|
|
81
|
+
t = shlex.split(cmd, posix=False)
|
|
82
|
+
except ValueError:
|
|
83
|
+
return None
|
|
84
|
+
if not t or t[0] != "ls":
|
|
85
|
+
return None
|
|
86
|
+
chars, args, i = [], [], 1
|
|
87
|
+
while i < len(t):
|
|
88
|
+
x = t[i]
|
|
89
|
+
if x.startswith("--"):
|
|
90
|
+
if x in LONG:
|
|
91
|
+
chars.append(LONG[x])
|
|
92
|
+
elif x in SPECIAL:
|
|
93
|
+
if SPECIAL[x]:
|
|
94
|
+
k, v = SPECIAL[x]
|
|
95
|
+
s[k] = v
|
|
96
|
+
elif x.startswith("--ignore="):
|
|
97
|
+
s["ignore"] = x.split("=", 1)[1].strip("'\"")
|
|
98
|
+
else:
|
|
99
|
+
return None
|
|
100
|
+
elif x.startswith("-") and len(x) > 1:
|
|
101
|
+
body = x[1:]
|
|
102
|
+
if "I" in body:
|
|
103
|
+
body, pat = body.split("I", 1)
|
|
104
|
+
if not pat:
|
|
105
|
+
i += 1
|
|
106
|
+
if i >= len(t):
|
|
107
|
+
return None
|
|
108
|
+
pat = t[i]
|
|
109
|
+
s["ignore"] = pat.strip("'\"")
|
|
110
|
+
chars += list(body)
|
|
111
|
+
else:
|
|
112
|
+
args.append(x)
|
|
113
|
+
i += 1
|
|
114
|
+
|
|
115
|
+
known = set(FORMATS + ALLS + SORTS + TIMES + INDICATORS + "".join(BOOLS.values()))
|
|
116
|
+
if any(c not in known for c in chars):
|
|
117
|
+
return None
|
|
118
|
+
cs = set(chars)
|
|
119
|
+
fmt = cs & set(FORMATS)
|
|
120
|
+
if "1" in fmt and len(fmt) > 1:
|
|
121
|
+
return None
|
|
122
|
+
if len(fmt - {"l"}) > 1:
|
|
123
|
+
return None
|
|
124
|
+
s["format"] = next(iter(fmt - {"l"}), "l" if fmt else None)
|
|
125
|
+
for key, group in (("all", ALLS), ("sort", SORTS), ("time", TIMES), ("indicator", INDICATORS)):
|
|
126
|
+
hit = cs & set(group)
|
|
127
|
+
if len(hit) > 1 or (key == "time" and hit and s["time"]):
|
|
128
|
+
return None
|
|
129
|
+
if hit:
|
|
130
|
+
s[key] = hit.pop()
|
|
131
|
+
for k, c in BOOLS.items():
|
|
132
|
+
s[k] = c in cs
|
|
133
|
+
if s["time_style"] == "full-time" and s["format"] == "l":
|
|
134
|
+
s["format"] = None # --full-time already implies -l
|
|
135
|
+
|
|
136
|
+
globs = [a for a in args if any(c in a for c in "*?[")]
|
|
137
|
+
if globs:
|
|
138
|
+
if len(args) != 1:
|
|
139
|
+
return None
|
|
140
|
+
base, g = _split_glob(args[0])
|
|
141
|
+
if not glob_kind(g):
|
|
142
|
+
return None
|
|
143
|
+
s["path"], s["glob"] = [base], g
|
|
144
|
+
elif args:
|
|
145
|
+
s["path"] = [a.rstrip("/") or "/" for a in args]
|
|
146
|
+
return s
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def build(s):
|
|
150
|
+
"""Rule engine: slots -> canonical ls command."""
|
|
151
|
+
f = (s["format"] or "") + (s["all"] or "") + ("h" if s["human"] else "") + (s["sort"] or "")
|
|
152
|
+
f += s["time"] if s["time"] in ("u", "c") else ""
|
|
153
|
+
for k in ("reverse", "recursive", "directory", "inode", "blocks"):
|
|
154
|
+
f += BOOLS[k] if s[k] else ""
|
|
155
|
+
f += (s["indicator"] or "") + ("B" if s["backups"] else "") + ("L" if s["deref"] else "")
|
|
156
|
+
out = ["ls"] + (["-" + f] if f else [])
|
|
157
|
+
if s["dirs_first"]:
|
|
158
|
+
out.append("--group-directories-first")
|
|
159
|
+
if s["time_style"] == "full-time":
|
|
160
|
+
out.append("--full-time")
|
|
161
|
+
elif s["time_style"]:
|
|
162
|
+
out.append(f"--time-style={s['time_style']}")
|
|
163
|
+
if s["time"] == "birth":
|
|
164
|
+
out.append("--time=birth")
|
|
165
|
+
if s["ignore"]:
|
|
166
|
+
out += ["-I", f"'{s['ignore']}'"]
|
|
167
|
+
if s["glob"]:
|
|
168
|
+
p = s["path"][0]
|
|
169
|
+
out.append(s["glob"] if p == "." else ("/" if p == "/" else p + "/") + s["glob"])
|
|
170
|
+
elif s["path"] != ["."]:
|
|
171
|
+
out += s["path"]
|
|
172
|
+
c = " ".join(out)
|
|
173
|
+
if s["action"] != "none":
|
|
174
|
+
a = s["action"]
|
|
175
|
+
for k, v in s["args"].items():
|
|
176
|
+
a = a.replace("{" + k + "}", v)
|
|
177
|
+
c += " " + a
|
|
178
|
+
return c
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# ---------------------------------------------------------------- BIO tagging
|
|
182
|
+
def _norm(w):
|
|
183
|
+
return w.lower().strip("?,.'\"").rstrip("/") if w not in ("/",) else w
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _ext_of(word):
|
|
187
|
+
from .rules import EXT_LEX
|
|
188
|
+
w = word.lower().strip("?,'\"*")
|
|
189
|
+
w = w[1:] if w.startswith(".") else w
|
|
190
|
+
return EXT_LEX.get(w, EXT_LEX.get(w[:-1] if w.endswith("s") else w))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def tag(intent, s):
|
|
194
|
+
toks = intent.split()
|
|
195
|
+
tags = ["O"] * len(toks)
|
|
196
|
+
low = [_norm(w) for w in toks]
|
|
197
|
+
|
|
198
|
+
def mark(label, ok, last=False):
|
|
199
|
+
idx = range(len(toks) - 1, -1, -1) if last else range(len(toks))
|
|
200
|
+
for k in idx:
|
|
201
|
+
if tags[k] == "O" and ok(toks[k], low[k]):
|
|
202
|
+
tags[k] = "B-" + label
|
|
203
|
+
return
|
|
204
|
+
|
|
205
|
+
multi = len(s["path"]) > 1
|
|
206
|
+
for p in s["path"]:
|
|
207
|
+
# a bare "/" is left to path_default: "marking folders with /" also contains that token
|
|
208
|
+
if multi or p not in (".", "~", "/"):
|
|
209
|
+
mark("PATH", lambda w, l, p=p: l == p.lower().rstrip("/"))
|
|
210
|
+
kind = glob_kind(s["glob"])
|
|
211
|
+
if kind == "ext":
|
|
212
|
+
e = s["glob"][2:]
|
|
213
|
+
mark("EXT", lambda w, l: _ext_of(w) == e)
|
|
214
|
+
elif kind in ("prefix", "contains"):
|
|
215
|
+
core = s["glob"].strip("*")
|
|
216
|
+
mark("NAME", lambda w, l: l == core.lower())
|
|
217
|
+
if s["ignore"]:
|
|
218
|
+
ig = s["ignore"]
|
|
219
|
+
if ig.startswith("*."):
|
|
220
|
+
mark("IGNORE", lambda w, l: _ext_of(w) == ig[2:], last=True)
|
|
221
|
+
else:
|
|
222
|
+
mark("IGNORE", lambda w, l: l == ig.lower(), last=True)
|
|
223
|
+
if "N" in s["args"]:
|
|
224
|
+
mark("N", lambda w, l: l == s["args"]["N"])
|
|
225
|
+
return toks, tags
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def targets(s, intent):
|
|
229
|
+
words = {_norm(w) for w in intent.split()}
|
|
230
|
+
p = s["path"]
|
|
231
|
+
if p in (["."], ["~"], ["/"]):
|
|
232
|
+
pd = p[0]
|
|
233
|
+
else:
|
|
234
|
+
pd = "tagged" if all(x.lower() in words for x in p) else "lex"
|
|
235
|
+
ig = s["ignore"]
|
|
236
|
+
t = {
|
|
237
|
+
"format": s["format"] or "none", "all": s["all"] or "none", "sort": s["sort"] or "none",
|
|
238
|
+
"time_field": s["time"] or "none", "indicator": s["indicator"] or "none",
|
|
239
|
+
"time_style": s["time_style"] or "none", "glob_kind": glob_kind(s["glob"]),
|
|
240
|
+
"ignore_kind": "none" if not ig else "ext" if ig.startswith("*.") else "exact",
|
|
241
|
+
"path_default": pd, "action": s["action"],
|
|
242
|
+
}
|
|
243
|
+
for f in FLAGS:
|
|
244
|
+
t[f] = str(bool(s[f]))
|
|
245
|
+
return t
|