diff --git a/bash/autocomplete.go b/bash/autocomplete.go index 9ff97b3..d7b5138 100644 --- a/bash/autocomplete.go +++ b/bash/autocomplete.go @@ -13,7 +13,9 @@ const ( CommonConfigName bashArg = "config_name" ModuleName bashArg = "module_name" ModuleData bashArg = "module_data" - Empty bashArg = "empty" + + VariableName bashArg = "variable_name" + Empty bashArg = "empty" ) type bashArg string @@ -34,36 +36,59 @@ func (c bashCommand) Complete(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { return } + switch ctx.NArg() { case 0: - switch c.first { - case ModuleName: - if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - return - } else { - for _, module := range arrayOfModules { - fmt.Println(module.Name) - } - } - } + c.completeFirstArg(ctx) case 1: - switch c.second { - case ModuleName: - if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - return - } else { - for _, module := range arrayOfModules { - fmt.Println(module.Name) - } - } - case ModuleData: - if moduleConfiguration, err := service.Config.GetConfigurationByModuleName(ctx.Args().First()); err != nil { - return - } else { - for key, _ := range bellows.Flatten(moduleConfiguration.Data) { - fmt.Printf(".%v\n", key) - } - } - } + c.completeSecondArg(ctx) + } +} + +func (c bashCommand) completeFirstArg(ctx *cli.Context) { + switch c.first { + case ModuleName: + printAvailableModules() + case VariableName: + printAvailableVariables() + } +} + +func (c bashCommand) completeSecondArg(ctx *cli.Context) { + switch c.second { + case ModuleName: + printAvailableModules() + case ModuleData: + printModuleData(ctx.Args().First()) + } +} + +func printAvailableVariables() { + vars, err := service.Config.GetAllVariables() + if err != nil { + return + } + for _, v := range vars { + fmt.Println(v.Name) + } +} + +func printAvailableModules() { + modules, err := service.Config.GetAvailableConfigs() + if err != nil { + return + } + for _, module := range modules { + fmt.Println(module.Name) + } +} + +func printModuleData(moduleName string) { + config, err := service.Config.GetConfigurationByModuleName(moduleName) + if err != nil { + return + } + for key := range bellows.Flatten(config.Data) { + fmt.Printf(".%v\n", key) } } diff --git a/cfg/client.go b/cfg/client.go index be4c51c..196b203 100644 --- a/cfg/client.go +++ b/cfg/client.go @@ -85,3 +85,56 @@ func (c *ConfigClient) GetSchemaByModuleId(moduleId string) (*ConfigSchema, erro } return response, nil } + +func (c *ConfigClient) GetAllVariables() ([]Variable, error) { + response := make([]Variable, 0) + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + defer cancel() + err := c.cli.Invoke(getAllVariables). + JsonResponseBody(&response). + Do(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "call %s", getAllVariables) + } + return response, nil +} + +func (c *ConfigClient) GetVariableByName(variableName string) (*Variable, error) { + request := VariableByNameRequest{Name: variableName} + response := new(Variable) + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + defer cancel() + err := c.cli.Invoke(getVariableByName). + JsonRequestBody(request). + JsonResponseBody(&response). + Do(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "call %s", getVariableByName) + } + return response, nil +} + +func (c *ConfigClient) UpsertVariables(request []UpsertVariableRequest) error { + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + defer cancel() + err := c.cli.Invoke(upsertVariable). + JsonRequestBody(request). + Do(ctx) + if err != nil { + return errors.WithMessagef(err, "call %s", upsertVariable) + } + return nil +} + +func (c *ConfigClient) DeleteVariable(variableName string) error { + request := VariableByNameRequest{Name: variableName} + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + defer cancel() + err := c.cli.Invoke(deleteVariable). + JsonRequestBody(request). + Do(ctx) + if err != nil { + return errors.WithMessagef(err, "call %s", deleteVariable) + } + return nil +} diff --git a/cfg/method_name.go b/cfg/method_name.go index 86c01e9..01334cc 100644 --- a/cfg/method_name.go +++ b/cfg/method_name.go @@ -5,4 +5,9 @@ const ( getConfigByModuleName = "config/config/get_active_config_by_module_name" createUpdateConfig = "config/config/create_update_config" getSchemaByModuleId = "config/schema/get_by_module_id" + + getAllVariables = "config/variable/all" + getVariableByName = "config/variable/get_by_name" + upsertVariable = "config/variable/upsert" + deleteVariable = "config/variable/delete" ) diff --git a/cfg/variable.go b/cfg/variable.go index 9f91045..ed00f25 100644 --- a/cfg/variable.go +++ b/cfg/variable.go @@ -1,5 +1,12 @@ package cfg +const ( + SecretVariableType = "SECRET" + TextVariableType = "TEXT" + + ErrCodeVariableNotFound = 2006 +) + type Variable struct { Name string Description string @@ -16,7 +23,7 @@ type LinkedConfig struct { type UpsertVariableRequest struct { Name string `validate:"required"` - Description string `validate:"required"` + Description string Type string `validate:"required,oneof=SECRET TEXT"` Value string `validate:"required"` } diff --git a/command/vars.go b/command/vars.go new file mode 100644 index 0000000..50eeb79 --- /dev/null +++ b/command/vars.go @@ -0,0 +1,176 @@ +package command + +import ( + "encoding/csv" + "fmt" + "ispctl/bash" + "ispctl/cfg" + "ispctl/command/utils" + "ispctl/flag" + "ispctl/service" + "os" + "strings" + + "github.com/olekukonko/tablewriter" + "github.com/urfave/cli/v2" +) + +func VariablesCommands() *cli.Command { + return &cli.Command{ + Name: "vars", + Usage: "manage variables", + Subcommands: []*cli.Command{ + { + Name: "get", + Usage: "vars get ", + Action: varsComm.getByName, + BashComplete: bash.Get(bash.VariableName, bash.Empty).Complete, + }, + { + Name: "list", + Usage: "list all variables", + Action: varsComm.list, + }, + { + Name: "set", + Usage: "vars set ", + Action: varsComm.set, + Flags: []cli.Flag{ + flag.SetVariableSecretType, + }, + BashComplete: bash.Get(bash.VariableName, bash.Empty).Complete, + }, + { + Name: "delete", + Usage: "vars delete ", + Action: varsComm.delete, + BashComplete: bash.Get(bash.VariableName, bash.Empty).Complete, + }, + { + Name: "upload", + Usage: "vars upload ", + Action: varsComm.upload, + }, + }, + } +} + +var varsComm varsCommands + +type varsCommands struct{} + +func (g varsCommands) list(ctx *cli.Context) error { + if err := flag.CheckGlobal(ctx); err != nil { + return err + } + + vars, err := service.Config.GetAllVariables() + if err != nil { + return err + } + table := tablewriter.NewWriter(os.Stdout) + table.SetHeader([]string{"Name", "Description", "Type", "Value", "Configs"}) + + for _, v := range vars { + configs := make([]string, 0, len(v.ContainsInConfigs)) + for _, c := range v.ContainsInConfigs { + configs = append(configs, c.Name) + } + table.Append([]string{v.Name, v.Description, v.Type, v.Value, strings.Join(configs, ",")}) + } + + table.SetBorder(true) + table.SetRowLine(true) + table.Render() + return nil +} + +func (g varsCommands) getByName(ctx *cli.Context) error { + if err := flag.CheckGlobal(ctx); err != nil { + return err + } + + variableName := ctx.Args().Get(0) + variable, err := service.Config.GetVariableByName(variableName) + if err != nil { + return err + } + utils.PrintAnswer(variable) + return nil +} + +func (g varsCommands) set(ctx *cli.Context) error { + if err := flag.CheckGlobal(ctx); err != nil { + return err + } + + variableName := ctx.Args().Get(0) + variableValue := ctx.Args().Get(1) + variableType := cfg.TextVariableType + + if ctx.Bool(flag.SetVariableSecretType.Name) { + variableType = cfg.SecretVariableType + } + return service.Config.UpsertVariables([]cfg.UpsertVariableRequest{{ + Name: variableName, + Value: variableValue, + Type: variableType, + }}) +} + +func (g varsCommands) delete(ctx *cli.Context) error { + if err := flag.CheckGlobal(ctx); err != nil { + return err + } + + variableName := ctx.Args().Get(0) + return service.Config.DeleteVariable(variableName) +} + +func (g varsCommands) upload(ctx *cli.Context) error { + if err := flag.CheckGlobal(ctx); err != nil { + return err + } + + filepath := ctx.Args().First() + variables, err := g.readVariablesFromCsv(filepath) + if err != nil { + return err + } + + return service.Config.UpsertVariables(variables) +} + +func (g varsCommands) readVariablesFromCsv(filepath string) ([]cfg.UpsertVariableRequest, error) { + file, err := os.Open(filepath) + if err != nil { + return nil, fmt.Errorf("failed to open file %s: %w", filepath, err) + } + defer file.Close() + + reader := csv.NewReader(file) + reader.TrimLeadingSpace = true + records, err := reader.ReadAll() + if err != nil { + return nil, fmt.Errorf("failed to read CSV file: %w", err) + } + if len(records) < 2 { + return nil, fmt.Errorf("CSV file must have a header and at least one data row") + } + header := records[0] + columnIndexes := map[string]int{} + for i, col := range header { + columnIndexes[strings.ToLower(col)] = i + } + + variables := make([]cfg.UpsertVariableRequest, 0, len(records)-1) + for _, row := range records[1:] { + variables = append(variables, cfg.UpsertVariableRequest{ + Name: row[columnIndexes["name"]], + Type: row[columnIndexes["type"]], + Value: row[columnIndexes["value"]], + Description: row[columnIndexes["description"]], + }) + } + return variables, nil +} diff --git a/flag/description.go b/flag/description.go index 55bce5a..2b96052 100644 --- a/flag/description.go +++ b/flag/description.go @@ -13,11 +13,11 @@ const ( OutPrintJsonValue = "json" OutPrintHtmlValue = "html" - withCommonConfigName = "full" - withCommonConfigUsage = "compile data with common configs" + secretVariableName = "secret" ) var ( outPrintStatusUsage = fmt.Sprintf("out print for status; %s", OutPrintJsonValue) outPrintSchemaUsage = fmt.Sprintf("out print for schema; %s or %s", OutPrintJsonValue, OutPrintHtmlValue) + secretVariableUsage = "set variable as secret" ) diff --git a/flag/structure.go b/flag/structure.go index 992e84e..12a6f27 100644 --- a/flag/structure.go +++ b/flag/structure.go @@ -3,8 +3,9 @@ package flag import ( "strings" - "github.com/urfave/cli/v2" "ispctl/service" + + "github.com/urfave/cli/v2" ) var ( @@ -20,6 +21,8 @@ var ( //---local--- OutPrintStatus = &cli.StringFlag{Name: outPrintName, Usage: outPrintStatusUsage} OutPrintSchema = &cli.StringFlag{Name: outPrintName, Usage: outPrintSchemaUsage, Value: OutPrintJsonValue} + + SetVariableSecretType = &cli.BoolFlag{Name: secretVariableName, Usage: secretVariableUsage} ) func CheckGlobal(c *cli.Context) error { diff --git a/main.go b/main.go index 2fddf48..d6c5aa2 100644 --- a/main.go +++ b/main.go @@ -34,6 +34,7 @@ func initCommands() { command.Schema(), command.Merge(), command.GitGet(), + command.VariablesCommands(), } app.BashComplete = func(context *cli.Context) { for _, appCommand := range app.Commands { diff --git a/service/config.go b/service/config.go index 368989b..9b572bb 100644 --- a/service/config.go +++ b/service/config.go @@ -5,12 +5,14 @@ import ( "fmt" "os" + "ispctl/cfg" + "github.com/pkg/errors" + "github.com/txix-open/isp-kit/grpc/apierrors" "github.com/txix-open/isp-kit/rc/schema" epb "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "ispctl/cfg" ) var Config configService @@ -92,3 +94,33 @@ func (c configService) CreateUpdateConfigV2(configuration *cfg.Config) (map[stri return resp.Data, nil } } + +func (configService) GetAllVariables() ([]cfg.Variable, error) { + return ConfigClient.GetAllVariables() +} + +func (configService) GetVariableByName(variableName string) (*cfg.Variable, error) { + variable, err := ConfigClient.GetVariableByName(variableName) + if err == nil { + return variable, nil + } + + apiError := apierrors.FromError(err) + if apiError != nil && apiError.ErrorCode == cfg.ErrCodeVariableNotFound { + return nil, errors.Errorf("variable [%s] not found", variableName) + } + return nil, err +} + +func (configService) DeleteVariable(variableName string) error { + err := ConfigClient.DeleteVariable(variableName) + apiError := apierrors.FromError(err) + if apiError != nil && apiError.ErrorCode == cfg.ErrCodeVariableNotFound { + return errors.Errorf("variable [%s] not found", variableName) + } + return err +} + +func (configService) UpsertVariables(vars []cfg.UpsertVariableRequest) error { + return ConfigClient.UpsertVariables(vars) +}