codegen: Introduce TS codegen veneer (#54816)

* Split all named types out into defs, etc.

* Use latest cuetsy, refactor generators accordingly

* Return AST type from plugin TS generator

* Near-complete checkin of TS veneer code generator

* First full completed pass

* Improve the attribute name

* Defer use of the dashboard veneer type to follow-up

* Remove dummy index, prettier on veneer

* Fix merge errors in gen.go

* Add match field to SpecialValueMap

* Fix backend lint errors
This commit is contained in:
sam boyer
2022-09-26 11:26:18 -04:00
committed by GitHub
parent f8240e4b0a
commit e2ff875976
26 changed files with 1920 additions and 517 deletions
+41 -52
View File
@@ -17,14 +17,15 @@ import (
"github.com/deepmap/oapi-codegen/pkg/codegen"
"github.com/getkin/kin-openapi/openapi3"
"github.com/grafana/cuetsy"
tsast "github.com/grafana/cuetsy/ts/ast"
"github.com/grafana/grafana/pkg/cuectx"
"github.com/grafana/thema"
"github.com/grafana/thema/encoding/openapi"
)
// ExtractedLineage contains the results of statically analyzing a Grafana
// CoremodelDeclaration contains the results of statically analyzing a Grafana
// directory for a Thema lineage.
type ExtractedLineage struct {
type CoremodelDeclaration struct {
Lineage thema.Lineage
// Absolute path to the coremodel's coremodel.cue file.
LineagePath string
@@ -48,12 +49,12 @@ type ExtractedLineage struct {
// This loading approach is intended primarily for use with code generators, or
// other use cases external to grafana-server backend. For code within
// grafana-server, prefer lineage loaders provided in e.g. pkg/coremodel/*.
func ExtractLineage(path string, lib thema.Library) (*ExtractedLineage, error) {
func ExtractLineage(path string, lib thema.Library) (*CoremodelDeclaration, error) {
if !filepath.IsAbs(path) {
return nil, fmt.Errorf("must provide an absolute path, got %q", path)
}
ec := &ExtractedLineage{
ec := &CoremodelDeclaration{
LineagePath: path,
}
@@ -107,14 +108,14 @@ func ExtractLineage(path string, lib thema.Library) (*ExtractedLineage, error) {
}
// toTemplateObj extracts creates a struct with all the useful strings for template generation.
func (ls *ExtractedLineage) toTemplateObj() tplVars {
lin := ls.Lineage
func (cd *CoremodelDeclaration) toTemplateObj() tplVars {
lin := cd.Lineage
sch := thema.SchemaP(lin, thema.LatestVersion(lin))
return tplVars{
Name: lin.Name(),
LineagePath: ls.RelativePath,
PkgPath: filepath.ToSlash(filepath.Join("github.com/grafana/grafana", filepath.Dir(ls.RelativePath))),
LineagePath: cd.RelativePath,
PkgPath: filepath.ToSlash(filepath.Join("github.com/grafana/grafana", filepath.Dir(cd.RelativePath))),
TitleName: strings.Title(lin.Name()), // nolint
LatestSeqv: sch.Version()[0],
LatestSchv: sch.Version()[1],
@@ -139,13 +140,22 @@ var nonAPITypes = map[string]bool{
"pluginmeta": true,
}
// PathVersion returns the string path element to use for the latest schema.
// "x" if not yet canonical, otherwise, "v<major>"
func (cd *CoremodelDeclaration) PathVersion() string {
if !cd.IsCanonical {
return "x"
}
return fmt.Sprintf("v%v", thema.LatestVersion(cd.Lineage)[0])
}
// GenerateGoCoremodel generates a standard Go model struct and coremodel
// implementation from a coremodel CUE declaration.
//
// The provided path must be a directory. Generated code files will be written
// to that path. The final element of the path must match the Lineage.Name().
func (ls *ExtractedLineage) GenerateGoCoremodel(path string) (WriteDiffer, error) {
lin, lib := ls.Lineage, ls.Lineage.Library()
func (cd *CoremodelDeclaration) GenerateGoCoremodel(path string) (WriteDiffer, error) {
lin, lib := cd.Lineage, cd.Lineage.Library()
_, name := filepath.Split(path)
if name != lin.Name() {
return nil, fmt.Errorf("lineage name %q must match final element of path, got %q", lin.Name(), path)
@@ -190,7 +200,7 @@ func (ls *ExtractedLineage) GenerateGoCoremodel(path string) (WriteDiffer, error
buf := new(bytes.Buffer)
if err = tmpls.Lookup("autogen_header.tmpl").Execute(buf, tvars_autogen_header{
LineagePath: ls.RelativePath,
LineagePath: cd.RelativePath,
GeneratorPath: "pkg/framework/coremodel/gen.go", // FIXME hardcoding is not OK
}); err != nil {
return nil, fmt.Errorf("error executing header template: %w", err)
@@ -198,7 +208,7 @@ func (ls *ExtractedLineage) GenerateGoCoremodel(path string) (WriteDiffer, error
fmt.Fprint(buf, "\n", gostr)
vars := ls.toTemplateObj()
vars := cd.toTemplateObj()
err = tmpls.Lookup("addenda.tmpl").Execute(buf, vars)
if err != nil {
panic(err)
@@ -228,59 +238,38 @@ type tplVars struct {
IsComposed bool
}
func (ls *ExtractedLineage) GenerateTypescriptCoremodel(path string) (WriteDiffer, error) {
_, name := filepath.Split(path)
if name != ls.Lineage.Name() {
return nil, fmt.Errorf("lineage name %q must match final element of path, got %q", ls.Lineage.Name(), path)
}
func (cd *CoremodelDeclaration) GenerateTypescriptCoremodel() (*tsast.File, error) {
schv := thema.SchemaP(cd.Lineage, thema.LatestVersion(cd.Lineage)).UnwrapCUE()
schv := thema.SchemaP(ls.Lineage, thema.LatestVersion(ls.Lineage)).UnwrapCUE()
parts, err := cuetsy.GenerateAST(schv, cuetsy.Config{})
tf, err := cuetsy.GenerateAST(schv, cuetsy.Config{
Export: true,
})
if err != nil {
return nil, fmt.Errorf("cuetsy parts gen failed: %w", err)
return nil, fmt.Errorf("cuetsy tf gen failed: %w", err)
}
top, err := cuetsy.GenerateSingleAST(strings.Title(ls.Lineage.Name()), schv, cuetsy.TypeInterface)
top, err := cuetsy.GenerateSingleAST(strings.Title(cd.Lineage.Name()), schv, cuetsy.TypeInterface)
if err != nil {
return nil, fmt.Errorf("cuetsy top gen failed: %s", cerrors.Details(err, nil))
}
// TODO until cuetsy can toposort its outputs, put the top/parent type at the bottom of the file.
parts.Nodes = append(parts.Nodes, top.T)
if top.D != nil {
parts.Nodes = append(parts.Nodes, top.D)
}
var strb strings.Builder
var str string
fpath := ls.Lineage.Name() + ".gen.ts"
if err := tmpls.Lookup("autogen_header.tmpl").Execute(&strb, tvars_autogen_header{
LineagePath: ls.RelativePath,
buf := new(bytes.Buffer)
if err := tmpls.Lookup("autogen_header.tmpl").Execute(buf, tvars_autogen_header{
LineagePath: cd.RelativePath,
GeneratorPath: "pkg/framework/coremodel/gen.go", // FIXME hardcoding is not OK
}); err != nil {
return nil, fmt.Errorf("error executing header template: %w", err)
}
if !ls.IsCanonical {
fpath = fmt.Sprintf("%s_experimental.gen.ts", ls.Lineage.Name())
strb.WriteString(`
// This model is a WIP and not yet canonical. Consequently, its members are
// not exported to exclude it from grafana-schema's public API surface.
`)
strb.WriteString(fmt.Sprint(parts))
// TODO replace this regexp with cuetsy config for whether members are exported
re := regexp.MustCompile(`(?m)^export `)
str = re.ReplaceAllLiteralString(strb.String(), "")
} else {
strb.WriteString(fmt.Sprint(parts))
str = strb.String()
tf.Doc = &tsast.Comment{
Text: buf.String(),
}
wd := NewWriteDiffer()
wd[filepath.Join(path, fpath)] = []byte(str)
return wd, nil
// TODO until cuetsy can toposort its outputs, put the top/parent type at the bottom of the file.
tf.Nodes = append(tf.Nodes, top.T)
if top.D != nil {
tf.Nodes = append(tf.Nodes, top.D)
}
return tf, nil
}
type prefixDropper struct {
@@ -319,7 +308,7 @@ func (d prefixDropper) Visit(n ast.Node) ast.Visitor {
// GenerateCoremodelRegistry produces Go files that define a registry with
// references to all the Go code that is expected to be generated from the
// provided lineages.
func GenerateCoremodelRegistry(path string, ecl []*ExtractedLineage) (WriteDiffer, error) {
func GenerateCoremodelRegistry(path string, ecl []*CoremodelDeclaration) (WriteDiffer, error) {
var cml []tplVars
for _, ec := range ecl {
cml = append(cml, ec.toTemplateObj())
+50 -55
View File
@@ -14,6 +14,7 @@ import (
"github.com/deepmap/oapi-codegen/pkg/codegen"
"github.com/getkin/kin-openapi/openapi3"
"github.com/grafana/cuetsy"
tsast "github.com/grafana/cuetsy/ts/ast"
"github.com/grafana/grafana/pkg/framework/coremodel"
"github.com/grafana/grafana/pkg/plugins/pfs"
"github.com/grafana/thema"
@@ -101,15 +102,22 @@ type PluginTreeOrErr struct {
// It is, for now, tailored specifically to Grafana core's codegen needs.
type PluginTree pfs.Tree
func (pt *PluginTree) GenerateTS(path string) (WriteDiffer, error) {
func (pt *PluginTree) GenerateTypeScriptAST() (*tsast.File, error) {
t := (*pfs.Tree)(pt)
f := &tsast.File{}
// TODO replace with cuetsy's TS AST
f := &tvars_cuetsy_multi{
Header: tvars_autogen_header{
GeneratorPath: "public/app/plugins/gen.go", // FIXME hardcoding is not OK
LineagePath: "models.cue",
},
tf := tvars_autogen_header{
GeneratorPath: "public/app/plugins/gen.go", // FIXME hardcoding is not OK
LineagePath: "models.cue",
}
var buf bytes.Buffer
err := tmpls.Lookup("autogen_header.tmpl").Execute(&buf, tf)
if err != nil {
return nil, fmt.Errorf("error executing header template: %w", err)
}
f.Doc = &tsast.Comment{
Text: buf.String(),
}
pi := t.RootPlugin()
@@ -118,7 +126,9 @@ func (pt *PluginTree) GenerateTS(path string) (WriteDiffer, error) {
return nil, nil
}
for _, im := range pi.CUEImports() {
if tsim := convertImport(im); tsim != nil {
if tsim, err := convertImport(im); err != nil {
return nil, err
} else if tsim.From.Value != "" {
f.Imports = append(f.Imports, tsim)
}
}
@@ -126,37 +136,36 @@ func (pt *PluginTree) GenerateTS(path string) (WriteDiffer, error) {
for slotname, lin := range slotimps {
v := thema.LatestVersion(lin)
sch := thema.SchemaP(lin, v)
// TODO need call expressions in cuetsy tsast to be able to do these
sec := tsSection{
V: v,
ModelName: slotname,
}
// Inject a node for the const with the version
f.Nodes = append(f.Nodes, tsast.Raw{
// TODO need call expressions in cuetsy tsast to be able to do these properly
Data: fmt.Sprintf("export const %sModelVersion = Object.freeze([%v, %v]);", slotname, v[0], v[1]),
})
// TODO this is hardcoded for now, but should ultimately be a property of
// whether the slot is a grouped lineage:
// https://github.com/grafana/thema/issues/62
if isGroupLineage(slotname) {
b, err := cuetsy.Generate(sch.UnwrapCUE(), cuetsy.Config{})
tsf, err := cuetsy.GenerateAST(sch.UnwrapCUE(), cuetsy.Config{
Export: true,
})
if err != nil {
return nil, fmt.Errorf("%s: error translating %s lineage to TypeScript: %w", path, slotname, err)
return nil, fmt.Errorf("error translating %s lineage to TypeScript: %w", slotname, err)
}
sec.Body = string(b)
f.Nodes = append(f.Nodes, tsf.Nodes...)
} else {
a, err := cuetsy.GenerateSingleAST(strings.Title(lin.Name()), sch.UnwrapCUE(), cuetsy.TypeInterface)
pair, err := cuetsy.GenerateSingleAST(strings.Title(lin.Name()), sch.UnwrapCUE(), cuetsy.TypeInterface)
if err != nil {
return nil, fmt.Errorf("%s: error translating %s lineage to TypeScript: %w", path, slotname, err)
return nil, fmt.Errorf("error translating %s lineage to TypeScript: %w", slotname, err)
}
f.Nodes = append(f.Nodes, pair.T)
if pair.D != nil {
f.Nodes = append(f.Nodes, pair.D)
}
sec.Body = fmt.Sprint(a)
}
f.Sections = append(f.Sections, sec)
}
wd := NewWriteDiffer()
var buf bytes.Buffer
err := tmpls.Lookup("cuetsy_multi.tmpl").Execute(&buf, f)
if err != nil {
return nil, fmt.Errorf("%s: error executing plugin TS generator template: %w", path, err)
}
wd[filepath.Join(path, "models.gen.ts")] = buf.Bytes()
return wd, nil
return f, nil
}
func isGroupLineage(slotname string) bool {
@@ -414,41 +423,27 @@ type TreeAndPath struct {
}
// TODO convert this to use cuetsy ts types, once import * form is supported
func convertImport(im *ast.ImportSpec) *tsImport {
var err error
tsim := &tsImport{}
tsim.Pkg, err = MapCUEImportToTS(strings.Trim(im.Path.Value, "\""))
if err != nil {
// should be unreachable if paths has been verified already
panic(err)
func convertImport(im *ast.ImportSpec) (tsast.ImportSpec, error) {
tsim := tsast.ImportSpec{}
pkg, err := MapCUEImportToTS(strings.Trim(im.Path.Value, "\""))
if err != nil || pkg == "" {
// err should be unreachable if paths has been verified already
// Empty string mapping means skip it
return tsim, err
}
if tsim.Pkg == "" {
// Empty string mapping means skip it
return nil
}
tsim.From = tsast.Str{Value: pkg}
if im.Name != nil && im.Name.String() != "" {
tsim.Ident = im.Name.String()
tsim.AsName = im.Name.String()
} else {
sl := strings.Split(im.Path.Value, "/")
final := sl[len(sl)-1]
if idx := strings.Index(final, ":"); idx != -1 {
tsim.Pkg = final[idx:]
tsim.AsName = final[idx:]
} else {
tsim.Pkg = final
tsim.AsName = final
}
}
return tsim
}
type tsSection struct {
V thema.SyntacticVersion
ModelName string
Body string
}
type tsImport struct {
Ident string
Pkg string
return tsim, nil
}
+12 -5
View File
@@ -1,6 +1,7 @@
package codegen
import (
"bytes"
"embed"
"text/template"
"time"
@@ -48,11 +49,6 @@ type (
SlotImpls []tvars_plugin_lineage_binding
Header tvars_autogen_header
}
tvars_cuetsy_multi struct {
Header tvars_autogen_header
Imports []*tsImport
Sections []tsSection
}
tvars_plugin_registry struct {
Header tvars_autogen_header
Plugins []struct {
@@ -63,3 +59,14 @@ type (
}
}
)
type HeaderVars = tvars_autogen_header
// GenGrafanaHeader creates standard header elements for generated Grafana files.
func GenGrafanaHeader(vars HeaderVars) string {
buf := new(bytes.Buffer)
if err := tmpls.Lookup("autogen_header.tmpl").Execute(buf, vars); err != nil {
panic(err)
}
return buf.String()
}
+1 -6
View File
@@ -1,7 +1,2 @@
{{ template "autogen_header.tmpl" .Header -}}
{{range .Imports}}
import * as {{.Ident}} from '{{.Pkg}}';{{end}}
{{range .Sections}}{{if ne .ModelName "" }}
export const {{.ModelName}}ModelVersion = Object.freeze([{{index .V 0}}, {{index .V 1}}]);
{{end}}
{{.Body}}{{end}}
{{ .Body }}
+116 -61
View File
@@ -12,6 +12,8 @@ seqs: [
{
schemas: [
{// 0.0
@grafana(TSVeneer="type")
// Unique numeric identifier for the dashboard.
// TODO must isolate or remove identifiers local to a Grafana instance...?
id?: int64
@@ -192,6 +194,59 @@ seqs: [
steps: [...#Threshold] @reviewme()
} @cuetsy(kind="interface") @reviewme()
// TODO docs
#ValueMapping: #ValueMap | #RangeMap | #RegexMap | #SpecialValueMap @cuetsy(kind="type") @reviewme()
// TODO docs
#MappingType: "value" | "range" | "regex" | "special" @cuetsy(kind="enum",memberNames="ValueToText|RangeToText|RegexToText|SpecialValue") @reviewme()
// TODO docs
#ValueMap: {
type: #MappingType & "value"
options: [string]: #ValueMappingResult
} @cuetsy(kind="interface")
// TODO docs
#RangeMap: {
type: #MappingType & "range"
options: {
// to and from are `number | null` in current ts, really not sure what to do
from: int32 @reviewme()
to: int32 @reviewme()
result: #ValueMappingResult
}
} @cuetsy(kind="interface") @reviewme()
// TODO docs
#RegexMap: {
type: #MappingType & "regex"
options: {
pattern: string
result: #ValueMappingResult
}
} @cuetsy(kind="interface") @reviewme()
// TODO docs
#SpecialValueMap: {
type: #MappingType & "special"
options: {
match: "true" | "false"
pattern: string
result: #ValueMappingResult
}
} @cuetsy(kind="interface") @reviewme()
// TODO docs
#SpecialValueMatch: "true" | "false" | "null" | "nan" | "null+nan" | "empty" @cuetsy(kind="enum",memberNames="True|False|Null|NaN|NullAndNan|Empty")
// TODO docs
#ValueMappingResult: {
text?: string
color?: string
icon?: string
index?: int32
} @cuetsy(kind="interface")
// TODO docs
// FIXME this is extremely underspecfied; wasn't obvious which typescript types corresponded to it
#Transformation: {
@@ -282,82 +337,82 @@ seqs: [
// plugin schemas.
options: {...} @reviewme()
fieldConfig: {
defaults: {
// The display value for this field. This supports template variables blank is auto
displayName?: string @reviewme()
fieldConfig: #FieldConfigSource
} @cuetsy(kind="interface") @grafana(TSVeneer="type") @reviewme()
// This can be used by data sources that return and explicit naming structure for values and labels
// When this property is configured, this value is used rather than the default naming strategy.
displayNameFromDS?: string @reviewme()
#FieldConfigSource: {
defaults: #FieldConfig
overrides: [...{
matcher: #MatcherConfig
properties: [...#DynamicConfigValue]
}] @reviewme()
} @cuetsy(kind="interface") @grafana(TSVeneer="type") @reviewme()
// Human readable field metadata
description?: string @reviewme()
#MatcherConfig: {
id: string | *"" @reviewme()
options?: _ @reviewme()
} @cuetsy(kind="interface")
// An explict path to the field in the datasource. When the frame meta includes a path,
// This will default to `${frame.meta.path}/${field.name}
//
// When defined, this value can be used as an identifier within the datasource scope, and
// may be used to update the results
path?: string @reviewme()
#DynamicConfigValue: {
id: string | *"" @reviewme()
value?: _ @reviewme()
}
// True if data source can write a value to the path. Auth/authz are supported separately
writeable?: bool @reviewme()
#FieldConfig: {
// The display value for this field. This supports template variables blank is auto
displayName?: string @reviewme()
// True if data source field supports ad-hoc filters
filterable?: bool @reviewme()
// This can be used by data sources that return and explicit naming structure for values and labels
// When this property is configured, this value is used rather than the default naming strategy.
displayNameFromDS?: string @reviewme()
// Numeric Options
unit?: string @reviewme()
// Human readable field metadata
description?: string @reviewme()
// Significant digits (for display)
decimals?: number @reviewme()
// An explict path to the field in the datasource. When the frame meta includes a path,
// This will default to `${frame.meta.path}/${field.name}
//
// When defined, this value can be used as an identifier within the datasource scope, and
// may be used to update the results
path?: string @reviewme()
min?: number @reviewme()
max?: number @reviewme()
// True if data source can write a value to the path. Auth/authz are supported separately
writeable?: bool @reviewme()
// Convert input values into a display string
//
// TODO this one corresponds to a complex type with
// generics on the typescript side. Ouch. Will
// either need special care, or we'll just need to
// accept a very loosely specified schema. It's very
// unlikely we'll be able to translate cue to
// typescript generics in the general case, though
// this particular one *may* be able to work.
mappings?: [...{...}] @reviewme()
// True if data source field supports ad-hoc filters
filterable?: bool @reviewme()
// Map numeric values to states
thresholds?: #ThresholdsConfig @reviewme()
// Numeric Options
unit?: string @reviewme()
// // Map values to a display color
color?: #FieldColor @reviewme()
// Significant digits (for display)
decimals?: number @reviewme()
// // Used when reducing field values
// nullValueMode?: NullValueMode
min?: number @reviewme()
max?: number @reviewme()
// // The behavior when clicking on a result
links?: [...] @reviewme()
// Convert input values into a display string
mappings?: [...#ValueMapping] @reviewme()
// Alternative to empty string
noValue?: string @reviewme()
// Map numeric values to states
thresholds?: #ThresholdsConfig @reviewme()
// custom is specified by the PanelFieldConfig field
// in panel plugin schemas.
custom?: {...} @reviewme()
} @reviewme()
overrides: [...{
matcher: {
id: string | *"" @reviewme()
options?: _ @reviewme()
}
properties: [...{
id: string | *"" @reviewme()
value?: _ @reviewme()
}]
}] @reviewme()
}
} @cuetsy(kind="interface") @reviewme()
// Map values to a display color
color?: #FieldColor @reviewme()
// Used when reducing field values
// nullValueMode?: NullValueMode
// The behavior when clicking on a result
links?: [...] @reviewme()
// Alternative to empty string
noValue?: string @reviewme()
// custom is specified by the PanelFieldConfig field
// in panel plugin schemas.
custom?: {...} @reviewme()
} @cuetsy(kind="interface") @grafana(TSVeneer="type") @reviewme()
// Row panel
#RowPanel: {
+317 -12
View File
@@ -90,6 +90,17 @@ const (
HeatmapPanelTypeHeatmap HeatmapPanelType = "heatmap"
)
// Defines values for MappingType.
const (
MappingTypeRange MappingType = "range"
MappingTypeRegex MappingType = "regex"
MappingTypeSpecial MappingType = "special"
MappingTypeValue MappingType = "value"
)
// Defines values for PanelRepeatDirection.
const (
PanelRepeatDirectionH PanelRepeatDirection = "h"
@@ -97,11 +108,48 @@ const (
PanelRepeatDirectionV PanelRepeatDirection = "v"
)
// Defines values for RangeMapType.
const (
RangeMapTypeRange RangeMapType = "range"
)
// Defines values for RegexMapType.
const (
RegexMapTypeRegex RegexMapType = "regex"
)
// Defines values for RowPanelType.
const (
RowPanelTypeRow RowPanelType = "row"
)
// Defines values for SpecialValueMapOptionsMatch.
const (
SpecialValueMapOptionsMatchFalse SpecialValueMapOptionsMatch = "false"
SpecialValueMapOptionsMatchTrue SpecialValueMapOptionsMatch = "true"
)
// Defines values for SpecialValueMapType.
const (
SpecialValueMapTypeSpecial SpecialValueMapType = "special"
)
// Defines values for SpecialValueMatch.
const (
SpecialValueMatchEmpty SpecialValueMatch = "empty"
SpecialValueMatchFalse SpecialValueMatch = "false"
SpecialValueMatchNan SpecialValueMatch = "nan"
SpecialValueMatchNull SpecialValueMatch = "null"
SpecialValueMatchNullNan SpecialValueMatch = "null+nan"
SpecialValueMatchTrue SpecialValueMatch = "true"
)
// Defines values for ThresholdsConfigMode.
const (
ThresholdsConfigModeAbsolute ThresholdsConfigMode = "absolute"
@@ -116,6 +164,11 @@ const (
ThresholdsModePercentage ThresholdsMode = "percentage"
)
// Defines values for ValueMapType.
const (
ValueMapTypeValue ValueMapType = "value"
)
// Defines values for VariableModelType.
const (
VariableModelTypeAdhoc VariableModelType = "adhoc"
@@ -336,6 +389,15 @@ type DashboardLink struct {
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type DashboardLinkType string
// DynamicConfigValue is the Go representation of a dashboard.DynamicConfigValue.
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type DynamicConfigValue struct {
Id string `json:"id"`
Value *interface{} `json:"value,omitempty"`
}
// TODO docs
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
@@ -363,6 +425,126 @@ type FieldColorModeId string
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type FieldColorSeriesByMode string
// FieldConfig is the Go representation of a dashboard.FieldConfig.
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type FieldConfig struct {
// TODO docs
Color *FieldColor `json:"color,omitempty"`
// custom is specified by the PanelFieldConfig field
// in panel plugin schemas.
Custom *map[string]interface{} `json:"custom,omitempty"`
// Significant digits (for display)
Decimals *float32 `json:"decimals,omitempty"`
// Human readable field metadata
Description *string `json:"description,omitempty"`
// The display value for this field. This supports template variables blank is auto
DisplayName *string `json:"displayName,omitempty"`
// This can be used by data sources that return and explicit naming structure for values and labels
// When this property is configured, this value is used rather than the default naming strategy.
DisplayNameFromDS *string `json:"displayNameFromDS,omitempty"`
// True if data source field supports ad-hoc filters
Filterable *bool `json:"filterable,omitempty"`
// The behavior when clicking on a result
Links *[]interface{} `json:"links,omitempty"`
// Convert input values into a display string
Mappings *[]ValueMapping `json:"mappings,omitempty"`
Max *float32 `json:"max,omitempty"`
Min *float32 `json:"min,omitempty"`
// Alternative to empty string
NoValue *string `json:"noValue,omitempty"`
// An explict path to the field in the datasource. When the frame meta includes a path,
// This will default to `${frame.meta.path}/${field.name}
//
// When defined, this value can be used as an identifier within the datasource scope, and
// may be used to update the results
Path *string `json:"path,omitempty"`
Thresholds *ThresholdsConfig `json:"thresholds,omitempty"`
// Numeric Options
Unit *string `json:"unit,omitempty"`
// True if data source can write a value to the path. Auth/authz are supported separately
Writeable *bool `json:"writeable,omitempty"`
}
// FieldConfigSource is the Go representation of a dashboard.FieldConfigSource.
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type FieldConfigSource struct {
Defaults struct {
// TODO docs
Color *FieldColor `json:"color,omitempty"`
// custom is specified by the PanelFieldConfig field
// in panel plugin schemas.
Custom *map[string]interface{} `json:"custom,omitempty"`
// Significant digits (for display)
Decimals *float32 `json:"decimals,omitempty"`
// Human readable field metadata
Description *string `json:"description,omitempty"`
// The display value for this field. This supports template variables blank is auto
DisplayName *string `json:"displayName,omitempty"`
// This can be used by data sources that return and explicit naming structure for values and labels
// When this property is configured, this value is used rather than the default naming strategy.
DisplayNameFromDS *string `json:"displayNameFromDS,omitempty"`
// True if data source field supports ad-hoc filters
Filterable *bool `json:"filterable,omitempty"`
// The behavior when clicking on a result
Links *[]interface{} `json:"links,omitempty"`
// Convert input values into a display string
Mappings *[]ValueMapping `json:"mappings,omitempty"`
Max *float32 `json:"max,omitempty"`
Min *float32 `json:"min,omitempty"`
// Alternative to empty string
NoValue *string `json:"noValue,omitempty"`
// An explict path to the field in the datasource. When the frame meta includes a path,
// This will default to `${frame.meta.path}/${field.name}
//
// When defined, this value can be used as an identifier within the datasource scope, and
// may be used to update the results
Path *string `json:"path,omitempty"`
Thresholds *ThresholdsConfig `json:"thresholds,omitempty"`
// Numeric Options
Unit *string `json:"unit,omitempty"`
// True if data source can write a value to the path. Auth/authz are supported separately
Writeable *bool `json:"writeable,omitempty"`
} `json:"defaults"`
Overrides []struct {
Matcher struct {
Id string `json:"id"`
Options *interface{} `json:"options,omitempty"`
} `json:"matcher"`
Properties []struct {
Id string `json:"id"`
Value *interface{} `json:"value,omitempty"`
} `json:"properties"`
} `json:"overrides"`
}
// GraphPanel is the Go representation of a dashboard.GraphPanel.
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
@@ -413,6 +595,21 @@ type HeatmapPanel struct {
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type HeatmapPanelType string
// TODO docs
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type MappingType string
// MatcherConfig is the Go representation of a dashboard.MatcherConfig.
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type MatcherConfig struct {
Id string `json:"id"`
Options *interface{} `json:"options,omitempty"`
}
// Model panels. Panels are canonically defined inline
// because they share a version timeline with the dashboard
// schema; they do not evolve independently.
@@ -453,21 +650,13 @@ type Panel struct {
// True if data source field supports ad-hoc filters
Filterable *bool `json:"filterable,omitempty"`
// // The behavior when clicking on a result
// The behavior when clicking on a result
Links *[]interface{} `json:"links,omitempty"`
// Convert input values into a display string
//
// TODO this one corresponds to a complex type with
// generics on the typescript side. Ouch. Will
// either need special care, or we'll just need to
// accept a very loosely specified schema. It's very
// unlikely we'll be able to translate cue to
// typescript generics in the general case, though
// this particular one *may* be able to work.
Mappings *[]map[string]interface{} `json:"mappings,omitempty"`
Max *float32 `json:"max,omitempty"`
Min *float32 `json:"min,omitempty"`
Mappings *[]ValueMapping `json:"mappings,omitempty"`
Max *float32 `json:"max,omitempty"`
Min *float32 `json:"min,omitempty"`
// Alternative to empty string
NoValue *string `json:"noValue,omitempty"`
@@ -568,6 +757,54 @@ type Panel struct {
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type PanelRepeatDirection string
// TODO docs
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type RangeMap struct {
Options struct {
// to and from are `number | null` in current ts, really not sure what to do
From int32 `json:"from"`
Result struct {
Color *string `json:"color,omitempty"`
Icon *string `json:"icon,omitempty"`
Index *int32 `json:"index,omitempty"`
Text *string `json:"text,omitempty"`
} `json:"result"`
To int32 `json:"to"`
} `json:"options"`
Type RangeMapType `json:"type"`
}
// RangeMapType is the Go representation of a RangeMap.Type.
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type RangeMapType string
// TODO docs
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type RegexMap struct {
Options struct {
Pattern string `json:"pattern"`
Result struct {
Color *string `json:"color,omitempty"`
Icon *string `json:"icon,omitempty"`
Index *int32 `json:"index,omitempty"`
Text *string `json:"text,omitempty"`
} `json:"result"`
} `json:"options"`
Type RegexMapType `json:"type"`
}
// RegexMapType is the Go representation of a RegexMap.Type.
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type RegexMapType string
// Row panel
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
@@ -596,6 +833,42 @@ type RowPanel struct {
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type RowPanelType string
// TODO docs
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type SpecialValueMap struct {
Options struct {
Match SpecialValueMapOptionsMatch `json:"match"`
Pattern string `json:"pattern"`
Result struct {
Color *string `json:"color,omitempty"`
Icon *string `json:"icon,omitempty"`
Index *int32 `json:"index,omitempty"`
Text *string `json:"text,omitempty"`
} `json:"result"`
} `json:"options"`
Type SpecialValueMapType `json:"type"`
}
// SpecialValueMapOptionsMatch is the Go representation of a SpecialValueMap.Options.Match.
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type SpecialValueMapOptionsMatch string
// SpecialValueMapType is the Go representation of a SpecialValueMap.Type.
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type SpecialValueMapType string
// TODO docs
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type SpecialValueMatch string
// Schema for panel targets is specified by datasource
// plugins. We use a placeholder definition, which the Go
// schema loader either left open/as-is with the Base
@@ -671,6 +944,38 @@ type Transformation struct {
Options map[string]interface{} `json:"options"`
}
// TODO docs
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type ValueMap struct {
Options map[string]interface{} `json:"options"`
Type ValueMapType `json:"type"`
}
// ValueMapType is the Go representation of a ValueMap.Type.
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type ValueMapType string
// TODO docs
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type ValueMapping interface{}
// TODO docs
//
// THIS TYPE IS INTENDED FOR INTERNAL USE BY THE GRAFANA BACKEND, AND IS SUBJECT TO BREAKING CHANGES.
// Equivalent Go types at stable import paths are provided in https://github.com/grafana/grok.
type ValueMappingResult struct {
Color *string `json:"color,omitempty"`
Icon *string `json:"icon,omitempty"`
Index *int32 `json:"index,omitempty"`
Text *string `json:"text,omitempty"`
}
// FROM: packages/grafana-data/src/types/templateVars.ts
// TODO docs
// TODO what about what's in public/app/features/types.ts?
+320 -19
View File
@@ -7,21 +7,42 @@ package main
import (
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
"cuelang.org/go/cue"
"cuelang.org/go/cue/cuecontext"
"cuelang.org/go/cue/errors"
"cuelang.org/go/cue/load"
"github.com/grafana/cuetsy"
"github.com/grafana/thema"
"github.com/grafana/cuetsy/ts"
"github.com/grafana/cuetsy/ts/ast"
gcgen "github.com/grafana/grafana/pkg/codegen"
"github.com/grafana/thema"
)
var lib = thema.NewLibrary(cuecontext.New())
const sep = string(filepath.Separator)
var tsroot, cmroot, groot string
func init() {
cwd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "could not get working directory: %s", err)
os.Exit(1)
}
// TODO this binds us to only having coremodels in a single directory. If we need more, compgen is the way
groot = filepath.Dir(filepath.Dir(filepath.Dir(cwd))) // the working dir is <grafana_dir>/pkg/framework/coremodel. Going up 3 dirs we get the grafana root
cmroot = filepath.Join(groot, "pkg", "coremodel")
tsroot = filepath.Join(groot, "packages", "grafana-schema", "src")
}
// Generate Go and Typescript implementations for all coremodels, and populate the
// coremodel static registry.
func main() {
@@ -30,25 +51,13 @@ func main() {
os.Exit(1)
}
cwd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "could not get working directory: %s", err)
os.Exit(1)
}
// TODO this binds us to only having coremodels in a single directory. If we need more, compgen is the way
groot := filepath.Dir(filepath.Dir(filepath.Dir(cwd))) // the working dir is <grafana_dir>/pkg/framework/coremodel. Going up 3 dirs we get the grafana root
cmroot := filepath.Join(groot, "pkg", "coremodel")
tsroot := filepath.Join(groot, "packages", "grafana-schema", "src", "schema")
items, err := os.ReadDir(cmroot)
if err != nil {
fmt.Fprintf(os.Stderr, "could not read coremodels parent dir %s: %s\n", cmroot, err)
os.Exit(1)
}
var lins []*gcgen.ExtractedLineage
var lins []*gcgen.CoremodelDeclaration
for _, item := range items {
if item.IsDir() {
lin, err := gcgen.ExtractLineage(filepath.Join(cmroot, item.Name(), "coremodel.cue"), lib)
@@ -64,6 +73,9 @@ func main() {
return lins[i].Lineage.Name() < lins[j].Lineage.Name()
})
// The typescript veneer index.gen.ts file, which we'll build up over time
// from the exported types.
tsvidx := new(ast.File)
wd := gcgen.NewWriteDiffer()
for _, ls := range lins {
gofiles, err := ls.GenerateGoCoremodel(filepath.Join(cmroot, ls.Lineage.Name()))
@@ -75,15 +87,26 @@ func main() {
// Only generate TS for API types
if ls.IsAPIType {
tsfiles, err := ls.GenerateTypescriptCoremodel(filepath.Join(tsroot, ls.Lineage.Name()))
tsf, err := ls.GenerateTypescriptCoremodel()
if err != nil {
fmt.Fprintf(os.Stderr, "failed to generate TypeScript for %s: %s\n", ls.Lineage.Name(), err)
fmt.Fprintf(os.Stderr, "error generating TypeScript for %s: %s\n", ls.Lineage.Name(), err)
os.Exit(1)
}
wd.Merge(tsfiles)
tsf.Doc = mkTSHeader(ls)
wd[filepath.FromSlash(filepath.Join(tsroot, rawTSGenPath(ls)))] = []byte(tsf.String())
decls, err := extractTSIndexVeneerElements(ls, tsf)
if err != nil {
fmt.Fprintf(os.Stderr, "error generating TypeScript veneer for %s: %s\n", ls.Lineage.Name(), errors.Details(err, nil))
os.Exit(1)
}
tsvidx.Nodes = append(tsvidx.Nodes, decls...)
}
}
tsvidx.Doc = mkTSHeader(nil)
wd[filepath.Join(tsroot, "index.gen.ts")] = []byte(tsvidx.String())
regfiles, err := gcgen.GenerateCoremodelRegistry(filepath.Join(groot, "pkg", "framework", "coremodel", "registry", "registry_gen.go"), lins)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to generate coremodel registry: %s\n", err)
@@ -113,6 +136,26 @@ func main() {
}
}
}
// generates the path relative to packages/grafana-schema/src at which the raw
// type definitions should be exported for the latest schema of this type
func rawTSGenPath(cm *gcgen.CoremodelDeclaration) string {
return fmt.Sprintf("raw/%s/%s/%s.gen.ts", cm.Lineage.Name(), cm.PathVersion(), cm.Lineage.Name())
}
func mkTSHeader(cm *gcgen.CoremodelDeclaration) *ast.Comment {
v := gcgen.HeaderVars{
GeneratorPath: "pkg/framework/coremodel/gen.go",
}
if cm != nil {
v.LineagePath = cm.RelativePath
}
v.GeneratorPath = "pkg/framework/coremodel/gen.go"
return &ast.Comment{
Text: strings.TrimSpace(gcgen.GenGrafanaHeader(v)),
}
}
func genSharedSchemas(groot string) (gcgen.WriteDiffer, error) {
abspath := filepath.Join(groot, "packages", "grafana-schema", "src", "schema")
cfg := &load.Config{
@@ -132,7 +175,9 @@ func genSharedSchemas(groot string) (gcgen.WriteDiffer, error) {
return nil, fmt.Errorf("errors while building CUE in %s: %s", abspath, v.Err())
}
b, err := cuetsy.Generate(v, cuetsy.Config{})
b, err := cuetsy.Generate(v, cuetsy.Config{
Export: true,
})
if err != nil {
return nil, fmt.Errorf("failed to generate TS: %w", err)
}
@@ -146,3 +191,259 @@ func genSharedSchemas(groot string) (gcgen.WriteDiffer, error) {
`), b...)
return wd, nil
}
// TODO make this more generic and reusable
func extractTSIndexVeneerElements(cm *gcgen.CoremodelDeclaration, tf *ast.File) ([]ast.Decl, error) {
lin := cm.Lineage
sch := thema.SchemaP(lin, thema.LatestVersion(lin))
// Check the root, then walk the tree
rootv := sch.UnwrapCUE()
var raw, custom, rawD, customD ast.Idents
var terr errors.Error
visit := func(p cue.Path, wv cue.Value) bool {
var name string
sels := p.Selectors()
switch len(sels) {
case 0:
name = strings.Title(cm.Lineage.Name())
fallthrough
case 1:
// Only deal with subpaths that are definitions, for now
// TODO incorporate smarts about grouped lineages here
if name == "" {
if !sels[0].IsDefinition() {
return false
}
// It might seem to make sense that we'd strip out the leading # here for
// definitions. However, cuetsy's tsast actually has the # still present in its
// Ident types, stripping it out on the fly when stringifying.
name = sels[0].String()
}
// Search the generated TS AST for the type and default decl nodes
pair := findDeclNode(name, tf)
if pair.T == nil {
// No generated type for this item, skip it
return false
}
cust, perr := getCustomVeneerAttr(wv)
if perr != nil {
terr = errors.Append(terr, errors.Promote(perr, fmt.Sprintf("%s: ", p.String())))
}
var has bool
for _, tgt := range cust {
has = has || tgt.target == "type"
}
if has {
custom = append(custom, *pair.T)
if pair.D != nil {
customD = append(customD, *pair.D)
}
} else {
raw = append(raw, *pair.T)
if pair.D != nil {
rawD = append(rawD, *pair.D)
}
}
}
return true
}
walk(rootv, visit, nil)
if len(errors.Errors(terr)) != 0 {
return nil, terr
}
ret := make([]ast.Decl, 0)
if len(raw) > 0 {
ret = append(ret, ast.ExportSet{
CommentList: []ast.Comment{ts.CommentFromString(fmt.Sprintf("Raw generated types from %s entity type.", cm.Lineage.Name()), 80, false)},
TypeOnly: true,
Exports: raw,
From: ast.Str{Value: fmt.Sprintf("./raw/%s/%s/%s.gen", cm.Lineage.Name(), cm.PathVersion(), cm.Lineage.Name())},
})
}
if len(rawD) > 0 {
ret = append(ret, ast.ExportSet{
CommentList: []ast.Comment{ts.CommentFromString(fmt.Sprintf("Raw generated default consts from %s entity type.", cm.Lineage.Name()), 80, false)},
TypeOnly: false,
Exports: rawD,
From: ast.Str{Value: fmt.Sprintf("./raw/%s/%s/%s.gen", cm.Lineage.Name(), cm.PathVersion(), cm.Lineage.Name())},
})
}
vtfile := fmt.Sprintf("./veneer/%s.types", cm.Lineage.Name())
customstr := fmt.Sprintf(`// The following exported declarations correspond to types in the %s@%s schema with
// attribute @grafana(TSVeneer="type"). (lineage declared in file: %s)
//
// The handwritten file for these type and default veneers is expected to be at
// %s.ts.
// This re-export declaration enforces that the handwritten veneer file exists,
// and exports all the symbols in the list.
//
// TODO generate code such that tsc enforces type compatibility between raw and veneer decls`,
cm.Lineage.Name(), thema.LatestVersion(cm.Lineage), cm.RelativePath, filepath.Clean(path.Join("packages", "grafana-schema", "src", vtfile)))
customComments := []ast.Comment{{Text: customstr}}
if len(custom) > 0 {
ret = append(ret, ast.ExportSet{
CommentList: customComments,
TypeOnly: true,
Exports: custom,
From: ast.Str{Value: vtfile},
})
}
if len(customD) > 0 {
ret = append(ret, ast.ExportSet{
CommentList: customComments,
TypeOnly: false,
Exports: customD,
From: ast.Str{Value: vtfile},
})
}
// TODO emit a decl in the index.gen.ts that ensures any custom veneer types are "compatible" with current version raw types
return ret, nil
}
type declPair struct {
T, D *ast.Ident
}
func findDeclNode(name string, tf *ast.File) declPair {
var p declPair
for _, decl := range tf.Nodes {
// Peer through export keywords
if ex, is := decl.(ast.ExportKeyword); is {
decl = ex.Decl
}
switch x := decl.(type) {
case ast.TypeDecl:
if x.Name.Name == name {
p.T = &x.Name
}
case ast.VarDecl:
if x.Names.Idents[0].Name == "default"+name {
p.D = &x.Names.Idents[0]
}
}
}
return p
}
type tsVeneerAttr struct {
target string
}
func walk(v cue.Value, before func(cue.Path, cue.Value) bool, after func(cue.Path, cue.Value)) {
innerWalk(cue.MakePath(), v, before, after)
}
func innerWalk(p cue.Path, v cue.Value, before func(cue.Path, cue.Value) bool, after func(cue.Path, cue.Value)) {
// switch v.IncompleteKind() {
switch v.Kind() {
default:
if before != nil && !before(p, v) {
return
}
case cue.StructKind:
if before != nil && !before(p, v) {
return
}
iter, err := v.Fields(cue.All())
if err != nil {
panic(err)
}
for iter.Next() {
innerWalk(appendPath(p, iter.Selector()), iter.Value(), before, after)
}
if lv := v.LookupPath(cue.MakePath(cue.AnyString)); lv.Exists() {
innerWalk(appendPath(p, cue.AnyString), lv, before, after)
}
case cue.ListKind:
if before != nil && !before(p, v) {
return
}
list, err := v.List()
if err != nil {
panic(err)
}
for i := 0; list.Next(); i++ {
innerWalk(appendPath(p, cue.Index(i)), list.Value(), before, after)
}
if lv := v.LookupPath(cue.MakePath(cue.AnyIndex)); lv.Exists() {
innerWalk(appendPath(p, cue.AnyString), lv, before, after)
}
}
if after != nil {
after(p, v)
}
}
func appendPath(p cue.Path, sel cue.Selector) cue.Path {
return cue.MakePath(append(p.Selectors(), sel)...)
}
var allowedTSVeneers = map[string]bool{
"type": true,
}
func allowedTSVeneersString() string {
var list []string
for tgt := range allowedTSVeneers {
list = append(list, tgt)
}
sort.Strings(list)
return strings.Join(list, "|")
}
func getCustomVeneerAttr(v cue.Value) ([]tsVeneerAttr, error) {
var attrs []tsVeneerAttr
for _, a := range v.Attributes(cue.ValueAttr) {
if a.Name() != "grafana" {
continue
}
for i := 0; i < a.NumArgs(); i++ {
key, av := a.Arg(i)
if key != "TSVeneer" {
return nil, valError(v, "attribute 'grafana' only allows the arg 'TSVeneer'")
}
aterr := valError(v, "@grafana(TSVeneer=\"x\") requires one or more of the following separated veneer types for x: %s", allowedTSVeneersString())
var some bool
for _, tgt := range strings.Split(av, "|") {
some = true
if !allowedTSVeneers[tgt] {
return nil, aterr
}
attrs = append(attrs, tsVeneerAttr{
target: tgt,
})
}
if !some {
return nil, aterr
}
}
}
sort.Slice(attrs, func(i, j int) bool {
return attrs[i].target < attrs[j].target
})
return attrs, nil
}
func valError(v cue.Value, format string, args ...interface{}) error {
s := v.Source()
if s == nil {
return fmt.Errorf(format, args...)
}
return errors.Newf(s.Pos(), format, args...)
}