From dad884ddeb913a2ca033237a8439dac817e107ac Mon Sep 17 00:00:00 2001 From: Ionut Costin Craciun Date: Thu, 29 Oct 2020 14:47:27 +0200 Subject: [PATCH] Raise error when adding a new zot config with an existed saved name --- errors/errors.go | 1 + pkg/cli/config_cmd.go | 15 +++++++++++++++ pkg/cli/config_cmd_test.go | 14 ++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/errors/errors.go b/errors/errors.go index c123d9a0..36fc91c7 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -36,4 +36,5 @@ var ( ErrIllegalConfigKey = errors.New("cli: given config key is not allowed") ErrScanNotSupported = errors.New("search: scanning of image media type not supported") ErrCLITimeout = errors.New("cli: Query timed out while waiting for results") + ErrDuplicateConfigName = errors.New("cli: cli config name already added") ) diff --git a/pkg/cli/config_cmd.go b/pkg/cli/config_cmd.go index 4a01fcb3..3383692f 100644 --- a/pkg/cli/config_cmd.go +++ b/pkg/cli/config_cmd.go @@ -204,6 +204,10 @@ func addConfig(configPath, configName, url string) error { return zotErrors.ErrInvalidURL } + if configNameExists(configs, configName) { + return zotErrors.ErrDuplicateConfigName + } + configMap := make(map[string]interface{}) configMap["url"] = url configMap[nameKey] = configName @@ -361,6 +365,17 @@ func getAllConfig(configPath, configName string) (string, error) { return "", zotErrors.ErrConfigNotFound } +func configNameExists(configs []interface{}, configName string) bool { + for _, val := range configs { + configMap := val.(map[string]interface{}) + if configMap[nameKey] == configName { + return true + } + } + + return false +} + const ( examples = ` zot config add main https://zot-foo.com:8080 zot config main url diff --git a/pkg/cli/config_cmd_test.go b/pkg/cli/config_cmd_test.go index 4f92234f..1112ef4f 100644 --- a/pkg/cli/config_cmd_test.go +++ b/pkg/cli/config_cmd_test.go @@ -300,4 +300,18 @@ func TestConfigCmdMain(t *testing.T) { So(err, ShouldNotBeNil) So(buff.String(), ShouldContainSubstring, "cannot reset") }) + + Convey("Test add a config with an existing saved name", t, func() { + args := []string{"add", "configtest", "https://test-url.com/new"} + configPath := makeConfigFile(`{"configs":[{"_name":"configtest","url":"https://test-url.com","showspinner":false}]}`) + defer os.Remove(configPath) + cmd := NewConfigCommand() + buff := bytes.NewBufferString("") + cmd.SetOut(buff) + cmd.SetErr(ioutil.Discard) + cmd.SetArgs(args) + err := cmd.Execute() + So(err, ShouldNotBeNil) + So(buff.String(), ShouldContainSubstring, "cli config name already added") + }) }