106 lines
2.2 KiB
Go
106 lines
2.2 KiB
Go
package routers
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
"github.com/google/go-github/v39/github"
|
|
log "github.com/sirupsen/logrus"
|
|
"github.com/unrolled/render"
|
|
|
|
"gitea.com/gitea/pr-deployer/pkgs/services"
|
|
"gitea.com/gitea/pr-deployer/pkgs/settings"
|
|
)
|
|
|
|
var rnd *render.Render
|
|
|
|
func Web() {
|
|
rnd = render.New()
|
|
|
|
c := chi.NewRouter()
|
|
c.Use(middleware.Logger)
|
|
c.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Write([]byte("You are not login"))
|
|
})
|
|
c.Get("/prs", ListPRs)
|
|
c.Post("/pr/{index}/run", RunPR)
|
|
c.Post("/pr/{index}/stop", StopPR)
|
|
c.Post("/webhook", Webhook)
|
|
http.ListenAndServe(":3001", c)
|
|
}
|
|
|
|
func ListPRs(w http.ResponseWriter, r *http.Request) {
|
|
p, _ := strconv.Atoi(r.FormValue("p"))
|
|
if p < 1 {
|
|
p = 1
|
|
}
|
|
c := github.NewClient(http.DefaultClient)
|
|
pulls, _, err := c.PullRequests.List(context.Background(), "go-gitea", "gitea", &github.PullRequestListOptions{
|
|
Sort: "updated",
|
|
Direction: "desc",
|
|
ListOptions: github.ListOptions{
|
|
Page: p,
|
|
PerPage: 100,
|
|
},
|
|
})
|
|
if err != nil {
|
|
log.Error(err)
|
|
return
|
|
}
|
|
|
|
if err := rnd.HTML(w, http.StatusOK, "pulls", map[string]interface{}{
|
|
"pulls": pulls,
|
|
}); err != nil {
|
|
log.Error(err)
|
|
}
|
|
}
|
|
|
|
func RunPR(w http.ResponseWriter, r *http.Request) {
|
|
idx := chi.URLParam(r, "index")
|
|
i, _ := strconv.Atoi(idx)
|
|
if i <= 0 {
|
|
log.Error("start failed")
|
|
return
|
|
}
|
|
if err := services.UpdateAndStartPullRequest(i); err != nil {
|
|
log.Error("start failed")
|
|
}
|
|
}
|
|
|
|
func StopPR(w http.ResponseWriter, r *http.Request) {
|
|
idx := chi.URLParam(r, "index")
|
|
i, _ := strconv.Atoi(idx)
|
|
if i <= 0 {
|
|
log.Error("stop failed")
|
|
return
|
|
}
|
|
if err := services.StopPullRequest(i); err != nil {
|
|
log.Error("stop failed")
|
|
}
|
|
}
|
|
|
|
func Webhook(w http.ResponseWriter, r *http.Request) {
|
|
payload, err := github.ValidatePayload(r, settings.WebhookSecretKey)
|
|
if err != nil {
|
|
log.Error(err)
|
|
return
|
|
}
|
|
event, err := github.ParseWebHook(github.WebHookType(r), payload)
|
|
if err != nil {
|
|
log.Error(err)
|
|
return
|
|
}
|
|
|
|
switch evt := event.(type) {
|
|
case *github.PullRequestEvent:
|
|
if err := services.UpdateAndStartPullRequest(*evt.Number); err != nil {
|
|
log.Error(err)
|
|
}
|
|
default:
|
|
log.Warn("received %v type event, ignored", event)
|
|
}
|
|
}
|