From 1ae3aba19bf3bac2f1238b4b445884e0d14c8942 Mon Sep 17 00:00:00 2001 From: wackxu Date: Thu, 12 Oct 2017 10:19:28 +0800 Subject: [PATCH] prevent the same path load multiple times Kubernetes-commit: 973e610787db8a9cee5da098e2f72672be817aa9 --- tools/clientcmd/config.go | 4 +++- tools/clientcmd/loader.go | 18 +++++++++++++++++- tools/clientcmd/loader_test.go | 27 +++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/tools/clientcmd/config.go b/tools/clientcmd/config.go index 16ccdaf2..7092c5b1 100644 --- a/tools/clientcmd/config.go +++ b/tools/clientcmd/config.go @@ -68,7 +68,9 @@ func (o *PathOptions) GetEnvVarFiles() []string { return []string{} } - return filepath.SplitList(envVarValue) + fileList := filepath.SplitList(envVarValue) + // prevent the same path load multiple times + return deduplicate(fileList) } func (o *PathOptions) GetLoadingPrecedence() []string { diff --git a/tools/clientcmd/loader.go b/tools/clientcmd/loader.go index 95e7b154..3442475e 100644 --- a/tools/clientcmd/loader.go +++ b/tools/clientcmd/loader.go @@ -139,7 +139,9 @@ func NewDefaultClientConfigLoadingRules() *ClientConfigLoadingRules { envVarFiles := os.Getenv(RecommendedConfigPathEnvVar) if len(envVarFiles) != 0 { - chain = append(chain, filepath.SplitList(envVarFiles)...) + fileList := filepath.SplitList(envVarFiles) + // prevent the same path load multiple times + chain = append(chain, deduplicate(fileList)...) } else { chain = append(chain, RecommendedHomeFile) @@ -615,3 +617,17 @@ func MakeRelative(path, base string) (string, error) { } return path, nil } + +// deduplicate removes any duplicated values and returns a new slice, keeping the order unchanged +func deduplicate(s []string) []string { + encountered := map[string]bool{} + ret := make([]string, 0) + for i := range s { + if encountered[s[i]] { + continue + } + encountered[s[i]] = true + ret = append(ret, s[i]) + } + return ret +} diff --git a/tools/clientcmd/loader_test.go b/tools/clientcmd/loader_test.go index c2dbd019..09d0753b 100644 --- a/tools/clientcmd/loader_test.go +++ b/tools/clientcmd/loader_test.go @@ -592,3 +592,30 @@ func Example_mergingEverythingNoConflicts() { // user: // token: red-token } + +func TestDeduplicate(t *testing.T) { + testCases := []struct { + src []string + expect []string + }{ + { + src: []string{"a", "b", "c", "d", "e", "f"}, + expect: []string{"a", "b", "c", "d", "e", "f"}, + }, + { + src: []string{"a", "b", "c", "b", "e", "f"}, + expect: []string{"a", "b", "c", "e", "f"}, + }, + { + src: []string{"a", "a", "b", "b", "c", "b"}, + expect: []string{"a", "b", "c"}, + }, + } + + for _, testCase := range testCases { + get := deduplicate(testCase.src) + if !reflect.DeepEqual(get, testCase.expect) { + t.Errorf("expect: %v, get: %v", testCase.expect, get) + } + } +}