From 93071eef5b09e6df7f33ee79d692bd05ed1a0217 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Tue, 29 Oct 2019 16:47:21 +0300 Subject: [PATCH 1/5] add(commands for common configs) --- .version | 2 +- CHANGELOG.md | 2 + cfg/domain.go | 34 +++++++--- cfg/method_name.go | 11 +-- cfg/methods.go | 34 +++++++++- command/common.go | 67 +++++++++---------- command/commonConfig/delete.go | 96 ++++++++++++++++++++++++++ command/commonConfig/get.go | 91 +++++++++++++++++++++++++ command/commonConfig/link.go | 115 +++++++++++++++++++++++++++++++ command/commonConfig/remove.go | 71 ++++++++++++++++++++ command/commonConfig/set.go | 119 +++++++++++++++++++++++++++++++++ command/commonConfig/unlink.go | 117 ++++++++++++++++++++++++++++++++ command/delete.go | 15 +++-- command/get.go | 30 ++------- command/schema.go | 15 +++-- command/set.go | 61 +++-------------- command/status.go | 5 +- command/utils/common.go | 94 ++++++++++++++++++++++++++ command/utils/common_config.go | 14 ++++ command/utils/config.go | 14 ++++ main.go | 1 + service/common.go | 7 +- service/config.go | 63 ++++++++++++----- 23 files changed, 920 insertions(+), 158 deletions(-) create mode 100644 command/commonConfig/delete.go create mode 100644 command/commonConfig/get.go create mode 100644 command/commonConfig/link.go create mode 100644 command/commonConfig/remove.go create mode 100644 command/commonConfig/set.go create mode 100644 command/commonConfig/unlink.go create mode 100644 command/utils/common.go create mode 100644 command/utils/common_config.go create mode 100644 command/utils/config.go diff --git a/.version b/.version index e8ea05d..f0bb29e 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -1.2.4 +1.3.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index bb2560c..486cfbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +## v1.3.0 +* add commands for common configs ## v1.2.4 * migrate invoke to config service ## v1.2.3 diff --git a/cfg/domain.go b/cfg/domain.go index 5160874..a1fd25d 100644 --- a/cfg/domain.go +++ b/cfg/domain.go @@ -7,21 +7,31 @@ import ( ) type getModuleByUuidAndNameRequest struct { - Name string - Uuid string + ModuleName string + Uuid string } type getSchemaByModuleIdRequest struct { - ModuleId int32 + ModuleId string } type Config struct { - Id int64 + Id string + Name string + CommonConfigs []string + Description string + ModuleId string + Version int32 + Active bool + CreatedAt time.Time + UpdatedAt time.Time + Data map[string]interface{} +} + +type CommonConfig struct { + Id string Name string Description string - ModuleId int32 - Version int32 - Active bool CreatedAt time.Time UpdatedAt time.Time Data map[string]interface{} @@ -36,7 +46,7 @@ type Connection struct { } type ModuleInfo struct { - Id int32 + Id string Name string Active bool CreatedAt time.Time @@ -48,10 +58,14 @@ type ModuleInfo struct { } type ConfigSchema struct { - Id int32 + Id string Version string - ModuleId int32 + ModuleId string Schema schema.Schema CreatedAt time.Time UpdatedAt time.Time } + +type deleted struct { + Deleted int +} diff --git a/cfg/method_name.go b/cfg/method_name.go index 62ddeb0..3de4830 100644 --- a/cfg/method_name.go +++ b/cfg/method_name.go @@ -1,8 +1,11 @@ package cfg const ( - getAvailableConfigs = "config/module/get_modules_info" - getConfigByModuleName = "config/config/get_config_by_instance_uuid_and_module_name" - createUpdateConfig = "config/config/create_update_config" - getSchemaByModuleId = "config/schema/get_by_module_id" + getAvailableConfigs = "config/module/get_modules_info" + getConfigByModuleName = "config/config/get_active_config_by_module_name" + createUpdateConfig = "config/config/create_update_config" + getSchemaByModuleId = "config/schema/get_by_module_id" + getCommonConfigs = "config/common_config/get_configs" + createUpdateCommonConfig = "config/common_config/create_update_config" + deleteCommonConfig = "config/common_config/delete_config" ) diff --git a/cfg/methods.go b/cfg/methods.go index 7a64d28..078cfbc 100644 --- a/cfg/methods.go +++ b/cfg/methods.go @@ -53,7 +53,7 @@ func (c *configClient) GetAvailableConfigs() ([]ModuleInfo, error) { } func (c *configClient) GetConfigByModuleName(name string) (*Config, error) { - request := &getModuleByUuidAndNameRequest{Name: name, Uuid: c.instanceUuid} + request := &getModuleByUuidAndNameRequest{ModuleName: name, Uuid: c.instanceUuid} response := new(Config) err := c.cli.Invoke(getConfigByModuleName, callerId, request, response, backend.WithMetadata(c.headers)) if err != nil { @@ -73,7 +73,7 @@ func (c *configClient) CreateUpdateConfig(request Config) (*Config, error) { } } -func (c *configClient) GetSchemaByModuleId(moduleId int32) (*ConfigSchema, error) { +func (c *configClient) GetSchemaByModuleId(moduleId string) (*ConfigSchema, error) { request := &getSchemaByModuleIdRequest{ModuleId: moduleId} response := new(ConfigSchema) err := c.cli.Invoke(getSchemaByModuleId, callerId, &request, response, backend.WithMetadata(c.headers)) @@ -84,6 +84,36 @@ func (c *configClient) GetSchemaByModuleId(moduleId int32) (*ConfigSchema, error } } +func (c *configClient) GetCommonConfigs(req []string) ([]CommonConfig, error) { + response := make([]CommonConfig, 0) + err := c.cli.Invoke(getCommonConfigs, callerId, req, &response, backend.WithMetadata(c.headers)) + if err != nil { + return nil, c.errorHandler(err) + } else { + return response, nil + } +} + +func (c *configClient) CreateUpdateCommonConfig(req CommonConfig) (*CommonConfig, error) { + response := new(CommonConfig) + err := c.cli.Invoke(createUpdateCommonConfig, callerId, req, response, backend.WithMetadata(c.headers)) + if err != nil { + return nil, c.errorHandler(err) + } else { + return response, nil + } +} + +func (c *configClient) DeleteCommonConfig(req []string) (int, error) { + response := new(deleted) + err := c.cli.Invoke(deleteCommonConfig, callerId, req, response, backend.WithMetadata(c.headers)) + if err != nil { + return 0, c.errorHandler(err) + } else { + return response.Deleted, nil + } +} + func (c *configClient) errorHandler(err error) error { errStatus, ok := status.FromError(err) if !ok { diff --git a/command/common.go b/command/common.go index 5cefbfc..0a98384 100644 --- a/command/common.go +++ b/command/common.go @@ -1,49 +1,44 @@ package command import ( - "encoding/json" "fmt" - "github.com/pkg/errors" - "isp-ctl/cfg" - "isp-ctl/service" - "strings" + "github.com/codegangsta/cli" + "isp-ctl/command/commonConfig" ) -func checkPath(pathObject string) (string, error) { - str := strings.Split(pathObject, ".") - pathObject = "" - if len(str) == 1 || str[0] != "" { - return pathObject, errors.New("path must start with '.'") +func CommonConfig() cli.Command { + return cli.Command{ + Name: "common", + Usage: "access to common configs commands", + Action: cc.action, + BashComplete: cc.bachComplete, + Subcommands: []cli.Command{ + commonConfig.Get(), + commonConfig.Set(), + commonConfig.Delete(), + commonConfig.Remove(), + commonConfig.Link(), + commonConfig.UnLink(), + }, } - for key, value := range str { - if key == 0 { - continue +} + +var cc commonConfigCommand + +type commonConfigCommand struct{} + +func (g commonConfigCommand) action(ctx *cli.Context) { + if ctx.Args().First() == "" { + fmt.Print("need use command: ") + for _, comm := range CommonConfig().Subcommands { + fmt.Printf("[%s] ", comm.Name) } - if key == 1 { - pathObject = fmt.Sprintf("%s", value) - continue - } - pathObject = fmt.Sprintf("%s.%s", pathObject, value) - } - return pathObject, nil -} - -func createUpdateConfig(stringToChange string, configuration *cfg.Config) { - if answer, err := service.Config.CreateUpdateConfig(stringToChange, configuration); err != nil { - printError(err) - } else if answer != nil { - printAnswer(answer) + fmt.Printf("\n") } } -func printAnswer(data interface{}) { - if answer, err := json.MarshalIndent(data, "", " "); err != nil { - printError(err) - } else { - service.ColorService.Print(answer) +func (g commonConfigCommand) bachComplete(ctx *cli.Context) { + for _, command := range CommonConfig().Subcommands { + fmt.Println(command.Name) } } - -func printError(err error) { - fmt.Println("ERROR:", err) -} diff --git a/command/commonConfig/delete.go b/command/commonConfig/delete.go new file mode 100644 index 0000000..5fd8416 --- /dev/null +++ b/command/commonConfig/delete.go @@ -0,0 +1,96 @@ +package commonConfig + +import ( + "encoding/json" + "fmt" + "github.com/codegangsta/cli" + "github.com/integration-system/bellows" + "github.com/pkg/errors" + "github.com/tidwall/sjson" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Delete() cli.Command { + return cli.Command{ + Name: "delete", + Usage: "set common configurations", + Action: deleteComm.action, + BashComplete: deleteComm.bashComplete, + } +} + +var deleteComm deleteCommand + +type deleteCommand struct{} + +func (g deleteCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + ccName := ctx.Args().First() + pathObject := ctx.Args().Get(1) + + if ccName == "" { + utils.PrintError(errors.New("empty config name")) + return + } + + pathObject, err := utils.CheckPath(pathObject) + if err != nil { + utils.PrintError(err) + return + } + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[ccName] + if !ok { + utils.PrintError(errors.Errorf("common config %s not found", ccName)) + return + } + + if pathObject == "" { + utils.CreateUpdateCommonConfig("", config) + } else { + jsonObject, err := json.Marshal(config.Data) + if err != nil { + utils.PrintError(err) + return + } + if stringToChange, err := sjson.Delete(string(jsonObject), pathObject); err != nil { + utils.PrintError(err) + } else { + utils.CreateUpdateCommonConfig(stringToChange, config) + } + } +} + +func (g deleteCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if config, ok := commonConfigs[ctx.Args().First()]; ok { + for key, _ := range bellows.Flatten(config.Data) { + fmt.Printf(".%v\n", key) + } + } + } +} diff --git a/command/commonConfig/get.go b/command/commonConfig/get.go new file mode 100644 index 0000000..7f36550 --- /dev/null +++ b/command/commonConfig/get.go @@ -0,0 +1,91 @@ +package commonConfig + +import ( + "encoding/json" + "fmt" + "github.com/codegangsta/cli" + "github.com/integration-system/bellows" + "github.com/pkg/errors" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Get() cli.Command { + return cli.Command{ + Name: "get", + Usage: "get common configurations", + Action: get.action, + BashComplete: get.bashComplete, + } +} + +var get getCommand + +type getCommand struct{} + +func (g getCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + ccName := ctx.Args().First() + pathObject := ctx.Args().Get(1) + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + if ccName == "" { + for name := range commonConfigs { + fmt.Printf("%s ", name) + } + fmt.Println() + return + } + + pathObject, err = utils.CheckPath(pathObject) + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[ccName] + if !ok { + utils.PrintError(errors.Errorf("common config %s not found", ccName)) + return + } + + if pathObject == "" { + utils.PrintAnswer(config.Data) + } else if jsonObject, err := json.Marshal(config.Data); err != nil { + utils.PrintError(err) + } else { + utils.CheckObject(jsonObject, pathObject) + } +} + +func (g getCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if config, ok := commonConfigs[ctx.Args().First()]; ok { + for key, _ := range bellows.Flatten(config.Data) { + fmt.Printf(".%v\n", key) + } + } + } +} diff --git a/command/commonConfig/link.go b/command/commonConfig/link.go new file mode 100644 index 0000000..e2e53cc --- /dev/null +++ b/command/commonConfig/link.go @@ -0,0 +1,115 @@ +package commonConfig + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Link() cli.Command { + return cli.Command{ + Name: "link", + Usage: "link common configurations to module configuration", + Action: link.action, + BashComplete: link.bashComplete, + } +} + +var link linkCommand + +type linkCommand struct{} + +func (g linkCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + moduleName := ctx.Args().Get(1) + + if configName == "" { + utils.PrintError(errors.New("need config name")) + return + } + + if moduleName == "" { + utils.PrintError(errors.New("need module name")) + return + } + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[configName] + if !ok { + utils.PrintError(errors.Errorf("common config %s not found", configName)) + return + } + + moduleConfiguration, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + if err != nil { + utils.PrintError(err) + return + } + + ccIdNameMap := make(map[string]string) + for name, value := range commonConfigs { + ccIdNameMap[value.Id] = name + } + + needLink := true + for _, configId := range moduleConfiguration.CommonConfigs { + if config.Id == configId { + needLink = false + break + } + } + + if needLink { + moduleConfiguration.CommonConfigs = append(moduleConfiguration.CommonConfigs, config.Id) + if linked, err := service.Config.UpdateConfigAndGetLinkCommon(*moduleConfiguration); err != nil { + utils.PrintError(err) + } else { + for _, name := range linked { + fmt.Printf("[%s] ", ccIdNameMap[name]) + } + fmt.Printf("\n") + } + } else { + for _, name := range moduleConfiguration.CommonConfigs { + fmt.Printf("[%s] ", ccIdNameMap[name]) + } + fmt.Printf("\n") + } +} + +func (g linkCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { + return + } else { + for _, module := range arrayOfModules { + fmt.Println(module.Name) + } + } + } +} diff --git a/command/commonConfig/remove.go b/command/commonConfig/remove.go new file mode 100644 index 0000000..ad508af --- /dev/null +++ b/command/commonConfig/remove.go @@ -0,0 +1,71 @@ +package commonConfig + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Remove() cli.Command { + return cli.Command{ + Name: "remove", + Usage: "remove common configurations", + Action: remove.action, + BashComplete: remove.bashComplete, + } +} + +var remove removeCommand + +type removeCommand struct{} + +func (g removeCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + ccName := ctx.Args().First() + + if ccName == "" { + utils.PrintError(errors.New("empty common config name")) + return + } + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[ccName] + if !ok { + utils.PrintError(errors.Errorf("common config %s not found", ccName)) + return + } + + if deleted, err := service.Config.DeleteCommonConfig(config.Id); err != nil { + utils.PrintError(err) + } else { + fmt.Printf("count deleted config: %d\n", deleted) + } +} + +func (g removeCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + } +} diff --git a/command/commonConfig/set.go b/command/commonConfig/set.go new file mode 100644 index 0000000..988501f --- /dev/null +++ b/command/commonConfig/set.go @@ -0,0 +1,119 @@ +package commonConfig + +import ( + "encoding/json" + "fmt" + "github.com/codegangsta/cli" + "github.com/integration-system/bellows" + "github.com/pkg/errors" + "github.com/tidwall/sjson" + "io/ioutil" + "isp-ctl/cfg" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" + "os" +) + +func Set() cli.Command { + return cli.Command{ + Name: "set", + Usage: "set common configurations", + Action: set.action, + BashComplete: set.bashComplete, + } +} + +var set setCommand + +type setCommand struct{} + +func (g setCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + ccName := ctx.Args().First() + pathObject := ctx.Args().Get(1) + changeObject := ctx.Args().Get(2) + + if ccName == "" { + utils.PrintError(errors.New("empty config name")) + return + } + + mapConfigByName, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := mapConfigByName[ccName] + if !ok { + config = cfg.CommonConfig{ + Name: ccName, + } + } + + pathObject, err = utils.CheckPath(pathObject) + if err != nil { + utils.PrintError(err) + return + } + + if changeObject == "" { + bytes, err := ioutil.ReadAll(os.Stdin) + if err != nil { + utils.PrintError(err) + return + } + changeObject = string(bytes) + } + if changeObject == "" { + utils.PrintError(errors.New("expected argument")) + return + } + + if pathObject == "" { + utils.CreateUpdateCommonConfig(changeObject, config) + return + } else { + jsonObject, err := json.Marshal(config.Data) + if err != nil { + utils.PrintError(err) + return + } + + changeArgument := utils.ParseSetObject(changeObject) + if stringToChange, err := sjson.Set(string(jsonObject), pathObject, changeArgument); err != nil { + utils.PrintError(err) + return + } else { + utils.CreateUpdateCommonConfig(stringToChange, config) + return + } + } +} + +func (g setCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if config, ok := commonConfigs[ctx.Args().First()]; ok { + for key, _ := range bellows.Flatten(config.Data) { + fmt.Printf(".%v\n", key) + } + } + } +} diff --git a/command/commonConfig/unlink.go b/command/commonConfig/unlink.go new file mode 100644 index 0000000..0958c2a --- /dev/null +++ b/command/commonConfig/unlink.go @@ -0,0 +1,117 @@ +package commonConfig + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func UnLink() cli.Command { + return cli.Command{ + Name: "unlink", + Usage: "unlink common configurations from module configuration", + Action: unlink.action, + BashComplete: unlink.bashComplete, + } +} + +var unlink unlinkCommand + +type unlinkCommand struct{} + +func (g unlinkCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + moduleName := ctx.Args().Get(1) + + if configName == "" { + utils.PrintError(errors.New("need config name")) + return + } + + if moduleName == "" { + utils.PrintError(errors.New("need module name")) + return + } + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[configName] + if !ok { + utils.PrintError(errors.Errorf("common config %s not found", configName)) + return + } + + moduleConfig, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + if err != nil { + utils.PrintError(err) + return + } + + ccIdNameMap := make(map[string]string) + for name, value := range commonConfigs { + ccIdNameMap[value.Id] = name + } + + needUnlink := false + for i, configId := range moduleConfig.CommonConfigs { + if config.Id == configId { + copy(moduleConfig.CommonConfigs[i:], moduleConfig.CommonConfigs[i+1:]) + moduleConfig.CommonConfigs[len(moduleConfig.CommonConfigs)-1] = "" + moduleConfig.CommonConfigs = moduleConfig.CommonConfigs[:len(moduleConfig.CommonConfigs)-1] + needUnlink = true + break + } + } + + if needUnlink { + if linked, err := service.Config.UpdateConfigAndGetLinkCommon(*moduleConfig); err != nil { + utils.PrintError(err) + } else { + for _, name := range linked { + fmt.Printf("[%s] ", ccIdNameMap[name]) + } + fmt.Printf("\n") + } + } else { + for _, name := range moduleConfig.CommonConfigs { + fmt.Printf("[%s] ", ccIdNameMap[name]) + } + fmt.Printf("\n") + } +} + +func (g unlinkCommand) bashComplete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { + return + } else { + for _, module := range arrayOfModules { + fmt.Println(module.Name) + } + } + } +} diff --git a/command/delete.go b/command/delete.go index 77df5e8..f473455 100644 --- a/command/delete.go +++ b/command/delete.go @@ -4,6 +4,7 @@ import ( "github.com/codegangsta/cli" "github.com/tidwall/sjson" "isp-ctl/bash" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" ) @@ -23,7 +24,7 @@ type deleteCommand struct{} func (d deleteCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } moduleName := ctx.Args().First() @@ -31,24 +32,24 @@ func (d deleteCommand) action(ctx *cli.Context) { moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) if err != nil { - printError(err) + utils.PrintError(err) return } - pathObject, err = checkPath(pathObject) + pathObject, err = utils.CheckPath(pathObject) if err != nil { - printError(err) + utils.PrintError(err) return } if pathObject == "" { - createUpdateConfig("", moduleConfiguration) + utils.CreateUpdateConfig("", moduleConfiguration) } else { if stringToChange, err := sjson.Delete(string(jsonObject), pathObject); err != nil { - printError(err) + utils.PrintError(err) return } else { - createUpdateConfig(stringToChange, moduleConfiguration) + utils.CreateUpdateConfig(stringToChange, moduleConfiguration) } } } diff --git a/command/get.go b/command/get.go index f33ddad..d848f6d 100644 --- a/command/get.go +++ b/command/get.go @@ -1,11 +1,9 @@ package command import ( - "encoding/json" "github.com/codegangsta/cli" - "github.com/pkg/errors" - "github.com/tidwall/gjson" "isp-ctl/bash" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" ) @@ -25,7 +23,7 @@ type getCommand struct{} func (g getCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } moduleName := ctx.Args().First() @@ -33,33 +31,19 @@ func (g getCommand) action(ctx *cli.Context) { moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) if err != nil { - printError(err) + utils.PrintError(err) return } - pathObject, err = checkPath(pathObject) + pathObject, err = utils.CheckPath(pathObject) if err != nil { - printError(err) + utils.PrintError(err) return } if pathObject == "" { - printAnswer(moduleConfiguration.Data) + utils.PrintAnswer(moduleConfiguration.Data) } else { - g.checkObject(jsonObject, pathObject) - } -} - -func (g getCommand) checkObject(jsonObject []byte, depth string) { - jsonString := gjson.Get(string(jsonObject), depth) - if jsonString.Raw == "" { - printError(errors.Errorf("Path '%s' not found\n", depth)) - } else { - var data interface{} - if err := json.Unmarshal([]byte(jsonString.Raw), &data); err != nil { - printError(err) - } else { - printAnswer(data) - } + utils.CheckObject(jsonObject, pathObject) } } diff --git a/command/schema.go b/command/schema.go index e646128..3ec19de 100644 --- a/command/schema.go +++ b/command/schema.go @@ -5,6 +5,7 @@ import ( "github.com/pkg/errors" "html/template" "isp-ctl/bash" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" "isp-ctl/tmpl" @@ -29,7 +30,7 @@ type schemaCommand struct{} func (s schemaCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } moduleName := ctx.Args().First() @@ -40,11 +41,11 @@ func (s schemaCommand) action(ctx *cli.Context) { schema["schema"] = schemaConfig switch ctx.String(flag.OutPrint.Name) { case flag.OutPrintJsonValue: - printAnswer(schema) + utils.PrintAnswer(schema) case flag.OutPrintHtmlValue: s.printHtml(schema) default: - printError(errors.Errorf( + utils.PrintError(errors.Errorf( "invalid flag value, expected %s or %s", flag.OutPrintJsonValue, flag.OutPrintHtmlValue)) } } @@ -52,10 +53,10 @@ func (s schemaCommand) action(ctx *cli.Context) { func (s schemaCommand) getSchemaConfig(moduleName string) interface{} { if configuration, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName); err != nil { - printError(err) + utils.PrintError(err) return nil } else if schema, err := service.Config.GetSchemaByModuleId(configuration.ModuleId); err != nil { - printError(err) + utils.PrintError(err) return nil } else { return schema @@ -64,11 +65,11 @@ func (s schemaCommand) getSchemaConfig(moduleName string) interface{} { func (s schemaCommand) printHtml(schema map[string]interface{}) { if temp, err := template.New("template").Parse(tmpl.HtmlFile); err != nil { - printError(err) + utils.PrintError(err) return } else { if err := temp.ExecuteTemplate(os.Stdout, "template", schema); err != nil { - printError(err) + utils.PrintError(err) return } } diff --git a/command/set.go b/command/set.go index 6595403..fe9fe76 100644 --- a/command/set.go +++ b/command/set.go @@ -1,12 +1,12 @@ package command import ( - "encoding/json" "github.com/codegangsta/cli" "github.com/pkg/errors" "github.com/tidwall/sjson" "io/ioutil" "isp-ctl/bash" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" "os" @@ -27,7 +27,7 @@ type setCommand struct{} func (s setCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } @@ -37,79 +37,40 @@ func (s setCommand) action(ctx *cli.Context) { moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) if err != nil { - printError(err) + utils.PrintError(err) return } - pathObject, err = checkPath(pathObject) + pathObject, err = utils.CheckPath(pathObject) if err != nil { - printError(err) + utils.PrintError(err) return } if changeObject == "" { bytes, err := ioutil.ReadAll(os.Stdin) if err != nil { - printError(err) + utils.PrintError(err) return } changeObject = string(bytes) } if changeObject == "" { - printError(errors.New("expected argument")) + utils.PrintError(errors.New("expected argument")) return } if pathObject == "" { - createUpdateConfig(changeObject, moduleConfiguration) + utils.CreateUpdateConfig(changeObject, moduleConfiguration) return } else { - changeArgument := s.parseObject(changeObject) + changeArgument := utils.ParseSetObject(changeObject) if stringToChange, err := sjson.Set(string(jsonObject), pathObject, changeArgument); err != nil { - printError(err) + utils.PrintError(err) return } else { - createUpdateConfig(stringToChange, moduleConfiguration) + utils.CreateUpdateConfig(stringToChange, moduleConfiguration) return } } } - -func (s setCommand) parseObject(argument string) interface{} { - tryParse := []byte(argument) - if tryParse[0] == '"' && tryParse[len(tryParse)-1] == '"' { - tryParse = tryParse[1 : len(tryParse)-1] - return string(tryParse) - } - - if argument == "null" { - return nil - } - - mapStringInterface := make(map[string]interface{}) - if err := json.Unmarshal(tryParse, &mapStringInterface); err == nil { - return mapStringInterface - } - - arrayOfObject := make([]interface{}, 0) - if err := json.Unmarshal(tryParse, &arrayOfObject); err == nil { - return arrayOfObject - } - - var integer int64 - if err := json.Unmarshal(tryParse, &integer); err == nil { - return integer - } - - var float float64 - if err := json.Unmarshal(tryParse, &float); err == nil { - return float - } - - var flag bool - if err := json.Unmarshal(tryParse, &flag); err == nil { - return flag - } - - return argument -} diff --git a/command/status.go b/command/status.go index 95b9458..db7a375 100644 --- a/command/status.go +++ b/command/status.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/codegangsta/cli" "github.com/olekukonko/tablewriter" + "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" "os" @@ -32,11 +33,11 @@ type statusCommand struct{} func (statusCommand) action(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { - printError(err) + utils.PrintError(err) return } if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - printError(err) + utils.PrintError(err) } else { table := tablewriter.NewWriter(os.Stdout) table.SetBorders(tablewriter.Border{Left: false, Top: false, Right: false, Bottom: false}) diff --git a/command/utils/common.go b/command/utils/common.go new file mode 100644 index 0000000..b5674a7 --- /dev/null +++ b/command/utils/common.go @@ -0,0 +1,94 @@ +package utils + +import ( + "encoding/json" + "fmt" + "github.com/pkg/errors" + "github.com/tidwall/gjson" + "isp-ctl/service" + "strings" +) + +func CheckPath(pathObject string) (string, error) { + str := strings.Split(pathObject, ".") + pathObject = "" + if len(str) == 1 || str[0] != "" { + return pathObject, errors.New("path must start with '.'") + } + for key, value := range str { + if key == 0 { + continue + } + if key == 1 { + pathObject = fmt.Sprintf("%s", value) + continue + } + pathObject = fmt.Sprintf("%s.%s", pathObject, value) + } + return pathObject, nil +} + +func PrintAnswer(data interface{}) { + if answer, err := json.MarshalIndent(data, "", " "); err != nil { + PrintError(err) + } else { + service.ColorService.Print(answer) + } +} + +func PrintError(err error) { + fmt.Println("ERROR:", err) +} + +func ParseSetObject(argument string) interface{} { + tryParse := []byte(argument) + if tryParse[0] == '"' && tryParse[len(tryParse)-1] == '"' { + tryParse = tryParse[1 : len(tryParse)-1] + return string(tryParse) + } + + if argument == "null" { + return nil + } + + mapStringInterface := make(map[string]interface{}) + if err := json.Unmarshal(tryParse, &mapStringInterface); err == nil { + return mapStringInterface + } + + arrayOfObject := make([]interface{}, 0) + if err := json.Unmarshal(tryParse, &arrayOfObject); err == nil { + return arrayOfObject + } + + var integer int64 + if err := json.Unmarshal(tryParse, &integer); err == nil { + return integer + } + + var float float64 + if err := json.Unmarshal(tryParse, &float); err == nil { + return float + } + + var flag bool + if err := json.Unmarshal(tryParse, &flag); err == nil { + return flag + } + + return argument +} + +func CheckObject(jsonObject []byte, depth string) { + jsonString := gjson.Get(string(jsonObject), depth) + if jsonString.Raw == "" { + PrintError(errors.Errorf("path '%s' not found\n", depth)) + } else { + var data interface{} + if err := json.Unmarshal([]byte(jsonString.Raw), &data); err != nil { + PrintError(err) + } else { + PrintAnswer(data) + } + } +} diff --git a/command/utils/common_config.go b/command/utils/common_config.go new file mode 100644 index 0000000..af4780e --- /dev/null +++ b/command/utils/common_config.go @@ -0,0 +1,14 @@ +package utils + +import ( + "isp-ctl/cfg" + "isp-ctl/service" +) + +func CreateUpdateCommonConfig(stringToChange string, configuration cfg.CommonConfig) { + if answer, err := service.Config.CreateUpdateCommonConfig(stringToChange, configuration); err != nil { + PrintError(err) + } else if answer != nil { + PrintAnswer(answer) + } +} diff --git a/command/utils/config.go b/command/utils/config.go new file mode 100644 index 0000000..b18c8df --- /dev/null +++ b/command/utils/config.go @@ -0,0 +1,14 @@ +package utils + +import ( + "isp-ctl/cfg" + "isp-ctl/service" +) + +func CreateUpdateConfig(stringToChange string, configuration *cfg.Config) { + if answer, err := service.Config.CreateUpdateConfig(stringToChange, configuration); err != nil { + PrintError(err) + } else if answer != nil { + PrintAnswer(answer) + } +} diff --git a/main.go b/main.go index 3c78cf2..2746ea3 100644 --- a/main.go +++ b/main.go @@ -41,6 +41,7 @@ func initCommands() { command.Set(), command.Delete(), command.Schema(), + command.CommonConfig(), } app.BashComplete = func(context *cli.Context) { for _, command := range app.Commands { diff --git a/service/common.go b/service/common.go index f446e1a..ff99be4 100644 --- a/service/common.go +++ b/service/common.go @@ -1,6 +1,11 @@ package service -var configPath string +import "isp-ctl/cfg" + +var ( + configClient = cfg.NewConfigClient() + configPath string +) func SetConfigurationPath(path string) { configPath = path diff --git a/service/config.go b/service/config.go index b386d86..79294bb 100644 --- a/service/config.go +++ b/service/config.go @@ -11,28 +11,21 @@ import ( "isp-ctl/cfg" ) -var ( - configClient = cfg.NewConfigClient() - Config = &configService{} -) +var Config configService type configService struct { UnsafeEnable bool } -func (c *configService) ReceiveConfiguration(host, uuid string) error { +func (c configService) ReceiveConfiguration(host, uuid string) error { return configClient.ReceiveConfig(host, uuid) } -func (c *configService) GetAvailableConfigs() ([]cfg.ModuleInfo, error) { - if moduleInfo, err := configClient.GetAvailableConfigs(); err != nil { - return nil, err - } else { - return moduleInfo, nil - } +func (c configService) GetAvailableConfigs() ([]cfg.ModuleInfo, error) { + return configClient.GetAvailableConfigs() } -func (c *configService) GetConfigurationAndJsonByModuleName(moduleName string) (*cfg.Config, []byte, error) { +func (c configService) GetConfigurationAndJsonByModuleName(moduleName string) (*cfg.Config, []byte, error) { if moduleName == "" { return nil, nil, errors.New("need module name") } @@ -52,7 +45,7 @@ func (c *configService) GetConfigurationAndJsonByModuleName(moduleName string) ( } } -func (c *configService) GetSchemaByModuleId(moduleId int32) (schema.Schema, error) { +func (c configService) GetSchemaByModuleId(moduleId string) (schema.Schema, error) { if configSchema, err := configClient.GetSchemaByModuleId(moduleId); err != nil { return nil, err } else { @@ -61,7 +54,7 @@ func (c *configService) GetSchemaByModuleId(moduleId int32) (schema.Schema, erro } } -func (c *configService) CreateUpdateConfig(stringToChange string, configuration *cfg.Config) (map[string]interface{}, error) { +func (c configService) CreateUpdateConfig(stringToChange string, configuration *cfg.Config) (map[string]interface{}, error) { newData := make(map[string]interface{}) if stringToChange != "" { if err := json.Unmarshal([]byte(stringToChange), &newData); err != nil { @@ -83,7 +76,47 @@ func (c *configService) CreateUpdateConfig(stringToChange string, configuration } } -func (c *configService) checkSchema(moduleId int32, object map[string]interface{}) (bool, error) { +func (c configService) UpdateConfigAndGetLinkCommon(configuration cfg.Config) ([]string, error) { + if resp, err := configClient.CreateUpdateConfig(configuration); err != nil { + return nil, err + } else { + return resp.CommonConfigs, nil + } +} + +func (c configService) GetMapCommonConfigByName() (map[string]cfg.CommonConfig, error) { + collection, err := configClient.GetCommonConfigs([]string{}) + if err != nil { + return nil, err + } + response := make(map[string]cfg.CommonConfig) + for _, config := range collection { + response[config.Name] = config + } + return response, nil +} + +func (c configService) CreateUpdateCommonConfig(stringToChange string, config cfg.CommonConfig) (map[string]interface{}, error) { + newData := make(map[string]interface{}) + if stringToChange != "" { + if err := json.Unmarshal([]byte(stringToChange), &newData); err != nil { + return nil, err + } + } + + config.Data = newData + if resp, err := configClient.CreateUpdateCommonConfig(config); err != nil { + return nil, err + } else { + return resp.Data, nil + } +} + +func (c configService) DeleteCommonConfig(configId string) (int, error) { + return configClient.DeleteCommonConfig([]string{configId}) +} + +func (c configService) checkSchema(moduleId string, object map[string]interface{}) (bool, error) { if c.UnsafeEnable { return true, nil } From 1a3458ebddc43b326ee037c8eff38893c271600d Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Tue, 29 Oct 2019 18:06:41 +0300 Subject: [PATCH 2/5] update(ref bash complete) --- bash/autocomplete.go | 52 ----------------------- bash/common_config.go | 75 ++++++++++++++++++++++++++++++++++ bash/module.go | 53 ++++++++++++++++++++++++ command/commonConfig/delete.go | 27 +----------- command/commonConfig/get.go | 26 +----------- command/commonConfig/link.go | 27 +----------- command/commonConfig/remove.go | 19 +-------- command/commonConfig/set.go | 27 +----------- command/commonConfig/unlink.go | 27 +----------- command/delete.go | 2 +- command/get.go | 2 +- command/schema.go | 2 +- command/set.go | 2 +- main.go | 7 ++-- 14 files changed, 148 insertions(+), 200 deletions(-) delete mode 100644 bash/autocomplete.go create mode 100644 bash/common_config.go create mode 100644 bash/module.go diff --git a/bash/autocomplete.go b/bash/autocomplete.go deleted file mode 100644 index 541f307..0000000 --- a/bash/autocomplete.go +++ /dev/null @@ -1,52 +0,0 @@ -package bash - -import ( - "fmt" - "github.com/codegangsta/cli" - "github.com/integration-system/bellows" - "isp-ctl/flag" - "isp-ctl/service" -) - -var ( - ModuleNameAndConfigurationPath = bashAction{enableConfigurationBash: true} - ModuleName = bashAction{enableConfigurationBash: false} -) - -type ( - bashAction struct{ enableConfigurationBash bool } -) - -func (b bashAction) Complete(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - switch ctx.NArg() { - case 0: - b.moduleNameHelper() - case 1: - if b.enableConfigurationBash { - b.configurationPathHelper(ctx.Args().First(), ctx.Args().Get(1)) - } - } -} - -func (bashAction) moduleNameHelper() { - if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - return - } else { - for _, module := range arrayOfModules { - fmt.Println(module.Name) - } - } -} - -func (bashAction) configurationPathHelper(moduleName, path string) { - if moduleConfiguration, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName); err != nil { - return - } else { - for key, _ := range bellows.Flatten(moduleConfiguration.Data) { - fmt.Printf(".%v\n", key) - } - } -} diff --git a/bash/common_config.go b/bash/common_config.go new file mode 100644 index 0000000..2bb43ee --- /dev/null +++ b/bash/common_config.go @@ -0,0 +1,75 @@ +package bash + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/integration-system/bellows" + "isp-ctl/flag" + "isp-ctl/service" +) + +var CommonConfig commonConfig + +type commonConfig struct{} + +func (commonConfig) LinkUnlink(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { + return + } else { + for _, module := range arrayOfModules { + fmt.Println(module.Name) + } + } + } +} + +func (commonConfig) GetSetDelete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + case 1: + if config, ok := commonConfigs[ctx.Args().First()]; ok { + for key, _ := range bellows.Flatten(config.Data) { + fmt.Printf(".%v\n", key) + } + } + } +} + +func (commonConfig) Remove(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + return + } + switch ctx.NArg() { + case 0: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + } +} diff --git a/bash/module.go b/bash/module.go new file mode 100644 index 0000000..cfac811 --- /dev/null +++ b/bash/module.go @@ -0,0 +1,53 @@ +package bash + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/integration-system/bellows" + "isp-ctl/flag" + "isp-ctl/service" +) + +var Module module + +type module struct{} + +func (module) GetSetDelete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + switch ctx.NArg() { + case 0: + if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { + return + } else { + for _, module := range arrayOfModules { + fmt.Println(module.Name) + } + } + case 1: + if moduleConfiguration, _, err := service.Config.GetConfigurationAndJsonByModuleName(ctx.Args().Get(1)); err != nil { + return + } else { + for key, _ := range bellows.Flatten(moduleConfiguration.Data) { + fmt.Printf(".%v\n", key) + } + } + } +} + +func (module) Schema(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + switch ctx.NArg() { + case 0: + if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { + return + } else { + for _, module := range arrayOfModules { + fmt.Println(module.Name) + } + } + } +} diff --git a/command/commonConfig/delete.go b/command/commonConfig/delete.go index 5fd8416..054aaea 100644 --- a/command/commonConfig/delete.go +++ b/command/commonConfig/delete.go @@ -2,11 +2,10 @@ package commonConfig import ( "encoding/json" - "fmt" "github.com/codegangsta/cli" - "github.com/integration-system/bellows" "github.com/pkg/errors" "github.com/tidwall/sjson" + "isp-ctl/bash" "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" @@ -17,7 +16,7 @@ func Delete() cli.Command { Name: "delete", Usage: "set common configurations", Action: deleteComm.action, - BashComplete: deleteComm.bashComplete, + BashComplete: bash.CommonConfig.GetSetDelete, } } @@ -72,25 +71,3 @@ func (g deleteCommand) action(ctx *cli.Context) { } } } - -func (g deleteCommand) bashComplete(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - return - } - switch ctx.NArg() { - case 0: - for _, config := range commonConfigs { - fmt.Println(config.Name) - } - case 1: - if config, ok := commonConfigs[ctx.Args().First()]; ok { - for key, _ := range bellows.Flatten(config.Data) { - fmt.Printf(".%v\n", key) - } - } - } -} diff --git a/command/commonConfig/get.go b/command/commonConfig/get.go index 7f36550..2b3eb3b 100644 --- a/command/commonConfig/get.go +++ b/command/commonConfig/get.go @@ -4,8 +4,8 @@ import ( "encoding/json" "fmt" "github.com/codegangsta/cli" - "github.com/integration-system/bellows" "github.com/pkg/errors" + "isp-ctl/bash" "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" @@ -16,7 +16,7 @@ func Get() cli.Command { Name: "get", Usage: "get common configurations", Action: get.action, - BashComplete: get.bashComplete, + BashComplete: bash.CommonConfig.GetSetDelete, } } @@ -67,25 +67,3 @@ func (g getCommand) action(ctx *cli.Context) { utils.CheckObject(jsonObject, pathObject) } } - -func (g getCommand) bashComplete(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - return - } - switch ctx.NArg() { - case 0: - for _, config := range commonConfigs { - fmt.Println(config.Name) - } - case 1: - if config, ok := commonConfigs[ctx.Args().First()]; ok { - for key, _ := range bellows.Flatten(config.Data) { - fmt.Printf(".%v\n", key) - } - } - } -} diff --git a/command/commonConfig/link.go b/command/commonConfig/link.go index e2e53cc..a30ed53 100644 --- a/command/commonConfig/link.go +++ b/command/commonConfig/link.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/codegangsta/cli" "github.com/pkg/errors" + "isp-ctl/bash" "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" @@ -14,7 +15,7 @@ func Link() cli.Command { Name: "link", Usage: "link common configurations to module configuration", Action: link.action, - BashComplete: link.bashComplete, + BashComplete: bash.CommonConfig.LinkUnlink, } } @@ -89,27 +90,3 @@ func (g linkCommand) action(ctx *cli.Context) { fmt.Printf("\n") } } - -func (g linkCommand) bashComplete(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - return - } - switch ctx.NArg() { - case 0: - for _, config := range commonConfigs { - fmt.Println(config.Name) - } - case 1: - if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - return - } else { - for _, module := range arrayOfModules { - fmt.Println(module.Name) - } - } - } -} diff --git a/command/commonConfig/remove.go b/command/commonConfig/remove.go index ad508af..c9d24b6 100644 --- a/command/commonConfig/remove.go +++ b/command/commonConfig/remove.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/codegangsta/cli" "github.com/pkg/errors" + "isp-ctl/bash" "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" @@ -14,7 +15,7 @@ func Remove() cli.Command { Name: "remove", Usage: "remove common configurations", Action: remove.action, - BashComplete: remove.bashComplete, + BashComplete: bash.CommonConfig.Remove, } } @@ -53,19 +54,3 @@ func (g removeCommand) action(ctx *cli.Context) { fmt.Printf("count deleted config: %d\n", deleted) } } - -func (g removeCommand) bashComplete(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - return - } - switch ctx.NArg() { - case 0: - for _, config := range commonConfigs { - fmt.Println(config.Name) - } - } -} diff --git a/command/commonConfig/set.go b/command/commonConfig/set.go index 988501f..4e35ed8 100644 --- a/command/commonConfig/set.go +++ b/command/commonConfig/set.go @@ -2,12 +2,11 @@ package commonConfig import ( "encoding/json" - "fmt" "github.com/codegangsta/cli" - "github.com/integration-system/bellows" "github.com/pkg/errors" "github.com/tidwall/sjson" "io/ioutil" + "isp-ctl/bash" "isp-ctl/cfg" "isp-ctl/command/utils" "isp-ctl/flag" @@ -20,7 +19,7 @@ func Set() cli.Command { Name: "set", Usage: "set common configurations", Action: set.action, - BashComplete: set.bashComplete, + BashComplete: bash.CommonConfig.GetSetDelete, } } @@ -95,25 +94,3 @@ func (g setCommand) action(ctx *cli.Context) { } } } - -func (g setCommand) bashComplete(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - return - } - switch ctx.NArg() { - case 0: - for _, config := range commonConfigs { - fmt.Println(config.Name) - } - case 1: - if config, ok := commonConfigs[ctx.Args().First()]; ok { - for key, _ := range bellows.Flatten(config.Data) { - fmt.Printf(".%v\n", key) - } - } - } -} diff --git a/command/commonConfig/unlink.go b/command/commonConfig/unlink.go index 0958c2a..9c2a4e3 100644 --- a/command/commonConfig/unlink.go +++ b/command/commonConfig/unlink.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/codegangsta/cli" "github.com/pkg/errors" + "isp-ctl/bash" "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" @@ -14,7 +15,7 @@ func UnLink() cli.Command { Name: "unlink", Usage: "unlink common configurations from module configuration", Action: unlink.action, - BashComplete: unlink.bashComplete, + BashComplete: bash.CommonConfig.LinkUnlink, } } @@ -91,27 +92,3 @@ func (g unlinkCommand) action(ctx *cli.Context) { fmt.Printf("\n") } } - -func (g unlinkCommand) bashComplete(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - return - } - switch ctx.NArg() { - case 0: - for _, config := range commonConfigs { - fmt.Println(config.Name) - } - case 1: - if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - return - } else { - for _, module := range arrayOfModules { - fmt.Println(module.Name) - } - } - } -} diff --git a/command/delete.go b/command/delete.go index f473455..3071682 100644 --- a/command/delete.go +++ b/command/delete.go @@ -14,7 +14,7 @@ func Delete() cli.Command { Name: "delete", Usage: "delete configuration by module_name", Action: deleteComm.action, - BashComplete: bash.ModuleNameAndConfigurationPath.Complete, + BashComplete: bash.Module.GetSetDelete, } } diff --git a/command/get.go b/command/get.go index d848f6d..d8dcf09 100644 --- a/command/get.go +++ b/command/get.go @@ -13,7 +13,7 @@ func Get() cli.Command { Name: "get", Usage: "get configuration by module_name", Action: get.action, - BashComplete: bash.ModuleNameAndConfigurationPath.Complete, + BashComplete: bash.Module.GetSetDelete, } } diff --git a/command/schema.go b/command/schema.go index 3ec19de..7f4b91c 100644 --- a/command/schema.go +++ b/command/schema.go @@ -20,7 +20,7 @@ func Schema() cli.Command { Flags: []cli.Flag{ flag.OutPrint, }, - BashComplete: bash.ModuleName.Complete, + BashComplete: bash.Module.Schema, } } diff --git a/command/set.go b/command/set.go index fe9fe76..9367840 100644 --- a/command/set.go +++ b/command/set.go @@ -17,7 +17,7 @@ func Set() cli.Command { Name: "set", Usage: "set configuration by module_name", Action: set.action, - BashComplete: bash.ModuleNameAndConfigurationPath.Complete, + BashComplete: bash.Module.GetSetDelete, } } diff --git a/main.go b/main.go index 2746ea3..1f6773e 100644 --- a/main.go +++ b/main.go @@ -25,7 +25,8 @@ func initCommands() { ispctl [flag...] get module_name property_path ispctl [flag...] set module_name property_path [new_object] ispctl [flag...] delete module_name property_path - ispctl [flag...] schema module_name [local_flag]` + ispctl [flag...] schema module_name [local_flag] + ispctl [flag...] common ` app.Version = version app.Flags = []cli.Flag{ @@ -44,8 +45,8 @@ func initCommands() { command.CommonConfig(), } app.BashComplete = func(context *cli.Context) { - for _, command := range app.Commands { - fmt.Println(command.Name) + for _, appCommand := range app.Commands { + fmt.Println(appCommand.Name) } } From 8b8815d2f2995bfc8cd7d0c593d5a3ef96c9c914 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 30 Oct 2019 14:58:50 +0300 Subject: [PATCH 3/5] add 'contain' command for common configs add flag 'full' for 'get' command update bash complete --- README.md | 137 ++++++++++++++++++++++++++++++-- bash/common_config.go | 6 +- bash/module.go | 7 +- cfg/domain.go | 16 +++- cfg/method_name.go | 2 + cfg/methods.go | 32 ++++++-- command/common.go | 1 + command/commonConfig/contain.go | 57 +++++++++++++ command/commonConfig/delete.go | 4 +- command/commonConfig/get.go | 4 +- command/commonConfig/link.go | 6 +- command/commonConfig/remove.go | 13 ++- command/commonConfig/set.go | 2 +- command/commonConfig/unlink.go | 6 +- command/delete.go | 11 ++- command/get.go | 23 +++++- command/schema.go | 6 +- command/set.go | 11 ++- flag/description.go | 3 + flag/structure.go | 3 +- service/config.go | 52 +++++++++--- 21 files changed, 348 insertions(+), 54 deletions(-) create mode 100644 command/commonConfig/contain.go diff --git a/README.md b/README.md index b8bc2aa..cb3e70f 100644 --- a/README.md +++ b/README.md @@ -25,11 +25,13 @@ instanceUuid: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ## Использование ```bash ispctl [flag...] status -ispctl [flag...] get module_name property_path +ispctl [flag...] get module_name property_path [local_flag] ispctl [flag...] set module_name property_path [new_object] ispctl [flag...] delete module_name property_path ispctl [flag...] schema module_name [local_flag] +ispctl [flag...] common sub_command ``` + ## Описание | Команды | Описание | @@ -39,6 +41,7 @@ ispctl [flag...] schema module_name [local_flag] | `set` | изменяет объект конфигурации указанного модуля | | `delete` | удаляет объект конфигурации указанного модуля | | `schema` | возвращает схему конфигурации указанного модуля | +| `common` | комманда для взаимодействие с общими конфигурациями | | | | | Флаги | Параметры | Описание | @@ -51,15 +54,37 @@ ispctl [flag...] schema module_name [local_flag] | Аргументы | Описание | |-----------------|-------------------------------------------------------------------------------------------------------------| -| `module_name` | Модуль с которым происходит взаимодействие | +| `module_name` | Название модуля с которым происходит взаимодействие | +| `proprtry_path` | Путь к объекту конфигурации, при значении `.` работа происходит со всей конфигурацией модуля | +| `new_object` | Новый объект, значение должно быть экранировано с помощью `' '`, при отсутсвии ожидается ввод из stdin | +| | | + +| Локальные флаги | Параметры | Команды | Описание | +|-----------------|-----------|---------|---------------------------------------------------------------------------------------------------------------------------------| +| `-o` | string | schema | определяет формат вывода схемы в stdout; по умолчанию `json`; возможные значения `json`, `html` | +| `-full` | bool | get | осуществляет взаимодействие с объектами конфигурации модуля с учетом объектом общих конфигураций, которые имеют связь с модулем | +| | | | | + +### sub_command +#### common +```bash +ispctl [flag...] common set config_name property_path [new_object] +ispctl [flag...] common get [config_name] property_path +ispctl [flag...] common delete config_name property_path +ispctl [flag...] common remove config_name +ispctl [flag...] common link config_name module_name +ispctl [flag...] common unlink config_name module_name +ispctl [flag...] common contain config_name +``` + +| Аргументы | Описание | +|-----------------|-------------------------------------------------------------------------------------------------------------| +| `config_name` | Названия конфига с которым происходит взаимодействие | +| `module_name` | Название модуля с которым происходит взаимодействие | | `proprtry_path` | Путь к объекту конфигурации, при значении `.` работа происходит со всей конфигурацией модуля | | `new_object` | Новый объект, значение должно быть экранировано с помощью `' '`, при отсутсвии ожидается ввод из stdin | | | | -| Локальные флаги | Параметры | Описание | -|-----------------|-----------|--------------------------------------------------------------------------------------------------| -| `-o` | string | определяет формат вывода схемы в stdout; по умолчанию `json`; возможные значения `json`, `html` | -| | | | ## Пример ### ispctl status @@ -318,6 +343,106 @@ ispctl schema example -o html ``` +### ispctl common +#### get +Возвращает список названий общих конфигураций или, если в первом аргументе указано название общей конфигурации, возвращает объект общей конфигурации по указанному пути + +Запрос +```bash +ispctl common get +``` +Ответ +```bash +test b c +``` +Запрос +```bash +ispctl common get test . +``` +Ответ +```bash +{ + "test": null +} +``` +#### set +Добавляет объект в общую конфигурацию по указанному пути + +Запрос +```bash +ispctl common set test .test '{"a":"a","b":"b"}' +``` +Ответ +```bash +{ + "test": { + "a": "a", + "b": "b" + } +} +``` +#### delete +Удаляет объект из общей конфигурации по указанному пути + +Запрос +```bash +ispctl common delete test .test.a +``` +Ответ +```bash +{ + "test": { + "b": "b" + } +} +``` +#### link +Связывает 'common_config' к конфигурации модуля по 'module_name'. Возвращает список общих конфигураций, которые связаны с модулем + +Запрос +```bash +ispctl common link test module_example +``` +Ответ +```bash +[test] [second_common_config] +``` +#### remove +Удаляет объект общий конфигурации, если он не связан с конфигурациями модулей. Если общая конфигурация имеет связи, выводит список модулей с которыми установлена связь + +Запрос +```bash +ispctl common remove test +``` +Ответ +```bash +config [test] not deleted, need unlink in next modules: +[module_example] +``` +#### unlink +Отвязывает 'common_config' от конфигурации модуля по 'module_name'. Возвращает список общих конфигураций, которые связаны с модулем + +Запрос +```bash +ispctl common unlink test module_example +``` +Ответ +Ответ +```bash +[second_common_config] +``` +#### contain +Возвращает список названий модулей, с которыми имеет связь общая конфигурация + +Запрос +```bash +isp-ctl common contain second_common_config +``` +Ответ +Ответ +```bash +[module_example] +``` ### Запрос с флагами Запрос diff --git a/bash/common_config.go b/bash/common_config.go index 2bb43ee..bb31dea 100644 --- a/bash/common_config.go +++ b/bash/common_config.go @@ -12,7 +12,7 @@ var CommonConfig commonConfig type commonConfig struct{} -func (commonConfig) LinkUnlink(ctx *cli.Context) { +func (commonConfig) ConfigName_ModuleName(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { return } @@ -36,7 +36,7 @@ func (commonConfig) LinkUnlink(ctx *cli.Context) { } } -func (commonConfig) GetSetDelete(ctx *cli.Context) { +func (commonConfig) ConfigName_ConfigData(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { return } @@ -58,7 +58,7 @@ func (commonConfig) GetSetDelete(ctx *cli.Context) { } } -func (commonConfig) Remove(ctx *cli.Context) { +func (commonConfig) ConfigName(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { return } diff --git a/bash/module.go b/bash/module.go index cfac811..64f088a 100644 --- a/bash/module.go +++ b/bash/module.go @@ -12,7 +12,7 @@ var Module module type module struct{} -func (module) GetSetDelete(ctx *cli.Context) { +func (module) ModuleName_ModuleData(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { return } @@ -26,7 +26,8 @@ func (module) GetSetDelete(ctx *cli.Context) { } } case 1: - if moduleConfiguration, _, err := service.Config.GetConfigurationAndJsonByModuleName(ctx.Args().Get(1)); err != nil { + moduleConfiguration, err := service.Config.GetConfigurationByModuleName(ctx.Args().Get(1)) + if err != nil { return } else { for key, _ := range bellows.Flatten(moduleConfiguration.Data) { @@ -36,7 +37,7 @@ func (module) GetSetDelete(ctx *cli.Context) { } } -func (module) Schema(ctx *cli.Context) { +func (module) ModuleName(ctx *cli.Context) { if err := flag.CheckGlobal(ctx); err != nil { return } diff --git a/cfg/domain.go b/cfg/domain.go index a1fd25d..4702fe0 100644 --- a/cfg/domain.go +++ b/cfg/domain.go @@ -66,6 +66,18 @@ type ConfigSchema struct { UpdatedAt time.Time } -type deleted struct { - Deleted int +type Deleted struct { + Deleted bool + Links Links +} + +type Links map[string][]string + +type identityRequest struct { + Id string +} + +type CompileConfigs struct { + Data map[string]interface{} + CommonConfigsIdList []string } diff --git a/cfg/method_name.go b/cfg/method_name.go index 3de4830..730a1ad 100644 --- a/cfg/method_name.go +++ b/cfg/method_name.go @@ -8,4 +8,6 @@ const ( getCommonConfigs = "config/common_config/get_configs" createUpdateCommonConfig = "config/common_config/create_update_config" deleteCommonConfig = "config/common_config/delete_config" + getLinksCommonConfig = "config/common_config/get_links" + compileCommonConfigs = "config/common_config/compile" ) diff --git a/cfg/methods.go b/cfg/methods.go index 078cfbc..7f4f0b0 100644 --- a/cfg/methods.go +++ b/cfg/methods.go @@ -104,13 +104,35 @@ func (c *configClient) CreateUpdateCommonConfig(req CommonConfig) (*CommonConfig } } -func (c *configClient) DeleteCommonConfig(req []string) (int, error) { - response := new(deleted) - err := c.cli.Invoke(deleteCommonConfig, callerId, req, response, backend.WithMetadata(c.headers)) +func (c *configClient) DeleteCommonConfig(id string) (*Deleted, error) { + request := identityRequest{Id: id} + response := new(Deleted) + err := c.cli.Invoke(deleteCommonConfig, callerId, request, response, backend.WithMetadata(c.headers)) if err != nil { - return 0, c.errorHandler(err) + return nil, c.errorHandler(err) } else { - return response.Deleted, nil + return response, nil + } +} + +func (c *configClient) GetLinksCommonConfig(id string) (*Links, error) { + request := identityRequest{Id: id} + response := new(Links) + err := c.cli.Invoke(getLinksCommonConfig, callerId, request, response, backend.WithMetadata(c.headers)) + if err != nil { + return nil, c.errorHandler(err) + } else { + return response, nil + } +} + +func (c *configClient) CompileCommonConfigs(request CompileConfigs) (map[string]interface{}, error) { + response := make(map[string]interface{}) + err := c.cli.Invoke(compileCommonConfigs, callerId, request, &response, backend.WithMetadata(c.headers)) + if err != nil { + return nil, c.errorHandler(err) + } else { + return response, nil } } diff --git a/command/common.go b/command/common.go index 0a98384..f20c8b2 100644 --- a/command/common.go +++ b/command/common.go @@ -19,6 +19,7 @@ func CommonConfig() cli.Command { commonConfig.Remove(), commonConfig.Link(), commonConfig.UnLink(), + commonConfig.Contain(), }, } } diff --git a/command/commonConfig/contain.go b/command/commonConfig/contain.go new file mode 100644 index 0000000..4054157 --- /dev/null +++ b/command/commonConfig/contain.go @@ -0,0 +1,57 @@ +package commonConfig + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/pkg/errors" + "isp-ctl/bash" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Contain() cli.Command { + return cli.Command{ + Name: "contain", + Usage: "availability common configuration in module", + Action: contain.action, + BashComplete: bash.CommonConfig.ConfigName, + } +} + +var contain containCommand + +type containCommand struct{} + +func (g containCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + ccName := ctx.Args().First() + + if ccName == "" { + utils.PrintError(errors.New("empty common config name")) + return + } + + commonConfigs, err := service.Config.GetMapCommonConfigByName() + if err != nil { + utils.PrintError(err) + return + } + + config, ok := commonConfigs[ccName] + if !ok { + utils.PrintError(errors.Errorf("common config [%s] not found", ccName)) + return + } + + links, err := service.Config.GetLinksCommonConfig(config.Id) + if err != nil { + utils.PrintError(err) + } else { + fmt.Printf("%v\n", links) + } +} diff --git a/command/commonConfig/delete.go b/command/commonConfig/delete.go index 054aaea..bd4eaf3 100644 --- a/command/commonConfig/delete.go +++ b/command/commonConfig/delete.go @@ -16,7 +16,7 @@ func Delete() cli.Command { Name: "delete", Usage: "set common configurations", Action: deleteComm.action, - BashComplete: bash.CommonConfig.GetSetDelete, + BashComplete: bash.CommonConfig.ConfigName_ConfigData, } } @@ -52,7 +52,7 @@ func (g deleteCommand) action(ctx *cli.Context) { config, ok := commonConfigs[ccName] if !ok { - utils.PrintError(errors.Errorf("common config %s not found", ccName)) + utils.PrintError(errors.Errorf("common config [%s] not found", ccName)) return } diff --git a/command/commonConfig/get.go b/command/commonConfig/get.go index 2b3eb3b..0c1f264 100644 --- a/command/commonConfig/get.go +++ b/command/commonConfig/get.go @@ -16,7 +16,7 @@ func Get() cli.Command { Name: "get", Usage: "get common configurations", Action: get.action, - BashComplete: bash.CommonConfig.GetSetDelete, + BashComplete: bash.CommonConfig.ConfigName_ConfigData, } } @@ -55,7 +55,7 @@ func (g getCommand) action(ctx *cli.Context) { config, ok := commonConfigs[ccName] if !ok { - utils.PrintError(errors.Errorf("common config %s not found", ccName)) + utils.PrintError(errors.Errorf("common config [%s] not found", ccName)) return } diff --git a/command/commonConfig/link.go b/command/commonConfig/link.go index a30ed53..869e879 100644 --- a/command/commonConfig/link.go +++ b/command/commonConfig/link.go @@ -15,7 +15,7 @@ func Link() cli.Command { Name: "link", Usage: "link common configurations to module configuration", Action: link.action, - BashComplete: bash.CommonConfig.LinkUnlink, + BashComplete: bash.CommonConfig.ConfigName_ModuleName, } } @@ -50,11 +50,11 @@ func (g linkCommand) action(ctx *cli.Context) { config, ok := commonConfigs[configName] if !ok { - utils.PrintError(errors.Errorf("common config %s not found", configName)) + utils.PrintError(errors.Errorf("common config [%s] not found", configName)) return } - moduleConfiguration, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + moduleConfiguration, err := service.Config.GetConfigurationByModuleName(moduleName) if err != nil { utils.PrintError(err) return diff --git a/command/commonConfig/remove.go b/command/commonConfig/remove.go index c9d24b6..3f7e288 100644 --- a/command/commonConfig/remove.go +++ b/command/commonConfig/remove.go @@ -15,7 +15,7 @@ func Remove() cli.Command { Name: "remove", Usage: "remove common configurations", Action: remove.action, - BashComplete: bash.CommonConfig.Remove, + BashComplete: bash.CommonConfig.ConfigName, } } @@ -44,13 +44,18 @@ func (g removeCommand) action(ctx *cli.Context) { config, ok := commonConfigs[ccName] if !ok { - utils.PrintError(errors.Errorf("common config %s not found", ccName)) + utils.PrintError(errors.Errorf("common config [%s] not found", ccName)) return } - if deleted, err := service.Config.DeleteCommonConfig(config.Id); err != nil { + links, deleted, err := service.Config.DeleteCommonConfig(config.Id) + if err != nil { utils.PrintError(err) + return + } + if deleted { + fmt.Printf("config [%s] deleted", config.Name) } else { - fmt.Printf("count deleted config: %d\n", deleted) + fmt.Printf("config [%s] not deleted, need unlink in next modules:\n%v\n", config.Name, links) } } diff --git a/command/commonConfig/set.go b/command/commonConfig/set.go index 4e35ed8..c3a544b 100644 --- a/command/commonConfig/set.go +++ b/command/commonConfig/set.go @@ -19,7 +19,7 @@ func Set() cli.Command { Name: "set", Usage: "set common configurations", Action: set.action, - BashComplete: bash.CommonConfig.GetSetDelete, + BashComplete: bash.CommonConfig.ConfigName_ConfigData, } } diff --git a/command/commonConfig/unlink.go b/command/commonConfig/unlink.go index 9c2a4e3..d3977c6 100644 --- a/command/commonConfig/unlink.go +++ b/command/commonConfig/unlink.go @@ -15,7 +15,7 @@ func UnLink() cli.Command { Name: "unlink", Usage: "unlink common configurations from module configuration", Action: unlink.action, - BashComplete: bash.CommonConfig.LinkUnlink, + BashComplete: bash.CommonConfig.ConfigName_ModuleName, } } @@ -50,11 +50,11 @@ func (g unlinkCommand) action(ctx *cli.Context) { config, ok := commonConfigs[configName] if !ok { - utils.PrintError(errors.Errorf("common config %s not found", configName)) + utils.PrintError(errors.Errorf("common config [%s] not found", configName)) return } - moduleConfig, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + moduleConfig, err := service.Config.GetConfigurationByModuleName(moduleName) if err != nil { utils.PrintError(err) return diff --git a/command/delete.go b/command/delete.go index 3071682..d488260 100644 --- a/command/delete.go +++ b/command/delete.go @@ -1,6 +1,7 @@ package command import ( + "encoding/json" "github.com/codegangsta/cli" "github.com/tidwall/sjson" "isp-ctl/bash" @@ -14,7 +15,7 @@ func Delete() cli.Command { Name: "delete", Usage: "delete configuration by module_name", Action: deleteComm.action, - BashComplete: bash.Module.GetSetDelete, + BashComplete: bash.Module.ModuleName_ModuleData, } } @@ -30,7 +31,7 @@ func (d deleteCommand) action(ctx *cli.Context) { moduleName := ctx.Args().First() pathObject := ctx.Args().Get(1) - moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + moduleConfiguration, err := service.Config.GetConfigurationByModuleName(moduleName) if err != nil { utils.PrintError(err) return @@ -45,6 +46,12 @@ func (d deleteCommand) action(ctx *cli.Context) { if pathObject == "" { utils.CreateUpdateConfig("", moduleConfiguration) } else { + jsonObject, err := json.Marshal(moduleConfiguration.Data) + if err != nil { + utils.PrintError(err) + return + } + if stringToChange, err := sjson.Delete(string(jsonObject), pathObject); err != nil { utils.PrintError(err) return diff --git a/command/get.go b/command/get.go index d8dcf09..d14d9ac 100644 --- a/command/get.go +++ b/command/get.go @@ -1,6 +1,7 @@ package command import ( + "encoding/json" "github.com/codegangsta/cli" "isp-ctl/bash" "isp-ctl/command/utils" @@ -13,7 +14,10 @@ func Get() cli.Command { Name: "get", Usage: "get configuration by module_name", Action: get.action, - BashComplete: bash.Module.GetSetDelete, + BashComplete: bash.Module.ModuleName_ModuleData, + Flags: []cli.Flag{ + flag.WithCommonConfig, + }, } } @@ -29,12 +33,20 @@ func (g getCommand) action(ctx *cli.Context) { moduleName := ctx.Args().First() pathObject := ctx.Args().Get(1) - moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + config, err := service.Config.GetConfigurationByModuleName(moduleName) if err != nil { utils.PrintError(err) return } + data := config.Data + if ctx.Bool(flag.WithCommonConfig.Name) { + if data, err = service.Config.CompileDataWithCommonConfigs(data, config.CommonConfigs); err != nil { + utils.PrintError(err) + return + } + } + pathObject, err = utils.CheckPath(pathObject) if err != nil { utils.PrintError(err) @@ -42,8 +54,13 @@ func (g getCommand) action(ctx *cli.Context) { } if pathObject == "" { - utils.PrintAnswer(moduleConfiguration.Data) + utils.PrintAnswer(data) } else { + jsonObject, err := json.Marshal(data) + if err != nil { + utils.PrintError(err) + return + } utils.CheckObject(jsonObject, pathObject) } } diff --git a/command/schema.go b/command/schema.go index 7f4b91c..0c3f3d1 100644 --- a/command/schema.go +++ b/command/schema.go @@ -20,7 +20,7 @@ func Schema() cli.Command { Flags: []cli.Flag{ flag.OutPrint, }, - BashComplete: bash.Module.Schema, + BashComplete: bash.Module.ModuleName, } } @@ -46,13 +46,13 @@ func (s schemaCommand) action(ctx *cli.Context) { s.printHtml(schema) default: utils.PrintError(errors.Errorf( - "invalid flag value, expected %s or %s", flag.OutPrintJsonValue, flag.OutPrintHtmlValue)) + "invalid flag value, expected [%s] or [%s]", flag.OutPrintJsonValue, flag.OutPrintHtmlValue)) } } } func (s schemaCommand) getSchemaConfig(moduleName string) interface{} { - if configuration, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName); err != nil { + 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 { diff --git a/command/set.go b/command/set.go index 9367840..e7cdd2c 100644 --- a/command/set.go +++ b/command/set.go @@ -1,6 +1,7 @@ package command import ( + "encoding/json" "github.com/codegangsta/cli" "github.com/pkg/errors" "github.com/tidwall/sjson" @@ -17,7 +18,7 @@ func Set() cli.Command { Name: "set", Usage: "set configuration by module_name", Action: set.action, - BashComplete: bash.Module.GetSetDelete, + BashComplete: bash.Module.ModuleName_ModuleData, } } @@ -35,7 +36,7 @@ func (s setCommand) action(ctx *cli.Context) { pathObject := ctx.Args().Get(1) changeObject := ctx.Args().Get(2) - moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + moduleConfiguration, err := service.Config.GetConfigurationByModuleName(moduleName) if err != nil { utils.PrintError(err) return @@ -64,6 +65,12 @@ func (s setCommand) action(ctx *cli.Context) { utils.CreateUpdateConfig(changeObject, moduleConfiguration) return } else { + jsonObject, err := json.Marshal(moduleConfiguration.Data) + if err != nil { + utils.PrintError(err) + return + } + changeArgument := utils.ParseSetObject(changeObject) if stringToChange, err := sjson.Set(string(jsonObject), pathObject, changeArgument); err != nil { utils.PrintError(err) diff --git a/flag/description.go b/flag/description.go index 85a792d..5330fbd 100644 --- a/flag/description.go +++ b/flag/description.go @@ -18,6 +18,9 @@ const ( outPrintName = "o" OutPrintJsonValue = "json" OutPrintHtmlValue = "html" + + withCommonConfigName = "full" + withCommonConfigUsage = "compile data with common configs" ) var ( diff --git a/flag/structure.go b/flag/structure.go index 0dbeab2..f13e081 100644 --- a/flag/structure.go +++ b/flag/structure.go @@ -13,7 +13,8 @@ var ( Color = cli.BoolFlag{Name: colorName, Usage: colorUsage} Unsafe = cli.BoolFlag{Name: unsafeName, Usage: unsafeUsage} //---local--- - OutPrint = cli.StringFlag{Name: outPrintName, Usage: outPrintUsage, Value: OutPrintJsonValue} + OutPrint = cli.StringFlag{Name: outPrintName, Usage: outPrintUsage, Value: OutPrintJsonValue} + WithCommonConfig = cli.BoolFlag{Name: withCommonConfigName, Usage: withCommonConfigUsage} ) func CheckGlobal(c *cli.Context) error { diff --git a/service/config.go b/service/config.go index 79294bb..bfeae1e 100644 --- a/service/config.go +++ b/service/config.go @@ -25,23 +25,21 @@ func (c configService) GetAvailableConfigs() ([]cfg.ModuleInfo, error) { return configClient.GetAvailableConfigs() } -func (c configService) GetConfigurationAndJsonByModuleName(moduleName string) (*cfg.Config, []byte, error) { +func (c configService) GetConfigurationByModuleName(moduleName string) (*cfg.Config, error) { if moduleName == "" { - return nil, nil, errors.New("need module name") + return nil, errors.New("need module name") } if moduleConfiguration, err := configClient.GetConfigByModuleName(moduleName); err != nil { if errorStatus, ok := status.FromError(err); ok { switch errorStatus.Code() { case codes.NotFound: - return nil, nil, errors.Errorf("module '%s' not found", moduleName) + return nil, errors.Errorf("module [%s] not found", moduleName) } } - return nil, nil, err - } else if jsonObject, err := json.Marshal(moduleConfiguration.Data); err != nil { - return nil, nil, err + return nil, err } else { - return moduleConfiguration, jsonObject, nil + return moduleConfiguration, nil } } @@ -112,8 +110,44 @@ func (c configService) CreateUpdateCommonConfig(stringToChange string, config cf } } -func (c configService) DeleteCommonConfig(configId string) (int, error) { - return configClient.DeleteCommonConfig([]string{configId}) +func (c configService) DeleteCommonConfig(configId string) ([]string, bool, error) { + deletedInfo, err := configClient.DeleteCommonConfig(configId) + if err != nil { + return nil, false, err + } + arrayOfModuleName := make([]string, 0) + for moduleName := range deletedInfo.Links { + arrayOfModuleName = append(arrayOfModuleName, moduleName) + } + return arrayOfModuleName, deletedInfo.Deleted, nil +} + +func (c configService) GetLinksCommonConfig(configId string) ([]string, error) { + link, err := configClient.GetLinksCommonConfig(configId) + if err != nil { + return nil, err + } + arrayOfModuleName := make([]string, 0) + for moduleName := range *link { + arrayOfModuleName = append(arrayOfModuleName, moduleName) + } + return arrayOfModuleName, nil +} + +func (c configService) CompileDataWithCommonConfigs( + data map[string]interface{}, commonConfigs []string) (map[string]interface{}, error) { + + req := cfg.CompileConfigs{ + Data: data, + CommonConfigsIdList: commonConfigs, + } + var err error + data, err = configClient.CompileCommonConfigs(req) + if err != nil { + return nil, err + } else { + return data, nil + } } func (c configService) checkSchema(moduleId string, object map[string]interface{}) (bool, error) { From cf23b95af127fba54678c80ad8a699adbff663cc Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 30 Oct 2019 19:06:32 +0300 Subject: [PATCH 4/5] ref --- README.md | 37 +++++-- bash/autocomplete.go | 83 +++++++++++++++ bash/common_config.go | 75 ------------- bash/module.go | 54 ---------- command/common.go | 16 +-- command/commonConfig/link.go | 92 ---------------- command/commonConfig/unlink.go | 94 ---------------- .../contain.go | 22 ++-- .../{commonConfig => common_config}/delete.go | 16 +-- .../{commonConfig => common_config}/get.go | 17 +-- command/common_config/link.go | 36 +++++++ .../{commonConfig => common_config}/remove.go | 19 ++-- .../{commonConfig => common_config}/set.go | 33 ++---- command/common_config/unlink.go | 36 +++++++ command/delete.go | 3 +- command/get.go | 2 +- command/schema.go | 2 +- command/set.go | 29 ++--- command/utils/common.go | 18 ++++ service/config.go | 100 +++++++++++++++++- 20 files changed, 361 insertions(+), 423 deletions(-) create mode 100644 bash/autocomplete.go delete mode 100644 bash/common_config.go delete mode 100644 bash/module.go delete mode 100644 command/commonConfig/link.go delete mode 100644 command/commonConfig/unlink.go rename command/{commonConfig => common_config}/contain.go (67%) rename command/{commonConfig => common_config}/delete.go (78%) rename command/{commonConfig => common_config}/get.go (74%) create mode 100644 command/common_config/link.go rename command/{commonConfig => common_config}/remove.go (70%) rename command/{commonConfig => common_config}/set.go (71%) create mode 100644 command/common_config/unlink.go diff --git a/README.md b/README.md index cb3e70f..061f118 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,29 @@ # ispctl -## Описание Консольная утилита для получения и переопределения конфигруации модулей isp +* [Требования](#Требования) +* [Установка](#Установка) +* [Конифгурация](#Конифгурация) +* [Использование](#Использование) +* [Описание](#Описание) +* [Примеры](#Пример) + - [ispctl status](#ispctl-status) + - [ispctl get](#ispctl-get) + - [ispctl set](#ispctl-set) + - [ispctl delete](#ispctl-delete) + - [ispctl schema](#ispctl-schema) + - [ispctl common](#ispctl-common) + * [set](#ispctl-common-set) + * [get](#ispctl-common-get) + * [delete](#ispctl-common-delete) + * [remove](#ispctl-common-remove) + * [link](#ispctl-common-link) + * [unlink](#ispctl-common-unlink) + * [contain](#ispctl-common-contain) + - [запрос с флагами](#Запрос-с-флагами) + + ## Требования * Linux @@ -344,7 +365,7 @@ ispctl schema example -o html ``` ### ispctl common -#### get +#### ispctl common get Возвращает список названий общих конфигураций или, если в первом аргументе указано название общей конфигурации, возвращает объект общей конфигурации по указанному пути Запрос @@ -365,7 +386,7 @@ ispctl common get test . "test": null } ``` -#### set +#### ispctl common set Добавляет объект в общую конфигурацию по указанному пути Запрос @@ -381,7 +402,7 @@ ispctl common set test .test '{"a":"a","b":"b"}' } } ``` -#### delete +#### ispctl common delete Удаляет объект из общей конфигурации по указанному пути Запрос @@ -396,7 +417,7 @@ ispctl common delete test .test.a } } ``` -#### link +#### ispctl common link Связывает 'common_config' к конфигурации модуля по 'module_name'. Возвращает список общих конфигураций, которые связаны с модулем Запрос @@ -407,7 +428,7 @@ ispctl common link test module_example ```bash [test] [second_common_config] ``` -#### remove +#### ispctl common remove Удаляет объект общий конфигурации, если он не связан с конфигурациями модулей. Если общая конфигурация имеет связи, выводит список модулей с которыми установлена связь Запрос @@ -419,7 +440,7 @@ ispctl common remove test config [test] not deleted, need unlink in next modules: [module_example] ``` -#### unlink +#### ispctl common unlink Отвязывает 'common_config' от конфигурации модуля по 'module_name'. Возвращает список общих конфигураций, которые связаны с модулем Запрос @@ -431,7 +452,7 @@ ispctl common unlink test module_example ```bash [second_common_config] ``` -#### contain +#### ispctl common contain Возвращает список названий модулей, с которыми имеет связь общая конфигурация Запрос diff --git a/bash/autocomplete.go b/bash/autocomplete.go new file mode 100644 index 0000000..a7461b3 --- /dev/null +++ b/bash/autocomplete.go @@ -0,0 +1,83 @@ +package bash + +import ( + "fmt" + "github.com/codegangsta/cli" + "github.com/integration-system/bellows" + "isp-ctl/flag" + "isp-ctl/service" +) + +const ( + CommonConfigName bashArg = "config_name" + CommonConfigData bashArg = "config_data" + ModuleName bashArg = "module_name" + ModuleData bashArg = "module_data" + Empty bashArg = "empty" +) + +type bashArg string + +type bashCommand struct { + first bashArg + second bashArg +} + +func Get(first bashArg, second bashArg) *bashCommand { + return &bashCommand{ + first: first, + second: second, + } +} + +func (c bashCommand) Complete(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + return + } + commonConfigs, err := service.Config.GetMapNameCommonConfig() + if 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) + } + } + case CommonConfigName: + for _, config := range commonConfigs { + fmt.Println(config.Name) + } + } + case 1: + switch c.second { + case CommonConfigData: + if config, ok := commonConfigs[ctx.Args().First()]; ok { + for key, _ := range bellows.Flatten(config.Data) { + fmt.Printf(".%v\n", key) + } + } + 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) + } + } + } + } +} diff --git a/bash/common_config.go b/bash/common_config.go deleted file mode 100644 index bb31dea..0000000 --- a/bash/common_config.go +++ /dev/null @@ -1,75 +0,0 @@ -package bash - -import ( - "fmt" - "github.com/codegangsta/cli" - "github.com/integration-system/bellows" - "isp-ctl/flag" - "isp-ctl/service" -) - -var CommonConfig commonConfig - -type commonConfig struct{} - -func (commonConfig) ConfigName_ModuleName(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - return - } - switch ctx.NArg() { - case 0: - for _, config := range commonConfigs { - fmt.Println(config.Name) - } - case 1: - if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - return - } else { - for _, module := range arrayOfModules { - fmt.Println(module.Name) - } - } - } -} - -func (commonConfig) ConfigName_ConfigData(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - return - } - switch ctx.NArg() { - case 0: - for _, config := range commonConfigs { - fmt.Println(config.Name) - } - case 1: - if config, ok := commonConfigs[ctx.Args().First()]; ok { - for key, _ := range bellows.Flatten(config.Data) { - fmt.Printf(".%v\n", key) - } - } - } -} - -func (commonConfig) ConfigName(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - return - } - switch ctx.NArg() { - case 0: - for _, config := range commonConfigs { - fmt.Println(config.Name) - } - } -} diff --git a/bash/module.go b/bash/module.go deleted file mode 100644 index 64f088a..0000000 --- a/bash/module.go +++ /dev/null @@ -1,54 +0,0 @@ -package bash - -import ( - "fmt" - "github.com/codegangsta/cli" - "github.com/integration-system/bellows" - "isp-ctl/flag" - "isp-ctl/service" -) - -var Module module - -type module struct{} - -func (module) ModuleName_ModuleData(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - switch ctx.NArg() { - case 0: - if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - return - } else { - for _, module := range arrayOfModules { - fmt.Println(module.Name) - } - } - case 1: - moduleConfiguration, err := service.Config.GetConfigurationByModuleName(ctx.Args().Get(1)) - if err != nil { - return - } else { - for key, _ := range bellows.Flatten(moduleConfiguration.Data) { - fmt.Printf(".%v\n", key) - } - } - } -} - -func (module) ModuleName(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - return - } - switch ctx.NArg() { - case 0: - if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { - return - } else { - for _, module := range arrayOfModules { - fmt.Println(module.Name) - } - } - } -} diff --git a/command/common.go b/command/common.go index f20c8b2..a88ca10 100644 --- a/command/common.go +++ b/command/common.go @@ -3,7 +3,7 @@ package command import ( "fmt" "github.com/codegangsta/cli" - "isp-ctl/command/commonConfig" + "isp-ctl/command/common_config" ) func CommonConfig() cli.Command { @@ -13,13 +13,13 @@ func CommonConfig() cli.Command { Action: cc.action, BashComplete: cc.bachComplete, Subcommands: []cli.Command{ - commonConfig.Get(), - commonConfig.Set(), - commonConfig.Delete(), - commonConfig.Remove(), - commonConfig.Link(), - commonConfig.UnLink(), - commonConfig.Contain(), + common_config.Get(), + common_config.Set(), + common_config.Delete(), + common_config.Remove(), + common_config.Link(), + common_config.UnLink(), + common_config.Contain(), }, } } diff --git a/command/commonConfig/link.go b/command/commonConfig/link.go deleted file mode 100644 index 869e879..0000000 --- a/command/commonConfig/link.go +++ /dev/null @@ -1,92 +0,0 @@ -package commonConfig - -import ( - "fmt" - "github.com/codegangsta/cli" - "github.com/pkg/errors" - "isp-ctl/bash" - "isp-ctl/command/utils" - "isp-ctl/flag" - "isp-ctl/service" -) - -func Link() cli.Command { - return cli.Command{ - Name: "link", - Usage: "link common configurations to module configuration", - Action: link.action, - BashComplete: bash.CommonConfig.ConfigName_ModuleName, - } -} - -var link linkCommand - -type linkCommand struct{} - -func (g linkCommand) action(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - utils.PrintError(err) - return - } - - configName := ctx.Args().First() - moduleName := ctx.Args().Get(1) - - if configName == "" { - utils.PrintError(errors.New("need config name")) - return - } - - if moduleName == "" { - utils.PrintError(errors.New("need module name")) - return - } - - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - utils.PrintError(err) - return - } - - config, ok := commonConfigs[configName] - if !ok { - utils.PrintError(errors.Errorf("common config [%s] not found", configName)) - return - } - - moduleConfiguration, err := service.Config.GetConfigurationByModuleName(moduleName) - if err != nil { - utils.PrintError(err) - return - } - - ccIdNameMap := make(map[string]string) - for name, value := range commonConfigs { - ccIdNameMap[value.Id] = name - } - - needLink := true - for _, configId := range moduleConfiguration.CommonConfigs { - if config.Id == configId { - needLink = false - break - } - } - - if needLink { - moduleConfiguration.CommonConfigs = append(moduleConfiguration.CommonConfigs, config.Id) - if linked, err := service.Config.UpdateConfigAndGetLinkCommon(*moduleConfiguration); err != nil { - utils.PrintError(err) - } else { - for _, name := range linked { - fmt.Printf("[%s] ", ccIdNameMap[name]) - } - fmt.Printf("\n") - } - } else { - for _, name := range moduleConfiguration.CommonConfigs { - fmt.Printf("[%s] ", ccIdNameMap[name]) - } - fmt.Printf("\n") - } -} diff --git a/command/commonConfig/unlink.go b/command/commonConfig/unlink.go deleted file mode 100644 index d3977c6..0000000 --- a/command/commonConfig/unlink.go +++ /dev/null @@ -1,94 +0,0 @@ -package commonConfig - -import ( - "fmt" - "github.com/codegangsta/cli" - "github.com/pkg/errors" - "isp-ctl/bash" - "isp-ctl/command/utils" - "isp-ctl/flag" - "isp-ctl/service" -) - -func UnLink() cli.Command { - return cli.Command{ - Name: "unlink", - Usage: "unlink common configurations from module configuration", - Action: unlink.action, - BashComplete: bash.CommonConfig.ConfigName_ModuleName, - } -} - -var unlink unlinkCommand - -type unlinkCommand struct{} - -func (g unlinkCommand) action(ctx *cli.Context) { - if err := flag.CheckGlobal(ctx); err != nil { - utils.PrintError(err) - return - } - - configName := ctx.Args().First() - moduleName := ctx.Args().Get(1) - - if configName == "" { - utils.PrintError(errors.New("need config name")) - return - } - - if moduleName == "" { - utils.PrintError(errors.New("need module name")) - return - } - - commonConfigs, err := service.Config.GetMapCommonConfigByName() - if err != nil { - utils.PrintError(err) - return - } - - config, ok := commonConfigs[configName] - if !ok { - utils.PrintError(errors.Errorf("common config [%s] not found", configName)) - return - } - - moduleConfig, err := service.Config.GetConfigurationByModuleName(moduleName) - if err != nil { - utils.PrintError(err) - return - } - - ccIdNameMap := make(map[string]string) - for name, value := range commonConfigs { - ccIdNameMap[value.Id] = name - } - - needUnlink := false - for i, configId := range moduleConfig.CommonConfigs { - if config.Id == configId { - copy(moduleConfig.CommonConfigs[i:], moduleConfig.CommonConfigs[i+1:]) - moduleConfig.CommonConfigs[len(moduleConfig.CommonConfigs)-1] = "" - moduleConfig.CommonConfigs = moduleConfig.CommonConfigs[:len(moduleConfig.CommonConfigs)-1] - needUnlink = true - break - } - } - - if needUnlink { - if linked, err := service.Config.UpdateConfigAndGetLinkCommon(*moduleConfig); err != nil { - utils.PrintError(err) - } else { - for _, name := range linked { - fmt.Printf("[%s] ", ccIdNameMap[name]) - } - fmt.Printf("\n") - } - } else { - for _, name := range moduleConfig.CommonConfigs { - fmt.Printf("[%s] ", ccIdNameMap[name]) - } - fmt.Printf("\n") - } -} diff --git a/command/commonConfig/contain.go b/command/common_config/contain.go similarity index 67% rename from command/commonConfig/contain.go rename to command/common_config/contain.go index 4054157..f76cffe 100644 --- a/command/commonConfig/contain.go +++ b/command/common_config/contain.go @@ -1,4 +1,4 @@ -package commonConfig +package common_config import ( "fmt" @@ -15,7 +15,7 @@ func Contain() cli.Command { Name: "contain", Usage: "availability common configuration in module", Action: contain.action, - BashComplete: bash.CommonConfig.ConfigName, + BashComplete: bash.Get(bash.CommonConfigName, bash.Empty).Complete, } } @@ -29,29 +29,27 @@ func (g containCommand) action(ctx *cli.Context) { return } - ccName := ctx.Args().First() + configName := ctx.Args().First() - if ccName == "" { + if configName == "" { utils.PrintError(errors.New("empty common config name")) return } - commonConfigs, err := service.Config.GetMapCommonConfigByName() + config, err := service.Config.GetCommonConfigByName(configName) if err != nil { utils.PrintError(err) return } - config, ok := commonConfigs[ccName] - if !ok { - utils.PrintError(errors.Errorf("common config [%s] not found", ccName)) - return - } - links, err := service.Config.GetLinksCommonConfig(config.Id) if err != nil { utils.PrintError(err) } else { - fmt.Printf("%v\n", links) + fmt.Printf("config [%s] linked with next modules:\n", configName) + for _, link := range links { + fmt.Printf("[%s] ", link) + } + fmt.Printf("\n") } } diff --git a/command/commonConfig/delete.go b/command/common_config/delete.go similarity index 78% rename from command/commonConfig/delete.go rename to command/common_config/delete.go index bd4eaf3..0b9127a 100644 --- a/command/commonConfig/delete.go +++ b/command/common_config/delete.go @@ -1,4 +1,4 @@ -package commonConfig +package common_config import ( "encoding/json" @@ -16,7 +16,7 @@ func Delete() cli.Command { Name: "delete", Usage: "set common configurations", Action: deleteComm.action, - BashComplete: bash.CommonConfig.ConfigName_ConfigData, + BashComplete: bash.Get(bash.CommonConfigName, bash.CommonConfigData).Complete, } } @@ -30,10 +30,10 @@ func (g deleteCommand) action(ctx *cli.Context) { return } - ccName := ctx.Args().First() + configName := ctx.Args().First() pathObject := ctx.Args().Get(1) - if ccName == "" { + if configName == "" { utils.PrintError(errors.New("empty config name")) return } @@ -44,18 +44,12 @@ func (g deleteCommand) action(ctx *cli.Context) { return } - commonConfigs, err := service.Config.GetMapCommonConfigByName() + config, err := service.Config.GetCommonConfigByName(configName) if err != nil { utils.PrintError(err) return } - config, ok := commonConfigs[ccName] - if !ok { - utils.PrintError(errors.Errorf("common config [%s] not found", ccName)) - return - } - if pathObject == "" { utils.CreateUpdateCommonConfig("", config) } else { diff --git a/command/commonConfig/get.go b/command/common_config/get.go similarity index 74% rename from command/commonConfig/get.go rename to command/common_config/get.go index 0c1f264..c0a51ae 100644 --- a/command/commonConfig/get.go +++ b/command/common_config/get.go @@ -1,4 +1,4 @@ -package commonConfig +package common_config import ( "encoding/json" @@ -16,7 +16,7 @@ func Get() cli.Command { Name: "get", Usage: "get common configurations", Action: get.action, - BashComplete: bash.CommonConfig.ConfigName_ConfigData, + BashComplete: bash.Get(bash.CommonConfigName, bash.CommonConfigData).Complete, } } @@ -30,18 +30,19 @@ func (g getCommand) action(ctx *cli.Context) { return } - ccName := ctx.Args().First() + configName := ctx.Args().First() pathObject := ctx.Args().Get(1) - commonConfigs, err := service.Config.GetMapCommonConfigByName() + commonConfigs, err := service.Config.GetMapNameCommonConfig() if err != nil { utils.PrintError(err) return } - if ccName == "" { + if configName == "" { + fmt.Printf("available next common configs:\n") for name := range commonConfigs { - fmt.Printf("%s ", name) + fmt.Printf("[%s] ", name) } fmt.Println() return @@ -53,9 +54,9 @@ func (g getCommand) action(ctx *cli.Context) { return } - config, ok := commonConfigs[ccName] + config, ok := commonConfigs[configName] if !ok { - utils.PrintError(errors.Errorf("common config [%s] not found", ccName)) + utils.PrintError(errors.Errorf("common config [%s] not found", configName)) return } diff --git a/command/common_config/link.go b/command/common_config/link.go new file mode 100644 index 0000000..2564981 --- /dev/null +++ b/command/common_config/link.go @@ -0,0 +1,36 @@ +package common_config + +import ( + "github.com/codegangsta/cli" + "isp-ctl/bash" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func Link() cli.Command { + return cli.Command{ + Name: "link", + Usage: "link common configurations to module configuration", + Action: link.action, + BashComplete: bash.Get(bash.CommonConfigName, bash.ModuleName).Complete, + } +} + +var link linkCommand + +type linkCommand struct{} + +func (g linkCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + moduleName := ctx.Args().Get(1) + + if err := service.Config.LinkCommonConfigToModule(configName, moduleName); err != nil { + utils.PrintError(err) + } +} diff --git a/command/commonConfig/remove.go b/command/common_config/remove.go similarity index 70% rename from command/commonConfig/remove.go rename to command/common_config/remove.go index 3f7e288..f9c4f78 100644 --- a/command/commonConfig/remove.go +++ b/command/common_config/remove.go @@ -1,4 +1,4 @@ -package commonConfig +package common_config import ( "fmt" @@ -15,7 +15,7 @@ func Remove() cli.Command { Name: "remove", Usage: "remove common configurations", Action: remove.action, - BashComplete: bash.CommonConfig.ConfigName, + BashComplete: bash.Get(bash.CommonConfigName, bash.Empty).Complete, } } @@ -29,32 +29,27 @@ func (g removeCommand) action(ctx *cli.Context) { return } - ccName := ctx.Args().First() + configName := ctx.Args().First() - if ccName == "" { + if configName == "" { utils.PrintError(errors.New("empty common config name")) return } - commonConfigs, err := service.Config.GetMapCommonConfigByName() + config, err := service.Config.GetCommonConfigByName(configName) if err != nil { utils.PrintError(err) return } - config, ok := commonConfigs[ccName] - if !ok { - utils.PrintError(errors.Errorf("common config [%s] not found", ccName)) - return - } - links, deleted, err := service.Config.DeleteCommonConfig(config.Id) if err != nil { utils.PrintError(err) return } + if deleted { - fmt.Printf("config [%s] deleted", config.Name) + fmt.Printf("config [%s] deleted\n", config.Name) } else { fmt.Printf("config [%s] not deleted, need unlink in next modules:\n%v\n", config.Name, links) } diff --git a/command/commonConfig/set.go b/command/common_config/set.go similarity index 71% rename from command/commonConfig/set.go rename to command/common_config/set.go index c3a544b..d0753a5 100644 --- a/command/commonConfig/set.go +++ b/command/common_config/set.go @@ -1,17 +1,15 @@ -package commonConfig +package common_config import ( "encoding/json" "github.com/codegangsta/cli" "github.com/pkg/errors" "github.com/tidwall/sjson" - "io/ioutil" "isp-ctl/bash" "isp-ctl/cfg" "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" - "os" ) func Set() cli.Command { @@ -19,7 +17,7 @@ func Set() cli.Command { Name: "set", Usage: "set common configurations", Action: set.action, - BashComplete: bash.CommonConfig.ConfigName_ConfigData, + BashComplete: bash.Get(bash.CommonConfigName, bash.CommonConfigData).Complete, } } @@ -33,25 +31,25 @@ func (g setCommand) action(ctx *cli.Context) { return } - ccName := ctx.Args().First() + configName := ctx.Args().First() pathObject := ctx.Args().Get(1) changeObject := ctx.Args().Get(2) - if ccName == "" { + if configName == "" { utils.PrintError(errors.New("empty config name")) return } - mapConfigByName, err := service.Config.GetMapCommonConfigByName() + mapConfigByName, err := service.Config.GetMapNameCommonConfig() if err != nil { utils.PrintError(err) return } - config, ok := mapConfigByName[ccName] + config, ok := mapConfigByName[configName] if !ok { config = cfg.CommonConfig{ - Name: ccName, + Name: configName, } } @@ -61,36 +59,25 @@ func (g setCommand) action(ctx *cli.Context) { return } - if changeObject == "" { - bytes, err := ioutil.ReadAll(os.Stdin) - if err != nil { - utils.PrintError(err) - return - } - changeObject = string(bytes) - } - if changeObject == "" { - utils.PrintError(errors.New("expected argument")) + changeObject, err = utils.CheckChangeObject(changeObject) + if err != nil { + utils.PrintError(err) return } if pathObject == "" { utils.CreateUpdateCommonConfig(changeObject, config) - return } else { jsonObject, err := json.Marshal(config.Data) if err != nil { utils.PrintError(err) return } - changeArgument := utils.ParseSetObject(changeObject) if stringToChange, err := sjson.Set(string(jsonObject), pathObject, changeArgument); err != nil { utils.PrintError(err) - return } else { utils.CreateUpdateCommonConfig(stringToChange, config) - return } } } diff --git a/command/common_config/unlink.go b/command/common_config/unlink.go new file mode 100644 index 0000000..e776c6a --- /dev/null +++ b/command/common_config/unlink.go @@ -0,0 +1,36 @@ +package common_config + +import ( + "github.com/codegangsta/cli" + "isp-ctl/bash" + "isp-ctl/command/utils" + "isp-ctl/flag" + "isp-ctl/service" +) + +func UnLink() cli.Command { + return cli.Command{ + Name: "unlink", + Usage: "unlink common configurations from module configuration", + Action: unlink.action, + BashComplete: bash.Get(bash.CommonConfigName, bash.ModuleName).Complete, + } +} + +var unlink unlinkCommand + +type unlinkCommand struct{} + +func (g unlinkCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { + utils.PrintError(err) + return + } + + configName := ctx.Args().First() + moduleName := ctx.Args().Get(1) + + if err := service.Config.UnlinkCommonConfigFromModule(configName, moduleName); err != nil { + utils.PrintError(err) + } +} diff --git a/command/delete.go b/command/delete.go index d488260..3183c8b 100644 --- a/command/delete.go +++ b/command/delete.go @@ -15,7 +15,7 @@ func Delete() cli.Command { Name: "delete", Usage: "delete configuration by module_name", Action: deleteComm.action, - BashComplete: bash.Module.ModuleName_ModuleData, + BashComplete: bash.Get(bash.ModuleName, bash.ModuleData).Complete, } } @@ -54,7 +54,6 @@ func (d deleteCommand) action(ctx *cli.Context) { if stringToChange, err := sjson.Delete(string(jsonObject), pathObject); err != nil { utils.PrintError(err) - return } else { utils.CreateUpdateConfig(stringToChange, moduleConfiguration) } diff --git a/command/get.go b/command/get.go index d14d9ac..d5cbb55 100644 --- a/command/get.go +++ b/command/get.go @@ -14,7 +14,7 @@ func Get() cli.Command { Name: "get", Usage: "get configuration by module_name", Action: get.action, - BashComplete: bash.Module.ModuleName_ModuleData, + BashComplete: bash.Get(bash.ModuleName, bash.ModuleData).Complete, Flags: []cli.Flag{ flag.WithCommonConfig, }, diff --git a/command/schema.go b/command/schema.go index 0c3f3d1..843d79f 100644 --- a/command/schema.go +++ b/command/schema.go @@ -20,7 +20,7 @@ func Schema() cli.Command { Flags: []cli.Flag{ flag.OutPrint, }, - BashComplete: bash.Module.ModuleName, + BashComplete: bash.Get(bash.ModuleName, bash.Empty).Complete, } } diff --git a/command/set.go b/command/set.go index e7cdd2c..9815cf9 100644 --- a/command/set.go +++ b/command/set.go @@ -3,14 +3,11 @@ package command import ( "encoding/json" "github.com/codegangsta/cli" - "github.com/pkg/errors" "github.com/tidwall/sjson" - "io/ioutil" "isp-ctl/bash" "isp-ctl/command/utils" "isp-ctl/flag" "isp-ctl/service" - "os" ) func Set() cli.Command { @@ -18,7 +15,7 @@ func Set() cli.Command { Name: "set", Usage: "set configuration by module_name", Action: set.action, - BashComplete: bash.Module.ModuleName_ModuleData, + BashComplete: bash.Get(bash.ModuleName, bash.ModuleData).Complete, } } @@ -36,7 +33,7 @@ func (s setCommand) action(ctx *cli.Context) { pathObject := ctx.Args().Get(1) changeObject := ctx.Args().Get(2) - moduleConfiguration, err := service.Config.GetConfigurationByModuleName(moduleName) + config, err := service.Config.GetConfigurationByModuleName(moduleName) if err != nil { utils.PrintError(err) return @@ -48,24 +45,16 @@ func (s setCommand) action(ctx *cli.Context) { return } - if changeObject == "" { - bytes, err := ioutil.ReadAll(os.Stdin) - if err != nil { - utils.PrintError(err) - return - } - changeObject = string(bytes) - } - if changeObject == "" { - utils.PrintError(errors.New("expected argument")) + changeObject, err = utils.CheckChangeObject(changeObject) + if err != nil { + utils.PrintError(err) return } if pathObject == "" { - utils.CreateUpdateConfig(changeObject, moduleConfiguration) - return + utils.CreateUpdateConfig(changeObject, config) } else { - jsonObject, err := json.Marshal(moduleConfiguration.Data) + jsonObject, err := json.Marshal(config.Data) if err != nil { utils.PrintError(err) return @@ -74,10 +63,8 @@ func (s setCommand) action(ctx *cli.Context) { changeArgument := utils.ParseSetObject(changeObject) if stringToChange, err := sjson.Set(string(jsonObject), pathObject, changeArgument); err != nil { utils.PrintError(err) - return } else { - utils.CreateUpdateConfig(stringToChange, moduleConfiguration) - return + utils.CreateUpdateConfig(stringToChange, config) } } } diff --git a/command/utils/common.go b/command/utils/common.go index b5674a7..18b6e46 100644 --- a/command/utils/common.go +++ b/command/utils/common.go @@ -5,7 +5,9 @@ import ( "fmt" "github.com/pkg/errors" "github.com/tidwall/gjson" + "io/ioutil" "isp-ctl/service" + "os" "strings" ) @@ -28,6 +30,21 @@ func CheckPath(pathObject string) (string, error) { return pathObject, nil } +func CheckChangeObject(changeObject string) (string, error) { + if changeObject == "" { + bytes, err := ioutil.ReadAll(os.Stdin) + if err != nil { + return "", err + } + changeObject = string(bytes) + } + if changeObject == "" { + return "", errors.New("expected argument") + } else { + return changeObject, nil + } +} + func PrintAnswer(data interface{}) { if answer, err := json.MarshalIndent(data, "", " "); err != nil { PrintError(err) @@ -38,6 +55,7 @@ func PrintAnswer(data interface{}) { func PrintError(err error) { fmt.Println("ERROR:", err) + os.Exit(-1) } func ParseSetObject(argument string) interface{} { diff --git a/service/config.go b/service/config.go index bfeae1e..b1b489e 100644 --- a/service/config.go +++ b/service/config.go @@ -82,7 +82,17 @@ func (c configService) UpdateConfigAndGetLinkCommon(configuration cfg.Config) ([ } } -func (c configService) GetMapCommonConfigByName() (map[string]cfg.CommonConfig, error) { +func (c configService) GetCommonConfigByName(configName string) (cfg.CommonConfig, error) { + if commonConfigs, err := c.GetMapNameCommonConfig(); err != nil { + return cfg.CommonConfig{}, err + } else if config, ok := commonConfigs[configName]; !ok { + return cfg.CommonConfig{}, errors.Errorf("common config [%s] not found", configName) + } else { + return config, nil + } +} + +func (c configService) GetMapNameCommonConfig() (map[string]cfg.CommonConfig, error) { collection, err := configClient.GetCommonConfigs([]string{}) if err != nil { return nil, err @@ -150,6 +160,94 @@ func (c configService) CompileDataWithCommonConfigs( } } +func (c configService) UnlinkCommonConfigFromModule(configName, moduleName string) error { + return c.linked(configName, moduleName, + func(configId string, configIdentities []string) (bool, []string) { + needUnlink := false + for i, id := range configIdentities { + if configId == id { + copy(configIdentities[i:], configIdentities[i+1:]) + configIdentities[len(configIdentities)-1] = "" + configIdentities = configIdentities[:len(configIdentities)-1] + needUnlink = true + break + } + } + return needUnlink, configIdentities + }) +} + +func (c configService) LinkCommonConfigToModule(configName, moduleName string) error { + return c.linked(configName, moduleName, + func(configId string, configIdentities []string) (bool, []string) { + needLink := true + for _, id := range configIdentities { + if configId == id { + needLink = false + break + } + } + if needLink { + configIdentities = append(configIdentities, configId) + } + return needLink, configIdentities + }) +} + +func (c configService) linked(configName, moduleName string, + linkHandler func(configId string, configIdentities []string) (bool, []string)) error { + + if configName == "" { + return errors.New("empty config name") + } + + if moduleName == "" { + return errors.New("empty module name") + } + + commonConfigs, err := c.GetMapNameCommonConfig() + if err != nil { + return err + } + + config, ok := commonConfigs[configName] + if !ok { + return errors.Errorf("common config [%s] not found", configName) + } + + moduleConfig, err := c.GetConfigurationByModuleName(moduleName) + if err != nil { + return err + } + + configIdConfigNameMap := make(map[string]string) + for name, value := range commonConfigs { + configIdConfigNameMap[value.Id] = name + } + + needUpdate, newCommonConfigs := linkHandler(config.Id, moduleConfig.CommonConfigs) + + if needUpdate { + moduleConfig.CommonConfigs = newCommonConfigs + if linked, err := c.UpdateConfigAndGetLinkCommon(*moduleConfig); err != nil { + return err + } else { + fmt.Printf("module [%s] have next link:\n", moduleName) + for _, name := range linked { + fmt.Printf("[%s] ", configIdConfigNameMap[name]) + } + fmt.Printf("\n") + } + } else { + fmt.Printf("module [%s] have next link:\n", moduleName) + for _, name := range moduleConfig.CommonConfigs { + fmt.Printf("[%s] ", configIdConfigNameMap[name]) + } + fmt.Printf("\n") + } + return nil +} + func (c configService) checkSchema(moduleId string, object map[string]interface{}) (bool, error) { if c.UnsafeEnable { return true, nil From 5f219e9f0d2d06165964c0aec72bd823e7d0980f Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Thu, 31 Oct 2019 16:58:34 +0300 Subject: [PATCH 5/5] change validation schema --- cfg/domain.go | 1 + service/config.go | 49 +++++++++++++++++------------------------------ 2 files changed, 19 insertions(+), 31 deletions(-) diff --git a/cfg/domain.go b/cfg/domain.go index 4702fe0..57411f2 100644 --- a/cfg/domain.go +++ b/cfg/domain.go @@ -26,6 +26,7 @@ type Config struct { CreatedAt time.Time UpdatedAt time.Time Data map[string]interface{} + Unsafe bool } type CommonConfig struct { diff --git a/service/config.go b/service/config.go index b1b489e..5229c10 100644 --- a/service/config.go +++ b/service/config.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/integration-system/isp-lib/config/schema" "github.com/pkg/errors" - "github.com/xeipuuv/gojsonschema" + epb "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "isp-ctl/cfg" @@ -60,14 +60,25 @@ func (c configService) CreateUpdateConfig(stringToChange string, configuration * } } - if ok, err := c.checkSchema(configuration.ModuleId, newData); err != nil { - return nil, err - } else if !ok { - return nil, nil - } - + configuration.Unsafe = c.UnsafeEnable configuration.Data = newData if resp, err := configClient.CreateUpdateConfig(*configuration); err != nil { + if errorStatus, ok := status.FromError(err); ok { + switch errorStatus.Code() { + case codes.InvalidArgument: + fmt.Print("doesn't match with schema:\n") + for _, value := range errorStatus.Details() { + if a, ok := value.(*epb.BadRequest); ok { + for _, value := range a.FieldViolations { + fmt.Printf("%s | %s\n", value.Field, value.Description) + } + } else { + fmt.Println(value) + } + return nil, nil + } + } + } return nil, err } else { return resp.Data, nil @@ -247,27 +258,3 @@ func (c configService) linked(configName, moduleName string, } return nil } - -func (c configService) checkSchema(moduleId string, object map[string]interface{}) (bool, error) { - if c.UnsafeEnable { - return true, nil - } - - if resp, err := configClient.GetSchemaByModuleId(moduleId); err != nil { - return false, err - } else { - schemaLoader := gojsonschema.NewGoLoader(resp.Schema) - documentLoader := gojsonschema.NewGoLoader(object) - - if result, err := gojsonschema.Validate(schemaLoader, documentLoader); err != nil { - return false, err - } else if result.Valid() { - return true, nil - } else { - for _, desc := range result.Errors() { - fmt.Printf("- %s\n", desc) - } - return false, nil - } - } -}