/filter/filter.go

https://bitbucket.org/marthjod/ansible-one-inventory · Go · 38 lines · 24 code · 7 blank · 7 comment · 4 complexity · da5888d37a09291eeae8d57e42025926 MD5 · raw file

  1. // Package filter handles group assignment via hostname filtering.
  2. package filter
  3. import (
  4. "fmt"
  5. "github.com/marthjod/ansible-one-inventory/model"
  6. "regexp"
  7. )
  8. // A GroupFilter is a key-value map mapping group names to regexps
  9. // which describe hostnames belonging to a respective group.
  10. type GroupFilters map[string]string
  11. // Takes a list of hostnames and returns an InventoryGroup
  12. // consisting of those matching regex.
  13. func Filter(hostNames []string, regex string) (model.InventoryGroup, error) {
  14. ig := model.InventoryGroup{}
  15. re, err := regexp.Compile(regex)
  16. if err != nil {
  17. return ig, fmt.Errorf("%q: %s", regex, err.Error())
  18. }
  19. for _, h := range hostNames {
  20. if re.MatchString(h) {
  21. ig = append(ig, h)
  22. }
  23. }
  24. return ig, nil
  25. }
  26. // AdjustPatternName can be used to make auto-discovered patterns
  27. // more readable.
  28. func AdjustPatternName(regex, replacement string) string {
  29. re := regexp.MustCompile(replacement)
  30. return re.ReplaceAllString(regex, "")
  31. }