forked from Tufin/oasdiff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
examples_diff.go
107 lines (82 loc) · 2.4 KB
/
examples_diff.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package diff
import (
"fmt"
"github.com/rjmohammad/kin-openapi/openapi3"
)
// ExamplesDiff describes the changes between a pair of sets of example objects: https://swagger.io/specification/#example-object
type ExamplesDiff struct {
Added StringList `json:"added,omitempty" yaml:"added,omitempty"`
Deleted StringList `json:"deleted,omitempty" yaml:"deleted,omitempty"`
Modified ModifiedExamples `json:"modified,omitempty" yaml:"modified,omitempty"`
}
// ModifiedExamples is map of enconding names to their respective diffs
type ModifiedExamples map[string]*ExampleDiff
// Empty indicates whether a change was found in this element
func (diff *ExamplesDiff) Empty() bool {
if diff == nil {
return true
}
return len(diff.Added) == 0 &&
len(diff.Deleted) == 0 &&
len(diff.Modified) == 0
}
func newExamplessDiff() *ExamplesDiff {
return &ExamplesDiff{
Added: StringList{},
Deleted: StringList{},
Modified: ModifiedExamples{},
}
}
func getExamplesDiff(config *Config, state *state, examples1, examples2 openapi3.Examples) (*ExamplesDiff, error) {
diff, err := getExamplesDiffInternal(config, state, examples1, examples2)
if err != nil {
return nil, err
}
if diff.Empty() {
return nil, nil
}
return diff, nil
}
func getExamplesDiffInternal(config *Config, state *state, examples1, examples2 openapi3.Examples) (*ExamplesDiff, error) {
if config.ExcludeExamples {
return nil, nil
}
result := newExamplessDiff()
for name1, exampleRef1 := range examples1 {
if exampleRef2, ok := examples2[name1]; ok {
value1, err := derefExample(exampleRef1)
if err != nil {
return nil, err
}
value2, err := derefExample(exampleRef2)
if err != nil {
return nil, err
}
diff := getExampleDiff(config, state, value1, value2)
if !diff.Empty() {
result.Modified[name1] = diff
}
} else {
result.Deleted = append(result.Deleted, name1)
}
}
for name2 := range examples2 {
if _, ok := examples1[name2]; !ok {
result.Added = append(result.Added, name2)
}
}
return result, nil
}
func derefExample(ref *openapi3.ExampleRef) (*openapi3.Example, error) {
if ref == nil || ref.Value == nil {
return nil, fmt.Errorf("example reference is nil")
}
return ref.Value, nil
}
func (diff *ExamplesDiff) getSummary() *SummaryDetails {
return &SummaryDetails{
Added: len(diff.Added),
Deleted: len(diff.Deleted),
Modified: len(diff.Modified),
}
}