-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtool.py
More file actions
62 lines (47 loc) · 2.06 KB
/
Copy pathtool.py
File metadata and controls
62 lines (47 loc) · 2.06 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
import pathlib
import subprocess
from typing import Tuple
from langchain_core.tools import tool
PROJECT_ROOT = pathlib.Path.cwd() / "generated_project"
def safe_path_for_project(path: str) -> pathlib.Path:
p = (PROJECT_ROOT / path).resolve()
if PROJECT_ROOT.resolve() not in p.parents and PROJECT_ROOT.resolve() != p.parent and PROJECT_ROOT.resolve() != p:
raise ValueError("Attempt to write outside project root")
return p
@tool
def write_file(path: str, content: str) -> str:
"""Writes content to a file at the specified path within the project root."""
p = safe_path_for_project(path)
p.parent.mkdir(parents=True, exist_ok=True)
with open(p, "w", encoding="utf-8") as f:
f.write(content)
return f"WROTE:{p}"
@tool
def read_file(path: str) -> str:
"""Reads content from a file at the specified path within the project root."""
p = safe_path_for_project(path)
if not p.exists():
return ""
with open(p, "r", encoding="utf-8") as f:
return f.read()
@tool
def get_current_directory() -> str:
"""Returns the current working directory."""
return str(PROJECT_ROOT)
@tool
def list_files(directory: str = ".") -> str:
"""Lists all files in the specified directory within the project root."""
p = safe_path_for_project(directory)
if not p.is_dir():
return f"ERROR: {p} is not a directory"
files = [str(f.relative_to(PROJECT_ROOT)) for f in p.glob("**/*") if f.is_file()]
return "\n".join(files) if files else "No files found."
@tool
def run_cmd(cmd: str, cwd: str = None, timeout: int = 30) -> Tuple[int, str, str]:
"""Runs a shell command in the specified directory and returns the result."""
cwd_dir = safe_path_for_project(cwd) if cwd else PROJECT_ROOT
res = subprocess.run(cmd, shell=True, cwd=str(cwd_dir), capture_output=True, text=True, timeout=timeout)
return res.returncode, res.stdout, res.stderr
def init_project_root():
PROJECT_ROOT.mkdir(parents=True, exist_ok=True)
return str(PROJECT_ROOT)