prevent the same path load multiple times

This commit is contained in:
wackxu 2017-10-12 10:19:28 +08:00
parent 83e46f0a9e
commit 973e610787
3 changed files with 47 additions and 2 deletions

View File

@ -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 {

View File

@ -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)
@ -610,3 +612,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
}

View File

@ -577,3 +577,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)
}
}
}