forked from viliproject/vili
-
Notifications
You must be signed in to change notification settings - Fork 0
/
environments.go
93 lines (81 loc) · 2.11 KB
/
environments.go
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
package api
import (
"encoding/json"
"net/http"
"github.com/airware/vili/environments"
"github.com/airware/vili/git"
"github.com/airware/vili/templates"
"gopkg.in/labstack/echo.v1"
)
// EnvironmentCreateRequest is a request to create a new environment
type EnvironmentCreateRequest struct {
Name string `json:"name"`
Branch string `json:"branch"`
Spec string `json:"spec"`
}
func environmentCreateHandler(c *echo.Context) error {
envCreateRequest := &EnvironmentCreateRequest{}
decoder := json.NewDecoder(c.Request().Body)
err := decoder.Decode(envCreateRequest)
if err != nil {
return err
}
if envCreateRequest.Name == "" || envCreateRequest.Branch == "" || envCreateRequest.Spec == "" {
return c.JSON(http.StatusBadRequest, "Must provide a non-empty name, branch, and spec")
}
resources, err := environments.Create(envCreateRequest.Name, envCreateRequest.Branch, envCreateRequest.Spec)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusCreated, resources)
}
func environmentDeleteHandler(c *echo.Context) error {
env := c.Param("env")
if err := environments.Delete(env); err != nil {
return err
}
return c.NoContent(http.StatusNoContent)
}
func environmentBranchesHandler(c *echo.Context) error {
branches, err := git.Branches()
if err != nil {
return err
}
return c.JSON(http.StatusOK, map[string][]string{
"branches": branches,
})
}
func environmentSpecHandler(c *echo.Context) error {
namespace := c.Query("name")
branch := c.Query("branch")
fields := environmentTemplateFields{
Namespace: namespace,
Branch: branch,
}
templ, err := templates.Environment(branch)
if err != nil {
templ = defaultTemplate
}
templ, err = templ.Populate(fields)
if err != nil {
return err
}
return c.JSON(http.StatusOK, map[string]string{
"spec": string(templ),
})
}
type environmentTemplateFields struct {
Namespace string
Branch string
}
const defaultTemplate templates.Template = `---
apiVersion: v1
kind: Namespace
metadata:
name: {{.Namespace}}
annotations:
vili.environment-branch: {{.Branch}}
spec:
finalizers:
- kubernetes
`