Skip to content

Commit

Permalink
Correctly resolve path of yaml resource if double referenced.
Browse files Browse the repository at this point in the history
Where previously following path was resolved `testdata/components/models/error.yaml`, missing `recursiveRef` folder.

 Author:    davor.sauer <davor.sauer@gmail.com>
  • Loading branch information
d-sauer committed Sep 23, 2022
1 parent a7c6ee9 commit 34dc382
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
13 changes: 8 additions & 5 deletions openapi3/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,14 @@ func join(basePath *url.URL, relativePath *url.URL) (*url.URL, error) {
if err != nil {
return nil, fmt.Errorf("cannot copy path: %q", basePath.String())
}
newPath.Path = path.Join(path.Dir(newPath.Path), relativePath.Path)

// check if basePath is reference to the file
if strings.LastIndex(basePath.Path, ".") > strings.LastIndex(basePath.Path, "/") {
newPath.Path = path.Join(path.Dir(newPath.Path), relativePath.Path)
} else {
newPath.Path = path.Join(newPath.Path, relativePath.Path)
}

return newPath, nil
}

Expand Down Expand Up @@ -421,10 +428,6 @@ func (loader *Loader) documentPathForRecursiveRef(current *url.URL, resolvedRef
return current
}

if resolvedRef == "" {
return current
}

return &url.URL{Path: path.Join(loader.rootDir, resolvedRef)}
}

Expand Down
17 changes: 17 additions & 0 deletions openapi3/loader_recursive_ref_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
package openapi3

import (
"net/url"
"testing"

"github.com/stretchr/testify/require"
)

func TestResolvePath(t *testing.T) {
var b = &url.URL{Path: "testdata/recursiveRef"}
var c = &url.URL{Path: "./components/models/error.yaml"}
u, err := resolvePath(b, c)

require.NoError(t, err)
require.Equal(t, &url.URL{Path: "testdata/recursiveRef/components/models/error.yaml"}, u)

b = &url.URL{Path: "testdata/recursiveRef/openapi.yaml"}
c = &url.URL{Path: "./components/models/error.yaml"}
u, err = resolvePath(b, c)

require.NoError(t, err)
require.Equal(t, &url.URL{Path: "testdata/recursiveRef/components/models/error.yaml"}, u)
}

func TestLoaderSupportsRecursiveReference(t *testing.T) {
loader := NewLoader()
loader.IsExternalRefsAllowed = true
Expand Down
2 changes: 1 addition & 1 deletion openapi3/testdata/recursiveRef/openapi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ components:
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
$ref: "#/components/schemas/Error"

0 comments on commit 34dc382

Please sign in to comment.