diff --git a/.version b/.version index 26aaba0..6085e94 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -1.2.0 +1.2.1 diff --git a/CHANGELOG.md b/CHANGELOG.md index fce8cc9..3cb4b07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## v1.2.1 +* fix bash complete with flag +* fix schema display to html ## v1.2.0 * add new command `schema` * add bash complete diff --git a/Gopkg.lock b/Gopkg.lock index fbf8447..e04ed8f 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -49,7 +49,8 @@ revision = "368713356c71961354e09ab9b734740ebdd94784" [[projects]] - digest = "1:ecb402b81b0ed58f59ee14a1587f94c9cef1d8710f0eac3e1cbbbc2cb254f8e8" + branch = "master" + digest = "1:8a49bb9fcaddea94bdee797ead2f2355534f6736e6a69c88378d52185b41e45c" name = "github.com/integration-system/isp-lib" packages = [ "config/schema", @@ -59,8 +60,7 @@ "utils", ] pruneopts = "UT" - revision = "d8ea213ec2182662432624bf09cf6726b56f12c4" - version = "v1.6.0" + revision = "e553b3a815fb9ce5d79aba955ec4ed528f83ec09" [[projects]] branch = "master" @@ -157,6 +157,14 @@ revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" version = "1.0.1" +[[projects]] + branch = "master" + digest = "1:84bd7f8a2e0bcd53ddc33c3b47c34c1fe340c8632cbe928f7f8ae10ec6ecdd62" + name = "github.com/mohae/deepcopy" + packages = ["."] + pruneopts = "UT" + revision = "c48cc78d482608239f6c4c92a4abd87eb8761c90" + [[projects]] digest = "1:abcdbf03ca6ca13d3697e2186edc1f33863bbdac2b3a44dfa39015e8903f7409" name = "github.com/olekukonko/tablewriter" @@ -327,7 +335,6 @@ "github.com/integration-system/bellows", "github.com/integration-system/isp-lib/config/schema", "github.com/integration-system/isp-lib/http", - "github.com/integration-system/isp-lib/logger", "github.com/integration-system/isp-lib/structure", "github.com/olekukonko/tablewriter", "github.com/tidwall/gjson", diff --git a/Gopkg.toml b/Gopkg.toml index a109e23..2f44ac3 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -32,3 +32,7 @@ [[override]] name = "github.com/valyala/fasthttp" branch = "master" + +[[override]] + name = "github.com/integration-system/isp-lib" + branch = "master" diff --git a/README.md b/README.md index e4ec396..977c424 100644 --- a/README.md +++ b/README.md @@ -41,20 +41,20 @@ ispctl [flag...] schema module_name [local_flag] | `schema` | возвращает схему конфигурации указанного модуля | | | | -| Флаги | Параметры | Описание | -|-------------|-----------|------------------------------------------------------------------| -| `-g` | string | переопределяет gateHost из конфигурации утилиты | -| `-u` | string | переопределяет instanceUuid из конфигурации утилиты | -| `-c` | | раскрашивает json перед выводом на экран | -| `-unsafe` | | отключает проверку схемы перед изменением конфигурации | -| | | | +| Флаги | Параметры | Описание | +|-------------|-----------|---------------------------------------------------------------------------------------------------------------------| +| `-g` | string | переопределяет gateHost из конфигурации утилиты, значение должно быть экранировано с помощью `' '` | +| `-u` | string | переопределяет instanceUuid из конфигурации утилиты, значение должно быть экранировано с помощью `' '` | +| `-c` | | раскрашивает json перед выводом на экран | +| `-unsafe` | | отключает проверку схемы перед изменением конфигурации | +| | | | -| Аргументы | Описание | -|-----------------|---------------------------------------------------------------------------------------------------| -| `module_name` | Модуль с которым происходит взаимодействие | -| `proprtry_path` | Путь к объекту конфигурации, при значении `.` работа происходит со всей конфигурацией модуля | -| `new_object` | Новый объект, должен быть экранирован с помощью `' '`, при отсутсвии ожидается ввод из stdin | -| | | +| Аргументы | Описание | +|-----------------|-------------------------------------------------------------------------------------------------------------| +| `module_name` | Модуль с которым происходит взаимодействие | +| `proprtry_path` | Путь к объекту конфигурации, при значении `.` работа происходит со всей конфигурацией модуля | +| `new_object` | Новый объект, значение должно быть экранировано с помощью `' '`, при отсутсвии ожидается ввод из stdin | +| | | | Локальные флаги | Параметры | Описание | |-----------------|-----------|--------------------------------------------------------------------------------------------------| @@ -322,7 +322,7 @@ ispctl schema example -o html ### Запрос с флагами Запрос ```bash -ispctl -u 00000000-1111-2222-3333-444444444444 -g 127.0.0.1:0000 -c set example . '{"metrics":{"address":{"ip":"127.0.0.1","newField":"100","port":1},"gc":1,"memory":false}}' +ispctl -u '00000000-1111-2222-3333-444444444444' -g '127.0.0.1:0000' -c set example . '{"metrics":{"address":{"ip":"127.0.0.1","newField":"100","port":1},"gc":1,"memory":false}}' ``` Ответ ```json diff --git a/bash/autocomplete.go b/bash/autocomplete.go new file mode 100644 index 0000000..541f307 --- /dev/null +++ b/bash/autocomplete.go @@ -0,0 +1,52 @@ +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/command/bash.go b/command/bash.go deleted file mode 100644 index 43b9f97..0000000 --- a/command/bash.go +++ /dev/null @@ -1,51 +0,0 @@ -package command - -import ( - "fmt" - "github.com/codegangsta/cli" - "github.com/integration-system/bellows" - "isp-ctl/service" -) - -var ( - bash = bashAction{enableConfigurationBash: true} - bashSchema = bashAction{enableConfigurationBash: false} -) - -type ( - bashAction struct{ enableConfigurationBash bool } -) - -func (b bashAction) run(ctx *cli.Context) { - if err := checkFlags(ctx); err != nil { - return - } - switch ctx.NArg() { - case 0: - b.moduleNameHelper() - case 1: - if b.enableConfigurationBash { - b.configurationHelper(ctx.Args().First(), ctx.Args().Get(1)) - } - } -} - -func (bashAction) moduleNameHelper() { - if arrayOfModules, err := service.ConfigClient.GetAvailableConfigs(); err != nil { - return - } else { - for _, module := range arrayOfModules { - fmt.Println(module.Name) - } - } -} - -func (bashAction) configurationHelper(moduleName, path string) { - moduleConfiguration, _ := getModuleConfiguration(moduleName) - if moduleConfiguration == nil { - return - } - for key, _ := range bellows.Flatten(moduleConfiguration.Data) { - fmt.Printf(".%v\n", key) - } -} diff --git a/command/common.go b/command/common.go index a31c0ba..9504075 100644 --- a/command/common.go +++ b/command/common.go @@ -4,65 +4,16 @@ import ( "encoding/json" "errors" "fmt" - "github.com/codegangsta/cli" - "github.com/integration-system/isp-lib/http" - "github.com/valyala/fasthttp" "isp-ctl/cfg" - "isp-ctl/flag" "isp-ctl/service" "strings" ) -func checkFlags(c *cli.Context) error { - var ( - uuid, host string - color bool - ) - colorFlag := strings.Split(flag.Color.Name, ", ") - if c.GlobalBool(colorFlag[0]) != false { - color = true - } else { - color = c.GlobalBool(colorFlag[1]) - } - service.ColorService.Enable = color - service.UnsafeService.Enable = c.GlobalBool(flag.Unsafe.Name) - - hostFlag := strings.Split(flag.Host.Name, ", ") - if c.GlobalString(hostFlag[0]) != "" { - host = c.GlobalString(hostFlag[0]) - } else { - host = c.GlobalString(hostFlag[1]) - } - - uuidFlag := strings.Split(flag.Uuid.Name, ", ") - if c.GlobalString(uuidFlag[0]) != "" { - uuid = c.GlobalString(uuidFlag[0]) - } else { - uuid = c.GlobalString(uuidFlag[1]) - } - - if uuid == "" || host == "" { - if configuration, err := service.YamlService.Parse(); err != nil { - return err - } else { - if uuid == "" { - uuid = configuration.InstanceUuid - } - if host == "" { - host = configuration.GateHost - } - } - } - service.ConfigService.ReceiveConfiguration(host, uuid) - return nil -} - -func checkPath(pathObject string) (string, bool) { +func checkPath(pathObject string) (string, error) { str := strings.Split(pathObject, ".") pathObject = "" if len(str) == 1 || str[0] != "" { - printError(errors.New("path must start with '.'")) - return pathObject, false + return pathObject, errors.New("path must start with '.'") } for key, value := range str { if key == 0 { @@ -74,7 +25,15 @@ func checkPath(pathObject string) (string, bool) { } pathObject = fmt.Sprintf("%s.%s", pathObject, value) } - return pathObject, true + 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) + } } func printAnswer(data interface{}) { @@ -85,58 +44,6 @@ func printAnswer(data interface{}) { } } -func getModuleConfiguration(moduleName string) (*cfg.Config, []byte) { - if moduleName == "" { - printError(errors.New("need module name. Use 'schema' for get module names")) - return nil, nil - } - - moduleConfiguration, err := service.ConfigClient.GetConfigByModuleName(moduleName) - if err != nil { - if errorResponse, ok := err.(http.ErrorResponse); ok { - if errorResponse.StatusCode == fasthttp.StatusNotFound { - printError(errors.New(fmt.Sprintf("module '%s' not found\n", moduleName))) - } else { - printError(err) - } - } else { - printError(err) - } - return nil, nil - } - - if jsonObject, err := json.Marshal(moduleConfiguration.Data); err != nil { - printError(err) - return nil, nil - } else { - return moduleConfiguration, jsonObject - } -} - -func createUpdateConfig(stringToChange string, configuration *cfg.Config) { - newData := make(map[string]interface{}) - if stringToChange != "" { - if err := json.Unmarshal([]byte(stringToChange), &newData); err != nil { - printError(err) - return - } - } - - if ok, err := service.UnsafeService.CheckConfigurationSchema(configuration.ModuleId, newData); err != nil { - printError(err) - return - } else if !ok { - return - } - - configuration.Data = newData - if resp, err := service.ConfigClient.CreateUpdateConfig(*configuration); err != nil { - printError(err) - } else { - printAnswer(resp.Data) - } -} - func printError(err error) { - fmt.Println("ERROR", err) + fmt.Println("ERROR:", err) } diff --git a/command/delete.go b/command/delete.go index 29e0837..77df5e8 100644 --- a/command/delete.go +++ b/command/delete.go @@ -3,6 +3,9 @@ package command import ( "github.com/codegangsta/cli" "github.com/tidwall/sjson" + "isp-ctl/bash" + "isp-ctl/flag" + "isp-ctl/service" ) func Delete() cli.Command { @@ -10,7 +13,7 @@ func Delete() cli.Command { Name: "delete", Usage: "delete configuration by module_name", Action: deleteComm.action, - BashComplete: bash.run, + BashComplete: bash.ModuleNameAndConfigurationPath.Complete, } } @@ -18,21 +21,23 @@ var deleteComm deleteCommand type deleteCommand struct{} -func (d deleteCommand) action(c *cli.Context) { - if err := checkFlags(c); err != nil { +func (d deleteCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { printError(err) return } - moduleName := c.Args().First() - pathObject := c.Args().Get(1) + moduleName := ctx.Args().First() + pathObject := ctx.Args().Get(1) - moduleConfiguration, jsonObject := getModuleConfiguration(moduleName) - if moduleConfiguration == nil { + moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + if err != nil { + printError(err) return } - pathObject, ok := checkPath(pathObject) - if !ok { + pathObject, err = checkPath(pathObject) + if err != nil { + printError(err) return } diff --git a/command/get.go b/command/get.go index feba54d..066799e 100644 --- a/command/get.go +++ b/command/get.go @@ -6,6 +6,9 @@ import ( "fmt" "github.com/codegangsta/cli" "github.com/tidwall/gjson" + "isp-ctl/bash" + "isp-ctl/flag" + "isp-ctl/service" ) func Get() cli.Command { @@ -13,7 +16,7 @@ func Get() cli.Command { Name: "get", Usage: "get configuration by module_name", Action: get.action, - BashComplete: bash.run, + BashComplete: bash.ModuleNameAndConfigurationPath.Complete, } } @@ -21,21 +24,23 @@ var get getCommand type getCommand struct{} -func (g getCommand) action(c *cli.Context) { - if err := checkFlags(c); err != nil { +func (g getCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { printError(err) return } - moduleName := c.Args().First() - pathObject := c.Args().Get(1) + moduleName := ctx.Args().First() + pathObject := ctx.Args().Get(1) - moduleConfiguration, jsonObject := getModuleConfiguration(moduleName) - if moduleConfiguration == nil { + moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + if err != nil { + printError(err) return } - pathObject, ok := checkPath(pathObject) - if !ok { + pathObject, err = checkPath(pathObject) + if err != nil { + printError(err) return } diff --git a/command/schema.go b/command/schema.go index 8b13e48..4796b36 100644 --- a/command/schema.go +++ b/command/schema.go @@ -4,10 +4,11 @@ import ( "errors" "fmt" "github.com/codegangsta/cli" - convert "github.com/integration-system/isp-lib/config/schema" "html/template" + "isp-ctl/bash" "isp-ctl/flag" "isp-ctl/service" + "isp-ctl/tmpl" "os" ) @@ -19,7 +20,7 @@ func Schema() cli.Command { Flags: []cli.Flag{ flag.OutPrint, }, - BashComplete: bashSchema.run, + BashComplete: bash.ModuleName.Complete, } } @@ -27,18 +28,18 @@ var schema schemaCommand type schemaCommand struct{} -func (s schemaCommand) action(c *cli.Context) { - if err := checkFlags(c); err != nil { +func (s schemaCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { printError(err) return } - moduleName := c.Args().First() + moduleName := ctx.Args().First() if schemaConfig := s.getSchemaConfig(moduleName); schemaConfig != nil { schema := make(map[string]interface{}) schema["title"] = moduleName schema["schema"] = schemaConfig - switch c.String(flag.OutPrint.Name) { + switch ctx.String(flag.OutPrint.Name) { case flag.OutPrintJsonValue: printAnswer(schema) case flag.OutPrintHtmlValue: @@ -51,18 +52,19 @@ func (s schemaCommand) action(c *cli.Context) { } func (s schemaCommand) getSchemaConfig(moduleName string) interface{} { - if configuration, _ := getModuleConfiguration(moduleName); configuration == nil { + if configuration, _, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName); err != nil { + printError(err) return nil - } else if schema, err := service.ConfigClient.GetSchemaByModuleId(configuration.ModuleId); err != nil { + } else if schema, err := service.Config.GetSchemaByModuleId(configuration.ModuleId); err != nil { printError(err) return nil } else { - return convert.DereferenceSchema(schema.Schema) + return schema } } func (s schemaCommand) printHtml(schema map[string]interface{}) { - if temp, err := template.New("template").Parse(htmlTemplate); err != nil { + if temp, err := template.New("template").Parse(tmpl.HtmlFile); err != nil { printError(err) return } else { diff --git a/command/set.go b/command/set.go index 98a3763..cec33f4 100644 --- a/command/set.go +++ b/command/set.go @@ -7,6 +7,9 @@ import ( "fmt" "github.com/codegangsta/cli" "github.com/tidwall/sjson" + "isp-ctl/bash" + "isp-ctl/flag" + "isp-ctl/service" "os" ) @@ -15,7 +18,7 @@ func Set() cli.Command { Name: "set", Usage: "set configuration by module_name", Action: set.action, - BashComplete: bash.run, + BashComplete: bash.ModuleNameAndConfigurationPath.Complete, } } @@ -23,23 +26,25 @@ var set setCommand type setCommand struct{} -func (s setCommand) action(c *cli.Context) { - if err := checkFlags(c); err != nil { +func (s setCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { printError(err) return } - moduleName := c.Args().First() - pathObject := c.Args().Get(1) - changeObject := c.Args().Get(2) + moduleName := ctx.Args().First() + pathObject := ctx.Args().Get(1) + changeObject := ctx.Args().Get(2) - moduleConfiguration, jsonObject := getModuleConfiguration(moduleName) - if moduleConfiguration == nil { + moduleConfiguration, jsonObject, err := service.Config.GetConfigurationAndJsonByModuleName(moduleName) + if err != nil { + printError(err) return } - pathObject, ok := checkPath(pathObject) - if !ok { + pathObject, err = checkPath(pathObject) + if err != nil { + printError(err) return } diff --git a/command/status.go b/command/status.go index 0640ec6..95b9458 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/flag" "isp-ctl/service" "os" ) @@ -29,12 +30,12 @@ var status statusCommand type statusCommand struct{} -func (statusCommand) action(c *cli.Context) { - if err := checkFlags(c); err != nil { +func (statusCommand) action(ctx *cli.Context) { + if err := flag.CheckGlobal(ctx); err != nil { printError(err) return } - if arrayOfModules, err := service.ConfigClient.GetAvailableConfigs(); err != nil { + if arrayOfModules, err := service.Config.GetAvailableConfigs(); err != nil { printError(err) } else { table := tablewriter.NewWriter(os.Stdout) diff --git a/flag/structure.go b/flag/structure.go index c301ec7..fb26c4a 100644 --- a/flag/structure.go +++ b/flag/structure.go @@ -1,6 +1,10 @@ package flag -import "github.com/codegangsta/cli" +import ( + "github.com/codegangsta/cli" + "isp-ctl/service" + "strings" +) var ( //---global--- @@ -11,3 +15,49 @@ var ( //---local--- OutPrint = cli.StringFlag{Name: outPrintName, Usage: outPrintUsage, Value: OutPrintJsonValue} ) + +func CheckGlobal(c *cli.Context) error { + var ( + uuid, host string + color bool + ) + colorFlag := strings.Split(Color.Name, ", ") + if c.GlobalBool(colorFlag[0]) != false { + color = true + } else { + color = c.GlobalBool(colorFlag[1]) + } + service.ColorService.Enable = color + service.Config.UnsafeEnable = c.GlobalBool(Unsafe.Name) + + hostFlag := strings.Split(Host.Name, ", ") + if c.GlobalString(hostFlag[0]) != "" { + host = c.GlobalString(hostFlag[0]) + } else { + host = c.GlobalString(hostFlag[1]) + } + + uuidFlag := strings.Split(Uuid.Name, ", ") + if c.GlobalString(uuidFlag[0]) != "" { + uuid = c.GlobalString(uuidFlag[0]) + } else { + uuid = c.GlobalString(uuidFlag[1]) + } + + uuid = strings.Replace(uuid, "'", "", -1) + host = strings.Replace(host, "'", "", -1) + if uuid == "" || host == "" { + if configuration, err := service.YamlService.Parse(); err != nil { + return err + } else { + if uuid == "" { + uuid = configuration.InstanceUuid + } + if host == "" { + host = configuration.GateHost + } + } + } + service.Config.ReceiveConfiguration(host, uuid) + return nil +} diff --git a/main.go b/main.go index fabe7cb..3c78cf2 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "github.com/codegangsta/cli" "isp-ctl/command" "isp-ctl/flag" @@ -41,6 +42,11 @@ func initCommands() { command.Delete(), command.Schema(), } + app.BashComplete = func(context *cli.Context) { + for _, command := range app.Commands { + fmt.Println(command.Name) + } + } err := app.Run(os.Args) if err != nil { diff --git a/service/config.go b/service/config.go index ca29429..e33b90d 100644 --- a/service/config.go +++ b/service/config.go @@ -1,16 +1,100 @@ package service import ( + "encoding/json" + "errors" + "fmt" + "github.com/integration-system/isp-lib/config/schema" "github.com/integration-system/isp-lib/http" + "github.com/valyala/fasthttp" + "github.com/xeipuuv/gojsonschema" "isp-ctl/cfg" ) -var ConfigClient = cfg.NewConfigClient(http.NewJsonRestClient()) +var ( + configClient = cfg.NewConfigClient(http.NewJsonRestClient()) + Config configService +) -var ConfigService configService - -type configService struct{} +type configService struct { + UnsafeEnable bool +} func (configService) ReceiveConfiguration(host, uuid string) { - ConfigClient.ReceiveConfig(host, uuid) + configClient.ReceiveConfig(host, uuid) +} + +func (configService) GetAvailableConfigs() ([]cfg.ModuleInfo, error) { + return configClient.GetAvailableConfigs() +} + +func (configService) GetConfigurationAndJsonByModuleName(moduleName string) (*cfg.Config, []byte, error) { + if moduleName == "" { + return nil, nil, errors.New("need module name") + } + if moduleConfiguration, err := configClient.GetConfigByModuleName(moduleName); err != nil { + if errorResponse, ok := err.(http.ErrorResponse); ok && errorResponse.StatusCode == fasthttp.StatusNotFound { + return nil, nil, errors.New(fmt.Sprintf("module '%s' not found", moduleName)) + } + return nil, nil, err + } else if jsonObject, err := json.Marshal(moduleConfiguration.Data); err != nil { + return nil, nil, err + } else { + return moduleConfiguration, jsonObject, nil + } +} + +func (configService) GetSchemaByModuleId(moduleId int32) (schema.Schema, error) { + if configSchema, err := configClient.GetSchemaByModuleId(moduleId); err != nil { + return nil, err + } else { + dereferenceSchema := schema.DereferenceSchema(configSchema.Schema) + return dereferenceSchema, nil + } +} + +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 { + return nil, err + } + } + + if ok, err := c.checkSchema(configuration.ModuleId, newData); err != nil { + return nil, err + } else if !ok { + return nil, nil + } + + configuration.Data = newData + if resp, err := configClient.CreateUpdateConfig(*configuration); err != nil { + return nil, err + } else { + return resp.Data, nil + } +} + +func (c configService) checkSchema(moduleId int32, 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 + } + } } diff --git a/service/unsafe.go b/service/unsafe.go deleted file mode 100644 index e3eaebd..0000000 --- a/service/unsafe.go +++ /dev/null @@ -1,36 +0,0 @@ -package service - -import ( - "fmt" - "github.com/xeipuuv/gojsonschema" -) - -var UnsafeService unsafeService - -type unsafeService struct { - Enable bool -} - -func (s unsafeService) CheckConfigurationSchema(moduleId int32, object map[string]interface{}) (bool, error) { - if s.Enable { - 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 - } - } -} diff --git a/command/html_template.go b/tmpl/html_template.go similarity index 96% rename from command/html_template.go rename to tmpl/html_template.go index 5e2fb12..7a90d45 100644 --- a/command/html_template.go +++ b/tmpl/html_template.go @@ -1,8 +1,8 @@ -package command +package tmpl -const htmlTemplate = ` +const HtmlFile = `
- +