about summary refs log tree commit diff
path: root/frontend/frontend.go
blob: 9c866aafe4dac2343dc930e1da06ad43564d83d2 (plain) (blame)
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
package frontend

import (
	"io/ioutil"
	"net/http"

	"html/template"

	"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
	"github.com/tweag/gerrit-queue/submitqueue"
)

//TODO: log last update

//loadTemplate loads a single template from statikFS and returns a template object
func loadTemplate(templateName string, funcMap template.FuncMap) (*template.Template, error) {
	tmpl := template.New(templateName).Funcs(funcMap)
	statikFS, err := fs.New()
	if err != nil {
		return nil, err
	}
	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
	}
	return tmpl.Parse(string(contents))
}

// MakeFrontend configures the router and returns a new Frontend struct
func MakeFrontend(runner *submitqueue.Runner) http.Handler {
	router := gin.Default()

	router.GET("/submit-queue.json", func(c *gin.Context) {
		submitQueue, _, _ := runner.GetState()
		c.JSON(http.StatusOK, submitQueue)
	})

	router.GET("/", func(c *gin.Context) {
		submitQueue, _, _ := 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)
			},
		}

		tmpl := template.Must(loadTemplate("submit-queue.tmpl.html", funcMap))

		tmpl.ExecuteTemplate(c.Writer, "submit-queue.tmpl.html", gin.H{
			"series":      submitQueue.Series,
			"projectName": submitQueue.ProjectName,
			"branchName":  submitQueue.BranchName,
			"HEAD":        submitQueue.HEAD,
		})
	})
	return router
}