Spaces:
Sleeping
Sleeping
Download tools/shell.py from Ahmad170412/dash: direct link, hf CLI and curl.
- Browser
- Download file 2.6 kB
-
https://huggingface.co/spaces/Ahmad170412/dash/resolve/main/tools/shell.py
- Command line
-
hf download hf://spaces/Ahmad170412/dash/tools/shell.py
-
curl -L -o shell.py https://huggingface.co/spaces/Ahmad170412/dash/resolve/main/tools/shell.py
2.6 kB
| import os | |
| import subprocess | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| def run_command(cmd, timeout=30, cwd=None): | |
| try: | |
| result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout, cwd=cwd) | |
| output = result.stdout | |
| if result.stderr: | |
| output += "\n[STDERR] " + result.stderr | |
| return {"success": result.returncode == 0, "output": output.strip(), "exit_code": result.returncode} | |
| except subprocess.TimeoutExpired: | |
| return {"success": False, "output": "Command timed out", "exit_code": -1} | |
| except Exception as e: | |
| return {"success": False, "output": str(e), "exit_code": -1} | |
| def create_file(filepath, content): | |
| try: | |
| abs_path = os.path.abspath(filepath) | |
| os.makedirs(os.path.dirname(abs_path), exist_ok=True) | |
| with open(abs_path, 'w') as f: | |
| f.write(content) | |
| _git_push(abs_path, filepath) | |
| return {"success": True, "output": f"Created: {filepath}"} | |
| except Exception as e: | |
| return {"success": False, "output": str(e)} | |
| def read_file(filepath): | |
| try: | |
| with open(filepath, 'r') as f: | |
| content = f.read() | |
| return {"success": True, "output": content} | |
| except Exception as e: | |
| return {"success": False, "output": str(e)} | |
| def list_directory(path="."): | |
| try: | |
| items = os.listdir(path) | |
| return {"success": True, "output": "\n".join(items) if items else "(empty)"} | |
| except Exception as e: | |
| return {"success": False, "output": str(e)} | |
| def _git_push(abs_path, rel_path): | |
| """Push file to HF Space repo for persistence.""" | |
| try: | |
| space_dir = os.environ.get("SPACE_DIR", "/home/user/app") | |
| if not os.path.exists(os.path.join(space_dir, ".git")): | |
| return | |
| rel_in_space = os.path.relpath(abs_path, space_dir) | |
| subprocess.run(["git", "add", rel_in_space], cwd=space_dir, capture_output=True, timeout=10) | |
| result = subprocess.run( | |
| ["git", "commit", "-m", f"agent: update {rel_in_space}"], | |
| cwd=space_dir, capture_output=True, text=True, timeout=10 | |
| ) | |
| if result.returncode == 0: | |
| token = os.environ.get("HF_TOKEN", "") | |
| remote = f"https://oauth2:{token}@huggingface.co/spaces/{os.environ.get('SPACE_REPO', 'Ahmad170412/dash')}" | |
| subprocess.run(["git", "push", remote, "main"], cwd=space_dir, capture_output=True, timeout=30) | |
| logger.info(f"Pushed {rel_in_space} to HF Hub") | |
| except Exception as e: | |
| logger.warning(f"Git push failed: {e}") | |