tvl-depot/frontend/frontend.go

94 lines
2.2 KiB
Go
Raw Normal View History

2019-11-18 15:40:46 +01:00
package frontend
import (
"fmt"
"io/ioutil"
2019-11-18 15:40:46 +01:00
"net/http"
"html/template"
2019-11-18 15:40:46 +01:00
"github.com/gin-gonic/gin"
"github.com/rakyll/statik/fs"
"github.com/tweag/gerrit-queue/gerrit"
_ "github.com/tweag/gerrit-queue/statik" // register static assets
2019-11-18 15:40:46 +01:00
"github.com/tweag/gerrit-queue/submitqueue"
)
2019-11-25 17:43:56 +01:00
//TODO: log last update
//loadTemplate loads a list of templates, relative to the statikFS root, and a FuncMap, and returns a template object
func loadTemplate(templateNames []string, funcMap template.FuncMap) (*template.Template, error) {
if len(templateNames) == 0 {
return nil, fmt.Errorf("templateNames can't be empty")
}
tmpl := template.New(templateNames[0]).Funcs(funcMap)
statikFS, err := fs.New()
if err != nil {
return nil, err
}
for _, templateName := range templateNames {
r, err := statikFS.Open("/" + templateName)
if err != nil {
return nil, err
}
defer r.Close()
contents, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
tmpl, err = tmpl.Parse(string(contents))
if err != nil {
return nil, err
}
}
return tmpl, nil
}
2019-11-18 15:40:46 +01:00
// MakeFrontend configures the router and returns a new Frontend struct
func MakeFrontend(runner *submitqueue.Runner) http.Handler {
router := gin.Default()
2019-11-18 15:40:46 +01:00
router.GET("/submit-queue.json", func(c *gin.Context) {
submitQueue, _, _ := runner.GetState()
2019-11-18 15:40:46 +01:00
c.JSON(http.StatusOK, submitQueue)
})
router.GET("/", func(c *gin.Context) {
submitQueue, currentlyRunning, results := runner.GetState()
funcMap := template.FuncMap{
"isAutoSubmittable": func(serie *submitqueue.Serie) bool {
return submitQueue.IsAutoSubmittable(serie)
},
"changesetURL": func(changeset *gerrit.Changeset) string {
return submitQueue.GetChangesetURL(changeset)
},
}
2019-11-27 11:38:54 +01:00
tmpl := template.Must(loadTemplate([]string{
"submit-queue.tmpl.html",
2019-11-27 11:41:45 +01:00
"series.tmpl.html",
2019-11-27 11:38:54 +01:00
"serie.tmpl.html",
"changeset.tmpl.html",
}, funcMap))
tmpl.ExecuteTemplate(c.Writer, "submit-queue.tmpl.html", gin.H{
// Config
2019-11-18 15:40:46 +01:00
"projectName": submitQueue.ProjectName,
"branchName": submitQueue.BranchName,
// State
"currentlyRunning": currentlyRunning,
"series": submitQueue.Series,
"HEAD": submitQueue.HEAD,
// History
"results": results,
2019-11-18 15:40:46 +01:00
})
})
return router
2019-11-18 15:40:46 +01:00
}