Spaces:
Sleeping
Sleeping
File size: 4,921 Bytes
71b4454 | 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | import asyncio
import os
import shutil
import subprocess
from typing import Any, Dict, List
class FileExplorerAPI:
"""Provides file system operations for browser workspace integration."""
def __init__(self, root_dir: str = "."):
self.root_dir = os.path.abspath(root_dir)
def _resolve(self, relative_path: str) -> str:
full_path = os.path.abspath(
os.path.join(self.root_dir, relative_path)
)
if not full_path.startswith(self.root_dir):
raise PermissionError("Access outside workspace boundary denied")
return full_path
def list_files(self, relative_path: str = "") -> List[Dict[str, Any]]:
target = self._resolve(relative_path)
if not os.path.exists(target):
return []
# Requested path is a file
if os.path.isfile(target):
rel = os.path.relpath(target, self.root_dir)
return [{
"name": os.path.basename(target),
"path": rel,
"is_directory": False,
"size": os.path.getsize(target),
}]
# Requested path is not a directory
if not os.path.isdir(target):
return []
entries: List[Dict[str, Any]] = []
for name in sorted(os.listdir(target)):
if name.startswith("."):
continue
if name in (
"__pycache__",
"node_modules",
"venv",
".venv",
):
continue
item_path = os.path.join(target, name)
entries.append({
"name": name,
"path": os.path.relpath(item_path, self.root_dir),
"is_directory": os.path.isdir(item_path),
"size": (
os.path.getsize(item_path)
if os.path.isfile(item_path)
else 0
),
})
return entries
def read_file(self, relative_path: str) -> str:
target = self._resolve(relative_path)
with open(target, "r", encoding="utf-8") as f:
return f.read()
def write_file(self, relative_path: str, content: str) -> bool:
target = self._resolve(relative_path)
os.makedirs(os.path.dirname(target), exist_ok=True)
with open(target, "w", encoding="utf-8") as f:
f.write(content)
return True
def delete_file(self, relative_path: str) -> bool:
target = self._resolve(relative_path)
if os.path.isfile(target):
os.remove(target)
return True
if os.path.isdir(target):
shutil.rmtree(target)
return True
return False
class TerminalAPI:
"""Executes asynchronous terminal operations."""
def __init__(self, root_dir: str = "."):
self.root_dir = os.path.abspath(root_dir)
async def run_command(self, command: str) -> Dict[str, Any]:
proc = await asyncio.create_subprocess_shell(
command,
cwd=self.root_dir,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await proc.communicate()
return {
"exit_code": proc.returncode,
"stdout": stdout.decode(errors="replace"),
"stderr": stderr.decode(errors="replace"),
}
class GitAPI:
"""Git wrapper."""
def __init__(self, root_dir: str = "."):
self.root_dir = os.path.abspath(root_dir)
def _git(self, *args) -> Dict[str, Any]:
res = subprocess.run(
["git", *args],
cwd=self.root_dir,
capture_output=True,
text=True,
)
return {
"exit_code": res.returncode,
"stdout": res.stdout.strip(),
"stderr": res.stderr.strip(),
}
def status(self):
return self._git("status", "--porcelain")
def commit(self, message: str):
self._git("add", "-A")
return self._git("commit", "-m", message)
def current_branch(self):
result = self._git("branch", "--show-current")
return result["stdout"] or "main"
class BrowserWorkspaceBackend:
"""Workspace backend."""
def __init__(self, root_dir: str = "."):
self.file_api = FileExplorerAPI(root_dir)
self.terminal_api = TerminalAPI(root_dir)
self.git_api = GitAPI(root_dir)
def get_build_status(self):
return {
"status": "ready",
"target": "production",
}
def get_preview_url(self, port: int = 3000):
return f"http://localhost:{port}/preview"
def deploy(self, environment: str = "staging"):
return {
"deployment_id": "dep_12345",
"environment": environment,
"status": "deployed",
}
|