1414package utils
1515
1616import (
17- "reflect"
18-
1917 glob "github.com/gobwas/glob"
18+ "reflect"
19+ "strings"
2020)
2121
22- // FilterMap receives a map with string keys and arbirary values (possibly
22+ // FilterMap receives a map with string keys and arbitrary values (possibly
2323// other maps) and return a new map which is a subset of the original one
24- // contaning only the keys matching any of the patterns in "include" and
24+ // containing only the keys matching any of the patterns in "include" and
2525// excluding keys matching any of the patterns in "exclude". The logic for
2626// determining if a key matches the pattern goes as follow:
2727//
@@ -45,10 +45,27 @@ func FilterMap(m map[string]interface{}, include, exclude []string) map[string]i
4545 cp := glob .MustCompile (p , '.' )
4646 includeGlob [i ] = cp
4747 }
48+ // For each include pattern that do not ends with **, add the same pattern
49+ // but ended in .**. This because when someone says that she wants to include
50+ // "foo.bar", where "foo.bar" is dictionary, what she actually expects is
51+ // getting the dictionary with all its keys, but the keys inside the
52+ // dictionary don't match the "foo.bar" pattern, so we add "foo.bar.**".
53+ for _ , p := range include {
54+ if ! strings .HasSuffix (p , "**" ) {
55+ includeGlob = append (includeGlob , glob .MustCompile (p + ".**" , '.' ))
56+ }
57+ }
4858 for i , p := range exclude {
4959 cp := glob .MustCompile (p , '.' )
5060 excludeGlob [i ] = cp
5161 }
62+ // The same happens if you exclude "foo.bar", what you actually mean is
63+ // excluding "foo.bar" and "foo.bar.**".
64+ for _ , p := range exclude {
65+ if ! strings .HasSuffix (p , "**" ) {
66+ excludeGlob = append (excludeGlob , glob .MustCompile (p + ".**" , '.' ))
67+ }
68+ }
5269 filtered := filterMap (reflect .ValueOf (m ), includeGlob , excludeGlob , "" )
5370 return filtered .Interface ().(map [string ]interface {})
5471}
0 commit comments