package got import ( "fmt" "strings" "text/template" . "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common" "git.eugeniocarvalho.dev/eugeniucarvalho/utils" G "github.com/dave/jennifer/jen" ) func CreateMetricFiles(project *Project) (err error) { if !project.HasMetrics { return } if err = createMetricIndex(project); err != nil { return } if err = createMetricHandler(project); err != nil { return } return nil } func createMetricIndex(project *Project) (err error) { var ( Index = G.NewFile("metrics") metricsTmpl *template.Template out string ) metricsTmpl, err = ParseTemplate(` import ( "github.com/eugeniucarvalho/metric-query-parser/parser" ) func InitMetrics() { {{range .metrics}} // {{.description}} parser.RegisterHandler("{{.id}}", {{.functionId}} ) {{end}} } `) metrics := []map[string]interface{}{} for id, metric := range project.Metrics { metrics = append(metrics, map[string]interface{}{ "id": id, "functionId": strings.Title(id), "description": metric.Description, }) } context:= map[string]interface{}{ "metrics": metrics, } if out, err = TemplateToString(metricsTmpl, context); err != nil { return } Index.Id(out) err = Write(project.Paths.Include("/go/metrics/index_gen.go"), Index) return } func createMetricHandler(project *Project) (err error) { var ( metricsTmpl *template.Template out string ) metricsTmpl, err = ParseTemplate(` {{if .metric.Return.Props}} type {{.functionId}}Result struct { {{range $id, $prop := .metric.Return.Props}} {{$prop.ID}} {{$prop.Type}} {{end}} } {{end}} // {{.metric.Description}} func {{.functionId}}(props map[string]interface{}) (result interface{}, err error) { // TO DO.... return {{.return}}, nil } `) for id, metric := range project.Metrics { path := project.Paths.Include("/go/metrics/%s_gen.go", id) if utils.FileExists(path) { continue } functionId := strings.Title(id) returnValue := `""` if metric.Return.Props != nil { returnValue = fmt.Sprintf("%sResult{}", functionId) for propId, prop := range metric.Return.Props { prop.ID = strings.Title(propId) } } if metric.Return.Range { returnValue = fmt.Sprintf("[]%s", returnValue) } context:= map[string]interface{}{ "id": id, "functionId": functionId, "metric": metric, "return": returnValue, } if out, err = TemplateToString(metricsTmpl, context); err != nil { return } Index := G.NewFile("metrics") Index.Id(out) err = Write(path, Index) } return }