import os import subprocess import shutil def clone_repo(token, repo_url, target_dir): """安全克隆私有仓库""" try: # 构造认证 URL auth_url = repo_url.replace("https://", f"https://x-access-token:{token}@") # 克隆仓库 subprocess.run(["git", "clone", auth_url, target_dir], check=True) # 清理 .git 目录 shutil.rmtree(os.path.join(target_dir, ".git")) print(f"仓库成功克隆到: {target_dir}") except Exception as e: print(f"克隆失败: {e}") raise if __name__ == "__main__": # 从环境变量获取 GitHub Token 和仓库 URL token = os.getenv("GITHUB_TOKEN") repo_url = "https://github.com/luoh-an/luoh-api.git" target_dir = "/app/luoh-api" if not token: raise ValueError("未提供 GITHUB_TOKEN 环境变量") # 克隆仓库 clone_repo(token, repo_url, target_dir) # 切换到项目目录 os.chdir(target_dir) # 安装依赖 subprocess.run(["pip", "install", "--no-cache-dir", "-r", "requirements.txt"], check=True) # 将用户二进制目录添加到 PATH os.environ["PATH"] = f"/home/appuser/.local/bin:{os.environ['PATH']}" # 启动 FastAPI 服务 subprocess.run(["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"])