conflict.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package merge
  14. import (
  15. "fmt"
  16. "sort"
  17. "strings"
  18. "sigs.k8s.io/structured-merge-diff/fieldpath"
  19. )
  20. // Conflict is a conflict on a specific field with the current manager of
  21. // that field. It does implement the error interface so that it can be
  22. // used as an error.
  23. type Conflict struct {
  24. Manager string
  25. Path fieldpath.Path
  26. }
  27. // Conflict is an error.
  28. var _ error = Conflict{}
  29. // Error formats the conflict as an error.
  30. func (c Conflict) Error() string {
  31. return fmt.Sprintf("conflict with %q: %v", c.Manager, c.Path)
  32. }
  33. // Conflicts accumulates multiple conflicts and aggregates them by managers.
  34. type Conflicts []Conflict
  35. var _ error = Conflicts{}
  36. // Error prints the list of conflicts, grouped by sorted managers.
  37. func (conflicts Conflicts) Error() string {
  38. if len(conflicts) == 1 {
  39. return conflicts[0].Error()
  40. }
  41. m := map[string][]fieldpath.Path{}
  42. for _, conflict := range conflicts {
  43. m[conflict.Manager] = append(m[conflict.Manager], conflict.Path)
  44. }
  45. managers := []string{}
  46. for manager := range m {
  47. managers = append(managers, manager)
  48. }
  49. // Print conflicts by sorted managers.
  50. sort.Strings(managers)
  51. messages := []string{}
  52. for _, manager := range managers {
  53. messages = append(messages, fmt.Sprintf("conflicts with %q:", manager))
  54. for _, path := range m[manager] {
  55. messages = append(messages, fmt.Sprintf("- %v", path))
  56. }
  57. }
  58. return strings.Join(messages, "\n")
  59. }
  60. // ConflictsFromManagers creates a list of conflicts given Managers sets.
  61. func ConflictsFromManagers(sets fieldpath.ManagedFields) Conflicts {
  62. conflicts := []Conflict{}
  63. for manager, set := range sets {
  64. set.Iterate(func(p fieldpath.Path) {
  65. conflicts = append(conflicts, Conflict{
  66. Manager: manager,
  67. Path: p,
  68. })
  69. })
  70. }
  71. return conflicts
  72. }