1 // Copyright 2015 go-swagger maintainers
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
25 "github.com/go-openapi/swag"
28 // PathLoader function to use when loading remote refs
29 var PathLoader func(string) (json.RawMessage, error)
32 PathLoader = func(path string) (json.RawMessage, error) {
33 data, err := swag.LoadFromFileOrHTTP(path)
37 return json.RawMessage(data), nil
41 // resolverContext allows to share a context during spec processing.
42 // At the moment, it just holds the index of circular references found.
43 type resolverContext struct {
44 // circulars holds all visited circular references, which allows shortcuts.
45 // NOTE: this is not just a performance improvement: it is required to figure out
46 // circular references which participate several cycles.
47 // This structure is privately instantiated and needs not be locked against
48 // concurrent access, unless we chose to implement a parallel spec walking.
49 circulars map[string]bool
53 func newResolverContext(originalBasePath string) *resolverContext {
54 return &resolverContext{
55 circulars: make(map[string]bool),
56 basePath: originalBasePath, // keep the root base path in context
60 type schemaLoader struct {
62 options *ExpandOptions
64 context *resolverContext
65 loadDoc func(string) (json.RawMessage, error)
68 func (r *schemaLoader) transitiveResolver(basePath string, ref Ref) (*schemaLoader, error) {
69 if ref.IsRoot() || ref.HasFragmentOnly {
73 baseRef, _ := NewRef(basePath)
74 currentRef := normalizeFileRef(&ref, basePath)
75 if strings.HasPrefix(currentRef.String(), baseRef.String()) {
79 // Set a new root to resolve against
80 rootURL := currentRef.GetURL()
82 root, _ := r.cache.Get(rootURL.String())
84 // shallow copy of resolver options to set a new RelativeBase when
85 // traversing multiple documents
86 newOptions := r.options
87 newOptions.RelativeBase = rootURL.String()
88 debugLog("setting new root: %s", newOptions.RelativeBase)
89 resolver, err := defaultSchemaLoader(root, newOptions, r.cache, r.context)
97 func (r *schemaLoader) updateBasePath(transitive *schemaLoader, basePath string) string {
99 debugLog("got a new resolver")
100 if transitive.options != nil && transitive.options.RelativeBase != "" {
101 basePath, _ = absPath(transitive.options.RelativeBase)
102 debugLog("new basePath = %s", basePath)
108 func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string) error {
109 tgt := reflect.ValueOf(target)
110 if tgt.Kind() != reflect.Ptr {
111 return fmt.Errorf("resolve ref: target needs to be a pointer")
114 refURL := ref.GetURL()
122 // Resolve against the root if it isn't nil, and if ref is pointing at the root, or has a fragment only which means
123 // it is pointing somewhere in the root.
125 if (ref.IsRoot() || ref.HasFragmentOnly) && root == nil && basePath != "" {
126 if baseRef, erb := NewRef(basePath); erb == nil {
127 root, _, _, _ = r.load(baseRef.GetURL())
130 if (ref.IsRoot() || ref.HasFragmentOnly) && root != nil {
133 baseRef := normalizeFileRef(ref, basePath)
134 debugLog("current ref is: %s", ref.String())
135 debugLog("current ref normalized file: %s", baseRef.String())
136 data, _, _, err = r.load(baseRef.GetURL())
143 if ref.String() != "" {
144 res, _, err = ref.GetPointer().Get(data)
149 return swag.DynamicJSONToStruct(res, target)
152 func (r *schemaLoader) load(refURL *url.URL) (interface{}, url.URL, bool, error) {
153 debugLog("loading schema from url: %s", refURL)
155 toFetch.Fragment = ""
157 normalized := normalizeAbsPath(toFetch.String())
159 data, fromCache := r.cache.Get(normalized)
161 b, err := r.loadDoc(normalized)
163 return nil, url.URL{}, false, err
166 if err := json.Unmarshal(b, &data); err != nil {
167 return nil, url.URL{}, false, err
169 r.cache.Set(normalized, data)
172 return data, toFetch, fromCache, nil
175 // isCircular detects cycles in sequences of $ref.
176 // It relies on a private context (which needs not be locked).
177 func (r *schemaLoader) isCircular(ref *Ref, basePath string, parentRefs ...string) (foundCycle bool) {
178 normalizedRef := normalizePaths(ref.String(), basePath)
179 if _, ok := r.context.circulars[normalizedRef]; ok {
180 // circular $ref has been already detected in another explored cycle
184 foundCycle = swag.ContainsStringsCI(parentRefs, normalizedRef)
186 r.context.circulars[normalizedRef] = true
191 // Resolve resolves a reference against basePath and stores the result in target
192 // Resolve is not in charge of following references, it only resolves ref by following its URL
193 // if the schema that ref is referring to has more refs in it. Resolve doesn't resolve them
194 // if basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct
195 func (r *schemaLoader) Resolve(ref *Ref, target interface{}, basePath string) error {
196 return r.resolveRef(ref, target, basePath)
199 func (r *schemaLoader) deref(input interface{}, parentRefs []string, basePath string) error {
201 switch refable := input.(type) {
211 return fmt.Errorf("deref: unsupported type %T", input)
214 curRef := ref.String()
216 normalizedRef := normalizeFileRef(ref, basePath)
217 normalizedBasePath := normalizedRef.RemoteURI()
219 if r.isCircular(normalizedRef, basePath, parentRefs...) {
223 if err := r.resolveRef(ref, input, basePath); r.shouldStopOnError(err) {
227 // NOTE(fredbi): removed basePath check => needs more testing
228 if ref.String() != "" && ref.String() != curRef {
229 parentRefs = append(parentRefs, normalizedRef.String())
230 return r.deref(input, parentRefs, normalizedBasePath)
237 func (r *schemaLoader) shouldStopOnError(err error) bool {
238 if err != nil && !r.options.ContinueOnError {
249 func defaultSchemaLoader(
251 expandOptions *ExpandOptions,
252 cache ResolutionCache,
253 context *resolverContext) (*schemaLoader, error) {
258 if expandOptions == nil {
259 expandOptions = &ExpandOptions{}
261 absBase, _ := absPath(expandOptions.RelativeBase)
263 context = newResolverContext(absBase)
265 return &schemaLoader{
267 options: expandOptions,
270 loadDoc: func(path string) (json.RawMessage, error) {
271 debugLog("fetching document at %q", path)
272 return PathLoader(path)