Skip to content

Commit

Permalink
refactoring templater
Browse files Browse the repository at this point in the history
  • Loading branch information
speier committed Dec 16, 2024
1 parent 0089244 commit 093739d
Show file tree
Hide file tree
Showing 10 changed files with 318 additions and 95 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VERSION=v0.2.6
VERSION=v0.3.0

tag:
@git tag -a ${VERSION} -m "version ${VERSION}" && git push origin ${VERSION}
50 changes: 50 additions & 0 deletions cmd/kube.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package cmd

import (
"fmt"

"github.com/spf13/cobra"

"github.com/moonwalker/comet/internal/exec"
"github.com/moonwalker/comet/internal/log"
"github.com/moonwalker/comet/internal/parser"
)

var (
kubeCmd = &cobra.Command{
Use: "kube [stack]",
Short: "Kubeconfig for stack",
Aliases: []string{"kubeconfig"},
RunE: kube,
Args: cobra.ExactArgs(1),
}
)

func init() {
rootCmd.AddCommand(kubeCmd)
}

func kube(cmd *cobra.Command, args []string) error {
executor, err := exec.GetExecutor(config)
if err != nil {
log.Fatal(err)
}

stacks, err := parser.LoadStacks(config.StacksDir)
if err != nil {
return err
}

stack, err := stacks.GetStack(args[0])
if stack == nil {
return err
}

kubeconfig, err := stack.Kubeconfig.Render(config, stacks, executor, stack.Name)
if err != nil {
return err
}

fmt.Println(kubeconfig)
return nil
}
2 changes: 1 addition & 1 deletion cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func run(args []string, reverse bool, cb func(*schema.Component, schema.Executor
}

for _, component := range components {
err := component.EnsurePath(config)
err := component.EnsurePath(config, true)
if err != nil {
log.Fatal(err)
}
Expand Down
8 changes: 8 additions & 0 deletions internal/parser/js/js.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func (vm *jsinterpreter) Parse(path string) (*schema.Stack, error) {
vm.rt.Set("backend", vm.registerBackend(stack))
vm.rt.Set("component", vm.registerComponent(stack))
vm.rt.Set("append", vm.registerAppend(stack))
vm.rt.Set("kubeconfig", vm.registerKubeconfig(stack))

src := result.OutputFiles[0].Contents
_, err := vm.rt.RunString(string(src))
Expand Down Expand Up @@ -147,6 +148,13 @@ func (vm *jsinterpreter) registerAppend(stack *schema.Stack) func(string, []stri
}
}

func (vm *jsinterpreter) registerKubeconfig(stack *schema.Stack) func(*schema.Kubeconfig) {
return func(kubeconfig *schema.Kubeconfig) {
log.Debug("register kubeconfig", "stack", stack.Name)
stack.Kubeconfig = kubeconfig
}
}

func (vm *jsinterpreter) getProxy(get func(property string) any) goja.Proxy {
obj := vm.rt.NewObject()
return vm.rt.NewProxy(obj, &goja.ProxyTrapConfig{
Expand Down
66 changes: 12 additions & 54 deletions internal/schema/component.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ package schema
import (
"fmt"
"path"
"path/filepath"

"dario.cat/mergo"
cp "github.com/otiai10/copy"
)

Expand All @@ -22,16 +20,17 @@ type (
)

// copy component to workdir if needed
func (c *Component) EnsurePath(config *Config) error {
func (c *Component) EnsurePath(config *Config, copy bool) error {
if len(config.WorkDir) > 0 {
dest := path.Join(config.WorkDir, c.Stack, c.Name)
err := cp.Copy(c.Path, dest)
if err != nil {
return err
if copy {
err := cp.Copy(c.Path, dest)
if err != nil {
return err
}
}
c.Path = dest
}

return nil
}

Expand All @@ -42,73 +41,32 @@ func (c *Component) PropertyRef(property string) string {

// resolve templates in component
func (c *Component) ResolveVars(config *Config, stacks *Stacks, executor Executor) error {
stack, err := stacks.GetStack(c.Stack)
if err != nil {
return err
}

stacksDirAbs, err := filepath.Abs(config.StacksDir)
if err != nil {
return err
}

tdata := map[string]interface{}{
"stacks_dir": stacksDirAbs,
"stack": stack.Name,
"component": c.Name,
"component": c.Name,
}
err = mergo.Merge(&tdata, stack.Options)

t, err := NewTemplater(config, stacks, executor, c.Stack)
if err != nil {
return err
}

funcMap := map[string]interface{}{
"state": stateFunc(stacks, executor),
}

// template backend
c.Backend.Config, err = tpl(c.Backend.Config, tdata, funcMap)
c.Backend.Config, err = t.Map(c.Backend.Config, tdata)
if err != nil {
return err
}

// template vars
c.Inputs, err = tpl(c.Inputs, tdata, funcMap)
c.Inputs, err = t.Map(c.Inputs, tdata)
if err != nil {
return err
}

// template providers
c.Providers, err = tpl(c.Providers, tdata, funcMap)
c.Providers, err = t.Map(c.Providers, tdata)
if err != nil {
return err
}

return nil
}

func stateFunc(stacks *Stacks, executor Executor) func(stack, component string) any {
return func(stack, component string) any {
refStack, err := stacks.GetStack(stack)
if err != nil {
return nil
}

refComponent, err := refStack.GetComponent(component)
if err != nil {
return nil
}

refState, err := executor.Output(refComponent)
if err != nil {
return nil
}

res := map[string]string{}
for k, v := range refState {
res[k] = v.String()
}

return res
}
}
97 changes: 97 additions & 0 deletions internal/schema/kubeconfig.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package schema

import (
"bytes"
"text/template"
)

type (
Kubeconfig struct {
Current int `json:"current"`
Clusters []*KubeconfgCluster `json:"clusters"`
}

KubeconfgCluster struct {
Context string `json:"context"`
Host string `json:"host"`
Cert string `json:"cert"`
ExecApiVersion string `json:"exec_apiversion"`
ExecCommand string `json:"exec_command"`
ExecArgs []string `json:"exec_args"`
}
)

const (
KubeconfigDefaultApiVersion = "client.authentication.k8s.io/v1beta1"
)

func (k *Kubeconfig) Render(config *Config, stacks *Stacks, executor Executor, stackName string) (string, error) {
if len(k.Clusters) == 0 {
return "", nil
}

if k.Current < 0 || k.Current >= len(k.Clusters) {
k.Current = 0
}

for _, c := range k.Clusters {
if len(c.ExecApiVersion) == 0 {
c.ExecApiVersion = KubeconfigDefaultApiVersion
}
}

t, err := NewTemplater(config, stacks, executor, stackName)
if err != nil {
return "", err
}

err = t.Any(k, nil)
if err != nil {
return "", err
}

tmpl, err := template.New("k").Parse(kubeconfigTemplate)
if err != nil {
return "", err
}

var b bytes.Buffer
err = tmpl.Execute(&b, k)
if err != nil {
return "", err
}

return b.String(), nil
}

const kubeconfigTemplate = `apiVersion: v1
kind: Config
current-context: {{ (index .Clusters .Current).Context }}
contexts:
{{- range .Clusters }}
- name: {{ .Context }}
context:
cluster: {{ .Context }}
user: {{ .Context }}
{{- end }}
clusters:
{{- range .Clusters }}
- name: {{ .Context }}
cluster:
server: {{ .Host }}
certificate-authority-data: {{ .Cert }}
{{- end }}
users:
{{- range .Clusters }}
- name: {{ .Context }}
user:
exec:
apiVersion: {{ .ExecApiVersion }}
command: {{ .ExecCommand }}
{{- if .ExecArgs }}
args:
{{- range .ExecArgs }}
- {{ . }}
{{- end }}
{{- end }}
{{- end }}`
1 change: 1 addition & 0 deletions internal/schema/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ type (
Backend Backend `json:"backend"`
Appends map[string][]string `json:"appends"`
Components []*Component `json:"components"`
Kubeconfig *Kubeconfig `json:"kubeconfig"`
}

Stacks struct {
Expand Down
Loading

0 comments on commit 093739d

Please sign in to comment.