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