From c267b1ae6ecd6c4f6cb59523e7bdf9e63b5664a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Fri, 21 Mar 2025 14:24:05 +0300 Subject: [PATCH] MSP-5014 Try get rid of global service and autocomplete --- bash/autocomplete.go | 84 +++++++++++++++++-------------- command/commands.go | 49 ++++++++++++++---- command/delete.go | 64 ++++++++++++++---------- command/flag/structure.go | 14 ------ command/get.go | 41 ++++++++------- command/gitget.go | 102 ++++++++++++++++++++------------------ command/merge.go | 75 +++++++++++++++++----------- command/schema.go | 88 +++++++++++++++++--------------- command/set.go | 64 ++++++++++++++---------- command/status.go | 69 ++++++++++++++------------ command/utils/config.go | 9 ++-- command/vars.go | 71 ++++++++++++++------------ main.go | 33 +++++++++++- repository/client.go | 4 +- service/config.go | 36 ++++++-------- 15 files changed, 468 insertions(+), 335 deletions(-) diff --git a/bash/autocomplete.go b/bash/autocomplete.go index 2e01ad5..c3b84d5 100644 --- a/bash/autocomplete.go +++ b/bash/autocomplete.go @@ -2,72 +2,82 @@ package bash import ( "fmt" + "ispctl/model" + "ispctl/service" "github.com/urfave/cli/v2" - "ispctl/command/flag" - "ispctl/service" - "github.com/txix-open/bellows" ) const ( - CommonConfigName bashArg = "config_name" - ModuleName bashArg = "module_name" - ModuleData bashArg = "module_data" + CommonConfigName = "config_name" + ModuleName = "module_name" + ModuleData = "module_data" - VariableName bashArg = "variable_name" - Empty bashArg = "empty" + VariableName = "variable_name" + Empty = "empty" ) -type bashArg string - -type bashCommand struct { - first bashArg - second bashArg +type BashService interface { + GetAllVariables() ([]model.Variable, error) + GetAvailableConfigs() ([]model.ModuleInfo, error) + GetConfigurationByModuleName(moduleName string) (*model.Config, error) } -func Get(first bashArg, second bashArg) *bashCommand { - return &bashCommand{ - first: first, - second: second, +type BeforeComplete func(ctx *cli.Context) (service.Config, error) + +type Autocomplete struct { + beforeComplete BeforeComplete + service BashService +} + +func NewAutocomplete(beforeComplete BeforeComplete) Autocomplete { + return Autocomplete{ + beforeComplete: beforeComplete, } } -func (c bashCommand) Complete(ctx *cli.Context) { - err := flag.ApplyGlobalFlags(ctx) - if err != nil { - return +func (c Autocomplete) Complete(first string, second string) cli.BashCompleteFunc { + return func(ctx *cli.Context) { + cfgService, err := c.beforeComplete(ctx) + if err != nil { + return + } + c.service = cfgService + c.complete(ctx, first, second) } +} +func (c Autocomplete) complete(ctx *cli.Context, first string, second string) { switch ctx.NArg() { case 0: - c.completeFirstArg(ctx) + c.completeFirstArg(ctx, first) case 1: - c.completeSecondArg(ctx) + c.completeSecondArg(ctx, second) } } -func (c bashCommand) completeFirstArg(ctx *cli.Context) { - switch c.first { +func (c Autocomplete) completeFirstArg(ctx *cli.Context, first string) { + switch first { case ModuleName: - printAvailableModules() + c.printAvailableModules() case VariableName: - printAvailableVariables() + c.printAvailableVariables() } } -func (c bashCommand) completeSecondArg(ctx *cli.Context) { - switch c.second { +func (c Autocomplete) completeSecondArg(ctx *cli.Context, second string) { + switch second { case ModuleName: - printAvailableModules() + c.printAvailableModules() case ModuleData: - printModuleData(ctx.Args().First()) + c.printModuleData(ctx.Args().First()) } } -func printAvailableVariables() { - vars, err := service.Config.GetAllVariables() +func (c Autocomplete) printAvailableVariables() { + vars, err := c.service.GetAllVariables() if err != nil { return } @@ -76,8 +86,8 @@ func printAvailableVariables() { } } -func printAvailableModules() { - modules, err := service.Config.GetAvailableConfigs() +func (c Autocomplete) printAvailableModules() { + modules, err := c.service.GetAvailableConfigs() if err != nil { return } @@ -86,8 +96,8 @@ func printAvailableModules() { } } -func printModuleData(moduleName string) { - config, err := service.Config.GetConfigurationByModuleName(moduleName) +func (c Autocomplete) printModuleData(moduleName string) { + config, err := c.service.GetConfigurationByModuleName(moduleName) if err != nil { return } diff --git a/command/commands.go b/command/commands.go index da17a21..225846a 100644 --- a/command/commands.go +++ b/command/commands.go @@ -1,16 +1,45 @@ package command -import "github.com/urfave/cli/v2" +import ( + "ispctl/model" -func AllCommands() []*cli.Command { + "github.com/txix-open/isp-kit/rc/schema" + "github.com/urfave/cli/v2" +) + +type AutoComplete interface { + Complete(first string, second string) cli.BashCompleteFunc +} + +type ConfigService interface { + CreateUpdateConfig(stringToChange string, configuration *model.Config) (map[string]any, error) + CreateUpdateConfigV2(configuration *model.Config) (map[string]any, error) + DeleteVariable(variableName string) error + GetAllVariables() ([]model.Variable, error) + GetAvailableConfigs() ([]model.ModuleInfo, error) + GetConfigurationByModuleName(moduleName string) (*model.Config, error) + GetSchemaByModuleId(moduleId string) (schema.Schema, error) + GetVariableByName(variableName string) (*model.Variable, error) + UpsertVariables(vars []model.UpsertVariableRequest) error +} + +func AllCommands(configService ConfigService, autoComplete AutoComplete) []*cli.Command { + status := NewStatus(configService) + get := NewGet(configService, autoComplete) + set := NewSet(configService, autoComplete) + delete := NewDelete(configService, autoComplete) + schema := NewSchema(configService, autoComplete) + merge := NewMerge(configService, autoComplete) + gitGet := NewGitGet() + variables := NewVariables(configService, autoComplete) return []*cli.Command{ - Status(), - Get(), - Set(), - Delete(), - Schema(), - Merge(), - GitGet(), - VariablesCommands(), + status.Command(), + get.Command(), + set.Command(), + delete.Command(), + schema.Command(), + merge.Command(), + gitGet.Command(), + variables.Command(), } } diff --git a/command/delete.go b/command/delete.go index 70d59ce..fe0dd0f 100644 --- a/command/delete.go +++ b/command/delete.go @@ -4,33 +4,44 @@ import ( "encoding/json" "ispctl/bash" - "ispctl/command/flag" "ispctl/command/utils" - "ispctl/service" + "ispctl/model" "github.com/tidwall/sjson" "github.com/urfave/cli/v2" ) -func Delete() *cli.Command { - return &cli.Command{ - Name: "delete", - Usage: "delete configuration by module_name", - Before: flag.ApplyGlobalFlags, - Action: deleteComm.action, - BashComplete: bash.Get(bash.ModuleName, bash.ModuleData).Complete, +type DeleteService interface { + GetConfigurationByModuleName(moduleName string) (*model.Config, error) + CreateUpdateConfig(stringToChange string, configuration *model.Config) (map[string]any, error) +} + +type Delete struct { + service DeleteService + autoComplete AutoComplete +} + +func NewDelete(service DeleteService, autoComplete AutoComplete) Delete { + return Delete{ + service: service, + autoComplete: autoComplete, } } -var deleteComm deleteCommand +func (c Delete) Command() *cli.Command { + return &cli.Command{ + Name: "delete", + Usage: "delete configuration by module_name", + Action: c.action, + BashComplete: c.autoComplete.Complete(bash.ModuleName, bash.ModuleData), + } +} -type deleteCommand struct{} - -func (d deleteCommand) action(ctx *cli.Context) error { +func (c Delete) action(ctx *cli.Context) error { moduleName := ctx.Args().First() pathObject := ctx.Args().Get(1) - moduleConfiguration, err := service.Config.GetConfigurationByModuleName(moduleName) + moduleConfiguration, err := c.service.GetConfigurationByModuleName(moduleName) if err != nil { return err } @@ -39,19 +50,18 @@ func (d deleteCommand) action(ctx *cli.Context) error { if err != nil { return err } - if pathObject == "" { - return utils.CreateUpdateConfig("", moduleConfiguration) - } else { - jsonObject, err := json.Marshal(moduleConfiguration.Data) - if err != nil { - return err - } - - if stringToChange, err := sjson.Delete(string(jsonObject), pathObject); err != nil { - return err - } else { - return utils.CreateUpdateConfig(stringToChange, moduleConfiguration) - } + return utils.CreateUpdateConfig("", moduleConfiguration, c.service) } + + jsonObject, err := json.Marshal(moduleConfiguration.Data) + if err != nil { + return err + } + stringToChange, err := sjson.Delete(string(jsonObject), pathObject) + if err != nil { + return err + } + + return utils.CreateUpdateConfig(stringToChange, moduleConfiguration, c.service) } diff --git a/command/flag/structure.go b/command/flag/structure.go index 5cc0cb0..b5fd06b 100644 --- a/command/flag/structure.go +++ b/command/flag/structure.go @@ -1,10 +1,6 @@ package flag import ( - "strings" - - "ispctl/service" - "github.com/urfave/cli/v2" ) @@ -24,13 +20,3 @@ var ( SetVariableSecretType = &cli.BoolFlag{Name: secretVariableName, Usage: secretVariableUsage} ) - -func ApplyGlobalFlags(c *cli.Context) error { - var host string - service.Config.UnsafeEnable = c.Bool(Unsafe.Name) - - host = c.String(Host.Name) - host = strings.Replace(host, "'", "", -1) - - return service.Config.ReceiveConfiguration(host) -} diff --git a/command/get.go b/command/get.go index c71e903..50ee8b9 100644 --- a/command/get.go +++ b/command/get.go @@ -4,35 +4,42 @@ import ( "encoding/json" "ispctl/bash" - "ispctl/command/flag" "ispctl/command/utils" - "ispctl/service" + "ispctl/model" "github.com/urfave/cli/v2" ) -func Get() *cli.Command { - return &cli.Command{ - Name: "get", - Usage: "get configuration by module_name", - Before: flag.ApplyGlobalFlags, - Action: get.action, - BashComplete: bash.Get(bash.ModuleName, bash.ModuleData).Complete, +type GetService interface { + GetConfigurationByModuleName(moduleName string) (*model.Config, error) +} + +type Get struct { + service SetService + autoComplete AutoComplete +} + +func NewGet(service SetService, autoComplete AutoComplete) Get { + return Get{ + service: service, + autoComplete: autoComplete, } } -var get getCommand - -type getCommand struct{} - -func (g getCommand) action(ctx *cli.Context) error { - if err := flag.ApplyGlobalFlags(ctx); err != nil { - return err +func (c Get) Command() *cli.Command { + return &cli.Command{ + Name: "get", + Usage: "get configuration by module_name", + Action: c.action, + BashComplete: c.autoComplete.Complete(bash.ModuleName, bash.ModuleData), } +} + +func (c Get) action(ctx *cli.Context) error { moduleName := ctx.Args().First() pathObject := ctx.Args().Get(1) - config, err := service.Config.GetConfigurationByModuleName(moduleName) + config, err := c.service.GetConfigurationByModuleName(moduleName) if err != nil { return err } diff --git a/command/gitget.go b/command/gitget.go index 3d51d0c..11ec47b 100644 --- a/command/gitget.go +++ b/command/gitget.go @@ -13,57 +13,65 @@ import ( "github.com/urfave/cli/v2" ) -var ( - semverRegexp = regexp.MustCompile(`v([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$`) -) +type GitGet struct { + semverRegexp *regexp.Regexp +} -func GitGet() *cli.Command { +func NewGitGet() GitGet { + return GitGet{ + semverRegexp: regexp.MustCompile(`v([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$`), + } +} + +func (c GitGet) Command() *cli.Command { return &cli.Command{ Name: "gitget", Usage: "gitget [repository] [file] (commit|tag)", Description: "clone and print specified file from specified repository and specified commit hash or tag", - Action: func(context *cli.Context) error { - storage := memory.NewStorage() - repo := context.Args().Get(0) - - file := context.Args().Get(1) - commit := context.Args().Get(2) - - repository, err := git.Clone(storage, memfs.New(), &git.CloneOptions{ - URL: repo, - }) - if err != nil { - return errors.WithMessagef(err, "clone %s", repo) - } - tree, err := repository.Worktree() - if err != nil { - return errors.WithMessage(err, "get worktree") - } - - if commit != "" { - checkoutOpts := git.CheckoutOptions{} - if semverRegexp.MatchString(commit) { - checkoutOpts.Branch = plumbing.NewTagReferenceName(commit) - } else { - checkoutOpts.Hash = plumbing.NewHash(commit) - } - err = tree.Checkout(&checkoutOpts) - if err != nil { - return errors.WithMessagef(err, "checkout: %s", commit) - } - } - - f, err := tree.Filesystem.Open(file) - if err != nil { - return errors.WithMessagef(err, "open %s", file) - } - - _, err = io.Copy(os.Stdout, f) - if err != nil { - return err - } - - return nil - }, + Action: c.action, } } + +func (c GitGet) action(ctx *cli.Context) error { + storage := memory.NewStorage() + repo := ctx.Args().Get(0) + + file := ctx.Args().Get(1) + commit := ctx.Args().Get(2) + + repository, err := git.Clone(storage, memfs.New(), &git.CloneOptions{ + URL: repo, + }) + if err != nil { + return errors.WithMessagef(err, "clone %s", repo) + } + tree, err := repository.Worktree() + if err != nil { + return errors.WithMessage(err, "get worktree") + } + + if commit != "" { + checkoutOpts := git.CheckoutOptions{} + if c.semverRegexp.MatchString(commit) { + checkoutOpts.Branch = plumbing.NewTagReferenceName(commit) + } else { + checkoutOpts.Hash = plumbing.NewHash(commit) + } + err = tree.Checkout(&checkoutOpts) + if err != nil { + return errors.WithMessagef(err, "checkout: %s", commit) + } + } + + f, err := tree.Filesystem.Open(file) + if err != nil { + return errors.WithMessagef(err, "open %s", file) + } + + _, err = io.Copy(os.Stdout, f) + if err != nil { + return err + } + + return nil +} diff --git a/command/merge.go b/command/merge.go index 13fbe85..bbe64aa 100644 --- a/command/merge.go +++ b/command/merge.go @@ -5,43 +5,60 @@ import ( "os" "ispctl/bash" - "ispctl/command/flag" "ispctl/command/utils" - "ispctl/service" + "ispctl/model" "github.com/pkg/errors" "github.com/urfave/cli/v2" ) -func Merge() *cli.Command { +type MergeService interface { + GetConfigurationByModuleName(moduleName string) (*model.Config, error) + CreateUpdateConfigV2(configuration *model.Config) (map[string]any, error) +} + +type Merge struct { + service MergeService + autoComplete AutoComplete +} + +func NewMerge(service MergeService, autoComplete AutoComplete) Merge { + return Merge{ + service: service, + autoComplete: autoComplete, + } +} + +func (c Merge) Command() *cli.Command { return &cli.Command{ Name: "merge", Usage: "merge actual config with config from stdin", - BashComplete: bash.Get(bash.CommonConfigName, bash.Empty).Complete, - Before: flag.ApplyGlobalFlags, - Action: func(context *cli.Context) error { - moduleName := context.Args().First() - config, err := service.Config.GetConfigurationByModuleName(moduleName) - if err != nil { - return errors.WithMessagef(err, "get module config '%s'", moduleName) - } - - inputConfig := make(map[string]any) - err = json.NewDecoder(os.Stdin).Decode(&inputConfig) - if err != nil { - return errors.WithMessage(err, "json unmarshal input config") - } - for key, value := range inputConfig { - config.Data[key] = value - } - - result, err := service.Config.CreateUpdateConfigV2(config) - if err != nil { - return errors.WithMessagef(err, "update module config '%s'", moduleName) - } - utils.PrintAnswer(result) - - return nil - }, + BashComplete: c.autoComplete.Complete(bash.CommonConfigName, bash.Empty), + Action: c.action, } } + +func (c Merge) action(ctx *cli.Context) error { + moduleName := ctx.Args().First() + config, err := c.service.GetConfigurationByModuleName(moduleName) + if err != nil { + return errors.WithMessagef(err, "get module config '%s'", moduleName) + } + + inputConfig := make(map[string]any) + err = json.NewDecoder(os.Stdin).Decode(&inputConfig) + if err != nil { + return errors.WithMessage(err, "json unmarshal input config") + } + for key, value := range inputConfig { + config.Data[key] = value + } + + result, err := c.service.CreateUpdateConfigV2(config) + if err != nil { + return errors.WithMessagef(err, "update module config '%s'", moduleName) + } + utils.PrintAnswer(result) + + return nil +} diff --git a/command/schema.go b/command/schema.go index e1c4720..4df2b20 100644 --- a/command/schema.go +++ b/command/schema.go @@ -7,36 +7,50 @@ import ( "ispctl/bash" "ispctl/command/flag" "ispctl/command/utils" - "ispctl/service" + "ispctl/model" "ispctl/tmpl" "github.com/pkg/errors" + "github.com/txix-open/isp-kit/rc/schema" "github.com/urfave/cli/v2" ) -func Schema() *cli.Command { - return &cli.Command{ - Name: "schema", - Usage: "get schema configuration by module_name", - Before: flag.ApplyGlobalFlags, - Action: schema.action, - Flags: []cli.Flag{ - flag.OutPrintSchema, - }, - BashComplete: bash.Get(bash.ModuleName, bash.Empty).Complete, +type SchemaService interface { + GetConfigurationByModuleName(moduleName string) (*model.Config, error) + GetSchemaByModuleId(moduleId string) (schema.Schema, error) +} + +type Schema struct { + service SchemaService + autoComplete AutoComplete +} + +func NewSchema(service SchemaService, autoComplete AutoComplete) Schema { + return Schema{ + service: service, + autoComplete: autoComplete, } } -var schema schemaCommand - -type schemaCommand struct{} - -func (s schemaCommand) action(ctx *cli.Context) error { - moduleName := ctx.Args().First() - schemaConfig := s.getSchemaConfig(moduleName) - if schemaConfig == nil { - return nil +func (c Schema) Command() *cli.Command { + return &cli.Command{ + Name: "schema", + Usage: "get schema configuration by module_name", + Action: c.action, + Flags: []cli.Flag{ + flag.OutPrintSchema, + }, + BashComplete: c.autoComplete.Complete(bash.ModuleName, bash.Empty), } +} + +func (c Schema) action(ctx *cli.Context) error { + moduleName := ctx.Args().First() + schemaConfig, err := c.getSchemaConfig(moduleName) + if err != nil { + return err + } + schema := make(map[string]any) schema["title"] = moduleName schema["schema"] = schemaConfig @@ -44,33 +58,29 @@ func (s schemaCommand) action(ctx *cli.Context) error { case flag.OutPrintJsonValue: utils.PrintAnswer(schema) case flag.OutPrintHtmlValue: - s.printHtml(schema) + return c.printHtml(schema) default: return errors.Errorf("invalid flag value, expected [%s] or [%s]", flag.OutPrintJsonValue, flag.OutPrintHtmlValue) } return nil } -func (s schemaCommand) getSchemaConfig(moduleName string) any { - if configuration, err := service.Config.GetConfigurationByModuleName(moduleName); err != nil { - utils.PrintError(err) - return nil - } else if schema, err := service.Config.GetSchemaByModuleId(configuration.ModuleId); err != nil { - utils.PrintError(err) - return nil - } else { - return schema +func (c Schema) getSchemaConfig(moduleName string) (schema.Schema, error) { + configuration, err := c.service.GetConfigurationByModuleName(moduleName) + if err != nil { + return nil, err } + schema, err := c.service.GetSchemaByModuleId(configuration.ModuleId) + if err != nil { + return nil, err + } + return schema, nil } -func (s schemaCommand) printHtml(schema map[string]any) { - if temp, err := template.New("template").Parse(tmpl.HtmlFile); err != nil { - utils.PrintError(err) - return - } else { - if err := temp.ExecuteTemplate(os.Stdout, "template", schema); err != nil { - utils.PrintError(err) - return - } +func (c Schema) printHtml(schema map[string]any) error { + temp, err := template.New("template").Parse(tmpl.HtmlFile) + if err != nil { + return err } + return temp.ExecuteTemplate(os.Stdout, "template", schema) } diff --git a/command/set.go b/command/set.go index 7fb92ea..d02d89c 100644 --- a/command/set.go +++ b/command/set.go @@ -4,34 +4,45 @@ import ( "encoding/json" "ispctl/bash" - "ispctl/command/flag" "ispctl/command/utils" - "ispctl/service" + "ispctl/model" "github.com/tidwall/sjson" "github.com/urfave/cli/v2" ) -func Set() *cli.Command { - return &cli.Command{ - Name: "set", - Usage: "set configuration by module_name", - Before: flag.ApplyGlobalFlags, - Action: set.action, - BashComplete: bash.Get(bash.ModuleName, bash.ModuleData).Complete, +type SetService interface { + GetConfigurationByModuleName(moduleName string) (*model.Config, error) + CreateUpdateConfig(stringToChange string, configuration *model.Config) (map[string]any, error) +} + +type Set struct { + service SetService + autoComplete AutoComplete +} + +func NewSet(service SetService, autoComplete AutoComplete) Set { + return Set{ + service: service, + autoComplete: autoComplete, } } -var set setCommand +func (c Set) Command() *cli.Command { + return &cli.Command{ + Name: "set", + Usage: "set configuration by module_name", + Action: c.action, + BashComplete: c.autoComplete.Complete(bash.ModuleName, bash.ModuleData), + } +} -type setCommand struct{} - -func (s setCommand) action(ctx *cli.Context) error { +func (c Set) action(ctx *cli.Context) error { moduleName := ctx.Args().First() pathObject := ctx.Args().Get(1) changeObject := ctx.Args().Get(2) - config, err := service.Config.GetConfigurationByModuleName(moduleName) + config, err := c.service.GetConfigurationByModuleName(moduleName) if err != nil { return err } @@ -47,18 +58,17 @@ func (s setCommand) action(ctx *cli.Context) error { } if pathObject == "" { - return utils.CreateUpdateConfig(changeObject, config) - } else { - jsonObject, err := json.Marshal(config.Data) - if err != nil { - return err - } - - changeArgument := utils.ParseSetObject(changeObject) - if stringToChange, err := sjson.Set(string(jsonObject), pathObject, changeArgument); err != nil { - return err - } else { - return utils.CreateUpdateConfig(stringToChange, config) - } + return utils.CreateUpdateConfig(changeObject, config, c.service) } + jsonObject, err := json.Marshal(config.Data) + if err != nil { + return err + } + + changeArgument := utils.ParseSetObject(changeObject) + stringToChange, err := sjson.Set(string(jsonObject), pathObject, changeArgument) + if err != nil { + return err + } + return utils.CreateUpdateConfig(stringToChange, config, c.service) } diff --git a/command/status.go b/command/status.go index 0294fc2..7f3737b 100644 --- a/command/status.go +++ b/command/status.go @@ -7,7 +7,7 @@ import ( "ispctl/command/flag" "ispctl/command/utils" - "ispctl/service" + "ispctl/model" "github.com/olekukonko/tablewriter" "github.com/urfave/cli/v2" @@ -22,48 +22,55 @@ const ( tableConnectedStatus = "CONNECTED" ) -func Status() *cli.Command { +type StatusService interface { + GetAvailableConfigs() ([]model.ModuleInfo, error) +} + +type Status struct { + service StatusService +} + +func NewStatus(service StatusService) Status { + return Status{service: service} +} + +func (c Status) Command() *cli.Command { return &cli.Command{ Name: "status", Usage: "get available configs", - Before: flag.ApplyGlobalFlags, - Action: status.action, + Action: c.action, Flags: []cli.Flag{ flag.OutPrintStatus, }, } } -var status statusCommand - -type statusCommand struct{} - -func (statusCommand) action(ctx *cli.Context) error { - if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { +func (c Status) action(ctx *cli.Context) error { + arrayOfModules, err := c.service.GetAvailableConfigs() + if err != nil { return err - } else { - switch ctx.String(flag.OutPrintStatus.Name) { - case flag.OutPrintJsonValue: - utils.PrintAnswer(arrayOfModules) - default: - table := tablewriter.NewWriter(os.Stdout) - table.SetBorders(tablewriter.Border{Left: false, Top: false, Right: false, Bottom: false}) - table.SetHeader([]string{tableHeaderModuleName, tableHeaderStatus, tableHeaderAddresses}) - for _, module := range arrayOfModules { - addresses := "" - connection := tableNotConnectedStatus - instanceList := make([]string, 0, len(module.Status)) - for _, value := range module.Status { - instanceList = append(instanceList, fmt.Sprintf("%s:%s %s", value.Address.IP, value.Address.Port, value.Version)) - } - addresses = strings.Join(instanceList, "\n") - if addresses != "" { - connection = tableConnectedStatus - } - table.Append([]string{module.Name, connection, addresses}) + } + switch ctx.String(flag.OutPrintStatus.Name) { + case flag.OutPrintJsonValue: + utils.PrintAnswer(arrayOfModules) + default: + table := tablewriter.NewWriter(os.Stdout) + table.SetBorders(tablewriter.Border{Left: false, Top: false, Right: false, Bottom: false}) + table.SetHeader([]string{tableHeaderModuleName, tableHeaderStatus, tableHeaderAddresses}) + for _, module := range arrayOfModules { + addresses := "" + connection := tableNotConnectedStatus + instanceList := make([]string, 0, len(module.Status)) + for _, value := range module.Status { + instanceList = append(instanceList, fmt.Sprintf("%s:%s %s", value.Address.IP, value.Address.Port, value.Version)) } - table.Render() + addresses = strings.Join(instanceList, "\n") + if addresses != "" { + connection = tableConnectedStatus + } + table.Append([]string{module.Name, connection, addresses}) } + table.Render() } return nil } diff --git a/command/utils/config.go b/command/utils/config.go index f509f65..2dd6040 100644 --- a/command/utils/config.go +++ b/command/utils/config.go @@ -2,11 +2,14 @@ package utils import ( "ispctl/model" - "ispctl/service" ) -func CreateUpdateConfig(stringToChange string, configuration *model.Config) error { - answer, err := service.Config.CreateUpdateConfig(stringToChange, configuration) +type UpdateConfigService interface { + CreateUpdateConfig(stringToChange string, configuration *model.Config) (map[string]any, error) +} + +func CreateUpdateConfig(stringToChange string, configuration *model.Config, service UpdateConfigService) error { + answer, err := service.CreateUpdateConfig(stringToChange, configuration) if err != nil { return err } else if answer != nil { diff --git a/command/vars.go b/command/vars.go index 2c12557..00fb40f 100644 --- a/command/vars.go +++ b/command/vars.go @@ -7,7 +7,6 @@ import ( "ispctl/command/flag" "ispctl/command/utils" "ispctl/model" - "ispctl/service" "os" "strings" @@ -15,7 +14,26 @@ import ( "github.com/urfave/cli/v2" ) -func VariablesCommands() *cli.Command { +type VariablesService interface { + GetAllVariables() ([]model.Variable, error) + GetVariableByName(variableName string) (*model.Variable, error) + DeleteVariable(variableName string) error + UpsertVariables(vars []model.UpsertVariableRequest) error +} + +type Variables struct { + service VariablesService + autoComplete AutoComplete +} + +func NewVariables(service VariablesService, autoComplete AutoComplete) Variables { + return Variables{ + service: service, + autoComplete: autoComplete, + } +} + +func (c Variables) Command() *cli.Command { return &cli.Command{ Name: "vars", Usage: "manage variables", @@ -23,49 +41,40 @@ func VariablesCommands() *cli.Command { { Name: "get", Usage: "vars get ", - Before: flag.ApplyGlobalFlags, - Action: varsComm.getByName, - BashComplete: bash.Get(bash.VariableName, bash.Empty).Complete, + Action: c.getByName, + BashComplete: c.autoComplete.Complete(bash.VariableName, bash.Empty), }, { Name: "list", Usage: "list all variables", - Before: flag.ApplyGlobalFlags, - Action: varsComm.list, + Action: c.list, }, { Name: "set", Usage: "vars set ", - Before: flag.ApplyGlobalFlags, - Action: varsComm.set, + Action: c.set, Flags: []cli.Flag{ flag.SetVariableSecretType, }, - BashComplete: bash.Get(bash.VariableName, bash.Empty).Complete, + BashComplete: c.autoComplete.Complete(bash.VariableName, bash.Empty), }, { Name: "delete", Usage: "vars delete ", - Before: flag.ApplyGlobalFlags, - Action: varsComm.delete, - BashComplete: bash.Get(bash.VariableName, bash.Empty).Complete, + Action: c.delete, + BashComplete: c.autoComplete.Complete(bash.VariableName, bash.Empty), }, { Name: "upload", Usage: "vars upload ", - Before: flag.ApplyGlobalFlags, - Action: varsComm.upload, + Action: c.upload, }, }, } } -var varsComm varsCommands - -type varsCommands struct{} - -func (g varsCommands) list(ctx *cli.Context) error { - vars, err := service.Config.GetAllVariables() +func (c Variables) list(ctx *cli.Context) error { + vars, err := c.service.GetAllVariables() if err != nil { return err } @@ -84,9 +93,9 @@ func (g varsCommands) list(ctx *cli.Context) error { return nil } -func (g varsCommands) getByName(ctx *cli.Context) error { +func (c Variables) getByName(ctx *cli.Context) error { variableName := ctx.Args().Get(0) - variable, err := service.Config.GetVariableByName(variableName) + variable, err := c.service.GetVariableByName(variableName) if err != nil { return err } @@ -94,33 +103,33 @@ func (g varsCommands) getByName(ctx *cli.Context) error { return nil } -func (g varsCommands) set(ctx *cli.Context) error { +func (c Variables) set(ctx *cli.Context) error { variableName := ctx.Args().Get(0) variableValue := ctx.Args().Get(1) variableType := model.TextVariableType if ctx.Bool(flag.SetVariableSecretType.Name) { variableType = model.SecretVariableType } - return service.Config.UpsertVariables([]model.UpsertVariableRequest{{ + return c.service.UpsertVariables([]model.UpsertVariableRequest{{ Name: variableName, Value: variableValue, Type: variableType, }}) } -func (g varsCommands) delete(ctx *cli.Context) error { - return service.Config.DeleteVariable(ctx.Args().Get(0)) +func (c Variables) delete(ctx *cli.Context) error { + return c.service.DeleteVariable(ctx.Args().Get(0)) } -func (g varsCommands) upload(ctx *cli.Context) error { - variables, err := g.readVariablesFromCsv(ctx.Args().First()) +func (c Variables) upload(ctx *cli.Context) error { + variables, err := c.readVariablesFromCsv(ctx.Args().First()) if err != nil { return err } - return service.Config.UpsertVariables(variables) + return c.service.UpsertVariables(variables) } -func (g varsCommands) readVariablesFromCsv(filepath string) ([]model.UpsertVariableRequest, error) { +func (c Variables) readVariablesFromCsv(filepath string) ([]model.UpsertVariableRequest, error) { file, err := os.Open(filepath) if err != nil { return nil, fmt.Errorf("failed to open file %s: %w", filepath, err) diff --git a/main.go b/main.go index e8207b6..400c673 100644 --- a/main.go +++ b/main.go @@ -4,9 +4,13 @@ import ( "fmt" "log" "os" + "strings" + "ispctl/bash" "ispctl/command" "ispctl/command/flag" + "ispctl/repository" + "ispctl/service" "github.com/urfave/cli/v2" ) @@ -27,7 +31,20 @@ func initCommands() { flag.Unsafe, } app.EnableBashCompletion = true - app.Commands = command.AllCommands() + + var configService service.Config + var autoComplete bash.Autocomplete + app.Before = func(ctx *cli.Context) error { + service, err := configServiceFromGlobalFlags(ctx) + if err != nil { + return err + } + configService = service + return nil + } + autoComplete = bash.NewAutocomplete(configServiceFromGlobalFlags) + app.Commands = command.AllCommands(&configService, autoComplete) + app.BashComplete = func(context *cli.Context) { for _, appCommand := range app.Commands { fmt.Println(appCommand.Name) @@ -39,3 +56,17 @@ func initCommands() { log.Fatal(err) } } + +func configServiceFromGlobalFlags(ctx *cli.Context) (service.Config, error) { + enableUnsafe := ctx.Bool(flag.Unsafe.Name) + + host := ctx.String(flag.Host.Name) + host = strings.Replace(host, "'", "", -1) + + configCli, err := repository.NewGrpcClientWithHost(host) + if err != nil { + return service.Config{}, err + } + configRepo := repository.NewConfig(configCli) + return service.NewConfig(enableUnsafe, configRepo), nil +} diff --git a/repository/client.go b/repository/client.go index c3046fc..84fb37e 100644 --- a/repository/client.go +++ b/repository/client.go @@ -4,11 +4,11 @@ import ( "github.com/txix-open/isp-kit/grpc/client" ) -func NewClientFromHost(address string) (*client.Client, error) { +func NewGrpcClientWithHost(host string) (*client.Client, error) { cli, err := client.Default() if err != nil { return nil, err } - cli.Upgrade([]string{address}) + cli.Upgrade([]string{host}) return cli, nil } diff --git a/service/config.go b/service/config.go index 3bb92ec..f788c3a 100644 --- a/service/config.go +++ b/service/config.go @@ -10,27 +10,23 @@ import ( "github.com/txix-open/isp-kit/rc/schema" ) -var Config = &ConfigService{} - -type ConfigService struct { - UnsafeEnable bool +type Config struct { + enableUnsafe bool configRepo repository.Config } -func (c *ConfigService) ReceiveConfiguration(host string) error { - cli, err := repository.NewClientFromHost(host) - if err != nil { - return err +func NewConfig(enableUnsafe bool, configRepo repository.Config) Config { + return Config{ + enableUnsafe: enableUnsafe, + configRepo: configRepo, } - c.configRepo = repository.NewConfig(cli) - return nil } -func (c *ConfigService) GetAvailableConfigs() ([]model.ModuleInfo, error) { +func (c Config) GetAvailableConfigs() ([]model.ModuleInfo, error) { return c.configRepo.GetAvailableConfigs() } -func (c *ConfigService) GetConfigurationByModuleName(moduleName string) (*model.Config, error) { +func (c Config) GetConfigurationByModuleName(moduleName string) (*model.Config, error) { if moduleName == "" { return nil, errors.New("need module name") } @@ -44,7 +40,7 @@ func (c *ConfigService) GetConfigurationByModuleName(moduleName string) (*model. } } -func (c *ConfigService) GetSchemaByModuleId(moduleId string) (schema.Schema, error) { +func (c Config) GetSchemaByModuleId(moduleId string) (schema.Schema, error) { configSchema, err := c.configRepo.GetSchemaByModuleId(moduleId) if err != nil { return nil, err @@ -52,7 +48,7 @@ func (c *ConfigService) GetSchemaByModuleId(moduleId string) (schema.Schema, err return configSchema.Schema, nil } -func (c *ConfigService) CreateUpdateConfig(stringToChange string, configuration *model.Config) (map[string]any, error) { +func (c Config) CreateUpdateConfig(stringToChange string, configuration *model.Config) (map[string]any, error) { newData := make(map[string]any) if stringToChange != "" { err := json.Unmarshal([]byte(stringToChange), &newData) @@ -65,8 +61,8 @@ func (c *ConfigService) CreateUpdateConfig(stringToChange string, configuration return c.CreateUpdateConfigV2(configuration) } -func (c *ConfigService) CreateUpdateConfigV2(configuration *model.Config) (map[string]any, error) { - configuration.Unsafe = c.UnsafeEnable +func (c Config) CreateUpdateConfigV2(configuration *model.Config) (map[string]any, error) { + configuration.Unsafe = c.enableUnsafe resp, err := c.configRepo.CreateUpdateConfig(*configuration) if err != nil { return nil, err @@ -74,11 +70,11 @@ func (c *ConfigService) CreateUpdateConfigV2(configuration *model.Config) (map[s return resp.Data, nil } -func (c *ConfigService) GetAllVariables() ([]model.Variable, error) { +func (c Config) GetAllVariables() ([]model.Variable, error) { return c.configRepo.GetAllVariables() } -func (c *ConfigService) GetVariableByName(variableName string) (*model.Variable, error) { +func (c Config) GetVariableByName(variableName string) (*model.Variable, error) { if variableName == "" { return nil, errors.New("need variable name") } @@ -94,7 +90,7 @@ func (c *ConfigService) GetVariableByName(variableName string) (*model.Variable, } } -func (c *ConfigService) DeleteVariable(variableName string) error { +func (c Config) DeleteVariable(variableName string) error { if variableName == "" { return errors.New("need variable name") } @@ -108,6 +104,6 @@ func (c *ConfigService) DeleteVariable(variableName string) error { } } -func (c *ConfigService) UpsertVariables(vars []model.UpsertVariableRequest) error { +func (c Config) UpsertVariables(vars []model.UpsertVariableRequest) error { return c.configRepo.UpsertVariables(vars) }