MCPcopy Create free account
hub / github.com/quay/clair / loadAsJSON

Function loadAsJSON

cmd/config.go:141–187  ·  view source on GitHub ↗
(path string)

Source from the content-addressed store, hash-verified

139}
140
141func loadAsJSON(path string) ([]byte, error) {
142 b, err := os.ReadFile(path)
143 if err != nil {
144 return nil, fmt.Errorf("error reading file %q: %w", path, err)
145 }
146 ext := filepath.Ext(path)
147 switch ext {
148 case ".json", ".json-patch":
149 if len(b) < 2 {
150 return nil, fmt.Errorf("malformed file %q: not a JSON document", path)
151 }
152 case ".yaml", ".yaml-patch":
153 var y interface{}
154 if err := yaml.Unmarshal(b, &y); err != nil {
155 msg := strings.TrimPrefix(err.Error(), `yaml: `)
156 return nil, fmt.Errorf("malformed file %q: %v", path, msg)
157 }
158 // For arbitrary yaml documents we'd have to do a step to ensure there's
159 // no disallowed constructs (binary keys, binary data tags) but we know
160 // this should only ever be some snippet of our config.Config type.
161 b, err = json.Marshal(y)
162 if err != nil { // Not sure how this would happen. 🤔
163 msg := strings.TrimPrefix(err.Error(), `json: `)
164 return nil, fmt.Errorf("malformed file %q: %s", path, msg)
165 }
166 default:
167 panic("programmer error: called on bad path")
168 }
169 switch ext {
170 case ".json":
171 if b[0] != '{' {
172 return nil, fmt.Errorf("malformed file %q: not a JSON object", path)
173 }
174 case ".json-patch", ".yaml-patch":
175 if b[0] != '[' {
176 return nil, fmt.Errorf("malformed file %q: not a patch document", path)
177 }
178 case ".yaml":
179 if b[0] != '{' {
180 // If this was an empty file (for some reason), note it and return an
181 // empty JSON object. This can't happen with JSON -- we checked if it
182 // meets the minimum size above.
183 b = []byte("{}")
184 }
185 }
186 return b, nil
187}

Callers 1

LoadConfigFunction · 0.85

Calls 1

ErrorMethod · 0.45

Tested by

no test coverage detected