package cli import ( "context" "flag" "fmt" "strings" "github.com/peterbourgon/ff/v3/ffcli" dashmgr "edge-infra.dev/pkg/lib/gcp/monitoring/dashboardmanager" ) type addArgsT struct { overwrite bool templatePath string validate bool clean bool } var addArgs addArgsT var addFlagSet = newAddFlagSet(&addArgs) func newAddFlagSet(addArgs *addArgsT) *flag.FlagSet { addf := newFlagSet("add") addf.BoolVar(&addArgs.overwrite, "overwrite", false, "Forces the overwrite of dashboards in the project if the specified template contains the same Display Name as an existing one\nNOTE: By default, dashboards will be created with the duplicate name without changing existing dashboards") addf.StringVar(&addArgs.templatePath, "path", "", "Path to dashboard JSON template file or folder containing multiple dashboard JSON templates") addf.BoolVar(&addArgs.validate, "dryrun", false, "Validates the dashboard action without committing the changes.") addf.BoolVar(&addArgs.clean, "clean", false, "Remove unnecessary fields from create dashboard request.\nNOTE: Does not save changes to the template, only strips the fields in the API request.") return addf } var addCmd = &ffcli.Command{ Name: "add", ShortUsage: "add [flags]", ShortHelp: "Add dashboard(s) from JSON template or template folder to project", LongHelp: strings.TrimSpace(` Creates dashboards in the project using JSON templates specified with the required [path] parameter. `), FlagSet: withGlobalFlags(addFlagSet), Exec: runAdd, } func runAdd(ctx context.Context, args []string) error { var err error if len(args) > 0 { Fatalf("too many non-flag arguments: %q", args) } if !checkAddFlags() { Println() return flag.ErrHelp } client, err := dashmgr.New(ctx, projectID) if err != nil { return Errorf("failed to create dashboards service: %w", err) } // Get the dashboard configuration template(s) from the path sourceDashboards, err := dashmgr.ReadDashboardsFromPath(tPath) if err != nil { return Errorf("failed to read dashboard configuration from file: %w", err) } for i := 0; i < len(sourceDashboards); i++ { if client.DisplayNameExists(sourceDashboards[i].DisplayName) { // TODO: remove duplicate name if overwrite specified return fmt.Errorf("%s dashboard already exists in project %s", sourceDashboards[i].DisplayName, projectID) } err := client.CreateDashboard(sourceDashboards[i], addArgs.validate) if err != nil { return err } } return nil } // validates the required add subcommand flags have been provided func checkAddFlags() bool { if len(projectID) == 0 { Println("Error: no value specified for [project] - a valid project-id is required") return false } if len(addArgs.templatePath) == 0 { Println("Error: no value specified for [path] - a valid template source file or folder path is required") return false } if !checkPath(addArgs.templatePath, false) { Printf("Error: invalid template [path] specified - %s\n", addArgs.templatePath) return false } return true }