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
|
from pathlib import Path
from typing import Optional
import subprocess
def _path_checked(path: Path, cwd=Path.cwd()) -> Optional[Path]:
"""Resolves `path`, returning `None` if it's not a subdirectory of `cwd`."""
path = (path if path.is_absolute() else (cwd / path)).resolve()
cwd = cwd.resolve()
return path if path.is_relative_to(cwd) else None
def _path_helper(path_str: str, callback, cwd=Path.cwd()):
path = _path_checked(Path(path_str), cwd=cwd)
if path is None:
return {"status": "error", "reason": f"Permission denied: {path_str}"}
else:
try:
return {"status": "success", **callback(path)}
except Exception as e:
return {"status": "error", "reason": f"Failure: {e}"}
def ls(args, workdir=Path.cwd()):
'{"action": "ls", "path": PATH} - list files at PATH'
def inner(path: Path):
return {"content": list(map(lambda s: str(s), path.iterdir()))}
match args:
case {"action": "ls", "path": path_str}:
return _path_helper(path_str, inner, cwd=workdir)
def read(args, workdir=Path.cwd()):
'{"action": "read", "path": PATH} - read file at PATH'
def inner(path: Path):
contents = path.read_text(encoding="utf-8")
return {"content": contents}
match args:
case {"action": "read", "path": path_str}:
return _path_helper(path_str, inner, cwd=workdir)
def write(args, workdir=Path.cwd()):
'{"action": "write", "path": PATH, "content": CONTENT} - write CONTENT into file at PATH'
def inner(path: Path, text: str):
n_bytes = path.write_text(text)
return {"bytes": n_bytes}
match args:
case {"action": "write", "path": path_str, "content": content}:
return _path_helper(path_str, lambda path: inner(path, content), cwd=workdir)
def tldr(args, workdir=Path.cwd()):
'{"action": "tldr", "program": PROGRAM} - read tldr docs for PROGRAM'
match args:
case {"action": "tldr", "program": program_str}:
try:
result = subprocess.run(
["tldr", program_str],
capture_output=True,
text=True,
check=True
)
return {"status": "success", "content": result.stdout}
except subprocess.CalledProcessError:
return {"status": "error", "reason": f"Tldr for '{program_str}' not found."}
except Exception as e:
return {"status": "error", "reason": f"An unexpected error occurred: {e}"}
|