123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- 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
- }
|