rules.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2020 Jebbs. All rights reserved.
  2. // Use of this source code is governed by MIT
  3. // license that can be found in the LICENSE file.
  4. package merge
  5. const priorityKey string = "_priority"
  6. const tagKey string = "_tag"
  7. // ApplyRules applies merge rules according to _tag, _priority fields, and remove them
  8. func ApplyRules(m map[string]interface{}) error {
  9. err := sortMergeSlices(m)
  10. if err != nil {
  11. return err
  12. }
  13. removeHelperFields(m)
  14. return nil
  15. }
  16. // sortMergeSlices enumerates all slices in a map, to sort by priority and merge by tag
  17. func sortMergeSlices(target map[string]interface{}) error {
  18. for key, value := range target {
  19. if slice, ok := value.([]interface{}); ok {
  20. sortByPriority(slice)
  21. s, err := mergeSameTag(slice)
  22. if err != nil {
  23. return err
  24. }
  25. target[key] = s
  26. for _, item := range s {
  27. if m, ok := item.(map[string]interface{}); ok {
  28. sortMergeSlices(m)
  29. }
  30. }
  31. } else if field, ok := value.(map[string]interface{}); ok {
  32. sortMergeSlices(field)
  33. }
  34. }
  35. return nil
  36. }
  37. func removeHelperFields(target map[string]interface{}) {
  38. for key, value := range target {
  39. if key == priorityKey || key == tagKey {
  40. delete(target, key)
  41. } else if slice, ok := value.([]interface{}); ok {
  42. for _, e := range slice {
  43. if el, ok := e.(map[string]interface{}); ok {
  44. removeHelperFields(el)
  45. }
  46. }
  47. } else if field, ok := value.(map[string]interface{}); ok {
  48. removeHelperFields(field)
  49. }
  50. }
  51. }