-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
94 lines (74 loc) · 2.47 KB
/
main.py
File metadata and controls
94 lines (74 loc) · 2.47 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
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
import uvicorn
import json
import os
from typing import List
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
class RepositoryConfig(BaseModel):
path: str
branch: str
commands: List[str]
class Config(BaseModel):
repositories: dict[str, RepositoryConfig]
app = FastAPI(
title="AutoDeploy API",
description="API for AutoDeploy",
version="1.0.0"
)
app.add_middleware(
CORSMiddleware,
allow_origins = ["*"],
allow_credentials = True,
allow_methods = ["*"],
allow_headers = ["*"],
)
@app.get("/health")
async def health_check():
return {"online": True}
@app.post("/deploy")
async def deploy(request: Request):
try:
event_type = request.headers.get("X-GitHub-Event")
if not event_type:
raise HTTPException(status_code=400, detail="Missing X-GitHub-Event header")
if event_type == "ping":
return {"status": "ok", "message": "Ping received"}
if event_type == "push":
payload = await request.json()
repo_name = payload.get("repository", {}).get("full_name", "")
ref = payload.get("ref", "").replace("refs/heads/", "")
if not repo_name:
raise HTTPException(status_code=400, detail="Repository name not found in payload")
try:
with open("config.json", "r") as f:
config_data = json.load(f)
config = Config(**config_data)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error reading config: {str(e)}")
repo_config = config.repositories.get(repo_name)
if not repo_config:
return {"status": "ignored", "message": f"Repository {repo_name} not configured"}
if ref != repo_config.branch:
return {"status": "ignored", "message": f"Push to branch {ref} ignored, configured for {repo_config.branch}"}
try:
os.chdir(repo_config.path)
os.system("git pull")
print(f"Pulled from repository: {repo_name}")
for command in repo_config.commands:
if command.strip():
os.system(command)
print(f"Executed command: {command}")
return {
"status": "success",
"repository": repo_name,
"branch": ref,
"message": "Deployment completed successfully"
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Deployment failed: {str(e)}")
return {"status": "ignored", "message": f"Unsupported event type: {event_type}"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)