Merge pull request #1381 from hashicorp/util-update

Updates to policy and string helpers
This commit is contained in:
Jeff Mitchell 2016-05-05 10:29:10 -04:00
commit 5b9458e697
2 changed files with 54 additions and 4 deletions

View file

@ -3,13 +3,29 @@ package policyutil
import (
"sort"
"strings"
"github.com/hashicorp/vault/helper/strutil"
)
func ParsePolicies(policiesRaw string) []string {
if policiesRaw == "" {
return []string{"default"}
}
policies := strings.Split(policiesRaw, ",")
return SanitizePolicies(policies)
}
func SanitizePolicies(policies []string) []string {
defaultFound := false
for i, p := range policies {
policies[i] = strings.ToLower(strings.TrimSpace(p))
// Eliminate unnamed policies.
if policies[i] == "" {
continue
}
// If 'root' policy is present, ignore all other policies.
if policies[i] == "root" {
policies = []string{"root"}
@ -26,10 +42,7 @@ func ParsePolicies(policiesRaw string) []string {
policies = append(policies, "default")
}
// Sort to make the computations on policies consistent.
sort.Strings(policies)
return policies
return strutil.RemoveDuplicates(policies)
}
// ComparePolicies checks whether the given policy sets are equivalent, as in,

View file

@ -1,5 +1,10 @@
package strutil
import (
"sort"
"strings"
)
// StrListContains looks for a string in a list of strings.
func StrListContains(haystack []string, needle string) bool {
for _, item := range haystack {
@ -20,3 +25,35 @@ func StrListSubset(super, sub []string) bool {
}
return true
}
// Parses a comma separated list of strings into a slice of strings.
// The return slice will be sorted and will not contain duplicate or
// empty items. The values will be converted to lower case.
func ParseStrings(input string) []string {
var parsed []string
if input == "" {
// Don't return nil
return parsed
}
return RemoveDuplicates(strings.Split(input, ","))
}
// Removes duplicate and empty elements from a slice of strings.
// This also converts the items in the slice to lower case and
// returns a sorted slice.
func RemoveDuplicates(items []string) []string {
itemsMap := map[string]bool{}
for _, item := range items {
item = strings.ToLower(strings.TrimSpace(item))
if item == "" {
continue
}
itemsMap[item] = true
}
items = []string{}
for item, _ := range itemsMap {
items = append(items, item)
}
sort.Strings(items)
return items
}