-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathutils.go
More file actions
196 lines (166 loc) · 4.84 KB
/
utils.go
File metadata and controls
196 lines (166 loc) · 4.84 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package testutils
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"io"
"iter"
"net/http"
"os"
"path/filepath"
"reflect"
"strconv"
"testing"
"unsafe"
"github.com/speakeasy-api/jsonpath/pkg/jsonpath"
"github.com/speakeasy-api/openapi/yml"
"github.com/stretchr/testify/assert"
"go.yaml.in/yaml/v4"
yamlv3 "gopkg.in/yaml.v3"
)
// TODO use these more in tests
func CreateStringYamlNode(value string, line, column int) *yaml.Node {
cfg := yml.GetDefaultConfig()
return &yaml.Node{
Value: value,
Kind: yaml.ScalarNode,
Style: cfg.ValueStringStyle,
Tag: "!!str",
Line: line,
Column: column,
}
}
func CreateIntYamlNode(value int, line, column int) *yaml.Node {
return &yaml.Node{
Value: strconv.Itoa(value),
Kind: yaml.ScalarNode,
Tag: "!!int",
Line: line,
Column: column,
}
}
func CreateBoolYamlNode(value bool, line, column int) *yaml.Node {
return &yaml.Node{
Value: strconv.FormatBool(value),
Kind: yaml.ScalarNode,
Tag: "!!bool",
Line: line,
Column: column,
}
}
func CreateMapYamlNode(contents []*yaml.Node, line, column int) *yaml.Node {
return &yaml.Node{
Content: contents,
Kind: yaml.MappingNode,
Tag: "!!map",
Line: line,
Column: column,
}
}
type SequencedMap interface {
Len() int
AllUntyped() iter.Seq2[any, any]
GetUntyped(key any) (any, bool)
}
// isInterfaceNil checks if an interface has a nil underlying value
func isInterfaceNil(i interface{}) bool {
if i == nil {
return true
}
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan, reflect.Func:
return v.IsNil()
default:
return false
}
}
func AssertEqualSequencedMap(t *testing.T, expected, actual SequencedMap) {
t.Helper()
// Check if both are truly nil (interface with nil type and value)
if expected == nil && actual == nil {
return
}
// Check if either is nil or has a nil underlying value
expectedIsNil := expected == nil || (expected != nil && isInterfaceNil(expected))
actualIsNil := actual == nil || (actual != nil && isInterfaceNil(actual))
if expectedIsNil && actualIsNil {
return
}
if expectedIsNil || actualIsNil {
assert.Fail(t, "expected and actual must not be nil")
return
}
assert.EqualExportedValues(t, expected, actual)
assert.Equal(t, expected.Len(), actual.Len())
alreadySeen := map[any]bool{}
for k, v := range expected.AllUntyped() {
actualV, ok := actual.GetUntyped(k)
assert.True(t, ok)
assert.EqualExportedValues(t, v, actualV)
alreadySeen[k] = true
}
for k, v := range actual.AllUntyped() {
if _, ok := alreadySeen[k]; ok {
continue
}
actualV, ok := actual.GetUntyped(k)
assert.True(t, ok)
assert.EqualExportedValues(t, v, actualV)
}
}
// DownloadFile downloads a file from a URL and caches it to avoid re-downloading.
// Uses the provided cacheEnvVar for cache location, fallback to system temp dir.
// The cacheDirName is used as the subdirectory name under the cache directory.
func DownloadFile(url, cacheEnvVar, cacheDirName string) (io.ReadCloser, error) {
// Use environment variable for cache directory, fallback to system temp dir
cacheDir := os.Getenv(cacheEnvVar)
if cacheDir == "" {
cacheDir = os.TempDir()
}
tempDir := filepath.Join(cacheDir, cacheDirName)
if err := os.MkdirAll(tempDir, 0o750); err != nil {
return nil, err
}
// hash url to create a unique filename
hash := sha256.Sum256([]byte(url))
filename := hex.EncodeToString(hash[:])
filepath := filepath.Join(tempDir, filename)
// check if file exists and return it otherwise download it
r, err := os.Open(filepath) // #nosec G304 -- filepath is controlled by caller in tests
if err == nil {
return r, nil
}
resp, err := http.Get(url) // #nosec G107 -- url is controlled by caller in tests
if err != nil {
return nil, err
}
if resp == nil {
return nil, io.ErrUnexpectedEOF
}
defer resp.Body.Close()
// Read all data from response body
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// Write data to cache file
f, err := os.OpenFile(filepath, os.O_CREATE|os.O_WRONLY, 0o600) // #nosec G304 -- filepath is controlled by caller in tests
if err != nil {
return nil, err
}
defer f.Close()
_, err = f.Write(data)
if err != nil {
return nil, err
}
// Return the data as a ReadCloser
return io.NopCloser(bytes.NewReader(data)), nil
}
// QueryV4 runs a jsonpath query using a v4 node by casting to v3 and back.
// This bridges the gap between jsonpath libraries that use yaml.v3 types and
// the v4 types used throughout this codebase.
func QueryV4(path *jsonpath.JSONPath, node *yaml.Node) []*yaml.Node {
v3result := path.Query((*yamlv3.Node)(unsafe.Pointer(node))) //nolint:gosec // v4.Node is a strict superset of v3.Node (verified at init)
return *(*[]*yaml.Node)(unsafe.Pointer(&v3result)) //nolint:gosec // pointer types have identical memory layouts
}