podman
338 строк · 9.0 Кб
1// Copyright 2015 go-swagger maintainers
2//
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//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package spec16
17import (18"encoding/json"19"fmt"20"log"21"net/url"22"reflect"23"strings"24
25"github.com/go-openapi/swag"26)
27
28// PathLoader is a function to use when loading remote refs.
29//
30// This is a package level default. It may be overridden or bypassed by
31// specifying the loader in ExpandOptions.
32//
33// NOTE: if you are using the go-openapi/loads package, it will override
34// this value with its own default (a loader to retrieve YAML documents as
35// well as JSON ones).
36var PathLoader = func(pth string) (json.RawMessage, error) {37data, err := swag.LoadFromFileOrHTTP(pth)38if err != nil {39return nil, err40}41return json.RawMessage(data), nil42}
43
44// resolverContext allows to share a context during spec processing.
45// At the moment, it just holds the index of circular references found.
46type resolverContext struct {47// circulars holds all visited circular references, to shortcircuit $ref resolution.48//49// This structure is privately instantiated and needs not be locked against50// concurrent access, unless we chose to implement a parallel spec walking.51circulars map[string]bool52basePath string53loadDoc func(string) (json.RawMessage, error)54rootID string55}
56
57func newResolverContext(options *ExpandOptions) *resolverContext {58expandOptions := optionsOrDefault(options)59
60// path loader may be overridden by options61var loader func(string) (json.RawMessage, error)62if expandOptions.PathLoader == nil {63loader = PathLoader64} else {65loader = expandOptions.PathLoader66}67
68return &resolverContext{69circulars: make(map[string]bool),70basePath: expandOptions.RelativeBase, // keep the root base path in context71loadDoc: loader,72}73}
74
75type schemaLoader struct {76root interface{}77options *ExpandOptions78cache ResolutionCache
79context *resolverContext80}
81
82func (r *schemaLoader) transitiveResolver(basePath string, ref Ref) *schemaLoader {83if ref.IsRoot() || ref.HasFragmentOnly {84return r85}86
87baseRef := MustCreateRef(basePath)88currentRef := normalizeRef(&ref, basePath)89if strings.HasPrefix(currentRef.String(), baseRef.String()) {90return r91}92
93// set a new root against which to resolve94rootURL := currentRef.GetURL()95rootURL.Fragment = ""96root, _ := r.cache.Get(rootURL.String())97
98// shallow copy of resolver options to set a new RelativeBase when99// traversing multiple documents100newOptions := r.options101newOptions.RelativeBase = rootURL.String()102
103return defaultSchemaLoader(root, newOptions, r.cache, r.context)104}
105
106func (r *schemaLoader) updateBasePath(transitive *schemaLoader, basePath string) string {107if transitive != r {108if transitive.options != nil && transitive.options.RelativeBase != "" {109return normalizeBase(transitive.options.RelativeBase)110}111}112
113return basePath114}
115
116func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string) error {117tgt := reflect.ValueOf(target)118if tgt.Kind() != reflect.Ptr {119return ErrResolveRefNeedsAPointer120}121
122if ref.GetURL() == nil {123return nil124}125
126var (127res interface{}128data interface{}129err error130)131
132// Resolve against the root if it isn't nil, and if ref is pointing at the root, or has a fragment only which means133// it is pointing somewhere in the root.134root := r.root135if (ref.IsRoot() || ref.HasFragmentOnly) && root == nil && basePath != "" {136if baseRef, erb := NewRef(basePath); erb == nil {137root, _, _, _ = r.load(baseRef.GetURL())138}139}140
141if (ref.IsRoot() || ref.HasFragmentOnly) && root != nil {142data = root143} else {144baseRef := normalizeRef(ref, basePath)145data, _, _, err = r.load(baseRef.GetURL())146if err != nil {147return err148}149}150
151res = data152if ref.String() != "" {153res, _, err = ref.GetPointer().Get(data)154if err != nil {155return err156}157}158return swag.DynamicJSONToStruct(res, target)159}
160
161func (r *schemaLoader) load(refURL *url.URL) (interface{}, url.URL, bool, error) {162debugLog("loading schema from url: %s", refURL)163toFetch := *refURL164toFetch.Fragment = ""165
166var err error167pth := toFetch.String()168normalized := normalizeBase(pth)169debugLog("loading doc from: %s", normalized)170
171unescaped, err := url.PathUnescape(normalized)172if err != nil {173return nil, url.URL{}, false, err174}175
176u := url.URL{Path: unescaped}177
178data, fromCache := r.cache.Get(u.RequestURI())179if fromCache {180return data, toFetch, fromCache, nil181}182
183b, err := r.context.loadDoc(normalized)184if err != nil {185return nil, url.URL{}, false, err186}187
188var doc interface{}189if err := json.Unmarshal(b, &doc); err != nil {190return nil, url.URL{}, false, err191}192r.cache.Set(normalized, doc)193
194return doc, toFetch, fromCache, nil195}
196
197// isCircular detects cycles in sequences of $ref.
198//
199// It relies on a private context (which needs not be locked).
200func (r *schemaLoader) isCircular(ref *Ref, basePath string, parentRefs ...string) (foundCycle bool) {201normalizedRef := normalizeURI(ref.String(), basePath)202if _, ok := r.context.circulars[normalizedRef]; ok {203// circular $ref has been already detected in another explored cycle204foundCycle = true205return206}207foundCycle = swag.ContainsStrings(parentRefs, normalizedRef) // normalized windows url's are lower cased208if foundCycle {209r.context.circulars[normalizedRef] = true210}211return212}
213
214// Resolve resolves a reference against basePath and stores the result in target.
215//
216// Resolve is not in charge of following references: it only resolves ref by following its URL.
217//
218// If the schema the ref is referring to holds nested refs, Resolve doesn't resolve them.
219//
220// If basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct
221func (r *schemaLoader) Resolve(ref *Ref, target interface{}, basePath string) error {222return r.resolveRef(ref, target, basePath)223}
224
225func (r *schemaLoader) deref(input interface{}, parentRefs []string, basePath string) error {226var ref *Ref227switch refable := input.(type) {228case *Schema:229ref = &refable.Ref230case *Parameter:231ref = &refable.Ref232case *Response:233ref = &refable.Ref234case *PathItem:235ref = &refable.Ref236default:237return fmt.Errorf("unsupported type: %T: %w", input, ErrDerefUnsupportedType)238}239
240curRef := ref.String()241if curRef == "" {242return nil243}244
245normalizedRef := normalizeRef(ref, basePath)246normalizedBasePath := normalizedRef.RemoteURI()247
248if r.isCircular(normalizedRef, basePath, parentRefs...) {249return nil250}251
252if err := r.resolveRef(ref, input, basePath); r.shouldStopOnError(err) {253return err254}255
256if ref.String() == "" || ref.String() == curRef {257// done with rereferencing258return nil259}260
261parentRefs = append(parentRefs, normalizedRef.String())262return r.deref(input, parentRefs, normalizedBasePath)263}
264
265func (r *schemaLoader) shouldStopOnError(err error) bool {266if err != nil && !r.options.ContinueOnError {267return true268}269
270if err != nil {271log.Println(err)272}273
274return false275}
276
277func (r *schemaLoader) setSchemaID(target interface{}, id, basePath string) (string, string) {278debugLog("schema has ID: %s", id)279
280// handling the case when id is a folder281// remember that basePath has to point to a file282var refPath string283if strings.HasSuffix(id, "/") {284// ensure this is detected as a file, not a folder285refPath = fmt.Sprintf("%s%s", id, "placeholder.json")286} else {287refPath = id288}289
290// updates the current base path291// * important: ID can be a relative path292// * registers target to be fetchable from the new base proposed by this id293newBasePath := normalizeURI(refPath, basePath)294
295// store found IDs for possible future reuse in $ref296r.cache.Set(newBasePath, target)297
298// the root document has an ID: all $ref relative to that ID may299// be rebased relative to the root document300if basePath == r.context.basePath {301debugLog("root document is a schema with ID: %s (normalized as:%s)", id, newBasePath)302r.context.rootID = newBasePath303}304
305return newBasePath, refPath306}
307
308func defaultSchemaLoader(309root interface{},310expandOptions *ExpandOptions,311cache ResolutionCache,312context *resolverContext) *schemaLoader {313
314if expandOptions == nil {315expandOptions = &ExpandOptions{}316}317
318cache = cacheOrDefault(cache)319
320if expandOptions.RelativeBase == "" {321// if no relative base is provided, assume the root document322// contains all $ref, or at least, that the relative documents323// may be resolved from the current working directory.324expandOptions.RelativeBase = baseForRoot(root, cache)325}326debugLog("effective expander options: %#v", expandOptions)327
328if context == nil {329context = newResolverContext(expandOptions)330}331
332return &schemaLoader{333root: root,334options: expandOptions,335cache: cache,336context: context,337}338}
339