From fc3ed34b221ada9fe37f1090873b6cc6d55f4e8d Mon Sep 17 00:00:00 2001 From: sam boyer Date: Thu, 18 Nov 2021 10:02:11 -0500 Subject: [PATCH] Add basic resource trimming command (#41780) * Add basic trim command * Indent properly * Actually apply defaults if the user asks for it --- pkg/cmd/grafana-cli/commands/commands.go | 16 ++++++ pkg/cmd/grafana-cli/commands/trim_command.go | 59 ++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 pkg/cmd/grafana-cli/commands/trim_command.go diff --git a/pkg/cmd/grafana-cli/commands/commands.go b/pkg/cmd/grafana-cli/commands/commands.go index 900b2269b46..cabaa44f3fa 100644 --- a/pkg/cmd/grafana-cli/commands/commands.go +++ b/pkg/cmd/grafana-cli/commands/commands.go @@ -214,6 +214,22 @@ so must be recompiled to validate newly-added CUE files.`, }, }, }, + { + Name: "trim-resource", + Usage: "trim schema-specified defaults from a resource", + Action: runCueCommand(cmd.trimResource), + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "dashboard", + Usage: "path to file containing (valid) dashboard JSON", + }, + &cli.BoolFlag{ + Name: "apply", + Usage: "invert the operation: apply defaults instead of trimming them", + Value: false, + }, + }, + }, { Name: "gen-ts", Usage: "generate TypeScript from all known CUE file types", diff --git a/pkg/cmd/grafana-cli/commands/trim_command.go b/pkg/cmd/grafana-cli/commands/trim_command.go new file mode 100644 index 00000000000..83a61ec7101 --- /dev/null +++ b/pkg/cmd/grafana-cli/commands/trim_command.go @@ -0,0 +1,59 @@ +package commands + +import ( + "bytes" + "encoding/json" + gerrors "errors" + "fmt" + "io" + "os" + "path/filepath" + + "cuelang.org/go/cue/errors" + "github.com/grafana/grafana/pkg/cmd/grafana-cli/utils" + "github.com/grafana/grafana/pkg/schema" + "github.com/grafana/grafana/pkg/schema/load" +) + +func (cmd Command) trimResource(c utils.CommandLine) error { + filename := c.String("dashboard") + if filename == "" { + return gerrors.New("must specify dashboard file path with --dashboard") + } + apply := c.Bool("apply") + + f, err := os.Open(filepath.Clean(filename)) + if err != nil { + return err + } + b, err := io.ReadAll(f) + if err != nil { + return err + } + + res := schema.Resource{Value: string(b), Name: filename} + sch, err := load.DistDashboardFamily(paths) + if err != nil { + return fmt.Errorf("error while loading dashboard scuemata, err: %w", err) + } + + var out schema.Resource + if apply { + out, err = schema.ApplyDefaults(res, sch.CUE()) + } else { + out, err = schema.TrimDefaults(res, sch.CUE()) + } + + if err != nil { + return gerrors.New(errors.Details(err, nil)) + } + + b = []byte(out.Value.(string)) + var buf bytes.Buffer + err = json.Indent(&buf, b, "", " ") + if err != nil { + return err + } + fmt.Println(buf.String()) + return nil +}