Files
devstar/modules/k8s/controller/devcontainer/utils/template_utils.go

94 lines
2.3 KiB
Go
Raw Normal View History

package utils
import (
"bytes"
"fmt"
"os"
"path/filepath"
"runtime"
"text/template"
devcontainer_apps_v1 "code.gitea.io/gitea/modules/k8s/api/v1"
app_v1 "k8s.io/api/apps/v1"
core_v1 "k8s.io/api/core/v1"
yaml_util "k8s.io/apimachinery/pkg/util/yaml"
)
// const (
// TemplatePath = "modules/k8s/controller/devcontainer/templates/"
// )
// parseTemplate 解析 Go Template 模板文件
func parseTemplate(templateName string, app *devcontainer_apps_v1.DevcontainerApp) []byte {
// 获取当前代码文件的绝对路径
_, filename, _, ok := runtime.Caller(0)
if !ok {
panic("无法获取当前文件路径")
}
// 通过当前代码文件的位置计算模板文件的位置
// utils 目录
utilsDir := filepath.Dir(filename)
// controller/devcontainer 目录
controllerDir := filepath.Dir(utilsDir)
// templates 目录
templatesDir := filepath.Join(controllerDir, "templates")
// 完整模板文件路径
templatePath := filepath.Join(templatesDir, templateName+".yaml")
// 打印调试信息
fmt.Printf("当前代码文件: %s\n", filename)
fmt.Printf("模板目录: %s\n", templatesDir)
fmt.Printf("使用模板文件: %s\n", templatePath)
// 检查模板文件是否存在
if _, err := os.Stat(templatePath); os.IsNotExist(err) {
panic(fmt.Errorf("模板文件不存在: %s", templatePath))
}
// 解析模板
tmpl, err := template.
New(filepath.Base(templatePath)).
Funcs(template.FuncMap{"default": DefaultFunc}).
ParseFiles(templatePath)
if err != nil {
panic(err)
}
b := new(bytes.Buffer)
err = tmpl.Execute(b, app)
if err != nil {
panic(err)
}
return b.Bytes()
}
// NewStatefulSet 创建 StatefulSet
func NewStatefulSet(app *devcontainer_apps_v1.DevcontainerApp) *app_v1.StatefulSet {
statefulSet := &app_v1.StatefulSet{}
err := yaml_util.Unmarshal(parseTemplate("statefulset", app), statefulSet)
if err != nil {
panic(err)
}
return statefulSet
}
// NewService 创建 Service
func NewService(app *devcontainer_apps_v1.DevcontainerApp) *core_v1.Service {
service := &core_v1.Service{}
err := yaml_util.Unmarshal(parseTemplate("service", app), service)
if err != nil {
panic(err)
}
return service
}
// DefaultFunc 函数用于实现默认值
func DefaultFunc(value interface{}, defaultValue interface{}) interface{} {
if value == nil || value == "" {
return defaultValue
}
return value
}