robotframework-mind 0.1.1__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.
- robot_mind.py +442 -0
- robot_mind_app/__init__.py +2 -0
- robot_mind_app/__main__.py +105 -0
- robot_mind_app/community_panel.py +106 -0
- robot_mind_app/editors.py +59 -0
- robot_mind_app/engine.py +24 -0
- robot_mind_app/folders.py +52 -0
- robot_mind_app/graph.py +140 -0
- robot_mind_app/graph_layout.py +97 -0
- robot_mind_app/graph_view.py +244 -0
- robot_mind_app/icons.py +141 -0
- robot_mind_app/lucide.py +71 -0
- robot_mind_app/settings.py +84 -0
- robot_mind_app/theme.py +204 -0
- robot_mind_app/widgets.py +157 -0
- robot_mind_app/window.py +621 -0
- robot_mind_app/worker.py +100 -0
- robotframework_mind-0.1.1.dist-info/METADATA +123 -0
- robotframework_mind-0.1.1.dist-info/RECORD +23 -0
- robotframework_mind-0.1.1.dist-info/WHEEL +5 -0
- robotframework_mind-0.1.1.dist-info/entry_points.txt +2 -0
- robotframework_mind-0.1.1.dist-info/licenses/NOTICE +9 -0
- robotframework_mind-0.1.1.dist-info/top_level.txt +2 -0
robot_mind.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
"""robotframework-mind: exact lookups over a Robot Framework test repo, for people and scripts.
|
|
2
|
+
|
|
3
|
+
Indexes tests (tags, docs, calls), user keywords (args, first doc line, calls),
|
|
4
|
+
variables (values), suite/test fixtures and the JSON files under docs/, then
|
|
5
|
+
answers short questions with one line per hit and its file:line.
|
|
6
|
+
|
|
7
|
+
Usage: python robot_mind.py [--root DIR] <ticket|kw|callers|tag|find> TERM [--limit N]
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from dataclasses import asdict, dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
ROBOT_EXTS = {".robot", ".resource"}
|
|
21
|
+
SOURCE_EXTS = ROBOT_EXTS | {".json"}
|
|
22
|
+
SKIP_DIRS = {".git", ".venv", "venv", "node_modules", "results", "__pycache__", "graphify-out"}
|
|
23
|
+
JSON_DIR = "docs"
|
|
24
|
+
JSON_MAX_BYTES = 5_000_000
|
|
25
|
+
ROBOT_MAX_BYTES = 50_000_000
|
|
26
|
+
VALUE_WIDTH = 160
|
|
27
|
+
JSON_WIDTH = 300
|
|
28
|
+
CACHE_VERSION = 1
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Entry:
|
|
33
|
+
kind: str # test | keyword | var | json | suite setup | test setup | ...
|
|
34
|
+
name: str
|
|
35
|
+
file: str # posix path relative to the root
|
|
36
|
+
line: int = 0
|
|
37
|
+
tags: list[str] = field(default_factory=list)
|
|
38
|
+
args: str = ""
|
|
39
|
+
doc: str = ""
|
|
40
|
+
value: str = ""
|
|
41
|
+
calls: list[list] = field(default_factory=list) # [[keyword name, line], ...]
|
|
42
|
+
refs: list[str] = field(default_factory=list) # normalized variable names used in the body
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Hit:
|
|
47
|
+
"""One lookup result, shaped for both the CLI and the desktop app."""
|
|
48
|
+
kind: str
|
|
49
|
+
name: str
|
|
50
|
+
file: str
|
|
51
|
+
line: int = 0 # the entry's own line
|
|
52
|
+
tags: list[str] = field(default_factory=list)
|
|
53
|
+
args: str = ""
|
|
54
|
+
doc: str = ""
|
|
55
|
+
value: str = ""
|
|
56
|
+
call_line: int = 0 # call-site line for callers hits, 0 otherwise
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def norm(name: str) -> str:
|
|
60
|
+
"""Robot matches keyword names case-, space- and underscore-insensitively."""
|
|
61
|
+
return name.lower().replace(" ", "").replace("_", "")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
VAR_REF = re.compile(r"[$@&%]\{([^}\[]+)")
|
|
65
|
+
CONTROLS = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def var_refs(text: str) -> list[str]:
|
|
69
|
+
return [norm(m) for m in VAR_REF.findall(text)]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def strip_controls(text: str) -> str:
|
|
73
|
+
"""Drop terminal control bytes so repo text cannot inject escapes into printed output."""
|
|
74
|
+
return CONTROLS.sub("", text)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# ---------------------------------------------------------------- parsing
|
|
78
|
+
|
|
79
|
+
def parse_robot(path: Path, rel: str) -> list[Entry]:
|
|
80
|
+
from robot.api import get_model, get_resource_model
|
|
81
|
+
from robot.api.parsing import ModelVisitor
|
|
82
|
+
|
|
83
|
+
model = (get_resource_model if path.suffix == ".resource" else get_model)(str(path))
|
|
84
|
+
entries: list[Entry] = []
|
|
85
|
+
file_tags: list[str] = []
|
|
86
|
+
default_tags: list[str] = []
|
|
87
|
+
|
|
88
|
+
class Visitor(ModelVisitor):
|
|
89
|
+
scope: Entry | None = None
|
|
90
|
+
|
|
91
|
+
def _body(self, node, entry):
|
|
92
|
+
entries.append(entry)
|
|
93
|
+
prev, self.scope = self.scope, entry
|
|
94
|
+
self.generic_visit(node)
|
|
95
|
+
self.scope = prev
|
|
96
|
+
|
|
97
|
+
def visit_TestCase(self, node):
|
|
98
|
+
if node.name:
|
|
99
|
+
self._body(node, Entry("test", node.name, rel, node.lineno))
|
|
100
|
+
|
|
101
|
+
def visit_Keyword(self, node):
|
|
102
|
+
if node.name:
|
|
103
|
+
self._body(node, Entry("keyword", node.name, rel, node.lineno))
|
|
104
|
+
|
|
105
|
+
def visit_Tags(self, node):
|
|
106
|
+
if self.scope:
|
|
107
|
+
self.scope.tags.extend(node.values)
|
|
108
|
+
|
|
109
|
+
def visit_TestTags(self, node):
|
|
110
|
+
file_tags.extend(node.values)
|
|
111
|
+
|
|
112
|
+
visit_ForceTags = visit_TestTags
|
|
113
|
+
|
|
114
|
+
def visit_DefaultTags(self, node):
|
|
115
|
+
default_tags.extend(node.values)
|
|
116
|
+
|
|
117
|
+
def visit_Documentation(self, node):
|
|
118
|
+
if self.scope:
|
|
119
|
+
self.scope.doc = node.value.split("\n")[0].strip()
|
|
120
|
+
self.scope.refs.extend(r for r in var_refs(node.value) if r not in self.scope.refs)
|
|
121
|
+
|
|
122
|
+
def visit_Arguments(self, node):
|
|
123
|
+
if self.scope:
|
|
124
|
+
self.scope.args = ", ".join(node.values)
|
|
125
|
+
|
|
126
|
+
def visit_Variable(self, node):
|
|
127
|
+
if node.name:
|
|
128
|
+
entries.append(Entry("var", node.name, rel, node.lineno, value=" ".join(node.value)))
|
|
129
|
+
|
|
130
|
+
def visit_Var(self, node):
|
|
131
|
+
if node.name:
|
|
132
|
+
entries.append(Entry("var", node.name, rel, node.lineno, value=" ".join(node.value)))
|
|
133
|
+
|
|
134
|
+
def visit_KeywordCall(self, node):
|
|
135
|
+
if self.scope and node.keyword:
|
|
136
|
+
self.scope.calls.append([node.keyword, node.lineno])
|
|
137
|
+
self.scope.refs.extend(r for r in var_refs(" ".join(node.args)) if r not in self.scope.refs)
|
|
138
|
+
|
|
139
|
+
def _scoped_fixture(self, node):
|
|
140
|
+
if self.scope and node.name:
|
|
141
|
+
self.scope.calls.append([node.name, node.lineno])
|
|
142
|
+
|
|
143
|
+
visit_Setup = visit_Teardown = _scoped_fixture
|
|
144
|
+
|
|
145
|
+
def _file_fixture(self, node, kind):
|
|
146
|
+
if node.name:
|
|
147
|
+
entries.append(Entry(kind, "", rel, node.lineno, calls=[[node.name, node.lineno]]))
|
|
148
|
+
|
|
149
|
+
def visit_SuiteSetup(self, node):
|
|
150
|
+
self._file_fixture(node, "suite setup")
|
|
151
|
+
|
|
152
|
+
def visit_SuiteTeardown(self, node):
|
|
153
|
+
self._file_fixture(node, "suite teardown")
|
|
154
|
+
|
|
155
|
+
def visit_TestSetup(self, node):
|
|
156
|
+
self._file_fixture(node, "test setup")
|
|
157
|
+
|
|
158
|
+
def visit_TestTeardown(self, node):
|
|
159
|
+
self._file_fixture(node, "test teardown")
|
|
160
|
+
|
|
161
|
+
Visitor().visit(model)
|
|
162
|
+
for e in entries:
|
|
163
|
+
if e.kind == "test":
|
|
164
|
+
if not e.tags:
|
|
165
|
+
e.tags.extend(t for t in default_tags if t not in e.tags)
|
|
166
|
+
e.tags.extend(t for t in file_tags if t not in e.tags)
|
|
167
|
+
return entries
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def flatten(value, prefix: str = "") -> list[str]:
|
|
171
|
+
if isinstance(value, dict):
|
|
172
|
+
out: list[str] = []
|
|
173
|
+
for k, v in value.items():
|
|
174
|
+
out.extend(flatten(v, f"{prefix}.{k}" if prefix else str(k)))
|
|
175
|
+
return out
|
|
176
|
+
text = json.dumps(value, ensure_ascii=False) if isinstance(value, list) else str(value)
|
|
177
|
+
return [f"{prefix}={text}" if prefix else text]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def parse_json(path: Path, rel: str) -> list[Entry]:
|
|
181
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
182
|
+
if not isinstance(data, dict):
|
|
183
|
+
return [Entry("json", path.stem, rel, value=" ".join(flatten(data)))]
|
|
184
|
+
entries = []
|
|
185
|
+
for top, section in data.items():
|
|
186
|
+
if isinstance(section, dict) and all(isinstance(v, dict) for v in section.values()):
|
|
187
|
+
entries += [Entry("json", f"{top}.{k}", rel, value=" ".join(flatten(v))) for k, v in section.items()]
|
|
188
|
+
else:
|
|
189
|
+
entries.append(Entry("json", str(top), rel, value=" ".join(flatten(section))))
|
|
190
|
+
return entries
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def parse_file(path: Path, rel: str) -> list[Entry]:
|
|
194
|
+
try:
|
|
195
|
+
return parse_json(path, rel) if path.suffix == ".json" else parse_robot(path, rel)
|
|
196
|
+
except Exception as exc: # one broken file must not hide the rest of the index
|
|
197
|
+
return [Entry("error", type(exc).__name__, rel, value=str(exc)[:VALUE_WIDTH])]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ---------------------------------------------------------------- index + cache
|
|
201
|
+
|
|
202
|
+
@dataclass(frozen=True)
|
|
203
|
+
class IgnoreRule:
|
|
204
|
+
base: str # posix path of the folder whose .gitignore holds the rule, ending in /
|
|
205
|
+
pattern: re.Pattern
|
|
206
|
+
negate: bool
|
|
207
|
+
dir_only: bool
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def glob_regex(glob: str) -> str:
|
|
211
|
+
"""A .gitignore glob as a regex: ** crosses folders, * and ? stay inside one."""
|
|
212
|
+
parts = {"**/": "(?:.*/)?", "**": ".*", "*": "[^/]*", "?": "[^/]"}
|
|
213
|
+
out, i = [], 0
|
|
214
|
+
while i < len(glob):
|
|
215
|
+
token = next((t for t in parts if glob.startswith(t, i)), None)
|
|
216
|
+
out.append(parts[token] if token else re.escape(glob[i]))
|
|
217
|
+
i += len(token) if token else 1
|
|
218
|
+
return "".join(out)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def ignore_rule(base: str, line: str) -> IgnoreRule | None:
|
|
222
|
+
"""One .gitignore line; None for blanks and comments. A slash before the end anchors it to base."""
|
|
223
|
+
line = line.rstrip()
|
|
224
|
+
if not line or line.startswith("#"):
|
|
225
|
+
return None
|
|
226
|
+
negate = line.startswith("!")
|
|
227
|
+
body = line[1:] if negate else line
|
|
228
|
+
dir_only = body.endswith("/")
|
|
229
|
+
body = body.rstrip("/")
|
|
230
|
+
regex = glob_regex(body.lstrip("/"))
|
|
231
|
+
return IgnoreRule(base, re.compile(regex if "/" in body else f"(?:.*/)?{regex}"), negate, dir_only)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def ignore_rules(folder: str) -> list[IgnoreRule]:
|
|
235
|
+
"""The rules a folder (posix path ending in /) adds: its .gitignore, and .git/info/exclude at a repo root."""
|
|
236
|
+
rules = []
|
|
237
|
+
for name in (".gitignore", ".git/info/exclude"):
|
|
238
|
+
try:
|
|
239
|
+
text = Path(folder + name).read_text(encoding="utf-8", errors="replace")
|
|
240
|
+
except OSError:
|
|
241
|
+
continue
|
|
242
|
+
rules += [rule for line in text.splitlines() if (rule := ignore_rule(folder, line))]
|
|
243
|
+
return rules
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def is_ignored(rules: list[IgnoreRule], path: str, is_dir: bool) -> bool:
|
|
247
|
+
"""The last matching rule decides, as in git. path is posix and lies under every rule's base."""
|
|
248
|
+
ignored = False
|
|
249
|
+
for rule in rules:
|
|
250
|
+
if (is_dir or not rule.dir_only) and rule.pattern.fullmatch(path, len(rule.base)):
|
|
251
|
+
ignored = not rule.negate
|
|
252
|
+
return ignored
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def candidate_files(root: Path) -> list[Path]:
|
|
256
|
+
"""Robot and JSON files under root minus SKIP_DIRS, hidden folders and what each .gitignore on the way
|
|
257
|
+
leaves out. A nested repo (a folder with .git) starts over with only its own rules."""
|
|
258
|
+
found: list[Path] = []
|
|
259
|
+
inherited: dict[str, list[IgnoreRule]] = {root.as_posix().rstrip("/") + "/": []}
|
|
260
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
261
|
+
here = dirpath.replace("\\", "/").rstrip("/") + "/"
|
|
262
|
+
parent = inherited.pop(here)
|
|
263
|
+
rules = ([] if os.path.exists(here + ".git") else parent) + ignore_rules(here)
|
|
264
|
+
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.startswith(".")
|
|
265
|
+
and (os.path.exists(here + d + "/.git") or not is_ignored(rules, here + d, True))]
|
|
266
|
+
inherited.update((here + d + "/", rules) for d in dirnames)
|
|
267
|
+
found += [Path(here + name) for name in filenames
|
|
268
|
+
if os.path.splitext(name)[1] in SOURCE_EXTS and not is_ignored(rules, here + name, False)]
|
|
269
|
+
return found
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def find_repos(root: Path) -> list[str]:
|
|
273
|
+
"""Posix paths, relative to root, of the repos (folders with .git) inside it; a repo's own inner repos
|
|
274
|
+
are not listed. Sorted."""
|
|
275
|
+
repos: list[str] = []
|
|
276
|
+
for dirpath, dirnames, _files in os.walk(root):
|
|
277
|
+
here = Path(dirpath)
|
|
278
|
+
if here != root and (here / ".git").exists():
|
|
279
|
+
repos.append(here.relative_to(root).as_posix())
|
|
280
|
+
dirnames[:] = []
|
|
281
|
+
continue
|
|
282
|
+
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.startswith(".")]
|
|
283
|
+
return sorted(repos)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def in_scope(entries: list[Entry], scope: list[str] | None) -> list[Entry]:
|
|
287
|
+
"""Entries under one of the scope folders (posix, relative to the root); all of them when scope is None."""
|
|
288
|
+
if scope is None:
|
|
289
|
+
return entries
|
|
290
|
+
prefixes = tuple(folder.rstrip("/") + "/" for folder in scope)
|
|
291
|
+
return [e for e in entries if e.file.startswith(prefixes)]
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def source_files(root: Path) -> list[Path]:
|
|
295
|
+
def wanted(path: Path) -> bool:
|
|
296
|
+
if not path.is_file():
|
|
297
|
+
return False
|
|
298
|
+
if path.suffix in ROBOT_EXTS:
|
|
299
|
+
return path.stat().st_size <= ROBOT_MAX_BYTES
|
|
300
|
+
return (path.suffix == ".json" and JSON_DIR in path.relative_to(root).parts[:-1]
|
|
301
|
+
and path.stat().st_size <= JSON_MAX_BYTES)
|
|
302
|
+
return sorted(p for p in candidate_files(root) if wanted(p))
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def load_index(root: Path, cache_dir: Path) -> list[Entry]:
|
|
306
|
+
"""Per-file cache keyed by mtime and size; only changed files are parsed again."""
|
|
307
|
+
root = root.resolve()
|
|
308
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
309
|
+
cache_file = cache_dir / (hashlib.sha1(str(root).encode()).hexdigest()[:16] + ".json")
|
|
310
|
+
try:
|
|
311
|
+
cached = json.loads(cache_file.read_text(encoding="utf-8"))
|
|
312
|
+
if cached.get("version") != CACHE_VERSION:
|
|
313
|
+
cached = {}
|
|
314
|
+
except (OSError, ValueError):
|
|
315
|
+
cached = {}
|
|
316
|
+
old_files = cached.get("files", {})
|
|
317
|
+
files, changed = {}, False
|
|
318
|
+
for path in source_files(root):
|
|
319
|
+
rel = path.relative_to(root).as_posix()
|
|
320
|
+
st = path.stat()
|
|
321
|
+
stamp = [st.st_mtime_ns, st.st_size]
|
|
322
|
+
hit = old_files.get(rel)
|
|
323
|
+
if hit and hit["stamp"] == stamp:
|
|
324
|
+
files[rel] = hit
|
|
325
|
+
else:
|
|
326
|
+
files[rel] = {"stamp": stamp, "entries": [asdict(e) for e in parse_file(path, rel)]}
|
|
327
|
+
changed = True
|
|
328
|
+
if changed or set(files) != set(old_files):
|
|
329
|
+
tmp = cache_file.with_suffix(".tmp")
|
|
330
|
+
tmp.write_text(json.dumps({"version": CACHE_VERSION, "root": str(root), "files": files}), encoding="utf-8")
|
|
331
|
+
tmp.replace(cache_file)
|
|
332
|
+
return [Entry(**e) for f in files.values() for e in f["entries"]]
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
# ---------------------------------------------------------------- queries
|
|
336
|
+
|
|
337
|
+
def q_ticket(entries, term):
|
|
338
|
+
t = term.lower()
|
|
339
|
+
return [e for e in entries if e.kind in ("test", "keyword")
|
|
340
|
+
and (any(t in tag.lower() for tag in e.tags) or t in e.name.lower() or t in e.doc.lower())]
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def q_kw(entries, term):
|
|
344
|
+
exact = [e for e in entries if e.kind == "keyword" and norm(e.name) == norm(term)]
|
|
345
|
+
return exact or [e for e in entries if e.kind == "keyword" and norm(term) in norm(e.name)]
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def q_callers(entries, term):
|
|
349
|
+
target = norm(term)
|
|
350
|
+
exact = [(e, line) for e in entries for name, line in e.calls if norm(name) == target]
|
|
351
|
+
return exact or [(e, line) for e in entries for name, line in e.calls if target in norm(name)]
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def q_tag(entries, term):
|
|
355
|
+
t = term.lower()
|
|
356
|
+
match = (lambda tag: tag.lower().startswith(t[:-1])) if t.endswith("*") else (lambda tag: tag.lower() == t)
|
|
357
|
+
return [e for e in entries if any(match(tag) for tag in e.tags)]
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def find_rank(e: Entry, t: str) -> int | None:
|
|
361
|
+
"""0 exact name, 1 name contains, 2 tag contains, 3 doc/args/value contains, None no hit."""
|
|
362
|
+
tiers = [[e.name.lower()] if e.name.lower() == t else [], [e.name.lower()],
|
|
363
|
+
[tag.lower() for tag in e.tags], [e.doc.lower(), e.args.lower(), e.value.lower()]]
|
|
364
|
+
return next((rank for rank, texts in enumerate(tiers) if any(t in text for text in texts)), None)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def q_find(entries, term):
|
|
368
|
+
t = term.lower()
|
|
369
|
+
ranked = sorted(((r, i, e) for i, e in enumerate(entries)
|
|
370
|
+
if e.kind != "error" and (r := find_rank(e, t)) is not None),
|
|
371
|
+
key=lambda x: (x[0], x[1]))
|
|
372
|
+
hits = [e for _, _, e in ranked]
|
|
373
|
+
hit_ids = {id(e) for e in hits}
|
|
374
|
+
used = {ref for e in hits if e.kind == "var" for ref in var_refs(e.name)}
|
|
375
|
+
users = [e for e in entries if id(e) not in hit_ids and used.intersection(e.refs)]
|
|
376
|
+
return hits + users
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def clip(text: str, width: int) -> str:
|
|
380
|
+
return text if len(text) <= width else text[:width] + "..."
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
SUFFIX = {
|
|
384
|
+
"test": lambda e: f" [{' '.join(e.tags)}]" if e.tags else "",
|
|
385
|
+
"keyword": lambda e: (f" ({e.args})" if e.args else "") + (f" - {e.doc}" if e.doc else ""),
|
|
386
|
+
"var": lambda e: " = " + clip(e.value, VALUE_WIDTH),
|
|
387
|
+
"error": lambda e: " = " + clip(e.value, VALUE_WIDTH),
|
|
388
|
+
"json": lambda e: " = " + clip(e.value, JSON_WIDTH),
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def fmt_hit(h: Hit) -> str:
|
|
393
|
+
"""One line per hit; a call-site line (callers) prints the location only."""
|
|
394
|
+
at = h.call_line or h.line
|
|
395
|
+
loc = f"{h.file}:{at}" if at else h.file
|
|
396
|
+
head = " ".join(part for part in (h.kind, h.name, loc) if part)
|
|
397
|
+
return strip_controls(head if h.call_line else head + SUFFIX.get(h.kind, lambda _: "")(h))
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def default_cache() -> Path:
|
|
401
|
+
return Path.home() / ".cache" / "robotframework-mind"
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def lookup(entries: list[Entry], command: str, term: str) -> list[tuple[Entry, int]]:
|
|
405
|
+
"""Matching entries, each with its call-site line for callers and 0 otherwise."""
|
|
406
|
+
if command == "callers":
|
|
407
|
+
return q_callers(entries, term)
|
|
408
|
+
fn = {"ticket": q_ticket, "kw": q_kw, "tag": q_tag, "find": q_find}[command]
|
|
409
|
+
return [(e, 0) for e in fn(entries, term)]
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def to_hits(matches: list[tuple[Entry, int]]) -> list[Hit]:
|
|
413
|
+
return [Hit(e.kind, e.name, e.file, e.line, e.tags, e.args, e.doc, e.value, line) for e, line in matches]
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def query(root: Path, command: str, term: str, cache_dir: Path | None = None) -> list[Hit]:
|
|
417
|
+
"""Structured hits for one lookup; the shared entry point for the CLI and the desktop app."""
|
|
418
|
+
return to_hits(lookup(load_index(root, cache_dir or default_cache()), command, term))
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def run(argv: list[str], root: Path | None = None, cache_dir: Path | None = None) -> str:
|
|
422
|
+
p = argparse.ArgumentParser(prog="robot_mind", description=__doc__.split("\n")[0])
|
|
423
|
+
p.add_argument("--root", type=Path, default=root or Path.cwd())
|
|
424
|
+
p.add_argument("command", choices=["ticket", "kw", "callers", "tag", "find"])
|
|
425
|
+
p.add_argument("term")
|
|
426
|
+
p.add_argument("--limit", type=int, default=20)
|
|
427
|
+
p.add_argument("--json", action="store_true", help="print hits as a JSON array")
|
|
428
|
+
a = p.parse_args(argv)
|
|
429
|
+
hits = query(a.root, a.command, a.term, cache_dir=cache_dir)
|
|
430
|
+
if a.json:
|
|
431
|
+
return json.dumps([asdict(h) for h in hits[: a.limit]], ensure_ascii=False)
|
|
432
|
+
lines = [fmt_hit(h) for h in hits]
|
|
433
|
+
if not lines:
|
|
434
|
+
return "no match"
|
|
435
|
+
extra = len(lines) - a.limit
|
|
436
|
+
out = lines[: a.limit] + ([f"({extra} more, raise --limit)"] if extra > 0 else [])
|
|
437
|
+
return "\n".join(out)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
if __name__ == "__main__":
|
|
441
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
442
|
+
print(run(sys.argv[1:]))
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Starts Robot Framework Mind.
|
|
2
|
+
|
|
3
|
+
python -m robot_mind_app open the window
|
|
4
|
+
python -m robot_mind_app --theme dark start in a theme (system, light, dark) without saving it
|
|
5
|
+
python -m robot_mind_app --self-check REPORT build the window offscreen, write a report, exit 0 when sound
|
|
6
|
+
python -m robot_mind_app --screenshots DIR light and dark screenshots plus review.html, for a visual review
|
|
7
|
+
"""
|
|
8
|
+
import argparse
|
|
9
|
+
import html
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def parse(argv):
|
|
15
|
+
parser = argparse.ArgumentParser(prog="robot_mind_app", description=__doc__,
|
|
16
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
17
|
+
parser.add_argument("--theme", choices=("system", "light", "dark"))
|
|
18
|
+
parser.add_argument("--self-check", metavar="REPORT")
|
|
19
|
+
parser.add_argument("--screenshots", metavar="DIR")
|
|
20
|
+
return parser.parse_args(argv)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def self_check(report):
|
|
24
|
+
"""What a packaged bundle must prove without a display: Qt, SVG icons, the window in both themes, and a query."""
|
|
25
|
+
from PySide6.QtCore import QSettings
|
|
26
|
+
from . import __version__
|
|
27
|
+
from .window import MainWindow
|
|
28
|
+
lines, ok = [f"version: {__version__}"], True
|
|
29
|
+
try:
|
|
30
|
+
window = MainWindow(settings=QSettings(os.path.join(os.path.dirname(os.path.abspath(report)),
|
|
31
|
+
"self-check.ini"), QSettings.Format.IniFormat))
|
|
32
|
+
for mode in ("light", "dark"):
|
|
33
|
+
window.set_theme(mode)
|
|
34
|
+
lines.append(f"theme {mode}: ok")
|
|
35
|
+
lines.append(f"icon sizes: {sorted(s.width() for s in window.windowIcon().availableSizes())}")
|
|
36
|
+
# Exercise the query path so the bundle carries robot.api too, not just the window.
|
|
37
|
+
import tempfile
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
from robot_mind import query
|
|
40
|
+
with tempfile.TemporaryDirectory() as work:
|
|
41
|
+
repo = Path(work)
|
|
42
|
+
(repo / "smoke.robot").write_text("*** Test Cases ***\nSmoke\n Log x\n", encoding="utf-8")
|
|
43
|
+
hits = query(repo, "ticket", "Smoke", cache_dir=repo / "cache")
|
|
44
|
+
lines.append(f"query: {len(hits)} hit")
|
|
45
|
+
ok = ok and len(hits) == 1
|
|
46
|
+
except Exception as err: # the report says why; the exit code says that it failed
|
|
47
|
+
lines.append(f"error: {type(err).__name__}: {err}")
|
|
48
|
+
ok = False
|
|
49
|
+
with open(report, "w", encoding="utf-8") as out:
|
|
50
|
+
out.write("\n".join(lines) + "\n")
|
|
51
|
+
return 0 if ok else 1
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def screenshots(folder):
|
|
55
|
+
"""Grabs the window in light and dark into one HTML page, so a review sees both themes side by side."""
|
|
56
|
+
from PySide6.QtCore import QSettings
|
|
57
|
+
from .window import MainWindow
|
|
58
|
+
os.makedirs(folder, exist_ok=True)
|
|
59
|
+
window = MainWindow(settings=QSettings(os.path.join(folder, "screens.ini"), QSettings.Format.IniFormat))
|
|
60
|
+
window.show()
|
|
61
|
+
shots = []
|
|
62
|
+
for mode in ("light", "dark"):
|
|
63
|
+
window.set_theme(mode)
|
|
64
|
+
window.repaint()
|
|
65
|
+
name = f"{mode}.png"
|
|
66
|
+
window.grab().save(os.path.join(folder, name))
|
|
67
|
+
shots.append(f'<figure><img src="{name}" alt="{mode} theme"><figcaption>{mode}</figcaption></figure>')
|
|
68
|
+
page = os.path.join(folder, "review.html")
|
|
69
|
+
with open(page, "w", encoding="utf-8") as out:
|
|
70
|
+
out.write("<!doctype html><meta charset=utf-8><title>%s screens</title><style>body{font:14px sans-serif;"
|
|
71
|
+
"margin:16px}img{max-width:100%%;border:1px solid #ccc}</style>%s"
|
|
72
|
+
% (html.escape("Robot Framework Mind"), "".join(shots)))
|
|
73
|
+
return page
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def main(argv=None):
|
|
77
|
+
args = parse(sys.argv[1:] if argv is None else argv)
|
|
78
|
+
if args.self_check: # no display needed; --screenshots needs one, offscreen Qt has no fonts
|
|
79
|
+
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
|
80
|
+
try:
|
|
81
|
+
from PySide6.QtWidgets import QApplication
|
|
82
|
+
except ImportError:
|
|
83
|
+
print("PySide6 is missing: pip install -e .[gui]", file=sys.stderr)
|
|
84
|
+
return 2
|
|
85
|
+
app = QApplication.instance() or QApplication(sys.argv[:1])
|
|
86
|
+
app.setApplicationName("Robot Framework Mind")
|
|
87
|
+
if args.self_check:
|
|
88
|
+
return self_check(args.self_check)
|
|
89
|
+
if args.screenshots:
|
|
90
|
+
print(screenshots(args.screenshots))
|
|
91
|
+
return 0
|
|
92
|
+
from .window import MainWindow
|
|
93
|
+
from .worker import start, stop
|
|
94
|
+
window = MainWindow()
|
|
95
|
+
if args.theme:
|
|
96
|
+
window.set_theme(args.theme, save=False)
|
|
97
|
+
thread = start(window.worker)
|
|
98
|
+
window.show()
|
|
99
|
+
code = app.exec()
|
|
100
|
+
stop(thread)
|
|
101
|
+
return code
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
if __name__ == "__main__":
|
|
105
|
+
sys.exit(main())
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""The COMMUNITIES list beside the graph: tick to show or hide a repo's dots, click a name to highlight them."""
|
|
2
|
+
from PySide6.QtCore import Qt, Signal
|
|
3
|
+
from PySide6.QtWidgets import QCheckBox, QFrame, QHBoxLayout, QScrollArea, QVBoxLayout, QWidget
|
|
4
|
+
|
|
5
|
+
from robot_mind import strip_controls
|
|
6
|
+
|
|
7
|
+
from .widgets import ElidedLabel, plain_label
|
|
8
|
+
|
|
9
|
+
PANEL_W = 250
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Row(QWidget):
|
|
13
|
+
"""One community: tick box, colour dot, name and count; a click outside the box highlights it."""
|
|
14
|
+
|
|
15
|
+
clicked = Signal(int)
|
|
16
|
+
|
|
17
|
+
def __init__(self, group, name, size, color):
|
|
18
|
+
super().__init__()
|
|
19
|
+
self.group = group
|
|
20
|
+
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
|
21
|
+
self.setToolTip(f"{strip_controls(name)}: click to highlight, untick to hide")
|
|
22
|
+
line = QHBoxLayout(self)
|
|
23
|
+
line.setContentsMargins(0, 0, 0, 0)
|
|
24
|
+
self.box = QCheckBox()
|
|
25
|
+
self.box.setChecked(True)
|
|
26
|
+
dot = plain_label("", "dot")
|
|
27
|
+
dot.setFixedSize(10, 10)
|
|
28
|
+
dot.setStyleSheet(f"background: {color}; border-radius: 5px;")
|
|
29
|
+
self.name = ElidedLabel(strip_controls(name)) # ends in ... when long, never scrolls
|
|
30
|
+
line.addWidget(self.box)
|
|
31
|
+
line.addWidget(dot)
|
|
32
|
+
line.addWidget(self.name, 1)
|
|
33
|
+
line.addWidget(plain_label(str(size), "hint"))
|
|
34
|
+
|
|
35
|
+
def mousePressEvent(self, event):
|
|
36
|
+
self.clicked.emit(self.group)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class CommunityPanel(QFrame):
|
|
40
|
+
"""Emits shown(set of community numbers) on a tick change and highlighted(number, or -1 for none)."""
|
|
41
|
+
|
|
42
|
+
shown = Signal(object)
|
|
43
|
+
highlighted = Signal(int)
|
|
44
|
+
|
|
45
|
+
def __init__(self):
|
|
46
|
+
super().__init__()
|
|
47
|
+
self.setObjectName("communities")
|
|
48
|
+
self.setFixedWidth(PANEL_W)
|
|
49
|
+
self.rows: list[Row] = []
|
|
50
|
+
self.current = -1
|
|
51
|
+
col = QVBoxLayout(self)
|
|
52
|
+
col.setContentsMargins(12, 10, 8, 10)
|
|
53
|
+
col.setSpacing(6)
|
|
54
|
+
col.addWidget(plain_label("REPOS AND FOLDERS", "label"))
|
|
55
|
+
self.select_all = QCheckBox("Show all")
|
|
56
|
+
self.select_all.setChecked(True)
|
|
57
|
+
self.select_all.clicked.connect(self._select_all)
|
|
58
|
+
col.addWidget(self.select_all)
|
|
59
|
+
self.list = QVBoxLayout()
|
|
60
|
+
self.list.setSpacing(4)
|
|
61
|
+
holder = QWidget()
|
|
62
|
+
holder.setObjectName("community_rows")
|
|
63
|
+
holder.setLayout(self.list)
|
|
64
|
+
scroll = QScrollArea()
|
|
65
|
+
scroll.setObjectName("community_scroll")
|
|
66
|
+
scroll.setWidgetResizable(True)
|
|
67
|
+
scroll.setFrameShape(QFrame.Shape.NoFrame)
|
|
68
|
+
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
|
69
|
+
scroll.setWidget(holder)
|
|
70
|
+
col.addWidget(scroll, 1)
|
|
71
|
+
|
|
72
|
+
def fill(self, names, sizes, colors):
|
|
73
|
+
while self.list.count():
|
|
74
|
+
old = self.list.takeAt(0).widget() # None for the closing stretch
|
|
75
|
+
if old is not None:
|
|
76
|
+
old.setParent(None) # gone now, not at the next event loop turn
|
|
77
|
+
old.deleteLater()
|
|
78
|
+
self.rows, self.current = [], -1
|
|
79
|
+
for group, (name, size) in enumerate(zip(names, sizes)):
|
|
80
|
+
row = Row(group, name, size, colors[group])
|
|
81
|
+
row.box.toggled.connect(self._ticked)
|
|
82
|
+
row.clicked.connect(self.highlight)
|
|
83
|
+
self.list.addWidget(row)
|
|
84
|
+
self.rows.append(row)
|
|
85
|
+
self.list.addStretch(1)
|
|
86
|
+
self.select_all.setChecked(True)
|
|
87
|
+
|
|
88
|
+
def highlight(self, group):
|
|
89
|
+
"""Click a name to light its dots up; click it again to go back to all."""
|
|
90
|
+
self.current = -1 if group == self.current else group
|
|
91
|
+
for row in self.rows:
|
|
92
|
+
row.name.setObjectName("label" if row.group == self.current else "")
|
|
93
|
+
row.name.style().polish(row.name)
|
|
94
|
+
self.highlighted.emit(self.current)
|
|
95
|
+
|
|
96
|
+
def _select_all(self, checked):
|
|
97
|
+
for row in self.rows:
|
|
98
|
+
row.box.blockSignals(True)
|
|
99
|
+
row.box.setChecked(checked)
|
|
100
|
+
row.box.blockSignals(False)
|
|
101
|
+
self._ticked()
|
|
102
|
+
|
|
103
|
+
def _ticked(self):
|
|
104
|
+
visible = {row.group for row in self.rows if row.box.isChecked()}
|
|
105
|
+
self.select_all.setChecked(len(visible) == len(self.rows))
|
|
106
|
+
self.shown.emit(visible)
|